页面简介
Debug and monitor Pydantic AI agents with Pydantic Logfire or any OpenTelemetry backend, tracing the model requests, tool calls and token usage of every run.
正文摘录
Pydantic Logfire Debugging and Monitoring While you build an agent, and once it is in production, its traces are how you find out why a run gave a wrong answer, took too long or cost too much. Pydantic AI emits OpenTelemetry traces of every run, model request and tool call; this page sets up Pydantic Logfire to view them, and covers any other OpenTelemetry backend too. 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. 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 is an AI engineering 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 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 in Logfire: A trace is generated for the agent run, and spans are emitted for each model request and tool call. When a model request ends with an error, streamed or not, its span records an exception event and its status is set to ERROR. A failure that an on_model_request_error hook recovers from isn’t recorded there, and neither is an error your own code raises while it consumes a stream. Using Logfire The quickest way to start is the Logfire wizard. Run it from your project: Terminaluvx logfire-cli wizard --task pydantic-ai It signs you in (or creates a free account), picks or creates a project, and hands the instrumentation to your coding agent, which then checks that the first trace arrived. If a coding agent is already doing the setup, it can run uvx logfire-cli --no-input --output json wizard --task pydantic-ai --print-prompt and follow the instructions it returns. To set it up by hand instead, you’ll need a Logfire account. The Logfire Python SDK is included with pydantic-ai: pip uv Terminalpip install pydantic-ai Or if you’re using the slim package, you can install it with the logfire optional group: pip uv Terminalpip install "pydantic-ai-slim[logfire]" Then authenticate your local environment with Logfire: Terminaluvx logfire-cli auth And connect this directory to a project to send data to, new or existing: Terminaluvx logfire-cli init 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: instrument_pydantic_ai.py import logfire from pydantic_ai import Agent logfire.configure() # (1) logfire.instrument_pydantic_ai() # (2) agent = Agent('openai:gpt-6.1-sol', name='hello_world_agent', instructions='Be concise, reply with one sentence.') # (4) result = agent.run_sync('Where does "hello world" come from?') # (3) print(result.output) """ The first known use of "hello, world" was in a 1974 textbook about the C programming language. """ 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. logfire.instrument_pydantic_ai() enables instrumentation of Pydantic AI. Since we've enabled instrumentation, a trace will be generated for each run, with spans emitted for models calls and tool function execution Passing name is optional but recommended: it labels the agent's run span in Logfire. When omitted, the name is inferred from the variable the agent is assigned to and falls back to 'agent' when it can't be (e.g. agents kept in a list or dict). This matters most when several agents run in one app and you need to tell their traces apart. (This example is complete, it can be run “as is”) Which will display in Logfire thus: The Logfire documentation has more details on how to use Logfire, including how to instrument other libraries like HTTPX and FastAPI. Since Logfire is built on OpenTelemetry, you can use the Logfire Python SDK to send data to any OpenTelemetry collector, see below. Use Logfire for local development, even if production uses something else You can use Logfire while you develop, whatever your company runs in production. Logfire’s free tier needs only a GitHub login, and setup is the two commands and two lines of code above. Pydantic AI’s instrumentation is plain OpenTelemetry, so the same spans can go to your company’s backend in production and to Logfire on your laptop. Tell Logfire to send only when it has a token: import logfire logfire.configure(send_to_logfire='if-token-present') logfire.instrument_pydantic_ai() On your machine, logfire.configure() reads the token from the .logfire directory that logfire-cli init wrote, which is gitignored. A deployment without that directory or a LOGFIRE_TOKEN sends nothing to Logfire (.gitignore does not keep it out of a Docker build context, so exclude it there too), and the Logfire SDK still exports to the backend set in the standard OTEL_EXPORTER_OTLP_ENDPOINT environment variable, as shown below. If your application sets up its own OpenTelemetry SDK in production instead, call logfire.configure() and logfire.instrument_pydantic_ai() only when developing locally, and use Agent.instrument_all() in production: it uses the global OpenTelemetry providers your SDK set up. 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: Realtime (speech-to-speech) sessions are instrumented by the same logfire.instrument_pydantic_ai() call: a session appears as an agent run whose child spans mark each model response, tool call, and turn boundary as the live conversation unfolds. 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: Monitoring HTTP Requests As per Hamel Husain’s influential 2024 blog post “Fuck You, Show Me The 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. Provider SDKs use either httpx or httpx2 internally, except for Bedrock, which uses boto3: with_logfire_instrument_httpx.py import logfire from pydantic_ai import Agent logfire.configure() logfire.instrument_pydantic_ai() logfire.instrument_httpx(capture_all=True) # (1) agent = Agent('openai:gpt-6.1-sol') result = agent.run_sync('What is the capital of France?') print(result.output) #> The capital of France is Paris. See the logfire.instrument_httpx docs for more details. capture_all=True means both headers and body are captured for both the request and response. httpx2 instrumentation requires opentelemetry-instrumentation-httpx>=0.65b0, which the logfire extra installs for you. If you pin OpenTelemetry yourself and end up below that version, logfire.instrument_httpx() reports the missing requirement and emits no httpx2 spans. Using OpenTelemetry Pydantic AI’s instrumentation uses OpenTelemetry (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, so while we think you’ll have the best experience using the Logfire platform 😉, 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 — an open source terminal based OTel backend and viewer (no association with Pydantic Validation). Run otel-tui with docker (see the otel-tui readme for more instructions): Terminaldocker run --rm -it -p 4318:4318 --name otel-tui ymtdzzz/otel-tui:latest then run, otel_tui.py import os import logfire from pydantic_ai import Agent os.environ['OTEL_EXPORTER_OTLP_ENDPOINT'] = 'http://localhost:4318' # (1) logfire.configure(send_to_logfire=False) # (2) logfire.instrument_pydantic_ai() logfire.instrument_httpx(capture_all=True) agent = Agent('openai:gpt-6.1-sol') result = agent.run_sync('What is the capital of France?') print(result.output) #> Paris 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. Of course, these can also be set outside the process, e.g. with export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318. We 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: Running the weather agent example connected to otel-tui shows how it can be used to visualise a more complex trace: For more information on using the Logfi