Trace PydanticAI applications ↗
noOriginal Documentation
Documentation Index#
Fetch the complete documentation index at: https://docs.langchain.com/llms.txt Use this file to discover all available pages before exploring further.
LangSmith can capture traces generated by PydanticAI using its built-in OpenTelemetry instrumentation. This guide shows you how to automatically capture traces from your PydanticAI agents and send them to LangSmith for monitoring and analysis.
Installation#
Install the required packages:
pip install langsmith pydantic-ai opentelemetry-exporter-otlpuv add langsmith pydantic-ai opentelemetry-exporter-otlp
Requires LangSmith Python SDK version langsmith>=0.4.26 for optimal OpenTelemetry support.
Setup#
1. Configure environment variables#
Set your API keys and project name:
export LANGSMITH_API_KEY=<your_langsmith_api_key>
export LANGSMITH_PROJECT=<your_project_name>
export OPENAI_API_KEY=<your_openai_api_key>2. Configure OpenTelemetry integration#
In your PydanticAI application, configure the LangSmith OpenTelemetry integration:
from langsmith.integrations.otel import configure
from pydantic_ai import Agent
# Configure LangSmith tracing
configure(project_name="pydantic-ai-demo")
# Instrument all PydanticAI agents
Agent.instrument_all()
You do not need to set any OpenTelemetry environment variables or configure exporters manually—configure() handles everything automatically.
3. Create and run your PydanticAI agent#
Once configured, your PydanticAI agents will automatically send traces to LangSmith:
from langsmith.integrations.otel import configure
from pydantic_ai import Agent
# Configure LangSmith tracing
configure(project_name="pydantic-ai-demo")
# Instrument all PydanticAI agents
Agent.instrument_all()
# Create and run an agent
agent = Agent('openai:gpt-4.1')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> ParisAdvanced usage#
Custom metadata and tags#
You can add custom metadata to your traces using OpenTelemetry span attributes:
from opentelemetry import trace
from pydantic_ai import Agent
from langsmith.integrations.otel import configure
configure(project_name="pydantic-ai-metadata")
Agent.instrument_all()
tracer = trace.get_tracer(__name__)
agent = Agent('openai:gpt-4.1')
with tracer.start_as_current_span("pydantic_ai_workflow") as span:
span.set_attribute("langsmith.metadata.user_id", "user_123")
span.set_attribute("langsmith.metadata.workflow_type", "question_answering")
span.set_attribute("langsmith.span.tags", "pydantic-ai,production")
result = agent.run_sync('Explain quantum computing in simple terms')
print(result.output)Edit this page on GitHub or file an issue.
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.