AuthenticationError
openai.AuthenticationError (HTTP 401)
Stack trace
openai.AuthenticationError: Invalid API key provided: sk-xxxxxx
at openai.api_requestor.APIRequestor._handle_error_response (/path/to/sdk/requestor.py:123)
at openai.api_requestor.APIRequestor.request (/path/to/sdk/requestor.py:85)
at openai.client.ChatCompletion.create (/path/to/sdk/client.py:45)
at main.py:15 Why it happens
This error happens because the OpenAI client cannot authenticate your request due to a missing, malformed, expired, or revoked API key. The server returns HTTP 401 Unauthorized, preventing any further API calls.
Detection
Check for openai.AuthenticationError exceptions during API calls and verify that the API key environment variable is set and correctly loaded before making requests.
Causes & fixes
API key environment variable is not set or misspelled
Set the environment variable OPENAI_API_KEY correctly before running your application, e.g., export OPENAI_API_KEY='your_key_here'.
Using an expired or revoked API key
Generate a new API key from the OpenAI dashboard and update your environment variable accordingly.
Passing the API key incorrectly in code (e.g., hardcoded or wrong parameter)
Use os.environ to load the API key and pass it to the OpenAI client constructor properly, never hardcode keys.
Network or proxy issues causing the API key to be stripped or altered
Ensure your network or proxy does not modify headers or environment variables; test connectivity without proxies.
Code: broken vs fixed
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}]) # Fails with AuthenticationError import os
from openai import OpenAI
os.environ["OPENAI_API_KEY"] = "your_actual_api_key_here" # Set your API key securely
client = OpenAI()
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response) Workaround
If you cannot set environment variables immediately, pass the API key explicitly when initializing the client if supported, or catch AuthenticationError and prompt for key input.
Prevention
Use environment variables to manage API keys securely and validate their presence at application startup to avoid runtime authentication failures.