LangChain Integration

SDK

Integrate 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

The LangChain integration requires the traccia[langchain] extra, which installs langchain-core as a dependency.

1Install Traccia with LangChain Support

Install Traccia with the LangChain extra:

bash
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:

main.py
python
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:

agent.py
python
from traccia.integrations.langchain import CallbackHandler
# Or use the full name: TracciaCallbackHandler
# Create handler instance (no arguments needed)
traccia_handler = CallbackHandler()

No configuration needed

The callback handler requires no arguments. It automatically uses the global Traccia configuration set by init().

4Use with LangChain Runnables

Pass the handler to any LangChain runnable via the config parameter:

agent.py
python
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
# Pass handler in config
result = 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:

movie_agent.py
python
from traccia import init
from traccia.integrations.langchain import CallbackHandler
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
# Initialize Traccia
init()
# Create handler
traccia_handler = CallbackHandler()
# Define output schema
class MovieRecommendations(BaseModel):
"""Schema for movie recommendations."""
recommendations: list[str] = Field(description="List of movie titles")
# Set up LangChain components
llm = 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 output
chain = prompt | llm.with_structured_output(MovieRecommendations)
# Run with Traccia tracing
result = 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

Spans created by the LangChain callback handler use the same attribute schema as Traccia's direct 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:

agent.py
python
from traccia import init, observe
from traccia.integrations.langchain import CallbackHandler
from langchain_openai import ChatOpenAI
init()
traccia_handler = CallbackHandler()
@observe() # Creates parent span for the entire function
def 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: AgentExecutor and custom agents
  • Tools: Tool invocations within agent runs

Troubleshooting

Issue: ModuleNotFoundError: No module named 'langchain_core'

Solution: Install the LangChain extra:

bash
pip install traccia[langchain]

Issue: No spans appearing for LangChain calls

Solution: Ensure you're passing the callback handler in the config:

python
# ✅ Correct
result = llm.invoke("...", config={"callbacks": [traccia_handler]})
# ❌ Wrong - handler not passed
result = 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.