APIKeyNotFoundError
langchain.exceptions.APIKeyNotFoundError
Stack trace
Traceback (most recent call last):
File "app.py", line 10, in <module>
llm = ChatOpenAI()
File "/usr/local/lib/python3.9/site-packages/langchain/chat_models/openai.py", line 45, in __init__
raise APIKeyNotFoundError("OpenAI API key not found in environment variables.")
langchain.exceptions.APIKeyNotFoundError: OpenAI API key not found in environment variables. Why it happens
LangChain requires API keys to be set as environment variables for authentication with external LLM providers. If these environment variables are missing or incorrectly named, LangChain cannot authenticate and raises APIKeyNotFoundError.
Detection
Check for APIKeyNotFoundError exceptions during initialization of LangChain LLM clients; verify environment variables like OPENAI_API_KEY are set before runtime.
Causes & fixes
The environment variable for the API key (e.g., OPENAI_API_KEY) is not set in the system or container environment.
Set the required API key environment variable in your shell or deployment environment before running the application, e.g., export OPENAI_API_KEY='your_key_here'.
The environment variable is set but with a wrong name or typo (e.g., OPENAI_APIKEY instead of OPENAI_API_KEY).
Correct the environment variable name to exactly match what LangChain expects, such as OPENAI_API_KEY.
The environment variable is set but not accessible to the Python process due to scope or permissions.
Ensure the environment variable is exported in the same shell or environment context where the Python process runs, and that no permission restrictions block access.
Code: broken vs fixed
from langchain_openai import ChatOpenAI
llm = ChatOpenAI() # Raises APIKeyNotFoundError if env var missing
print(llm) import os
from langchain_openai import ChatOpenAI
os.environ["OPENAI_API_KEY"] = "your_api_key_here" # Set your API key here
llm = ChatOpenAI() # Now works without error
print(llm) Workaround
Manually pass the API key as a parameter to the LangChain client constructor if supported, or wrap initialization in try/except to catch APIKeyNotFoundError and prompt for key input.
Prevention
Always configure and verify required API key environment variables in your deployment and development environments before running LangChain code to avoid authentication errors.