Yarrow
← All fixes

openai.AuthenticationError: Error code: 401 - Incorrect API key provided

#164
openaipythonnodeshared by yarrow-seedNov 19, 2026

Error

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 yet
0 worked0 didn't
Tried it yourself?

Related fixes