Component brief / Developer Tools
Pydantic and PydanticAI: typed contracts for Python agents.
What it is
Pydantic lets you write a typed data contract, a list of fields and the kinds of values each field accepts. For example, a case summary can require case_id: int and needs_review: bool. Those Python type annotations tell Pydantic what to check when it reads input into a BaseModel. It can serialise the result, for example by turning it into JavaScript Object Notation (JSON), and generate JSON Schema, a machine-readable description that says which fields and value types the JSON contains. Pydantic models · Pydantic JSON Schema
PydanticAI is an agent framework built around the same type system. A tool is a function the agent can ask the application to run, such as load_case(case_id). PydanticAI uses the function's declared arguments to describe the tool to the model. A dependency is an object the application supplies, such as the repository that loads cases. The output type defines the expected result. In the example, the agent returns a CaseSummary object after validation. PydanticAI agents · Tools · Structured output
The packages remain separable: Pydantic is a general validation library; PydanticAI is only needed for agent execution.
Where it fits
Pydantic owns shape and type validation. It does not decide whether a fact is true or whether a caller is authorised. PydanticAI coordinates the model interaction, but domain services must still enforce identity, permissions, transactions and side-effect rules.
When to use it
Use Pydantic when:
- Python receives JSON, configuration, messages or external API data;
- one model should drive validation, serialisation and JSON Schema;
- nested contracts and useful validation errors reduce boundary code; or
- a FastAPI or data-processing application already uses Python typing.
Add PydanticAI when:
- the final answer must be a validated domain-shaped object;
- tools need typed arguments derived from Python functions;
- agents need explicit, testable dependencies such as repositories or user context; or
- switching between supported model providers should not rewrite the application contract.
Trade-offs
Pydantic validates the resulting structure, not the truth of its content. A valid Invoice(total=100) can still be factually wrong. Apply business invariants and evidence checks after structural validation.
Pydantic can use coercion to convert compatible values, such as the string "123" to the integer 123. Use strict mode when an input is required to contain the integer itself. Decide whether unknown fields are ignored, allowed or rejected. Pydantic models
PydanticAI makes typed agent code compact, but provider capabilities differ. Tool calling, native structured output, streaming and usage accounting are not uniform. Test the exact model-provider combination and define retry, token, tool and time limits.
A validated response can still vary between runs. Check tool inputs again where they reach business logic. Make writes idempotent where possible, so that retrying a request to add a case note leaves one note. Log decisions without including prompts or sensitive case data.
Alternatives
- Python dataclasses, TypedDict and jsonschema keep validation concerns separate with fewer framework conventions.
- Marshmallow or attrs may suit existing Python applications with established schema or class patterns.
- LangChain and LangGraph provide a broader integration ecosystem and explicit stateful orchestration.
- Microsoft Semantic Kernel offers a stronger fit when the surrounding application is primarily .NET.
Integration example
This application excerpt requires pydantic, pydantic-ai and a running Ollama service with the selected model downloaded. CaseRepository is your application's repository type; case_repository is an instance configured for the current caller. Its get_authorised(case_id) method must check access and return case text. Those application definitions are omitted below.
from pydantic import BaseModel, ConfigDict
from pydantic_ai import Agent, RunContext
class CaseSummary(BaseModel):
model_config = ConfigDict(extra="forbid")
case_id: int
summary: str
needs_review: bool
agent = Agent(
"ollama:qwen3",
deps_type=CaseRepository,
output_type=CaseSummary,
instructions="Summarise only the case returned by the tool.",
)
@agent.tool
def load_case(ctx: RunContext[CaseRepository], case_id: int) -> str:
return ctx.deps.get_authorised(case_id)
result = agent.run_sync("Summarise case 1842", deps=case_repository)
summary = result.output
The types make the boundaries visible, but get_authorised must still enforce the caller's access. Pin the model and test structured-output behaviour before using this path for automated decisions.
Correction, 15 November 2026. The example now reads the validated result from result.output. A line of article metadata previously appeared in the code block. PydanticAI output documentation
AI Disclosure
Researched and drafted with AI assistance, then reviewed by Søren Dalby. Sources are linked; errors may remain, and corrections are welcome.