ValueError
langchain.langsmith.client.ValueError
Stack trace
Traceback (most recent call last):
File "app.py", line 10, in <module>
client = LangSmithClient()
File "langchain/langsmith/client.py", line 45, in __init__
raise ValueError("LANGCHAIN_API_KEY environment variable not set")
ValueError: LANGCHAIN_API_KEY environment variable not set Why it happens
The LangSmith client requires the LANGCHAIN_API_KEY environment variable to authenticate API requests. If this environment variable is missing or not loaded into the runtime environment, the client raises a ValueError to prevent unauthorized calls.
Detection
Check for the presence of LANGCHAIN_API_KEY in your environment variables before initializing LangSmithClient, or catch ValueError exceptions during client creation and log the missing key error.
Causes & fixes
LANGCHAIN_API_KEY environment variable is not set in the OS environment
Set the LANGCHAIN_API_KEY environment variable in your shell or deployment environment before running the application.
Environment variable is set but not loaded into the Python process environment
Ensure your runtime loads environment variables correctly, for example by using python-dotenv or exporting variables in the same shell session.
Code attempts to instantiate LangSmithClient before environment variables are loaded
Load environment variables at the very start of your script or application entry point before creating the LangSmithClient instance.
Code: broken vs fixed
from langchain.langsmith import LangSmithClient
client = LangSmithClient() # Raises ValueError: LANGCHAIN_API_KEY environment variable not set import os
from langchain.langsmith import LangSmithClient
os.environ["LANGCHAIN_API_KEY"] = os.environ.get("LANGCHAIN_API_KEY", "your_api_key_here") # Set your API key securely
client = LangSmithClient() # Now works without error
print("LangSmith client initialized successfully") Workaround
Wrap LangSmithClient initialization in try/except ValueError, and prompt the user or log a clear message to set LANGCHAIN_API_KEY before retrying.
Prevention
Use environment management tools like dotenv or container environment variables to ensure LANGCHAIN_API_KEY is always set before app startup, avoiding runtime authentication errors.