AuthenticationError
openai.AuthenticationError (HTTP 401)
Stack trace
openai.AuthenticationError: Invalid API key provided: sk-xxxxxxx
File "app.py", line 12, in <module>
response = client.chat.completions.create(model="gpt-4o-mini", messages=messages)
File "/usr/local/lib/python3.9/site-packages/openai/api_resources/chat_completion.py", line 25, in create
return super().create(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/openai/api_resource.py", line 123, in create
response, _, api_key = requestor.request(
File "/usr/local/lib/python3.9/site-packages/openai/api_requestor.py", line 120, in request
self._handle_error_response(response)
File "/usr/local/lib/python3.9/site-packages/openai/api_requestor.py", line 342, in _handle_error_response
raise error_class(message, response.status_code, response.headers, response.body)
Why it happens
This error occurs when the OpenAI API key is missing, invalid, expired, or incorrectly set in the environment variables. LangChain's ChatOpenAI client relies on this key to authenticate requests. Without proper authentication, the API rejects calls with a 401 Unauthorized error.
Detection
Check for AuthenticationError exceptions when calling ChatOpenAI methods. Log or assert that the environment variable OPENAI_API_KEY is set and valid before making API calls.
Causes & fixes
OPENAI_API_KEY environment variable is not set or is empty
Set the OPENAI_API_KEY environment variable with a valid OpenAI API key before running your application.
API key is invalid or revoked
Verify your API key on the OpenAI dashboard and replace the invalid key with a valid, active one.
Using incorrect environment variable name or loading it improperly
Ensure your code reads the API key from os.environ['OPENAI_API_KEY'] exactly and that the environment variable is exported correctly.
Passing API key directly in the client constructor incorrectly
Use environment variables for API keys instead of hardcoding or passing them incorrectly; follow LangChain and OpenAI SDK v1+ recommended patterns.
Code: broken vs fixed
from langchain_openai import ChatOpenAI
client = ChatOpenAI(model_name="gpt-4o-mini")
response = client.chat(messages=[{"role": "user", "content": "Hello"}]) # Raises AuthenticationError import os
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = "your_valid_api_key_here" # Set your API key securely
client = ChatOpenAI(model_name="gpt-4o-mini")
response = client.chat(messages=[{"role": "user", "content": "Hello"}])
print(response) # Works without AuthenticationError Workaround
Catch AuthenticationError exceptions and prompt the user or system to set or refresh the OPENAI_API_KEY environment variable before retrying the request.
Prevention
Use environment management tools or secrets managers to securely inject and verify API keys at runtime, and add startup checks to confirm valid authentication before processing requests.