# Pydantic AI Guide: Type-Safe Agents for Python Teams

> Pydantic AI is an open-source Python framework for AI agents, built by the Pydantic team. Outputs, tools and dependencies are typed and validated, and the model can be swapped for a test model in unit tests. Developers like it because agents become ordinary, reviewable, testable software.

Canonical URL: https://www.ruebstudio.de/en/guides/agent-frameworks/pydantic-ai-guide  
Author: Dr.-Ing. Marcus Rüb, CEO  
Published: 2026-11-18

Most agent frameworks make you learn their abstractions first. Pydantic AI goes the other way: it asks you to write the kind of Python you already write for web services, with typed models, plain functions and injected dependencies. This guide covers what the framework is, how its parts fit together, where it is a good fit for production work and where it is not. Everything here reflects Pydantic AI 2.70.0, checked on 18 November 2026.

## What is Pydantic AI, and what is it used for?

Pydantic AI is an open-source Python framework for AI agents, maintained by the team behind the Pydantic validation library. It connects a language model to tools, instructions and runtime dependencies and returns validated, typed results. Teams use it when an agent must live inside an existing Python codebase and meet the same standards.

The [official overview](https://pydantic.dev/docs/ai/overview/) calls it a "Python AI SDK for building typed agents", covering the agent loop, realtime voice, image generation and embeddings. The [GitHub README](https://github.com/pydantic/pydantic-ai) draws the line to FastAPI explicitly: Pydantic is the validation layer underneath FastAPI, and Pydantic AI aims to bring "that same feeling to agents". The project is MIT-licensed.

Common jobs for it include:

- **Pulling structured data out of documents.** Purchase orders, delivery notes, inspection reports or inbound emails become a fixed data model that an ERP, CRM or ticketing system can ingest without a human retyping fields.
- **Triage and routing.** Support tickets get a category, a priority and an owning team, and every field is guaranteed to exist and be valid.
- **Tool-using assistants.** An agent queries stock levels, order status or a document store through functions you define, then answers a question.
- **Long-running processes.** Workflows that pause for approval or run for days can be made durable.

The project has a clear support policy. [Version 2 went stable on 23 June 2026](https://pydantic.dev/docs/ai/project/version-policy/); the maintainers say they will not intentionally ship breaking changes in minor releases, and version 1 keeps receiving security fixes for at least six months after that date.

## How does Pydantic AI work? The building blocks

A Pydantic AI agent combines a model, instructions, tools, a dependency type and an output type. On each run the framework calls the model, executes the tools it asks for after validating their arguments, and checks the final answer against your Pydantic model. If validation fails, the error goes back to the model and it gets another attempt.

The parts you work with day to day:

- **`Agent`** is the central object. You choose the model with a string such as `anthropic:…` or `openai:…`. The [documentation](https://pydantic.dev/docs/ai/overview/) lists OpenAI, Anthropic, Google, Bedrock, Azure AI Foundry, Groq, Mistral, xAI and Ollama among supported providers.
- **`output_type`** is a Pydantic model, a simple type or a list of types. The result is validated, and failures trigger a retry.
- **Tools (`@agent.tool`)** are ordinary Python functions. Their schema comes from the signature and docstring, and arguments are validated before your code runs.
- **Dependencies (`deps_type`, `RunContext`)** carry database connections, API clients or request context into a run. Tools and instructions read them via `ctx.deps`.
- **Capabilities** are the core building block since version 2. Each one bundles tools, instructions, hooks and model settings into a reusable unit ([v2 announcement](https://pydantic.dev/articles/pydantic-ai-v2)).

Here is a compact example: an agent that reads a supplier's delivery note and checks it against the purchase order in the ERP. Tested with `pydantic-ai-slim[anthropic]` 2.70.0 on Python 3.12, November 2026.

```python
from dataclasses import dataclass

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


class LineItem(BaseModel):
    sku: str
    quantity: int = Field(gt=0)


class DeliveryNote(BaseModel):
    supplier: str
    items: list[LineItem]
    differs_from_order: bool


class ErpClient:
    # stand-in for your real ERP client
    def open_lines(self, order_id: str) -> list[dict]:
        return [{"sku": "A-100", "quantity": 20}]


@dataclass
class Deps:
    order_id: str
    erp: ErpClient


agent = Agent(
    "anthropic:claude-sonnet-5-5",
    deps_type=Deps,
    output_type=DeliveryNote,
    defer_model_check=True,  # resolve the model at run time (handy in tests)
    instructions="Read the delivery note and compare it with the purchase order.",
)


@agent.tool
def ordered_lines(ctx: RunContext[Deps]) -> list[dict]:
    """Return the open lines of the purchase order from the ERP."""
    return ctx.deps.erp.open_lines(ctx.deps.order_id)
```

You call it with `agent.run_sync(text, deps=Deps(...))`. What comes back in `result.output` is a `DeliveryNote` object, not free text. A quantity of zero or a missing field would fail validation.

## What makes Pydantic AI different from other agent frameworks?

Its defining idea is not a special agent pattern but engineering discipline: typed inputs and outputs, dependency injection for everything external, and tests that run without calling a model. That makes it a natural choice for teams who already rely on type checkers, unit tests and code review.

Three properties carry that approach.

**Typed end to end.** That is the README's own phrase: structured outputs, typed dependencies and typed tools. With Pyright or mypy in your editor, a tool that reads a field your dependency class does not have is flagged before anything runs. The README describes this as moving whole classes of errors from runtime to write-time.

**Dependency injection instead of globals.** The [dependencies documentation](https://pydantic.dev/docs/ai/core-concepts/dependencies/) states that dependencies can be any Python type, and that `deps_type` exists for static type checking rather than runtime use. The database handle, the tenant or the current user is passed in per run. Multi-tenant agents become straightforward, and there is no hidden coupling to module-level state.

**Testable without a model.** `agent.override(model=TestModel())` replaces the real model in tests, and setting `ALLOW_MODEL_REQUESTS = False` blocks accidental live calls, as the [testing guide](https://pydantic.dev/docs/ai/guides/testing) recommends. Dependencies can be overridden the same way.

Other frameworks optimise for different things. Graph-first frameworks model workflows as explicit state machines, multi-agent frameworks put roles and crews at the centre, and large ecosystems offer many ready-made connectors. For a neutral side-by-side, see our [comparison of AI agent frameworks](https://www.ruebstudio.de/en/guides/agent-frameworks/ai-agent-frameworks-comparison). Choosing Pydantic AI over a graph framework mostly changes your starting point: you begin with data models and functions rather than a flow diagram. If you do need an explicit graph, Pydantic Graph is available alongside it. Teams who think in state graphs from day one should read the [LangGraph guide](https://www.ruebstudio.de/en/guides/agent-frameworks/langgraph-guide) for the contrasting approach.

## How do you test a Pydantic AI agent?

You test it like any other code. In unit tests the model is replaced by `TestModel` or `FunctionModel`, and external services by fakes. The tests then check the wiring of tools, dependencies and output type deterministically, quickly and without paying for model calls.

According to the [testing guide](https://pydantic.dev/docs/ai/guides/testing), `TestModel` calls every tool on the agent by default and produces output that matches your schema. `FunctionModel` gives you full control over what the "model" returns. `capture_run_messages` lets you assert on the exact message exchange of a run.

```python
from pydantic_ai import models
from pydantic_ai.models.test import TestModel

from delivery_agent import Deps, DeliveryNote, ErpClient, agent

models.ALLOW_MODEL_REQUESTS = False  # never hit a real model in tests


def test_agent_returns_typed_result():
    deps = Deps(order_id="PO-4711", erp=ErpClient())
    with agent.override(model=TestModel()):
        result = agent.run_sync("delivery note text ...", deps=deps)
    assert isinstance(result.output, DeliveryNote)
```

Be clear about what this proves. These tests cover mechanics, not answer quality. For quality there is Pydantic Evals, which, per the [overview](https://pydantic.dev/docs/ai/overview/), grades final outputs and tool-call trajectories on datasets or live traffic. A production setup needs both: unit tests on every commit and evals against a curated set of real documents before any prompt, model or tool change ships. Our guide to [testing AI agents](https://www.ruebstudio.de/en/guides/ai-agent-development/testing-ai-agents) covers how to build both layers, independent of framework.

## Where does Pydantic AI fit? Common patterns

Pydantic AI covers everything from a single extraction function to long-running agents with approval steps. The deciding question is less about project size and more about whether a machine consumes the result. If it does, the typing pays off immediately.

**Extraction and classification.** The most common starting point: an agent with few or no tools whose `output_type` matches the target format exactly. The [output documentation](https://pydantic.dev/docs/ai/core-concepts/output/) describes three modes. Tool Output is the default and works with virtually all models; Native Output uses the provider's own structured-output feature; Prompted Output puts the schema into the instructions and is the least reliable, though it works with any model.

**Agents that call business systems.** A quoting assistant reads an enquiry, looks up product data and price lists through tools, and returns a structured draft quote. Our page on [AI agents for quotation](https://www.ruebstudio.de/en/ai-agents/quotation) shows what such a specialist agent looks like inside a real process.

**Reusable bundles with capabilities.** In version 2, a capability can package, say, customer-context tools and instructions for reuse across agents. With `defer_loading=True` a bundle stays out of the prompt until the model asks for it, which helps when an agent has many tools.

**Durable, interruptible runs.** The [overview](https://pydantic.dev/docs/ai/overview/) says runs can survive restarts through durable execution engines including Temporal, DBOS and Prefect, with human-in-the-loop approval via deferred tools.

**Local and private models.** If data cannot leave your infrastructure, you can point the agent at local models through Ollama. Our page on [sovereign AI](https://www.ruebstudio.de/en/sovereign-ai) covers the wider organisational and technical setup.

A step-by-step tutorial and a head-to-head comparison with LangChain are planned for this topic and will be listed on this page once published.

## What does a team need before starting?

You need people who write Python regularly, ideally with experience of type hints, Pydantic models and automated tests. Technically you need Python 3.11 or later, access to at least one model, and well-defined interfaces to the systems the agent will use.

In more detail:

- **Language and tooling.** Python 3.11+ ([PyPI](https://pypi.org/project/pydantic-ai/)), a package manager such as `uv` or `pip`, and an editor with type checking. Per the [v2 announcement](https://pydantic.dev/articles/pydantic-ai-v2), the full `pydantic-ai` package includes OpenAI, Anthropic and Google, while providers such as Bedrock, Groq and Mistral are opt-in extras. `pydantic-ai-slim` lets you install only what you use.
- **Model access.** An API key from a provider or a locally hosted model. On data protection: a setup can be operated in line with the GDPR once processing agreements, data location and access rights are sorted out. The framework does not decide that for you, and this is not legal advice.
- **Data and interfaces.** An agent's tools are only as good as the APIs behind them. If order data is only reachable via nightly CSV exports, fix that first.
- **Sample documents.** Tests and evals need real, anonymised examples, including the awkward edge cases, not just the clean ones.
- **Observability.** Instrumentation is built on OpenTelemetry. Pydantic Logfire is one option; any OTLP-compatible backend also works.

## How should you roll it out?

Work in small, verifiable steps: data model first, then an agent without tools, then tools and tests, and finally operations and monitoring. Each step can be tested on its own, which keeps failures easy to locate.

1. **Agree the target format.** Define the output model with the people who own the process. Which fields are mandatory, which values are valid, and what should happen when the input is ambiguous? A field like `uncertain: bool` with a reason is often worth more than a forced answer.
2. **Build the agent without tools.** Run a handful of real documents through it and check whether the model fills the format reliably and which output mode works best.
3. **Add tools and dependencies.** Give each function a clear docstring and a narrow signature, and keep access read-only for as long as you can. Add write actions only behind an approval step.
4. **Set up unit tests and evals.** `TestModel` and `ALLOW_MODEL_REQUESTS = False` in CI, plus an eval dataset with expected results that runs before every change to prompts, models or tools.
5. **Instrument and roll out gradually.** Log every run, including model calls, tool calls and token usage. Start in shadow mode: the agent proposes, a person decides.
6. **Manage versions deliberately.** Pin the version in your lock file and schedule upgrades. [PyPI](https://pypi.org/project/pydantic-ai/) shows several minor releases per month.

Step 1 tends to be underestimated. A clean target format surfaces business questions that would otherwise only appear in production.

## What are the limits and risks?

Types guarantee the shape of an answer, not its truth. An agent can return a perfectly valid `DeliveryNote` with the wrong SKU. On top of that come the usual agent risks, such as unexpected tool calls and [prompt injection](https://www.ruebstudio.de/en/glossary/prompt-injection) through input documents, plus the fast pace of the framework itself.

Plan for these points:

- **Valid structure, wrong content.** Put plausibility checks into validators or tools, for example matching against master data. A failing check can raise `ModelRetry` to trigger another attempt; per the [output documentation](https://pydantic.dev/docs/ai/core-concepts/output/), the default output retry budget is 1.
- **Retry costs.** Every validation failure means another model call. With weaker models or complex schemas this adds up.
- **A fast-moving API.** Version 2 changed several defaults; for instance, `openai:` model names now use the Responses API ([v2 announcement](https://pydantic.dev/articles/pydantic-ai-v2)). Under the [version policy](https://pydantic.dev/docs/ai/project/version-policy/), deprecated features are removed only in the next major version, no sooner than three months after 2.0. Many tutorials online predate these changes.
- **Python only.** If your systems run on Java, C# or TypeScript, the agent becomes a separate service you have to deploy and integrate.
- **Fewer ready-made connectors.** Large ecosystems ship more prebuilt integrations for document sources. With Pydantic AI you write more tools yourself, which gives you control but costs time.
- **Security.** Tools with write, file-system or network access need their own authorisation logic. The framework validates arguments; it does not decide whether an action is allowed.

Pydantic AI is a poor fit if nobody on the team writes Python regularly, if a no-code tool already solves the problem, or if the core of the work is a complex multi-agent workflow with lots of state that your team would rather model as an explicit graph.

## How do I get started?

Pick one narrow use case with a clear target format: one document type, one data model, one model, one test set. Install the package, build the agent without tools, and write your first `TestModel` test before adding any tools.

A sensible first day looks like this:

```bash
uv init delivery-agent && cd delivery-agent
uv add "pydantic-ai-slim[anthropic]" pytest
export ANTHROPIC_API_KEY="..."   # only for real runs, not for unit tests
```

Then define the data model, run ten real documents through the agent and write down where it fails. That list becomes the basis for your tools, validators and eval dataset. If several departments plan to build agents, it pays to maintain shared capabilities, for example ERP access or approval steps, as an internal package early on.

If you are still weighing frameworks, the [agent framework comparison](https://www.ruebstudio.de/en/guides/agent-frameworks/ai-agent-frameworks-comparison) helps place Pydantic AI among the alternatives. To see how finished specialist agents for sales, service and knowledge work are put together, start with our overview of [AI agents](https://www.ruebstudio.de/en/ai-agents).

## Frequently asked questions

### Is Pydantic AI free to use?

The framework is MIT-licensed. You pay for model calls with your chosen provider and, optionally, for an observability backend.

### Can Pydantic AI run with local models?

Yes. Ollama is listed among the supported providers, and you pick a model with a string. Whether a given local model handles structured output and tool calls reliably is something to verify with your own test cases.

### Which Python version does it require?

Version 2.70.0 requires Python 3.11 or later, according to PyPI (as of 18 November 2026).

### Should I pick Pydantic AI or LangChain?

Pydantic AI suits teams that want a small, typed core and are happy to write their own tools. If ready-made integrations matter more to you, compare the options in our agent framework comparison before deciding.

### What changed in version 2?

Capabilities became the core building block, bundling tools, instructions, hooks and model settings. Long-tail providers moved to optional extras, and openai: model names now use the Responses API.

## Sources

- [Pydantic AI – Overview (official documentation)](https://pydantic.dev/docs/ai/overview/)
- [Pydantic AI v2 – announcement by the Pydantic team (23 June 2026)](https://pydantic.dev/articles/pydantic-ai-v2)
- [Pydantic AI – Version Policy](https://pydantic.dev/docs/ai/project/version-policy/)
- [Pydantic AI – Dependencies](https://pydantic.dev/docs/ai/core-concepts/dependencies/)
- [Pydantic AI – Output](https://pydantic.dev/docs/ai/core-concepts/output/)
- [Pydantic AI – Unit testing](https://pydantic.dev/docs/ai/guides/testing)
- [pydantic/pydantic-ai on GitHub (README, licence)](https://github.com/pydantic/pydantic-ai)
- [pydantic-ai on PyPI (releases, Python requirement)](https://pypi.org/project/pydantic-ai/)
