Guide

Monitor your Pydantic AI agents in production.

Pydantic AI gives you typed, structured agents, and hands you the usage of every run. Agent Ping instruments them so each run reports cost, status and the quality of the structured output, attributed to the customer and feature it was for, without touching your agent definitions.

Two lines, then every run reports in.

Install the SDK and point it at your Pydantic AI agent. One record lands per run with the cost, status, latency and output behind it.

shellinstall
pip install "agentping-io[pydantic-ai]"
pythonmonitor your agent
import agentping
from pydantic_ai import Agent

agentping.init(api_key="apk_…")
agentping.instrument_pydantic_ai()

triage = Agent("anthropic:claude-sonnet-4-5", instructions="Classify the ticket.")

# Wrap the call in a run; the usage of the whole agent loop lands on it.
with agentping.run(agent="support-triage", customer_id="acme-corp"):
    result = triage.run_sync("My invoice is wrong")

instrument_pydantic_ai() patches Agent.run and Agent.run_sync once, at the class level. When a run returns, its RunUsage becomes one llm_call on the enclosing Agent Ping run, with the provider and model from the agent; a run that raises lands as an errored call and the exception is re-raised. Full reference is in the docs.

What Agent Ping tracks for Pydantic AI.

  • Cost per agent run, priced from the run's total token usage, attributed to the customer and feature you tag.
  • Retries and requests per run, so a prompt change that makes validation fail more often shows up as a cost rise, not a surprise.
  • A missed-run alert when a scheduled agent stops firing.
  • Output quality, including whether the structured result matched your schema and your rubric.

See the pillars behind these: Spend, Pulse and Verify.

Usage and cost: the run is the right grain.

A Pydantic AI run can make several model requests before it returns: tool calls, retries after a validation failure, a second pass at a structured answer. Pydantic AI sums them for you, and that sum is what Agent Ping prices.

What Pydantic AI reports

result.usage() returns a RunUsage with input_tokens, output_tokens, requests and tool_calls, summed across every model exchange in the agent loop, including retries. The cached prefix is already inside input_tokens, which is how providers bill it.

What Agent Ping adds

instrument_pydantic_ai() reads that same RunUsage when run() or run_sync() returns and emits one llm_call with the provider and model from the agent. Agent Ping prices it server side from a maintained rate card, so each run has a dollar figure, and the figure rolls up by customer, feature, agent and model. There is nothing to send by hand.

Hard limits inside a run, budgets across runs

Pass usage_limits=UsageLimits(request_limit=…, total_tokens_limit=…) to run() to stop an agent that loops. The UsageLimitExceeded it raises closes the Agent Ping run as failed with its partial usage, so a loop shows up as a failed run with a cost, not a quiet success. Agent Ping budgets work across runs: a monthly cap per agent or customer that alerts before it trips.

pythoncap one run, budget the month
from pydantic_ai import Agent
from pydantic_ai.usage import UsageLimits

agent = Agent("anthropic:claude-sonnet-4-5", instructions="Extract the invoice.")

with agentping.run(agent="invoice-extractor", customer_id="acme-corp", feature="ap-inbox"):
    result = agent.run_sync(
        email_body,
        usage_limits=UsageLimits(request_limit=8, total_tokens_limit=60_000),
    )
    # result.usage() -> RunUsage(requests=2, input_tokens=4120, output_tokens=310, ...)

Structured output and retries: catch the valid answer that is wrong.

Pydantic AI's strongest feature is that the model's answer has to validate. The monitoring question is what happens when it validates and is still wrong.

What the type system catches

With output_type set, Pydantic validates the answer and, on failure, sends the validation error back to the model for another attempt, up to retries. A run that exhausts its retries raises UnexpectedModelBehavior, which closes the Agent Ping run as failed with the message attached, so a model that stopped following the schema pages you.

What it does not catch

A result that validates can still be wrong: the right schema with the wrong invoice total. Write the result into the run output and give the agent a Verify rubric in plain English. Agent Ping scores every run against it and alerts when the pass rate drops, which is how a prompt or model change that broke accuracy shows up before the support inbox does.

Count the retries

Each retry is another model round trip and appears in requests on RunUsage. A rise in requests per run with no change in volume usually means a prompt or model change is making validation fail more often. Put requests in the run output so you can chart it next to cost.

pythonvalidate, retry, and record the result
from pydantic import BaseModel
from pydantic_ai import Agent, ModelRetry

class Invoice(BaseModel):
    supplier: str
    total: float
    currency: str

agent = Agent("openai:gpt-5", output_type=Invoice, retries=2)

@agent.output_validator
def total_is_positive(output: Invoice) -> Invoice:
    if output.total <= 0:
        raise ModelRetry("Total must be positive; re-read the invoice.")
    return output

with agentping.run(agent="invoice-extractor", customer_id="acme-corp") as run:
    result = agent.run_sync(email_body)
    run.finish(output={**result.output.model_dump(), "requests": result.usage().requests})

Streaming and iter(): what the patch does not see.

The instrumentation wraps the two entry points most agents use. The other two still report usage; you just emit the event yourself, or let OpenTelemetry carry it.

Covered automatically

instrument_pydantic_ai() wraps Agent.run and Agent.run_sync. Both return a result with a RunUsage, and that is where the llm_call comes from. Supported pydantic-ai versions are 1.x; outside that range the call warns once and leaves the agent alone.

Streaming and the node iterator

agent.run_stream() and agent.iter() are not wrapped. Usage is still available on the stream result and on the run inside iter(), so emit the llm_call when the stream completes, with the same fields the patch would have sent. The run still carries the status, output and schedule the same way.

Or go through OpenTelemetry

Pydantic AI emits OpenTelemetry spans with gen_ai attributes once you call Agent.instrument_all(). Point OTEL_EXPORTER_OTLP_TRACES_ENDPOINT at Agent Ping and every agent run, model request and tool call arrives as a run with steps, whichever entry point you used.

pythonemit usage from a streamed run
async with agentping.run(agent="summariser", customer_id="acme-corp") as run:
    async with agent.run_stream(document) as stream:
        async for chunk in stream.stream_text():
            yield chunk
        usage = stream.usage()
        run.event("llm_call", {
            "provider": "anthropic", "model": agent.model.model_name,
            "input_tokens": usage.input_tokens, "output_tokens": usage.output_tokens,
        })
How do I track token usage in Pydantic AI?
result.usage() on any run result returns a RunUsage: input_tokens, output_tokens, requests and tool_calls for the whole agent loop, retries included. Agent Ping records the same numbers automatically when run() returns, prices them from its rate card, and attributes them to the customer and feature on the run.
Does it work with structured output?
Yes. The run records the structured result, and you can add deterministic checks (required fields, schema) plus a rubric so a successful-but-wrong output is caught.
How do I stop a Pydantic AI agent that loops?
Pass usage_limits=UsageLimits(request_limit=…, total_tokens_limit=…) to run(). The UsageLimitExceeded it raises closes the Agent Ping run as failed with the partial usage, and an alert rule on failing runs pages you. For spend across runs, set a monthly budget on the agent or customer in Agent Ping.
Does it work with run_stream()?
Not through the patch, which wraps run() and run_sync(). Emit the llm_call yourself from stream.usage() when the stream finishes, or call Agent.instrument_all() and export OpenTelemetry to Agent Ping, which covers every entry point.
Do I rewrite my agents?
No. Call instrument_pydantic_ai() once after init; your agent definitions and run calls stay the same.
Will it slow runs down?
No. Telemetry is off the hot path with a hard timeout and a bounded queue, so your agent runs unchanged if Agent Ping is unreachable.

Monitor your Pydantic AI agents in minutes.

Add the SDK, send one run, and watch cost, status and quality land in the dashboard.

How to monitor LangGraph agents → How to monitor OpenAI Agents SDK agents → How to monitor CrewAI agents →