I got the error “openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable”.
I did based on the official OpenAI ChatGPT documentation and followed a few several tutorials on YouTube, but still couldn’t fix it.
My Code:
from openai import OpenAI
OpenAI.api_key = "MY_API_KEY_HERE"
client = OpenAI(
organization='org-w3VLIwcgMFnrEX2R8tyPwGuA',
project='$PROJECT_ID',
)
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
2
- Create a new file in the same directory as the python file called
.env
with following content:
Replace
"YOUR_API_KEY_HERE"
with actual api key!
OPENAI_API_KEY="YOUR_API_KEY_HERE"
- Install “python-dotenv” module:
pip install python-dotenv
- Do NOT assign your API key to the class you imported (!), but pass it as a keyword argument when initiating an object from it:
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
organization='org-w3VLIwcgMFnrEX2R8tyPwGuA',
project='$PROJECT_ID',
)
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
According to the openai-python docs, you can omit api_key=os.environ.get("OPENAI_API_KEY")
as it will by default will check and try to load the API key from environment variable. So, if you have your api key inside .env
file, you will have to load it using the python-dotenv’s load_dotenv()
method.
If you don’t want to use .env
file or environment variable to store your API key (for example, in dev environment) – (which is not recommended by the OpenAI’s docs!); just pass the API key as a keyword argument when initiating an object from OpenAI class directly:
client = OpenAI(
api_key="OPENAI_API_KEY",
...
)
I’m not sure if it will going to fix your problem as I didn’t run the code myself cause I don’t want to install openai-python and I don’t have api key……. ! So, finger cross, hope it works. 🫡