The OpenAI client says the API key is missing
Missing credentials. Please pass an `api_key`Short answer
OpenAI() looks for an api_key argument first and then the OPENAI_API_KEY environment variable. It raises as soon as the client is created if both are empty. Check the variable inside the same Python process that fails, load your .env file before the client is built, and use the Azure variable names if you use AzureOpenAI.
Fix it fast
1Find out which cause you have
Ask the failing process itself, not your terminal. If this prints False, the variable never reached it; the rest is finding out why.
python -c "import os; print('OPENAI_API_KEY' in os.environ)"2Match what you see, then jump to its fix
- 1
It works in one terminal tab, but not from the IDE run button, a cron job, a service or a container.The variable is set in a different shell or processFix - 2
The key exists in .env, yet the check above prints False, or the client is created at import time before load_dotenv() runs.The .env file is not loaded, or is loaded too lateFix - 3
The code builds AzureOpenAI(...), and the key you exported has the OpenAI name.Using AzureOpenAI but only OPENAI_API_KEY is setFix
- 1
What does the error look like?
Missing credentials. Please pass an `api_key`
Cause 1 of 3
The variable is set in a different shell or process
1Check
Compare the variable in the shell with the one the failing program sees. A variable exported in one terminal is invisible to other processes.
echo "${OPENAI_API_KEY:+set}"
python -c "import os; print(bool(os.environ.get('OPENAI_API_KEY')))"2Fix
Set the variable where the program is started: the shell profile, the service or container definition, or the IDE run configuration. Or pass the key in code, reading it from your secret store.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))3Verify
Run the program from the same place that failed before.
python app.pyConfirmed by github.com
Cause 2 of 3
The .env file is not loaded, or is loaded too late
1Check
load_dotenv() sets variables in os.environ and looks for .env next to the script, then in parent directories. By default it does not replace a variable that already exists.
grep -n "load_dotenv\|OpenAI(" *.py2Fix
Call load_dotenv() first, before any module that builds the client. Use override=True only if an old value in the environment is winning over the file.
from dotenv import load_dotenv
load_dotenv()
from openai import OpenAI
client = OpenAI()3Verify
Print whether the variable is present, without printing the key itself.
python -c "from dotenv import load_dotenv; import os; load_dotenv(); print('OPENAI_API_KEY' in os.environ)"Confirmed by raw.githubusercontent.com
Cause 3 of 3
Using AzureOpenAI but only OPENAI_API_KEY is set
1Check
The Azure client reads its own names: AZURE_OPENAI_API_KEY for the key, AZURE_OPENAI_ENDPOINT for the endpoint and OPENAI_API_VERSION for the API version.
env | grep -E 'AZURE_OPENAI|OPENAI_API_VERSION' | sed 's/=.*/=.../'2Fix
Set the Azure variable names, or pass api_key, azure_endpoint and api_version to AzureOpenAI explicitly.
from openai import AzureOpenAI
client = AzureOpenAI(
api_key=os.environ["AZURE_OPENAI_API_KEY"],
api_version=API_VERSION,
azure_endpoint=ENDPOINT,
)3Verify
Create the client and make one small request.
python app.pyConfirmed by github.com
How do I stop it coming back?
- Build the client in one module, after configuration has loaded, and import it elsewhere.
- Fail at startup with a clear message if the variable is empty, instead of at the first request.
- Keep .env out of git and set real keys in the host's secret settings.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
AI
Azure OpenAI says the API deployment for this resource does not exist
The API deployment for this resource does not exist
Azure OpenAI does not take a model name in the model field.
2 causes, each with a fixAI
Azure OpenAI fails with an SSL certificate verification error
httpx.ConnectError: [SSL: CERTIFICATE_VERIFY_FAILED]
The client checks the endpoint's certificate against its CA bundle, which is certifi by default.
2 causes, each with a fixAI
OpenAI says the model is a chat model and not supported in the v1/completions endpoint
This is a chat model and not supported in the v1/completions endpoint
The v1/completions endpoint accepts completion models such as gpt-3.5-turbo-instruct.
3 causes, each with a fixAI
Old openai.ChatCompletion or openai.Embedding code breaks on a new SDK
APIRemovedInV1
The Python SDK was rewritten in version 1.0.
2 causes, each with a fixAI
TypeError when you index an OpenAI response like a dictionary
TypeError: 'ChatCompletion' object is not subscriptable
Since SDK 1.0 the OpenAI Python library returns Pydantic model objects instead of dictionaries, so response['choices'] fails.
2 causes, each with a fixAI
TypeError: Client.__init__() got an unexpected keyword argument 'proxies'
TypeError: Client.__init__() got an unexpected keyword argument 'proxies'
httpx 0.28.0 removed its deprecated proxies argument.
2 causes, each with a fix