macOS: openai.OpenAIError: OPENAI_API_KEY environment variable

I’ve searched and found similar topics but none of them seem to fix a basic issue.
I’m trying to run sample python code from the API reference.

I’ve setup OPENAI_API_KEY as an environment variable on my Mac.
In Terminal, if I type ‘echo $OPENAI_API_KEY’, it prints the correct key.

I’m trying to execute the following python code:

If I use the curl version of the same code, I get the expected response, which tells me that the environment variable is setup correctly.

If I run the python version in a .py file, I get the following error:
Traceback (most recent call last):
File “/Users/my_user/chatgpt/”, line 2, in
client = OpenAI()
File “/Users/my_user/Library/Python/3.11/lib/python/site-packages/openai/”, line 92, in init
raise OpenAIError(
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 can confirm that my account has money in it.

I’ve seen solutions in the forum that ask to import dotenv, etc. but why do I need to do that if the OPENAI_API_KEY environment variable is set and the sample code doesn’t require dotenv, etc?

Thanks for any help!

1 Like

Kind of figured it out.
I tried to print the API key using python and it printed ‘KeyError’:
import os

Even though I had quit Terminal and re-launched it a few times, it didn’t work.

I ran the following in Terminal:
export OPENAI_API_KEY=‘your_key’

This fixed the issue.

I also noticed that the ~/.bash_profile had export and the remaining string on separate lines. It had wrapped like this:

I corrected it using TextEdit so that it was all on one line:
export OPENAI_API_KEY=‘the_very_long_key’

Hope this helps someone!

1 Like


Is it OK if a moderator closes this topic?

Yes, please close it.
Thanks for checking.