[ Skip to content ](https://ai.pydantic.dev/logfire/#pydantic-logfire-debugging-and-monitoring)
**Join us at the inaugural PyAI Conf in San Francisco on March 10th![Learn More](https://pyai.events/?utm_source=pydantic-ai) **
[ ![logo](https://ai.pydantic.dev/img/logo-white.svg) ](https://ai.pydantic.dev/ "Pydantic AI")
Pydantic AI
Debugging & Monitoring with Pydantic Logfire
Type to start searching
[ pydantic/pydantic-ai
  * v1.63.0
  * 15.1k
  * 1.7k

](https://github.com/pydantic/pydantic-ai "Go to repository")
[ ![logo](https://ai.pydantic.dev/img/logo-white.svg) ](https://ai.pydantic.dev/ "Pydantic AI") Pydantic AI
[ pydantic/pydantic-ai
  * v1.63.0
  * 15.1k
  * 1.7k

](https://github.com/pydantic/pydantic-ai "Go to repository")
  * [ Pydantic AI  ](https://ai.pydantic.dev/)
  * [ Installation  ](https://ai.pydantic.dev/install/)
  * [ Getting Help  ](https://ai.pydantic.dev/help/)
  * [ Troubleshooting  ](https://ai.pydantic.dev/troubleshooting/)
  * [ Pydantic AI Gateway  ](https://ai.pydantic.dev/gateway/)
  * Documentation
    * Core Concepts
      * [ Agents  ](https://ai.pydantic.dev/agent/)
      * [ Dependencies  ](https://ai.pydantic.dev/dependencies/)
      * [ Function Tools  ](https://ai.pydantic.dev/tools/)
      * [ Output  ](https://ai.pydantic.dev/output/)
      * [ Messages and chat history  ](https://ai.pydantic.dev/message-history/)
      * [ Direct Model Requests  ](https://ai.pydantic.dev/direct/)
    * Models & Providers
      * [ Overview  ](https://ai.pydantic.dev/models/overview/)
      * [ OpenAI  ](https://ai.pydantic.dev/models/openai/)
      * [ Anthropic  ](https://ai.pydantic.dev/models/anthropic/)
      * [ Google  ](https://ai.pydantic.dev/models/google/)
      * [ xAI  ](https://ai.pydantic.dev/models/xai/)
      * [ Bedrock  ](https://ai.pydantic.dev/models/bedrock/)
      * [ Cerebras  ](https://ai.pydantic.dev/models/cerebras/)
      * [ Cohere  ](https://ai.pydantic.dev/models/cohere/)
      * [ Groq  ](https://ai.pydantic.dev/models/groq/)
      * [ Hugging Face  ](https://ai.pydantic.dev/models/huggingface/)
      * [ Mistral  ](https://ai.pydantic.dev/models/mistral/)
      * [ OpenRouter  ](https://ai.pydantic.dev/models/openrouter/)
      * [ Outlines  ](https://ai.pydantic.dev/models/outlines/)
    * Tools & Toolsets
      * [ Function Tools  ](https://ai.pydantic.dev/tools/)
      * [ Advanced Tool Features  ](https://ai.pydantic.dev/tools-advanced/)
      * [ Toolsets  ](https://ai.pydantic.dev/toolsets/)
      * [ Deferred Tools  ](https://ai.pydantic.dev/deferred-tools/)
      * [ Built-in Tools  ](https://ai.pydantic.dev/builtin-tools/)
      * [ Common Tools  ](https://ai.pydantic.dev/common-tools/)
      * [ Third-Party Tools  ](https://ai.pydantic.dev/third-party-tools/)
    * Advanced Features
      * [ Image, Audio, Video & Document Input  ](https://ai.pydantic.dev/input/)
      * [ Thinking  ](https://ai.pydantic.dev/thinking/)
      * [ HTTP Request Retries  ](https://ai.pydantic.dev/retries/)
    * MCP
      * [ Overview  ](https://ai.pydantic.dev/mcp/overview/)
      * [ Client  ](https://ai.pydantic.dev/mcp/client/)
      * [ FastMCP Client  ](https://ai.pydantic.dev/mcp/fastmcp-client/)
      * [ Server  ](https://ai.pydantic.dev/mcp/server/)
    * [ Multi-Agent Patterns  ](https://ai.pydantic.dev/multi-agent-applications/)
    * [ Web Chat UI  ](https://ai.pydantic.dev/web/)
    * [ Embeddings  ](https://ai.pydantic.dev/embeddings/)
    * [ Testing  ](https://ai.pydantic.dev/testing/)
  * Pydantic Evals
    * [ Overview  ](https://ai.pydantic.dev/evals/)
    * Getting Started
      * [ Quick Start  ](https://ai.pydantic.dev/evals/quick-start/)
      * [ Core Concepts  ](https://ai.pydantic.dev/evals/core-concepts/)
    * Evaluators
      * [ Overview  ](https://ai.pydantic.dev/evals/evaluators/overview/)
      * [ Built-in Evaluators  ](https://ai.pydantic.dev/evals/evaluators/built-in/)
      * [ LLM Judge  ](https://ai.pydantic.dev/evals/evaluators/llm-judge/)
      * [ Custom Evaluators  ](https://ai.pydantic.dev/evals/evaluators/custom/)
      * [ Report Evaluators  ](https://ai.pydantic.dev/evals/evaluators/report-evaluators/)
      * [ Span-Based  ](https://ai.pydantic.dev/evals/evaluators/span-based/)
    * How-To Guides
      * [ Logfire Integration  ](https://ai.pydantic.dev/evals/how-to/logfire-integration/)
      * [ Dataset Management  ](https://ai.pydantic.dev/evals/how-to/dataset-management/)
      * [ Dataset Serialization  ](https://ai.pydantic.dev/evals/how-to/dataset-serialization/)
      * [ Concurrency & Performance  ](https://ai.pydantic.dev/evals/how-to/concurrency/)
      * [ Multi-Run Evaluation  ](https://ai.pydantic.dev/evals/how-to/multi-run/)
      * [ Retry Strategies  ](https://ai.pydantic.dev/evals/how-to/retry-strategies/)
      * [ Metrics & Attributes  ](https://ai.pydantic.dev/evals/how-to/metrics-attributes/)
    * Examples
      * [ Simple Validation  ](https://ai.pydantic.dev/evals/examples/simple-validation/)
  * Pydantic Graph
    * [ Overview  ](https://ai.pydantic.dev/graph/)
    * [ Beta API  ](https://ai.pydantic.dev/graph/beta/)
      * [ Steps  ](https://ai.pydantic.dev/graph/beta/steps/)
      * [ Joins & Reducers  ](https://ai.pydantic.dev/graph/beta/joins/)
      * [ Decisions  ](https://ai.pydantic.dev/graph/beta/decisions/)
      * [ Parallel Execution  ](https://ai.pydantic.dev/graph/beta/parallel/)
  * Integrations
    * Debugging & Monitoring with Pydantic Logfire  [ Debugging & Monitoring with Pydantic Logfire  ](https://ai.pydantic.dev/logfire/)
      * [ Pydantic Logfire  ](https://ai.pydantic.dev/logfire/#pydantic-logfire)
      * [ Using Logfire  ](https://ai.pydantic.dev/logfire/#using-logfire)
        * [ Debugging  ](https://ai.pydantic.dev/logfire/#debugging)
        * [ Monitoring Performance  ](https://ai.pydantic.dev/logfire/#monitoring-performance)
        * [ Monitoring HTTP Requests  ](https://ai.pydantic.dev/logfire/#monitoring-http-requests)
      * [ Using OpenTelemetry  ](https://ai.pydantic.dev/logfire/#using-opentelemetry)
        * [ Logfire with an alternative OTel backend  ](https://ai.pydantic.dev/logfire/#logfire-with-an-alternative-otel-backend)
        * [ OTel without Logfire  ](https://ai.pydantic.dev/logfire/#otel-without-logfire)
        * [ Alternative Observability backends  ](https://ai.pydantic.dev/logfire/#alternative-observability-backends)
      * [ Advanced usage  ](https://ai.pydantic.dev/logfire/#advanced-usage)
        * [ Aggregated usage attribute names  ](https://ai.pydantic.dev/logfire/#aggregated-usage-attribute-names)
        * [ Configuring data format  ](https://ai.pydantic.dev/logfire/#configuring-data-format)
          * [ Version 1 (Legacy, deprecated)  ](https://ai.pydantic.dev/logfire/#version-1-legacy-deprecated)
          * [ Version 2 (Default)  ](https://ai.pydantic.dev/logfire/#version-2-default)
          * [ Version 3  ](https://ai.pydantic.dev/logfire/#version-3)
          * [ Version 4  ](https://ai.pydantic.dev/logfire/#version-4)
        * [ Setting OpenTelemetry SDK providers  ](https://ai.pydantic.dev/logfire/#setting-opentelemetry-sdk-providers)
        * [ Instrumenting a specific Model  ](https://ai.pydantic.dev/logfire/#instrumenting-a-specific-model)
        * [ Excluding binary content  ](https://ai.pydantic.dev/logfire/#excluding-binary-content)
        * [ Excluding prompts and completions  ](https://ai.pydantic.dev/logfire/#excluding-prompts-and-completions)
        * [ Adding Custom Metadata  ](https://ai.pydantic.dev/logfire/#adding-custom-metadata)
    * Durable Execution
      * [ Overview  ](https://ai.pydantic.dev/durable_execution/overview/)
      * [ Temporal  ](https://ai.pydantic.dev/durable_execution/temporal/)
      * [ DBOS  ](https://ai.pydantic.dev/durable_execution/dbos/)
      * [ Prefect  ](https://ai.pydantic.dev/durable_execution/prefect/)
    * UI Event Streams
      * [ Overview  ](https://ai.pydantic.dev/ui/overview/)
      * [ AG-UI  ](https://ai.pydantic.dev/ui/ag-ui/)
      * [ Vercel AI  ](https://ai.pydantic.dev/ui/vercel-ai/)
    * [ Agent2Agent (A2A)  ](https://ai.pydantic.dev/a2a/)
  * Related Packages
    * [ clai  ](https://ai.pydantic.dev/cli/)
  * Examples
    * [ Setup  ](https://ai.pydantic.dev/examples/setup/)
    * Getting Started
      * [ Pydantic Model  ](https://ai.pydantic.dev/examples/pydantic-model/)
      * [ Weather agent  ](https://ai.pydantic.dev/examples/weather-agent/)
    * Conversational Agents
      * [ Chat App with FastAPI  ](https://ai.pydantic.dev/examples/chat-app/)
      * [ Bank support  ](https://ai.pydantic.dev/examples/bank-support/)
    * Data & Analytics
      * [ SQL Generation  ](https://ai.pydantic.dev/examples/sql-gen/)
      * [ Data Analyst  ](https://ai.pydantic.dev/examples/data-analyst/)
      * [ RAG  ](https://ai.pydantic.dev/examples/rag/)
    * Streaming
      * [ Stream markdown  ](https://ai.pydantic.dev/examples/stream-markdown/)
      * [ Stream whales  ](https://ai.pydantic.dev/examples/stream-whales/)
    * Complex Workflows
      * [ Flight booking  ](https://ai.pydantic.dev/examples/flight-booking/)
      * [ Question Graph  ](https://ai.pydantic.dev/examples/question-graph/)
    * Business Applications
      * [ Slack Lead Qualifier with Modal  ](https://ai.pydantic.dev/examples/slack-lead-qualifier/)
    * UI Examples
      * [ Agent User Interaction (AG-UI)  ](https://ai.pydantic.dev/examples/ag-ui/)
  * API Reference
    * pydantic_ai
      * [ pydantic_ai.ag_ui  ](https://ai.pydantic.dev/api/ag_ui/)
      * [ pydantic_ai.agent  ](https://ai.pydantic.dev/api/agent/)
      * [ pydantic_ai.builtin_tools  ](https://ai.pydantic.dev/api/builtin_tools/)
      * [ pydantic_ai.common_tools  ](https://ai.pydantic.dev/api/common_tools/)
      * [ pydantic_ai — Concurrency  ](https://ai.pydantic.dev/api/concurrency/)
      * [ pydantic_ai.direct  ](https://ai.pydantic.dev/api/direct/)
      * [ pydantic_ai.durable_exec  ](https://ai.pydantic.dev/api/durable_exec/)
      * [ pydantic_ai.embeddings  ](https://ai.pydantic.dev/api/embeddings/)
      * [ pydantic_ai.exceptions  ](https://ai.pydantic.dev/api/exceptions/)
      * [ pydantic_ai.ext  ](https://ai.pydantic.dev/api/ext/)
      * [ pydantic_ai.format_prompt  ](https://ai.pydantic.dev/api/format_prompt/)
      * [ pydantic_ai.mcp  ](https://ai.pydantic.dev/api/mcp/)
      * [ pydantic_ai.messages  ](https://ai.pydantic.dev/api/messages/)
      * [ pydantic_ai.models.anthropic  ](https://ai.pydantic.dev/api/models/anthropic/)
      * [ pydantic_ai.models  ](https://ai.pydantic.dev/api/models/base/)
      * [ pydantic_ai.models.bedrock  ](https://ai.pydantic.dev/api/models/bedrock/)
      * [ pydantic_ai.models.cerebras  ](https://ai.pydantic.dev/api/models/cerebras/)
      * [ pydantic_ai.models.cohere  ](https://ai.pydantic.dev/api/models/cohere/)
      * [ pydantic_ai.models.fallback  ](https://ai.pydantic.dev/api/models/fallback/)
      * [ pydantic_ai.models.function  ](https://ai.pydantic.dev/api/models/function/)
      * [ pydantic_ai.models.google  ](https://ai.pydantic.dev/api/models/google/)
      * [ pydantic_ai.models.xai  ](https://ai.pydantic.dev/api/models/xai/)
      * [ pydantic_ai.models.groq  ](https://ai.pydantic.dev/api/models/groq/)
      * [ pydantic_ai.models.huggingface  ](https://ai.pydantic.dev/api/models/huggingface/)
      * [ pydantic_ai.models.instrumented  ](https://ai.pydantic.dev/api/models/instrumented/)
      * [ pydantic_ai.models.mcp_sampling  ](https://ai.pydantic.dev/api/models/mcp-sampling/)
      * [ pydantic_ai.models.mistral  ](https://ai.pydantic.dev/api/models/mistral/)
      * [ pydantic_ai.models.openai  ](https://ai.pydantic.dev/api/models/openai/)
      * [ pydantic_ai.models.openrouter  ](https://ai.pydantic.dev/api/models/openrouter/)
      * [ pydantic_ai.models.outlines  ](https://ai.pydantic.dev/api/models/outlines/)
      * [ pydantic_ai.models.test  ](https://ai.pydantic.dev/api/models/test/)
      * [ pydantic_ai.models.wrapper  ](https://ai.pydantic.dev/api/models/wrapper/)
      * [ pydantic_ai.output  ](https://ai.pydantic.dev/api/output/)
      * [ pydantic_ai.profiles  ](https://ai.pydantic.dev/api/profiles/)
      * [ pydantic_ai.providers  ](https://ai.pydantic.dev/api/providers/)
      * [ pydantic_ai.result  ](https://ai.pydantic.dev/api/result/)
      * [ pydantic_ai.retries  ](https://ai.pydantic.dev/api/retries/)
      * [ pydantic_ai.run  ](https://ai.pydantic.dev/api/run/)
      * [ pydantic_ai.settings  ](https://ai.pydantic.dev/api/settings/)
      * [ pydantic_ai.tools  ](https://ai.pydantic.dev/api/tools/)
      * [ pydantic_ai.toolsets  ](https://ai.pydantic.dev/api/toolsets/)
      * [ pydantic_ai.ui.ag_ui  ](https://ai.pydantic.dev/api/ui/ag_ui/)
      * [ pydantic_ai.ui  ](https://ai.pydantic.dev/api/ui/base/)
      * [ pydantic_ai.ui.vercel_ai  ](https://ai.pydantic.dev/api/ui/vercel_ai/)
      * [ pydantic_ai.usage  ](https://ai.pydantic.dev/api/usage/)
    * pydantic_evals
      * [ pydantic_evals.dataset  ](https://ai.pydantic.dev/api/pydantic_evals/dataset/)
      * [ pydantic_evals.evaluators  ](https://ai.pydantic.dev/api/pydantic_evals/evaluators/)
      * [ pydantic_evals.reporting  ](https://ai.pydantic.dev/api/pydantic_evals/reporting/)
      * [ pydantic_evals.otel  ](https://ai.pydantic.dev/api/pydantic_evals/otel/)
      * [ pydantic_evals.generation  ](https://ai.pydantic.dev/api/pydantic_evals/generation/)
    * pydantic_graph
      * [ pydantic_graph  ](https://ai.pydantic.dev/api/pydantic_graph/graph/)
      * [ pydantic_graph.nodes  ](https://ai.pydantic.dev/api/pydantic_graph/nodes/)
      * [ pydantic_graph.persistence  ](https://ai.pydantic.dev/api/pydantic_graph/persistence/)
      * [ pydantic_graph.mermaid  ](https://ai.pydantic.dev/api/pydantic_graph/mermaid/)
      * [ pydantic_graph.exceptions  ](https://ai.pydantic.dev/api/pydantic_graph/exceptions/)
      * Beta API
        * [ pydantic_graph.beta  ](https://ai.pydantic.dev/api/pydantic_graph/beta/)
        * [ pydantic_graph.beta.graph  ](https://ai.pydantic.dev/api/pydantic_graph/beta_graph/)
        * [ pydantic_graph.beta.graph_builder  ](https://ai.pydantic.dev/api/pydantic_graph/beta_graph_builder/)
        * [ pydantic_graph.beta.step  ](https://ai.pydantic.dev/api/pydantic_graph/beta_step/)
        * [ pydantic_graph.beta.join  ](https://ai.pydantic.dev/api/pydantic_graph/beta_join/)
        * [ pydantic_graph.beta.decision  ](https://ai.pydantic.dev/api/pydantic_graph/beta_decision/)
        * [ pydantic_graph.beta.node  ](https://ai.pydantic.dev/api/pydantic_graph/beta_node/)
    * fasta2a
      * [ fasta2a  ](https://ai.pydantic.dev/api/fasta2a/)
  * Project
    * [ Contributing  ](https://ai.pydantic.dev/contributing/)
    * [ Upgrade Guide  ](https://ai.pydantic.dev/changelog/)
    * [ Version policy  ](https://ai.pydantic.dev/version-policy/)


  * [ Pydantic Logfire  ](https://ai.pydantic.dev/logfire/#pydantic-logfire)
  * [ Using Logfire  ](https://ai.pydantic.dev/logfire/#using-logfire)
    * [ Debugging  ](https://ai.pydantic.dev/logfire/#debugging)
    * [ Monitoring Performance  ](https://ai.pydantic.dev/logfire/#monitoring-performance)
    * [ Monitoring HTTP Requests  ](https://ai.pydantic.dev/logfire/#monitoring-http-requests)
  * [ Using OpenTelemetry  ](https://ai.pydantic.dev/logfire/#using-opentelemetry)
    * [ Logfire with an alternative OTel backend  ](https://ai.pydantic.dev/logfire/#logfire-with-an-alternative-otel-backend)
    * [ OTel without Logfire  ](https://ai.pydantic.dev/logfire/#otel-without-logfire)
    * [ Alternative Observability backends  ](https://ai.pydantic.dev/logfire/#alternative-observability-backends)
  * [ Advanced usage  ](https://ai.pydantic.dev/logfire/#advanced-usage)
    * [ Aggregated usage attribute names  ](https://ai.pydantic.dev/logfire/#aggregated-usage-attribute-names)
    * [ Configuring data format  ](https://ai.pydantic.dev/logfire/#configuring-data-format)
      * [ Version 1 (Legacy, deprecated)  ](https://ai.pydantic.dev/logfire/#version-1-legacy-deprecated)
      * [ Version 2 (Default)  ](https://ai.pydantic.dev/logfire/#version-2-default)
      * [ Version 3  ](https://ai.pydantic.dev/logfire/#version-3)
      * [ Version 4  ](https://ai.pydantic.dev/logfire/#version-4)
    * [ Setting OpenTelemetry SDK providers  ](https://ai.pydantic.dev/logfire/#setting-opentelemetry-sdk-providers)
    * [ Instrumenting a specific Model  ](https://ai.pydantic.dev/logfire/#instrumenting-a-specific-model)
    * [ Excluding binary content  ](https://ai.pydantic.dev/logfire/#excluding-binary-content)
    * [ Excluding prompts and completions  ](https://ai.pydantic.dev/logfire/#excluding-prompts-and-completions)
    * [ Adding Custom Metadata  ](https://ai.pydantic.dev/logfire/#adding-custom-metadata)


  1. [ Pydantic AI  ](https://ai.pydantic.dev/)
  2. [ Integrations  ](https://ai.pydantic.dev/logfire/)


# Pydantic Logfire Debugging and Monitoring
Applications that use LLMs have some challenges that are well known and understood: LLMs are **slow** , **unreliable** and **expensive**.
These applications also have some challenges that most developers have encountered much less often: LLMs are **fickle** and **non-deterministic**. Subtle changes in a prompt can completely change a model's performance, and there's no `EXPLAIN` query you can run to understand why.
Warning
From a software engineers point of view, you can think of LLMs as the worst database you've ever heard of, but worse.
If LLMs weren't so bloody useful, we'd never touch them.
To build successful applications with LLMs, we need new tools to understand both model performance, and the behavior of applications that rely on them.
LLM Observability tools that just let you understand how your model is performing are useless: making API calls to an LLM is easy, it's building that into an application that's hard.
## Pydantic Logfire
[Pydantic Logfire](https://pydantic.dev/logfire) is an observability platform developed by the team who created and maintain Pydantic Validation and Pydantic AI. Logfire aims to let you understand your entire application: Gen AI, classic predictive AI, HTTP traffic, database queries and everything else a modern application needs, all using OpenTelemetry.
Pydantic Logfire is a commercial product
Logfire is a commercially supported, hosted platform with an extremely generous and perpetual [free tier](https://pydantic.dev/pricing/). You can sign up and start using Logfire in a couple of minutes. Logfire can also be self-hosted on the enterprise tier.
Pydantic AI has built-in (but optional) support for Logfire. That means if the `logfire` package is installed and configured and agent instrumentation is enabled then detailed information about agent runs is sent to Logfire. Otherwise there's virtually no overhead and nothing is sent.
Here's an example showing details of running the [Weather Agent](https://ai.pydantic.dev/examples/weather-agent/) in Logfire:
[![Weather Agent Logfire](https://ai.pydantic.dev/img/logfire-weather-agent.png)](https://ai.pydantic.dev/img/logfire-weather-agent.png)
A trace is generated for the agent run, and spans are emitted for each model request and tool call.
## Using Logfire
To use Logfire, you'll need a Logfire [account](https://logfire.pydantic.dev). The Logfire Python SDK is included with `pydantic-ai`:
[pip](https://ai.pydantic.dev/logfire/#__tabbed_1_1)[uv](https://ai.pydantic.dev/logfire/#__tabbed_1_2)
```
pip install pydantic-ai

```

```
uv add pydantic-ai

```

Or if you're using the slim package, you can install it with the `logfire` optional group:
[pip](https://ai.pydantic.dev/logfire/#__tabbed_2_1)[uv](https://ai.pydantic.dev/logfire/#__tabbed_2_2)
```
pip install "pydantic-ai-slim[logfire]"

```

```
uv add "pydantic-ai-slim[logfire]"

```

Then authenticate your local environment with Logfire:
[pip](https://ai.pydantic.dev/logfire/#__tabbed_3_1)[uv](https://ai.pydantic.dev/logfire/#__tabbed_3_2)
```
 logfire auth

```

```
uv run logfire auth

```

And configure a project to send data to:
[pip](https://ai.pydantic.dev/logfire/#__tabbed_4_1)[uv](https://ai.pydantic.dev/logfire/#__tabbed_4_2)
```
 logfire projects new

```

```
uv run logfire projects new

```

(Or use an existing project with `logfire projects use`)
This will write to a `.logfire` directory in the current working directory, which the Logfire SDK will use for configuration at run time.
With that, you can start using Logfire to instrument Pydantic AI code:
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_5_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_5_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) instrument_pydantic_ai.py```
import logfire

from pydantic_ai import Agent

logfire.configure()  [](https://ai.pydantic.dev/logfire/#__code_8_annotation_1)
logfire.instrument_pydantic_ai()  [](https://ai.pydantic.dev/logfire/#__code_8_annotation_2)

agent = Agent('gateway/openai:gpt-5.2', instructions='Be concise, reply with one sentence.')
result = agent.run_sync('Where does "hello world" come from?')  [](https://ai.pydantic.dev/logfire/#__code_8_annotation_3)
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""

```

instrument_pydantic_ai.py```
import logfire

from pydantic_ai import Agent

logfire.configure()

[](https://ai.pydantic.dev/logfire/#__code_9_annotation_1)
logfire.instrument_pydantic_ai()

[](https://ai.pydantic.dev/logfire/#__code_9_annotation_2)

agent = Agent('openai:gpt-5.2', instructions='Be concise, reply with one sentence.')
result = agent.run_sync('Where does "hello world" come from?')

[](https://ai.pydantic.dev/logfire/#__code_9_annotation_3)
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""

```

  1. [`logfire.configure()`](https://logfire.pydantic.dev/docs/reference/api/logfire/#logfire.configure) configures the SDK, by default it will find the write token from the `.logfire` directory, but you can also pass a token directly.
  2. [`logfire.instrument_pydantic_ai()`](https://logfire.pydantic.dev/docs/reference/api/logfire/#logfire.Logfire.instrument_pydantic_ai) enables instrumentation of Pydantic AI.
  3. Since we've enabled instrumentation, a trace will be generated for each run, with spans emitted for models calls and tool function execution


_(This example is complete, it can be run "as is")_
Which will display in Logfire thus:
[![Logfire Simple Agent Run](https://ai.pydantic.dev/img/logfire-simple-agent.png)](https://ai.pydantic.dev/img/logfire-simple-agent.png)
The [Logfire documentation](https://logfire.pydantic.dev/docs/) has more details on how to use Logfire, including how to instrument other libraries like [HTTPX](https://logfire.pydantic.dev/docs/integrations/http-clients/httpx/) and [FastAPI](https://logfire.pydantic.dev/docs/integrations/web-frameworks/fastapi/).
Since Logfire is built on [OpenTelemetry](https://opentelemetry.io/), you can use the Logfire Python SDK to send data to any OpenTelemetry collector, see [below](https://ai.pydantic.dev/logfire/#using-opentelemetry).
### Debugging
To demonstrate how Logfire can let you visualise the flow of a Pydantic AI run, here's the view you get from Logfire while running the [chat app examples](https://ai.pydantic.dev/examples/chat-app/):
### Monitoring Performance
We can also query data with SQL in Logfire to monitor the performance of an application. Here's a real world example of using Logfire to monitor Pydantic AI runs inside Logfire itself:
[![Logfire monitoring Pydantic AI](https://ai.pydantic.dev/img/logfire-monitoring-pydanticai.png)](https://ai.pydantic.dev/img/logfire-monitoring-pydanticai.png)
### Monitoring HTTP Requests
As per Hamel Husain's influential 2024 blog post ["Fuck You, Show Me The Prompt."](https://hamel.dev/blog/posts/prompt/) (bear with the capitalization, the point is valid), it's often useful to be able to view the raw HTTP requests and responses made to model providers.
To observe raw HTTP requests made to model providers, you can use Logfire's [HTTPX instrumentation](https://logfire.pydantic.dev/docs/integrations/http-clients/httpx/) since all provider SDKs (except for [Bedrock](https://ai.pydantic.dev/models/bedrock/)) use the [HTTPX](https://www.python-httpx.org/) library internally:
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_6_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_6_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) with_logfire_instrument_httpx.py```
import logfire

from pydantic_ai import Agent

logfire.configure()
logfire.instrument_pydantic_ai()
logfire.instrument_httpx(capture_all=True)  [](https://ai.pydantic.dev/logfire/#__code_10_annotation_1)

agent = Agent('gateway/openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> The capital of France is Paris.

```

with_logfire_instrument_httpx.py```
import logfire

from pydantic_ai import Agent

logfire.configure()
logfire.instrument_pydantic_ai()
logfire.instrument_httpx(capture_all=True)

[](https://ai.pydantic.dev/logfire/#__code_11_annotation_1)

agent = Agent('openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> The capital of France is Paris.

```

  1. See the [`logfire.instrument_httpx` docs](https://logfire.pydantic.dev/docs/reference/api/logfire/#logfire.Logfire.instrument_httpx) more details, `capture_all=True` means both headers and body are captured for both the request and response.


[![Logfire with HTTPX instrumentation](https://ai.pydantic.dev/img/logfire-with-httpx.png)](https://ai.pydantic.dev/img/logfire-with-httpx.png)
## Using OpenTelemetry
Pydantic AI's instrumentation uses [OpenTelemetry](https://opentelemetry.io/) (OTel), which Logfire is based on.
This means you can debug and monitor Pydantic AI with any OpenTelemetry backend.
Pydantic AI follows the [OpenTelemetry Semantic Conventions for Generative AI systems](https://opentelemetry.io/docs/specs/semconv/gen-ai/), so while we think you'll have the best experience using the Logfire platform ![😉](https://cdn.jsdelivr.net/gh/jdecked/twemoji@16.0.1/assets/svg/1f609.svg), you should be able to use any OTel service with GenAI support.
### Logfire with an alternative OTel backend
You can use the Logfire SDK completely freely and send the data to any OpenTelemetry backend.
Here's an example of configuring the Logfire library to send data to the excellent [otel-tui](https://github.com/ymtdzzz/otel-tui) — an open source terminal based OTel backend and viewer (no association with Pydantic Validation).
Run `otel-tui` with docker (see [the otel-tui readme](https://github.com/ymtdzzz/otel-tui) for more instructions):
Terminal```
docker run --rm -it -p 4318:4318 --name otel-tui ymtdzzz/otel-tui:latest

```

then run,
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_7_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_7_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) otel_tui.py```
import os

import logfire

from pydantic_ai import Agent

os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://localhost:4318'  [](https://ai.pydantic.dev/logfire/#__code_13_annotation_1)
logfire.configure(send_to_logfire=False)  [](https://ai.pydantic.dev/logfire/#__code_13_annotation_2)
logfire.instrument_pydantic_ai()
logfire.instrument_httpx(capture_all=True)

agent = Agent('gateway/openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> Paris

```

otel_tui.py```
import os

import logfire

from pydantic_ai import Agent

os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://localhost:4318'

[](https://ai.pydantic.dev/logfire/#__code_14_annotation_1)
logfire.configure(send_to_logfire=False)

[](https://ai.pydantic.dev/logfire/#__code_14_annotation_2)
logfire.instrument_pydantic_ai()
logfire.instrument_httpx(capture_all=True)

agent = Agent('openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> Paris

```

  1. Set the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable to the URL of your OpenTelemetry backend. If you're using a backend that requires authentication, you may need to set [other environment variables](https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/). Of course, these can also be set outside the process, e.g. with `export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318`.
  2. We [configure](https://logfire.pydantic.dev/docs/reference/api/logfire/#logfire.configure) Logfire to disable sending data to the Logfire OTel backend itself. If you removed `send_to_logfire=False`, data would be sent to both Logfire and your OpenTelemetry backend.


Running the above code will send tracing data to `otel-tui`, which will display like this:
[![otel tui simple](https://ai.pydantic.dev/img/otel-tui-simple.png)](https://ai.pydantic.dev/img/otel-tui-simple.png)
Running the [weather agent](https://ai.pydantic.dev/examples/weather-agent/) example connected to `otel-tui` shows how it can be used to visualise a more complex trace:
[![otel tui weather agent](https://ai.pydantic.dev/img/otel-tui-weather.png)](https://ai.pydantic.dev/img/otel-tui-weather.png)
For more information on using the Logfire SDK to send data to alternative backends, see [the Logfire documentation](https://logfire.pydantic.dev/docs/how-to-guides/alternative-backends/).
### OTel without Logfire
You can also emit OpenTelemetry data from Pydantic AI without using Logfire at all.
To do this, you'll need to install and configure the OpenTelemetry packages you need. To run the following examples, use
Terminal```
uv run \
  --with 'pydantic-ai-slim[openai]' \
  --with opentelemetry-sdk \
  --with opentelemetry-exporter-otlp \
  raw_otel.py

```

[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_8_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_8_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) raw_otel.py```
import os

from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace import set_tracer_provider

from pydantic_ai import Agent

os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://localhost:4318'
exporter = OTLPSpanExporter()
span_processor = BatchSpanProcessor(exporter)
tracer_provider = TracerProvider()
tracer_provider.add_span_processor(span_processor)

set_tracer_provider(tracer_provider)

Agent.instrument_all()
agent = Agent('gateway/openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> Paris

```

raw_otel.py```
import os

from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace import set_tracer_provider

from pydantic_ai import Agent

os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://localhost:4318'
exporter = OTLPSpanExporter()
span_processor = BatchSpanProcessor(exporter)
tracer_provider = TracerProvider()
tracer_provider.add_span_processor(span_processor)

set_tracer_provider(tracer_provider)

Agent.instrument_all()
agent = Agent('openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> Paris

```

### Alternative Observability backends
Because Pydantic AI uses OpenTelemetry for observability, you can easily configure it to send data to any OpenTelemetry-compatible backend, not just our observability platform [Pydantic Logfire](https://ai.pydantic.dev/logfire/#pydantic-logfire).
The following providers have dedicated documentation on Pydantic AI:
  * [Langfuse](https://langfuse.com/docs/integrations/pydantic-ai)
  * [W&B Weave](https://weave-docs.wandb.ai/guides/integrations/pydantic_ai/)
  * [Arize](https://arize.com/docs/ax/observe/tracing-integrations-auto/pydantic-ai)
  * [Openlayer](https://www.openlayer.com/docs/integrations/pydantic-ai)
  * [OpenLIT](https://docs.openlit.io/latest/integrations/pydantic)
  * [LangWatch](https://docs.langwatch.ai/integration/python/integrations/pydantic-ai)
  * [Patronus AI](https://docs.patronus.ai/docs/percival/pydantic)
  * [Opik](https://www.comet.com/docs/opik/tracing/integrations/pydantic-ai)
  * [mlflow](https://mlflow.org/docs/latest/genai/tracing/integrations/listing/pydantic_ai)
  * [Agenta](https://docs.agenta.ai/observability/integrations/pydanticai)
  * [Confident AI](https://documentation.confident-ai.com/docs/llm-tracing/integrations/pydanticai)
  * [Braintrust](https://www.braintrust.dev/docs/integrations/sdk-integrations/pydantic-ai)
  * [SigNoz](https://signoz.io/docs/pydantic-ai-observability/)
  * [Laminar](https://docs.laminar.sh/tracing/integrations/pydantic-ai)


## Advanced usage
### Aggregated usage attribute names
By default, both model/request spans and agent run spans use the standard `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` attributes. Some observability backends (e.g., Datadog, New Relic, LangSmith, Opik) aggregate these attributes across all spans, which can cause double-counting since agent run spans report the sum of their child spans' usage.
To avoid this, you can enable `use_aggregated_usage_attribute_names` so that agent run spans use distinct attribute names (e.g., `gen_ai.aggregated_usage.input_tokens`, `gen_ai.aggregated_usage.output_tokens`, and `gen_ai.aggregated_usage.details.*`):
Custom namespace
The `gen_ai.aggregated_usage.*` namespace is a custom extension not part of the [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). It was introduced to work around double-counting in observability backends. If OpenTelemetry introduces an official convention for aggregated usage in the future, this namespace may be updated or deprecated.
```
from pydantic_ai import Agent
from pydantic_ai.models.instrumented import InstrumentationSettings

Agent.instrument_all(InstrumentationSettings(use_aggregated_usage_attribute_names=True))

```

### Configuring data format
Pydantic AI follows the [OpenTelemetry Semantic Conventions for Generative AI systems](https://opentelemetry.io/docs/specs/semconv/gen-ai/), specifically version 1.37.0 of the conventions. The instrumentation format can be configured using the `version` parameter of [`InstrumentationSettings`](https://ai.pydantic.dev/api/models/instrumented/#pydantic_ai.models.instrumented.InstrumentationSettings "InstrumentationSettings



      dataclass
  ").
**The default is`version=2`** , which provides a good balance between spec compliance and compatibility.
#### Version 1 (Legacy, deprecated)
Based on [OpenTelemetry semantic conventions version 1.36.0](https://github.com/open-telemetry/semantic-conventions/blob/v1.36.0/docs/gen-ai/README.md) or older. Messages are captured as individual events (logs) that are children of the request span. Use `event_mode='logs'` to emit events as OpenTelemetry log-based events:
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_9_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_9_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) instrumentation_settings_event_mode.py```
import logfire

from pydantic_ai import Agent

logfire.configure()
logfire.instrument_pydantic_ai(version=1, event_mode='logs')
agent = Agent('gateway/openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> The capital of France is Paris.

```

instrumentation_settings_event_mode.py```
import logfire

from pydantic_ai import Agent

logfire.configure()
logfire.instrument_pydantic_ai(version=1, event_mode='logs')
agent = Agent('openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)
#> The capital of France is Paris.

```

This version won't look as good in the Logfire UI and will be removed from Pydantic AI in a future release, but may be useful for backwards compatibility.
#### Version 2 (Default)
Uses the newer OpenTelemetry GenAI spec and stores messages in the following attributes:
  * `gen_ai.system_instructions` for instructions passed to the agent
  * `gen_ai.input.messages` and `gen_ai.output.messages` on model request spans
  * `pydantic_ai.all_messages` on agent run spans


Some span and attribute names are not fully spec-compliant for compatibility reasons. Use version 3 or 4 for better compliance.
#### Version 3
Builds on version 2 with the following improvements:
  * **Spec-compliant span names:**
    * `agent run` becomes `invoke_agent {gen_ai.agent.name}` (with the agent name filled in)
    * `running tool` becomes `execute_tool {gen_ai.tool.name}` (with the tool name filled in)
  * **Spec-compliant attribute names:**
    * `tool_arguments` becomes `gen_ai.tool.call.arguments`
    * `tool_response` becomes `gen_ai.tool.call.result`
  * **Thinking tokens support:** Captures thinking/reasoning tokens when available


#### Version 4
Builds on version 3 with improved multimodal content handling to better align with the [GenAI semantic conventions for multimodal inputs](https://opentelemetry.io/docs/specs/semconv/gen-ai/non-normative/examples-llm-calls/#multimodal-inputs-example):
**URL-based media (ImageUrl, AudioUrl, VideoUrl):**
  * Old (v1-3): `{"type": "image-url", "url": "..."}`
  * New (v4): `{"type": "uri", "modality": "image", "uri": "...", "mime_type": "..."}`


**Inline binary content (BinaryContent, FilePart):**
  * Old (v1-3): `{"type": "binary", "media_type": "...", "content": "..."}`
  * New (v4): `{"type": "blob", "modality": "image", "mime_type": "...", "content": "..."}`


Note: The `modality` field is only included for image, audio, and video content types as specified in the OTel spec. DocumentUrl and unsupported media types omit the `modality` field.
* * *
Note that the OpenTelemetry Semantic Conventions are still experimental and are likely to change.
### Setting OpenTelemetry SDK providers
By default, the global `TracerProvider` and `LoggerProvider` are used. These are set automatically by `logfire.configure()`. They can also be set by the `set_tracer_provider` and `set_logger_provider` functions in the OpenTelemetry Python SDK. You can set custom providers with [`InstrumentationSettings`](https://ai.pydantic.dev/api/models/instrumented/#pydantic_ai.models.instrumented.InstrumentationSettings "InstrumentationSettings



      dataclass
  ").
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_10_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_10_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) instrumentation_settings_providers.py```
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk.trace import TracerProvider

from pydantic_ai import Agent, InstrumentationSettings

instrumentation_settings = InstrumentationSettings(
    tracer_provider=TracerProvider(),
    logger_provider=LoggerProvider(),
)

agent = Agent('gateway/openai:gpt-5.2', instrument=instrumentation_settings)
# or to instrument all agents:
Agent.instrument_all(instrumentation_settings)

```

instrumentation_settings_providers.py```
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk.trace import TracerProvider

from pydantic_ai import Agent, InstrumentationSettings

instrumentation_settings = InstrumentationSettings(
    tracer_provider=TracerProvider(),
    logger_provider=LoggerProvider(),
)

agent = Agent('openai:gpt-5.2', instrument=instrumentation_settings)
# or to instrument all agents:
Agent.instrument_all(instrumentation_settings)

```

### Instrumenting a specific `Model`
instrumented_model_example.py```
from pydantic_ai import Agent
from pydantic_ai.models.instrumented import InstrumentationSettings, InstrumentedModel

settings = InstrumentationSettings()
model = InstrumentedModel('openai:gpt-5.2', settings)
agent = Agent(model)

```

### Excluding binary content
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_11_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_11_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) excluding_binary_content.py```
from pydantic_ai import Agent, InstrumentationSettings

instrumentation_settings = InstrumentationSettings(include_binary_content=False)

agent = Agent('gateway/openai:gpt-5.2', instrument=instrumentation_settings)
# or to instrument all agents:
Agent.instrument_all(instrumentation_settings)

```

excluding_binary_content.py```
from pydantic_ai import Agent, InstrumentationSettings

instrumentation_settings = InstrumentationSettings(include_binary_content=False)

agent = Agent('openai:gpt-5.2', instrument=instrumentation_settings)
# or to instrument all agents:
Agent.instrument_all(instrumentation_settings)

```

### Excluding prompts and completions
For privacy and security reasons, you may want to monitor your agent's behavior and performance without exposing sensitive user data or proprietary prompts in your observability platform. Pydantic AI allows you to exclude the actual content from telemetry while preserving the structural information needed for debugging and monitoring.
When `include_content=False` is set, Pydantic AI will exclude sensitive content from telemetry, including user prompts and model completions, tool call arguments and responses, and any other message content.
[With Pydantic AI Gateway](https://ai.pydantic.dev/logfire/#__tabbed_12_1)[Directly to Provider API](https://ai.pydantic.dev/logfire/#__tabbed_12_2)
[Learn about Gateway](https://ai.pydantic.dev/gateway) excluding_sensitive_content.py```
from pydantic_ai import Agent
from pydantic_ai.models.instrumented import InstrumentationSettings

instrumentation_settings = InstrumentationSettings(include_content=False)

agent = Agent('gateway/openai:gpt-5.2', instrument=instrumentation_settings)
# or to instrument all agents:
Agent.instrument_all(instrumentation_settings)

```

excluding_sensitive_content.py```
from pydantic_ai import Agent
from pydantic_ai.models.instrumented import InstrumentationSettings

instrumentation_settings = InstrumentationSettings(include_content=False)

agent = Agent('openai:gpt-5.2', instrument=instrumentation_settings)
# or to instrument all agents:
Agent.instrument_all(instrumentation_settings)

```

This setting is particularly useful in production environments where compliance requirements or data sensitivity concerns make it necessary to limit what content is sent to your observability platform.
### Adding Custom Metadata
Use the agent's `metadata` parameter to attach additional data to the agent's span. When instrumentation is enabled, the computed metadata is recorded on the agent span under the `metadata` attribute. See the [usage and metadata example in the agents guide](https://ai.pydantic.dev/agent/#run-metadata) for details and usage.
© Pydantic Services Inc. 2024 to present
