Here’s how to start your first Python program using OpenAI ChatGPT AI and create a chatbot assistant.
The revolutionary, easy-to-use AI “ChatGPT” is now available as API. OpenAI, the creator of ChatGPT, announced that the model (gpt-3.5-turbo
) is now available for your custom products and solutions. The cost is super affordable as well. It is currently priced at $0.002 for 1000 tokens.
The model is currently available alongside Whisper API, which is also used for text-to-speech solutions. The API is currently capable of the following:
- Create custom conversational agents and bots.
- Write Python code for you
- Draft emails or any documents you want
- You can integrate your current product/app/service or software with a natural language interface for your consumers.
- Language translation services
- Be a tutor for many subjects
- Simulate video game characters
As you can see, the opportunities are endless.
If you plan to try the API and get started, here’s a simple guide for you with step-by-step instructions on how to use it.
Table of Contents
OpenAI ChatGPT API: Getting Started
Pre-requisite
Make sure you have an OpenAI account. If you don’t visit this page and create an account. You can also use your Google or Microsoft account.
After you create an account, generate an API key which is exclusive to your account. Visit this page and create a new secret key.
Write down or save the key somewhere safe. It will not be visible from the OpenAI account section a second time for security reasons. And DO NOT share this key with anyone. If you plan to use enterprise solutions, check with your organizations for the API Key. This key is tied to your paid OpenAI plan; hence use it with caution.
Setting up environment
Install Python and pip
This guide uses Python programming language to consume the OpenAI API key. You can use Java or any other language to consume it.
Firstly, make sure you have Python installed in Linux or Windows. If not, follow the below guides to install Python. If you are using modern Linux distributions such as Ubuntu, Python should already be installed.
After Python is installed, make sure pip is available in Linux distributions. Run the following command to install it. For Windows, you should already have it as part of the Python installation.
Ubuntu, Debian and others
sudo apt install python3-pip
Fedora, RHEL, CentOS and others
sudo dnf install python3-pip
Arch Linux
sudo pacman -S python-pip
Set up OpenAI API Key as an environment variable
The API secret key which you have created in the above steps, you can directly use it in the program. But it is not recommended.
The best practice is to consume it from a file or your system’s environment variable.
For Windows, set up a PATH
variable with any name, for example, “API-KEY”. And add the key value.
For Linux, open /etc/environment
file using root privileges and add the key. For example:
API-KEY="<your key here>"
For file-based key access, use the below statement in your code:
openai.api_key_path = <your path to API key>
For direct access in code (not recommended), you can use the below statement in your code:
openai.api_key="your key here"
Note: If the authentication fails, OpenAI API throws the below error. You need to verify your key value, path and other parameters for correction: openai.error.AuthenticationError: No API key provided
Install OpenAI API
The final step is to install the Python library for OpenAI. Open a terminal or command window and install OpenAI API using the below.
pip install openai
At this stage, you are all set to write your first program!
Coding the assistant (step-by-step)
OpenAI API provides various modes of interface. Such as “chat completion”, “code completion”, “image generation”, etc. In this guide, I will use the “chat completion” features of the API. Using this, we can create a simple conversation chatbot.
Firstly, you need to import the OpenAI library. You can do it using the below statement in your Python program.
import openai
Following this statement, you should make sure you enable your API key. You can do it in any of the ways explained above.
openai.api_key="your key here"
openai.api_key="your environment variable"
openai.api_key_path = <your path to API key>
The basic function of OpenAI chat API is below. The openai.ChatCompletion.create
function takes several arguments in JSON format. The arguments are in the form of "role"
and "content"
.
openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ] )
Explanation
role: Valid values are “system”, “user”, “assistant”
system: Instruct the API on how to behave. Basically, it is the main prompt for OpenAI.
user: The question you want to ask. It is user input in single or multiple conversations. It can be multiple lines of text.
assistant: When you are coding a conversation, you need to use this role to append the response. So that the API remembers what the discussion is about.
Note: In one single message, you can send multiple roles. The behaviour, your question and the history as shown in above code snippet.
Let’s define an array to hold the entire message for OpenAI. Then show a prompt to the user and accept the system
instructions.
messages = []
system_message = input("What type of chatbot you want me to be?")
messages.append({"role":"system","content":system_message})
Once it has been set, prompt to the user again for further questions about the conversation. You can use the Python input function (or any other file input method) and set the content
for role user
.
print("Alright! I am ready to be your friendly chatbot" + "\n" + "You can now type your messages.")
message = input("")
messages.append({"role":"user","content": message})
At this stage, you have the array ready with basic JSON input to the OpenAI API. Now, all you need to do is call the create function for “chat completion” service using the created JSON.
response=openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
Now, you can either print the response or parse it for proper formatting. The response is in JSON format. The output response provides “choices
” array. The response is provided under message
JSON object with content
value.
For this example, we can read the first object in the choices array and read the content.
reply = response["choices"][0]["message"]["content"]
print(reply)
And finally, it will give you the output from the API.
Running the code
You can run the code from your favourite Python IDE or directly from the command line.
python OpenAIDemo2.py
Unformatted JSON output
Here’s a run of the above program with unformatted JSON output for your reference. As you can see, the response is under choices
array with content
.
[debugpoint@fedora python]$ python OpenAIDemo2.py What type of chatbot you want me to be?a friendly friend Alright! I am ready to be your friendly chatbot You can now type your messages. what do you think about kindness? { "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "As an AI language model, I don't have personal opinions, but I can tell you that kindness is a very positive and essential trait to have. Kindness is about being considerate and compassionate towards others, which creates positive emotions and reduces negativity. People who are kind towards others are more likely to inspire kindness and compassion in return. It is an important quality that helps to build positive relationships, promote cooperation, and create a more peaceful world.", "role": "assistant" } } ], "created": <removed>, "id": "chatcmpl-<removed>", "model": "gpt-3.5-turbo-0301", "object": "chat.completion", "usage": { "completion_tokens": 91, "prompt_tokens": 22, "total_tokens": 113 } }
Formatted output
Here’s a proper conversational output.
[debugpoint@fedora python]$ python OpenAIDemo2.py What type of chatbot you want me to be?a friendly friend Alright! I am ready to be your friendly chatbot You can now type your messages. what do you think about artificial general intelligence?
As an AI language model, I am programmed to be neutral and not have personal opinions. However, artificial general intelligence (AGI) is a fascinating field of study. AGI refers to the development of machines and algorithms that can perform any intellectual task that a human being can. The potential benefits and risks of AGI are still widely debated, with some experts worried about the implications of machines reaching human-like intelligence. However, many believe that AGI has the potential to revolutionize fields such as healthcare, education, and transportation. The key is to ensure that AGI is developed in a responsible and ethical manner.
Complete Code
Here’s the complete code which is used in the above demo.
import openai openai.api_key="<your key>" messages = [] system_message = input("What type of chatbot you want me to be?") messages.append({"role":"system","content":system_message}) print("Alright! I am ready to be your friendly chatbot" + "\n" + "You can now type your messages.") message = input("") messages.append({"role":"user","content": message}) response=openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) reply = response["choices"][0]["message"]["content"] print(reply)
Wrapping Up
I hope this simple guide can get you started with OpenAI CharGPT API. You can extend the above steps to a more complex conversational chatbot. Also, you can use the other offerings of OpenAI.
Stay tuned for further tutorials as I experiment and share them with you. And finally, don’t forget to follow us, so you don’t miss any articles.
Do let me know in the comment box if the above steps help you.
Cheers.