AuthenticationError
openai.AuthenticationError (HTTP 401)
Stack trace
openai.AuthenticationError: Error code: 401 - {'error': {'message': 'Invalid API key provided', 'type': 'authentication_error', 'param': null, 'code': 'invalid_api_key'}} Why it happens
This error occurs when the API key used in the OpenAI Assistants client is missing, malformed, expired, or revoked. The server rejects the request because it cannot authenticate the client without a valid key.
Detection
Check for openai.AuthenticationError exceptions in your API calls and verify the API key environment variable is set and correctly loaded before making requests.
Causes & fixes
API key environment variable is not set or misspelled
Ensure the environment variable (e.g., OPENAI_API_KEY) is set correctly in your environment and matches the variable your code reads.
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 the client initialization
Use the OpenAI SDK v1+ pattern with os.environ to load the key and pass it properly to the client constructor.
Code: broken vs fixed
from openai import OpenAI
client = OpenAI(api_key="wrong_or_missing_key") # This causes AuthenticationError
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response) import os
from openai import OpenAI
os.environ["OPENAI_API_KEY"] = "your_valid_api_key_here" # Set your valid API key here
client = OpenAI()
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response) # Works without AuthenticationError Workaround
If you cannot update the environment immediately, catch AuthenticationError exceptions and prompt for manual API key input or fallback to cached valid credentials.
Prevention
Use environment variables to manage API keys securely and validate their presence at application startup to avoid runtime authentication failures.