Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FrameworksAI guideIntermediate#frameworks#pydantic-ai#agents#python
Frame · ai-engineering / frameworks / 07-pydantic-ai.mdGuide 043 / 103

Pydantic AI, type safe agents in Python

Pydantic AI is an agent framework from the team behind Pydantic, the validation library that most Python LLM SDKs already depend on. Its pitch is simple: build agents the way you build a FastAPI app, with type hints, dependency injection and validated models, so your editor and type checker catch mistakes before the model does. As of October 2026 it is on the 2.x line (2.58 on PyPI). If your team likes typed Python and dislikes magic, this is often the most comfortable choice.

Why it matters

Most agent bugs I debug are not model bugs. They are shape bugs: a tool got a string where it expected an int, the output was missing a field, a database handle was a global that tests could not swap. Pydantic AI attacks those directly:

  • output_type: declare a Pydantic model (or a primitive, or a union) and the run is guaranteed to return an instance of it. Invalid outputs are sent back to the model to retry.
  • deps_type and RunContext: typed dependency injection. Your database connection, user id or HTTP client is passed per run and reaches tools and instructions through ctx.deps. Tests pass fakes.
  • Tools are functions: decorate with @agent.tool (gets RunContext) or @agent.tool_plain (no context). The signature and docstring become the tool schema.
  • Model agnostic: models are 'provider:model-name' strings, so switching providers is a string swap.
  • Observability: it is OpenTelemetry native; Pydantic Logfire is the first party backend, but any OTLP backend works.
  • Beyond a single loop: Pydantic Graph for typed graph control flow, Pydantic Evals for datasets and scoring, MCP support, and durable execution integrations with Temporal, DBOS and Prefect.

How it works

Rendering diagram…

If validation of tool arguments or the final output fails, the error is returned to the model as a retry prompt, up to a configurable retry limit. That loop is what turns "the model usually returns JSON" into "the function returns a SupportOutput".

Reference architecture

A common shape is an agent defined once at module level, with dependencies built per request in your web framework.

Rendering diagram…

Because the agent is stateless and dependencies are explicit, it is easy to unit test: build a fake deps, and use Pydantic AI's test model to avoid real API calls.

Code

A bank support agent in the spirit of the official example, using the documented Agent, RunContext, deps_type, output_type and @agent.tool APIs.

from dataclasses import dataclass

from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext


class FakeDB:
    async def customer_name(self, customer_id: int) -> str:
        return "Ada"

    async def balance(self, customer_id: int) -> float:
        return 123.45


@dataclass
class SupportDeps:
    customer_id: int
    db: FakeDB


class SupportOutput(BaseModel):
    support_advice: str = Field(description="Advice returned to the customer")
    block_card: bool = Field(description="Whether to block the customer's card")
    risk: int = Field(description="Risk level of the query", ge=0, le=10)


support_agent = Agent(
    "anthropic:claude-sonnet-4-6",
    deps_type=SupportDeps,
    output_type=SupportOutput,
    instructions=(
        "You are a support agent in our bank. Give the customer support "
        "and judge the risk level of their query."
    ),
)


@support_agent.tool
async def customer_balance(ctx: RunContext[SupportDeps]) -> float:
    """Return the customer's current account balance."""
    return await ctx.deps.db.balance(ctx.deps.customer_id)


@support_agent.tool
async def customer_name(ctx: RunContext[SupportDeps]) -> str:
    """Return the customer's first name."""
    return await ctx.deps.db.customer_name(ctx.deps.customer_id)


deps = SupportDeps(customer_id=123, db=FakeDB())
result = support_agent.run_sync("I just lost my card!", deps=deps)
print(result.output.block_card, result.output.risk)

result.output is a SupportOutput, so your IDE autocompletes its fields and your type checker knows risk is an int. For async code use await support_agent.run(...), and for streaming there are streaming run methods as well.

To see what happened, add tracing:

import logfire

logfire.configure()
logfire.instrument_pydantic_ai()

Trade-offs and pitfalls

  • Fewer batteries than LangChain. There is no giant integration catalogue for loaders and vector stores. You bring your own retrieval (often with plain SDKs or LlamaIndex) and expose it as a tool.
  • Validation retries cost tokens. A strict output model with many constraints can cause several retries. Keep output schemas as simple as the downstream code needs.
  • Fast release cadence. The project ships frequently. Pin versions and read the changelog, especially for newer features such as capabilities and durable execution.
  • Graphs are a separate tool. For complex multi step flows, Pydantic Graph or a durable execution engine is needed; the agent loop alone does not give you human approval checkpoints.
  • Python only. If your product is TypeScript, look at the Vercel AI SDK or Mastra instead.

When to pick it: typed Python teams (FastAPI style), agents whose outputs feed straight into code, apps that need clean dependency injection and testability, or teams already using Logfire or OpenTelemetry.

When not to: you need many off the shelf integrations, you want a visual graph runtime with built-in checkpoints out of the box, or you are building in TypeScript.

Checklist

  • Define output_type for anything a program consumes.
  • Pass all external resources through deps_type, never module globals.
  • Write tool docstrings as if they were API docs; they become the schema.
  • Keep output models minimal and use Field descriptions.
  • Instrument with Logfire or another OpenTelemetry backend from day one.
  • Unit test agents with fake deps and a test model.
  • Use a durable execution integration for long running work.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.