Sub topic 10
PydanticAI: typed, validated agents
This chapter assumes you can write basic Python with classes and virtual environments. It also assumes you have called a chat API before and have seen Pydantic models. You should know what structured output and tool calling are from the earlier chapters.
The design focus
PydanticAI is built around one idea: the model's reply should be a typed Python object, and your code should be able to rely on that type. LangChain focuses on composable components and integrations. LlamaIndex focuses on data ingestion and retrieval. PydanticAI focuses on the contract between your code and the model.
Earlier in this tutorial you wrote the manual version of this. You asked for JSON, parsed the reply, and caught a ValidationError. PydanticAI automates that loop.
A minimal 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)The model string "openai:gpt-4o-mini" names the provider and the model. Changing the provider is mostly a change to this string, plus an installed extra and an API key. The output_type argument tells the agent what shape the reply must have. result.output is a CityInfo instance, not a string.
What happens during a run
The agent sends your prompt along with a schema derived from CityInfo. When the reply arrives, it validates it against the model. If validation fails, the agent can send the error back to the model and ask it to try again. You write none of the retry code you wrote by hand earlier.
Tools and dependencies
PydanticAI also covers tool calling. You register a Python function as a tool, and the framework builds the schema from its type hints and runs the function when the model asks for it. The agent loop you wrote by hand in an earlier chapter, which called the tool and sent the result back, is handled for you.
For values a tool needs, such as a database connection, PydanticAI uses typed dependency injection. You declare a dependency type on the agent and the framework passes it into your tools. This keeps tools testable, because a test can supply a fake dependency instead of a real one.
Strengths and costs
| Aspect | What you get | What it costs |
|---|---|---|
| Typed output | Validated objects, fewer parsing bugs | Retries add extra model calls and cost |
| Tool schemas from type hints | Less schema boilerplate | Schemas are generated, so you must inspect them to see what the model gets |
| Provider strings | Easy provider switching | Provider-specific features may need extra settings |
| Smaller scope | Less dependency weight than a large framework | No built-in document indexing, so retrieval is up to you |
PydanticAI is a good fit when the main risk in your project is malformed or unexpected model output, and when your team already uses Pydantic. It is a weaker fit if your main task is indexing large document collections, where LlamaIndex does more for you.
Common errors
- Using old names. Examples written for early versions fail on current releases because attribute and argument names changed. See the API churn chapter for how to manage this.
- Missing credentials. The agent reads the provider's usual environment variable, such as
OPENAI_API_KEY. Without it, the first run fails. - Over-strict models. A schema with many required fields can cause repeated retries. Make fields optional when the data may genuinely be absent.
- Assuming validation means correctness. A reply can match the type and still be wrong.
urgency: 1is a valid integer for a site-wide outage.
Exercise
A teammate says that using output_type=CityInfo guarantees the model's answer is factually correct. What is wrong with that claim, and what does the agent actually guarantee?
Show answer
Validation only checks that the reply has the right shape and field types. The model can still return a well-formed but wrong answer, such as the wrong country. The agent guarantees that result.output is a valid CityInfo object, retrying when validation fails, but you still need other checks for factual accuracy.
Exercise
Name two things the hand-written structured-output code from the earlier chapter did that PydanticAI now does for you.
Show answer
It builds the output schema from the Pydantic model, so you no longer describe the JSON format in the system prompt. It also validates the reply and retries with the error message on failure, so you no longer write the try/except and retry logic yourself.