RuntimeError
langchain_langsmith.runtime.RuntimeError
Stack trace
Traceback (most recent call last):
File "app.py", line 10, in <module>
from langchain_langsmith import LangSmithTracer
File "/usr/local/lib/python3.9/site-packages/langchain_langsmith/__init__.py", line 5, in <module>
if os.environ["LANGCHAIN_HANDLER"] != "langsmith":
KeyError: 'LANGCHAIN_HANDLER' Why it happens
LangSmith tracing integration requires the LANGCHAIN_HANDLER environment variable to be set to 'langsmith' to enable tracing. If this environment variable is missing or set incorrectly, the LangSmith tracer cannot initialize and raises a KeyError or RuntimeError.
Detection
Check for the presence of the LANGCHAIN_HANDLER environment variable before initializing LangSmith tracing, or catch KeyError exceptions during tracer setup to detect missing configuration early.
Causes & fixes
LANGCHAIN_HANDLER environment variable is not set in the runtime environment
Set the environment variable LANGCHAIN_HANDLER=langsmith before running your application to enable LangSmith tracing.
LANGCHAIN_HANDLER is set to a value other than 'langsmith', disabling tracing
Ensure LANGCHAIN_HANDLER is exactly set to 'langsmith' to activate LangSmith tracing features.
Application code attempts to access LANGCHAIN_HANDLER without checking if it exists
Add a safe environment variable check with os.environ.get('LANGCHAIN_HANDLER') and handle missing cases gracefully.
Code: broken vs fixed
import os
from langchain_langsmith import LangSmithTracer
# This line triggers KeyError if LANGCHAIN_HANDLER is missing
if os.environ["LANGCHAIN_HANDLER"] != "langsmith":
raise RuntimeError("LangSmith tracing not enabled env var missing")
tracer = LangSmithTracer()
print("Tracing started") import os
from langchain_langsmith import LangSmithTracer
# Use os.environ.get to avoid KeyError and provide clear error message
if os.environ.get("LANGCHAIN_HANDLER") != "langsmith":
raise RuntimeError("LangSmith tracing not enabled: set LANGCHAIN_HANDLER=langsmith")
tracer = LangSmithTracer()
print("Tracing started")
# Note: Set environment variable before running:
# export LANGCHAIN_HANDLER=langsmith Workaround
Wrap the environment variable access in try/except KeyError and fallback to disabling tracing or logging a warning to avoid crashing the app.
Prevention
Always document and enforce setting LANGCHAIN_HANDLER=langsmith in deployment environments and CI/CD pipelines to guarantee LangSmith tracing is enabled without runtime errors.