You need to remove the lack of a key, just leave the api_key parameter out, and instead set an environment variable in your operating system OPENAI_API_KEY with an API key from your account.
Python should be version 3.8-3.11. Then you’ll need to again run pip install --upgrade openai
to get the latest version installed.
None of the scripts or files in your program directory - especially your own program - should be named openai. They would get called instead of the correct library.
Then - that code is an “assistant” a very poor way to enter the world of interacting with OpenAI AI models.
Here’s a script I made to be as simple as possible, while still supporting:
- latest openai python methods
- demonstration of system and user messages, and maintaining a chat history
- introduces itself, giving immediate confirmation all is working without you needing to type
- giving a limited number of past chat turns back to the AI for context understanding
- streaming output to the python console (without any formatting)
- looping conversation until you type “exit”
from openai import OpenAI
client = OpenAI()
system = [{"role": "system",
"content": """You are a chatbot, giving expert answers."""}]
user = [{"role": "user", "content": "brief introduction?"}]
chat = []
while not user[0]['content'] == "exit":
response = client.chat.completions.create(
messages = system + chat[-10:] + user,
model="gpt-3.5-turbo", top_p=0.9, stream=True)
reply = ""
for delta in response:
if not delta.choices[0].finish_reason:
word = delta.choices[0].delta.content or ""
reply += word
print(word, end ="")
chat += user + [{"role": "assistant", "content": reply}]
user = [{"role": "user", "content": input("\nPrompt: ")}]