> ## Documentation Index
> Fetch the complete documentation index at: https://docs.braintrust.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Pydantic AI

> Trace Pydantic AI agents in Braintrust to debug prompts, evaluate models, and monitor production usage

[Pydantic AI](https://ai.pydantic.dev) is a Python agent framework built on Pydantic. Braintrust traces Pydantic AI agents, including agent runs, the underlying model calls, and tool calls.

**Python**

## Setup

Install the Braintrust SDK and Pydantic AI:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
pip install braintrust pydantic-ai
```

> [!NOTE]
>
> Tracing Pydantic AI 2.0 or later requires the Braintrust Python SDK v0.26.0 or later.

## Auto-instrumentation

To trace Pydantic AI without modifying each agent call, call `init_logger()` and `auto_instrument()` once at startup. `auto_instrument()` patches Pydantic AI's agent and model APIs along with every other supported library.

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import braintrust
from pydantic_ai import Agent

braintrust.init_logger(project="my-pydantic-project")  # Replace with your project name
braintrust.auto_instrument()

# Use agents as normal - they're automatically traced
agent = Agent("openai:gpt-5-mini", system_prompt="You are a helpful assistant.")
result = await agent.run("What is the capital of France?")
```

> [accordion] Instrument only Pydantic AI
>
> To patch Pydantic AI without enabling Braintrust's other integrations, call `setup_pydantic_ai()` instead. It initializes a logger for you when one isn't already active.
>
> ```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
> from braintrust.wrappers.pydantic_ai import setup_pydantic_ai
> from pydantic_ai import Agent
>
> # Initialize Braintrust tracing for Pydantic AI
> setup_pydantic_ai(project_name="my-pydantic-project")
>
> # Use agents as normal - they're automatically traced
> agent = Agent("openai:gpt-5-mini", system_prompt="You are a helpful assistant.")
> result = await agent.run("What is the capital of France?")
> ```

### Tools and streaming

Tools and streaming responses are traced without extra configuration:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import braintrust
from pydantic_ai import Agent, ModelSettings

braintrust.init_logger(project="my-pydantic-project")  # Replace with your project name
braintrust.auto_instrument()

agent = Agent(
    "openai:gpt-5-mini",
    model_settings=ModelSettings(max_tokens=500),
)

@agent.tool_plain
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"22°C and sunny in {city}"

# Streaming is fully traced, including time-to-first-token
async with agent.run_stream("What's the weather in Paris?") as result:
    async for text in result.stream_text(delta=True):
        print(text, end="", flush=True)
```

### Nest under existing spans

If you already have a Braintrust span context (e.g., from `@traced` or `start_span`), Pydantic AI traces nest under it:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import braintrust
from pydantic_ai import Agent

braintrust.init_logger(project="my-pydantic-project")  # Replace with your project name
braintrust.auto_instrument()

agent = Agent("openai:gpt-5-mini")

@braintrust.traced
async def my_workflow(question: str):
    # Agent traces appear as children of this span
    result = await agent.run(question)
    return result.output
```

## OpenTelemetry

To trace Pydantic AI through an existing OpenTelemetry pipeline, attach a `BraintrustSpanProcessor` and enable Pydantic AI's built-in instrumentation.

**1. Install packages**

Install the Braintrust SDK with the OpenTelemetry extra, alongside Pydantic AI:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
pip install "braintrust[otel]" pydantic-ai
```

**2. Configure tracing**

Register the `BraintrustSpanProcessor` with your tracer provider, then call `Agent.instrument_all()` to emit Pydantic AI's instrumentation to Braintrust:

```python Python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
from braintrust.otel import BraintrustSpanProcessor
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from pydantic_ai import Agent

provider = TracerProvider()
trace.set_tracer_provider(provider)
provider.add_span_processor(BraintrustSpanProcessor())

Agent.instrument_all()
```

## What Braintrust traces

Braintrust captures:

* **Agent run spans** (`agent_run`, `agent_run_sync`, `agent_run_stream`, `agent_run_stream_sync`, `agent_to_cli_sync`), with the run input (including `system_prompt`, `instructions`, and `message_history` when present), agent metadata, output, and timing. When you pass a `conversation`, the input records its `conversation_id` and its messages as `message_history`.
* **Direct model-request spans** (`model_request`, `model_request_sync`), for `pydantic_ai.direct` API calls.
* **Model call spans** (`chat <model>`), for the underlying LLM calls made during a run, with invocation parameters (`temperature`, `max_tokens`, and similar model settings when provided) and tools in metadata. `completion_reasoning_tokens` is captured when the model produces reasoning tokens (Anthropic extended thinking, Google thinking). Audio duration is recorded in `metadata.pydantic_ai_usage.audio_seconds` and native web search request counts in `metadata.pydantic_ai_usage.web_search_requests` when the model reports them.
* **Tool call spans**, for tools invoked during an agent run. When a tool defers its call by raising `CallDeferred` or `ApprovalRequired`, the span records the deferral as `deferred` metadata (`external` or `unapproved`), plus any metadata passed to the exception as `deferred_metadata`, rather than as an error.

## Resources

* [Pydantic AI documentation](https://ai.pydantic.dev)
* [OpenTelemetry integration](https://docs.braintrust.dev/integrations/sdk-integrations/opentelemetry/send-traces-and-logs.md)
* [Trace LLM calls](https://docs.braintrust.dev/instrument/trace-llm-calls.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.