This code sets up a chatbot using OpenAI’s ChatGPT API to respond to user input.
import openai openai.api_key = "your keys goes here" messages = [{"role": "system", "content": "You are a helpful assistant."}] def gpt_chat(): try: completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) return completion.choices[0].message['content'] except Exception as oops: return 'GPT3 Error %s' % oops while True: user_ask = input("USER: ") new_message = { "role":"user","content":user_ask } messages.append(new_message) ai_response = gpt_chat() ai_message = {"role":"assistant","content": ai_response} messages.append(ai_message) ai = "AI: " + ai_response print(ai)
Here’s a brief overview of what the code does:
- The
openai
the module is imported, and the API key for the GPT-3 API is set to an empty string. This is where you would normally enter your own API key to authenticate with the service. - An initial message is added to the
messages
list, which is used to track the conversation history. The message is in the format of a dictionary with two key-value pairs:{"role": "system", "content": "You are a helpful assistant."}
. This message will be the first thing the chatbot says when it starts up. - The
gpt_chat()
the function is defined. This function calls the OpenAI API to generate a response based on the conversation history stored in themessages
list. Themodel
parameter specifies which GPT-3 model to use, and themessages
parameter specifies the conversation history. The function returns the response generated by the GPT-3 API. - The code enters an infinite loop that repeatedly asks the user for input using the
input()
function. The user’s input is stored in theuser_ask
variable. - A new message is created in the format of a dictionary using the user’s input, with the key “role” set to “user” and the key “content” set to the user’s input. This message is appended to the
messages
list. - The
gpt_chat()
the function is called to generate a response to the user’s input based on the conversation history stored in themessages
list. The response is stored in theai_response
variable. - A new message is created in the format of a dictionary using the response generated by the GPT-3 API, with the key “role” set to “assistant” and the key “content” set to the AI’s response. This message is appended to the
messages
list. - The AI’s response is printed to the console with the prefix “AI: “.
- The loop repeats, waiting for the next user input.
Note that the code is designed to run continuously until it is interrupted (e.g., by pressing Ctrl+C on the keyboard). This is because the loop condition while True:
will always be true, causing the loop to continue indefinitely.