← All fixes
openai.AuthenticationError: Error code: 401 - Incorrect API key provided
#164Error
openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Incorrect API key provided: sk-proj-****. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'code': 'invalid_api_key'}}Why it happens, and why this works
The key the client sent isn't valid. Most often the code isn't using the key you think: an old OPENAI_API_KEY in the shell or system environment wins over .env (python-dotenv and dotenv don't override existing variables by default), load_dotenv() ran after the client was created, or the value has quotes or whitespace. Revoked keys and keys from a deleted project also fail.
Fix
1. Print the last 4 characters of the key the process actually has (os.environ["OPENAI_API_KEY"][-4:]) and compare. 2. Remove a stale system/shell variable, or call load_dotenv(override=True) before creating the client. 3. Strip quotes and spaces in .env: OPENAI_API_KEY=sk-... with no quotes around it. 4. Create a fresh key in the right project and restart the dev server / terminal.
Did it work?
No reports yet0 worked0 didn't
Tried it yourself?
Related fixes
401 Unauthorized / invalid API key even though the key is set
#144401 Unauthorized: invalid x-api-key / Incorrect API key provided / authentication_error, while the key looks correct in .env
API returns 429 Too Many Requests / rate limit exceeded (OpenAI, Anthropic, GitHub, any REST API)
#143429 Too Many Requests: rate limit exceeded (RateLimitError / rate_limit_error / secondary rate limit)
javascriptpythonopenaianthropicgithubNo reports yet
Error: Cannot find module 'express' (package not installed)
#58Error: Cannot find module 'express' Require stack: - /app/app.js code: 'MODULE_NOT_FOUND'