LangChain Integration
SDKIntegrate Traccia with LangChain to trace your chains, agents, and LLM calls.
Traccia integrates with LangChain via a callback handler that automatically creates spans for LLM calls, chains, and agent executions. The handler captures the same rich metadata as Traccia's direct OpenAI instrumentation—including model, tokens, costs, prompts, and completions.
Optional extra required
traccia[langchain] extra, which installs langchain-core as a dependency.1Install Traccia with LangChain Support
Install Traccia with the LangChain extra:
pip install traccia[langchain]This installs traccia plus langchain-core. If you already have langchain-core installed (e.g., from langchain or langchain-openai), the base pip install traccia may work at runtime, but traccia[langchain] is the officially supported installation method.
2Initialize Traccia
Initialize Traccia at the start of your application:
from traccia import init
# Initialize Traccia (auto-loads from traccia.toml if present)init()
# Or with explicit configuration# init(endpoint="http://localhost:4318/v1/traces")3Create the Callback Handler
Import and instantiate the Traccia callback handler:
from traccia.integrations.langchain import CallbackHandler# Or use the full name: TracciaCallbackHandler
# Create handler instance (no arguments needed)traccia_handler = CallbackHandler()No configuration needed
init().4Use with LangChain Runnables
Pass the handler to any LangChain runnable via the config parameter:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
# Pass handler in configresult = llm.invoke( "Tell me a joke about Python", config={"callbacks": [traccia_handler]})Works with all LangChain runnable methods:
.invoke()
Synchronous single invocation
.stream()
Streaming responses
.batch()
Batch processing
.ainvoke()
Async invocation
Complete Example
Here's a full example with LangChain structured outputs:
from traccia import initfrom traccia.integrations.langchain import CallbackHandlerfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_openai import ChatOpenAIfrom pydantic import BaseModel, Field
# Initialize Tracciainit()
# Create handlertraccia_handler = CallbackHandler()
# Define output schemaclass MovieRecommendations(BaseModel): """Schema for movie recommendations.""" recommendations: list[str] = Field(description="List of movie titles")
# Set up LangChain componentsllm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7)prompt = ChatPromptTemplate.from_messages([ ("system", "You are a movie recommendation expert."), ("user", "Recommend {count} {genre} movies.")])
# Build chain with structured outputchain = prompt | llm.with_structured_output(MovieRecommendations)
# Run with Traccia tracingresult = chain.invoke( {"genre": "sci-fi", "count": 5}, config={"callbacks": [traccia_handler]})
print(result.recommendations)# ['Blade Runner 2049', 'Arrival', 'Interstellar', 'The Matrix', 'Inception']What Gets Traced
Traccia's LangChain callback handler automatically captures:
Model information
Vendor, model name, parameters
Token usage
Prompt, completion, and total tokens
Estimated costs
Calculated from token usage and pricing
Prompts
Input messages and prompts
Completions
LLM responses and outputs
Execution timing
Start time, duration, latency
Same attributes as OpenAI instrumentation
llm.model, llm.usage.prompt_tokens, llm.cost.usd, etc.), ensuring consistency across your traces.Combining with @observe Decorator
You can combine the LangChain callback handler with Traccia's @observe() decorator for complete tracing:
from traccia import init, observefrom traccia.integrations.langchain import CallbackHandlerfrom langchain_openai import ChatOpenAI
init()traccia_handler = CallbackHandler()
@observe() # Creates parent span for the entire functiondef generate_recommendations(genre: str, count: int): """Generate movie recommendations.""" llm = ChatOpenAI(model="gpt-4o-mini") # LLM call creates child span result = llm.invoke( f"Recommend {count} {genre} movies", config={"callbacks": [traccia_handler]} ) return result.content
# Creates trace hierarchy:# - generate_recommendations (from @observe)# └─ llm.langchain.run (from callback handler)recommendations = generate_recommendations("thriller", 5)Supported LangChain Components
The Traccia callback handler works with:
- Chat models:
ChatOpenAI,ChatAnthropic, etc. - LLMs:
OpenAI,Anthropic, etc. - Chains: Any chain built with LCEL (LangChain Expression Language)
- Agents:
AgentExecutorand custom agents - Tools: Tool invocations within agent runs
Troubleshooting
Issue: ModuleNotFoundError: No module named 'langchain_core'
Solution: Install the LangChain extra:
pip install traccia[langchain]Issue: No spans appearing for LangChain calls
Solution: Ensure you're passing the callback handler in the config:
# ✅ Correctresult = llm.invoke("...", config={"callbacks": [traccia_handler]})
# ❌ Wrong - handler not passedresult = llm.invoke("...")Issue: Missing token counts or costs
Solution: Ensure enable_token_counting and enable_costs are enabled in your Traccia configuration (both are enabled by default).
Next Steps
© 2026 Traccia.