High severity HTTP 401 beginner · Fix: 2-5 min

AuthenticationError

openai.AuthenticationError (HTTP 401)

What this error means
LangChain's ChatOpenAI client failed to authenticate due to missing, invalid, or misconfigured OpenAI API key.

Stack trace

traceback
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)
QUICK FIX
Set the OPENAI_API_KEY environment variable with a valid key before initializing ChatOpenAI to resolve authentication errors immediately.

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

1

OPENAI_API_KEY environment variable is not set or is empty

✓ Fix

Set the OPENAI_API_KEY environment variable with a valid OpenAI API key before running your application.

2

API key is invalid or revoked

✓ Fix

Verify your API key on the OpenAI dashboard and replace the invalid key with a valid, active one.

3

Using incorrect environment variable name or loading it improperly

✓ Fix

Ensure your code reads the API key from os.environ['OPENAI_API_KEY'] exactly and that the environment variable is exported correctly.

4

Passing API key directly in the client constructor incorrectly

✓ Fix

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

Broken - triggers the error
python
from langchain_openai import ChatOpenAI
client = ChatOpenAI(model_name="gpt-4o-mini")
response = client.chat(messages=[{"role": "user", "content": "Hello"}])  # Raises AuthenticationError
Fixed - works correctly
python
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
Added setting of OPENAI_API_KEY environment variable with a valid key so ChatOpenAI authenticates successfully.

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.

Python 3.9+ · langchain-openai >=0.1.0 · tested on 0.2.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.