Sub topic 10
PydanticAI: typed, validated agents
PydanticAI is a Python agent framework built by the team behind Pydantic. Its central idea is that a model's reply should be a typed Python object, and that your tools and dependencies should be typed too. This chapter explains the working model, shows how it relates to the manual structured-output code from earlier chapters, and covers the errors you are most likely to meet.
This chapter assumes you can write basic Python with classes and type hints, and that you have used Pydantic's BaseModel. It also assumes you have called a chat API and seen tool calling done by hand with a provider SDK. You need pip install pydantic-ai and an OPENAI_API_KEY in your environment to run the examples.
What PydanticAI is for
Earlier in this tutorial you wrote the manual version of structured output. You asked for JSON, parsed the reply with Ticket.model_validate_json, and handled ValidationError yourself. A real application also needs to retry when validation fails, and that is more code.
PydanticAI automates that loop. You declare the type you want, and the framework does these things:
- It sends the type's JSON schema to the model.
- It parses and validates the reply against your type.
- If validation fails, it sends the error back to the model and asks again, up to a retry limit.
- It returns an object of your type, so your editor and type checker know its fields.
Its design focus differs from the other two frameworks in this tutorial. LangChain concentrates on composable components and integrations. LlamaIndex concentrates on data ingestion and retrieval. PydanticAI concentrates on type safety and validation around the agent itself.
The smallest agent
from pydantic import BaseModel
from pydantic_ai import Agent
class CityInfo(BaseModel):
city: str
country: str
agent = Agent("openai:gpt-4o-mini", output_type=CityInfo)
result = agent.run_sync("Where were the 2012 Summer Olympics held?")
print(result.output)Three names matter here.
Agentis the object you configure once and reuse. It holds the model, the output type, instructions, tools, and dependencies.output_typeis the type the final answer must satisfy.result.outputis the validated value. Here it is aCityInfoinstance, not a string or a dictionary.
The model string "openai:gpt-4o-mini" has the form provider:model-name. Changing the prefix, for example to an Anthropic model, switches providers without changing the rest of the code. This is the same portability benefit you saw with LangChain's chat model classes.
Where the type is enforced
The output_type is more than a hint. PydanticAI turns it into a schema the model can follow, and it validates the reply when it arrives. By default it does this by registering an output tool whose parameters are your schema. The model "calls" that tool to give its final answer, and the framework validates the arguments.
This is the same retry you would write by hand in the JSON-mode example. The difference is that you do not maintain the loop. The cost is that the retry is hidden. A failing validation means extra model calls, and you pay for each one.
Constraints in the type
Because validation is Pydantic validation, every constraint you can express in a model is enforced. This includes ranges, patterns, and enumerations.
from typing import Literal
from pydantic import BaseModel, Field
from pydantic_ai import Agent
class Ticket(BaseModel):
category: Literal["billing", "outage", "account", "other"]
urgency: int = Field(ge=1, le=5, description="1 is lowest, 5 is highest")
triage = Agent(
"openai:gpt-4o-mini",
output_type=Ticket,
instructions="Classify the customer message as a support ticket.",
)
result = triage.run_sync("The site is down for all customers.")
print(result.output)Compare this with the earlier manual version. There, the schema lived in a prose system prompt (Reply with JSON like ...) and the validation lived in a separate class, so the two could drift apart. Here the Ticket class is the single source of truth. The Field descriptions are sent to the model, and the Literal and the ge/le bounds are checked on the way back.
Tools with typed arguments
PydanticAI uses a decorator to register tools. It reads the function signature and docstring and builds the JSON schema for you. In the SDK example you wrote that schema as a nested dictionary.
from pydantic_ai import Agent
agent = Agent(
"openai:gpt-4o-mini",
instructions="Answer weather questions using the tool. Be brief.",
)
@agent.tool_plain
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
# A real tool would call a weather API here.
return f"It is 18 degrees and cloudy in {city}."
result = agent.run_sync("What is the weather in Paris?")
print(result.output)@agent.tool_plain registers a tool that needs no access to run-time context. When the model requests get_weather, the framework validates the arguments against the signature, calls your function, sends the return value back to the model, and repeats until the model gives a final answer. That is the agent loop you wrote yourself earlier, supplied by the framework.
The docstring is not decoration. It becomes the tool description the model reads, so a vague docstring leads to poor tool choices.
Dependencies and run context
Tools often need things like a database connection or an HTTP client. Hard-coding them as globals makes tests difficult. PydanticAI handles this with typed dependencies, passed per run.
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext
@dataclass
class Deps:
customer_id: int
orders: dict[int, list[str]]
agent = Agent(
"openai:gpt-4o-mini",
deps_type=Deps,
instructions="Help the customer with questions about their orders.",
)
@agent.tool
def list_orders(ctx: RunContext[Deps]) -> list[str]:
"""List the order names for the current customer."""
return ctx.deps.orders.get(ctx.deps.customer_id, [])
deps = Deps(customer_id=7, orders={7: ["keyboard", "monitor"]})
result = agent.run_sync("What did I order?", deps=deps)
print(result.output)Notes on how this works:
deps_typedeclares the dependency type. A type checker can then verify thatctx.depshas the fields you use.@agent.tool(without_plain) means the function receives aRunContextas its first argument. The context is not part of the schema the model sees.- You pass real dependencies in production and fake ones in tests, with no global state.
Testing without a real model
Typed dependencies pair with a test model. PydanticAI ships TestModel, which calls your tools and fabricates schema-valid output without a network call.
from pydantic_ai.models.test import TestModel
with agent.override(model=TestModel()):
result = agent.run_sync("What did I order?", deps=deps)
print(result.output)TestModel does not check that the model would make good decisions. It checks that your tools, schemas, and wiring run without errors. Use it for fast unit tests, and keep a small number of tests against a real model for behavior.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `UnexpectedModelBehavior` after several attempts | The model could not satisfy the output type within the retry limit | Simplify the type, add field descriptions, or raise the retry count |
| `AttributeError: ... has no attribute 'data'` | Code written for an older release | Use `result.output` and `output_type` on recent versions |
| Tool is never called | Vague docstring or missing type hints | Write a clear docstring and annotate every parameter |
| Model error about a missing API key | Environment variable not set | Export `OPENAI_API_KEY` (or the key for your chosen provider) |
| Type checker rejects `ctx.deps.field` | `deps_type` missing or does not match the `RunContext[...]` parameter | Pass `deps_type` to `Agent` and match it in the tool signature |
Trade-offs
PydanticAI gives you the least abstraction of the three frameworks, and that is its main appeal. A request is still close to the provider call, and the types make the code easy to read and check. If you already use Pydantic and FastAPI, the style will feel familiar.
It also has costs.
- Fewer integrations. It does not ship the large catalog of loaders, vector stores, and retrievers that LangChain and LlamaIndex do. For a retrieval-heavy project, you will write more yourself or combine it with another library.
- Hidden retries. Validation retries cost tokens and latency. Log them, or limit the retry count.
- API change. The project is young, and the renamed fields above show it. Pin the version.
- Validation is not truth. A reply can match your schema and still be wrong.
urgency=5is valid whether or not the outage deserves it.
Exercise
Your support-triage agent returns urgency values of 7 even though the scale is 1 to 5, and you are using a plain str output with manual JSON parsing. Describe how moving to PydanticAI with output_type=Ticket and Field(ge=1, le=5) changes what happens when the model returns 7, and name one cost of this approach.
Show answer
The framework validates the reply against Ticket. A value of 7 violates le=5, so validation fails and PydanticAI sends the error message back to the model and asks again, up to the retry limit. If the model corrects itself, your code receives a valid Ticket. If it does not, an exception is raised instead of a bad value reaching your code. One cost is that each retry is an extra model call, which adds token cost and latency and is not visible unless you log it.
Exercise
What is the difference between @agent.tool_plain and @agent.tool, and why would you choose the second one for a tool that queries a database?
Show answer
@agent.tool_plain registers a function that takes only the model's arguments. @agent.tool registers a function whose first parameter is a RunContext, which gives access to ctx.deps, the typed dependencies passed to the run. A database tool should use @agent.tool so the connection comes in through deps instead of a global, which keeps the tool testable with fake dependencies and lets a type checker verify the fields you use.