Building AI Agents with Pydantic AI
Pydantic AI is a Python agent framework for building production-grade Generative AI applications.
This skill provides patterns, architecture guidance, and tested code examples for building applications with Pydantic AI.
When to Use This Skill
Invoke this skill when:
- User asks to build an AI agent, create an LLM-powered app, or mentions Pydantic AI
- User wants to add tools, capabilities (thinking, web search), or structured output to an agent
- User asks to define agents from YAML/JSON specs or use template strings
- User wants to stream agent events, delegate between agents, or test agent behavior
- Code imports
pydantic_ai or references Pydantic AI classes (Agent, RunContext, Tool)
- User asks about hooks, lifecycle interception, or agent observability with Logfire
- The agent design includes optional instructions, specialist workflows, long-tail tools, or any context the model does not need on most turns
Do not use this skill for:
- The Pydantic validation library alone (
pydantic/BaseModel without agents)
- Other AI frameworks (LangChain, LlamaIndex, CrewAI, AutoGen)
- General Python development unrelated to AI agents
Quick-Start Patterns
Create a Basic Agent
from pydantic_ai import Agent
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Be concise, reply with one sentence.',
)
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""
Add Tools to an Agent
import random
from pydantic_ai import Agent, RunContext
agent = Agent(
'google:gemini-3-flash-preview',
deps_type=str,
instructions=(
"You're a dice game, you should roll the die and see if the number "
"you get back matches the user's guess. If so, tell them they're a winner. "
"Use the player's name in the response."
),
)
@agent.tool_plain
def roll_dice() -> str:
"""Roll a six-sided die and return the result."""
return str(random.randint(1, 6))
@agent.tool
def get_player_name(ctx: RunContext[str]) -> str:
"""Get the player's name."""
return ctx.deps
dice_result = agent.run_sync('My guess is 4', deps='Anne')
print(dice_result.output)
#> Congratulations Anne, you guessed correctly! You're a winner!
Structured Output with Pydantic Models
from pydantic import BaseModel
from pydantic_ai import Agent
class CityLocation(BaseModel):
city: str
country: str
agent = Agent('google:gemini-3-flash-preview', output_type=CityLocation)
result = agent.run_sync('Where were the olympics held in 2012?')
print(result.output)
#> city='London' country='United Kingdom'
print(result.usage)
#> RunUsage(input_tokens=57, output_tokens=8, requests=1)
Dependency Injection
from datetime import date
from pydantic_ai import Agent, RunContext
agent = Agent(
'openai:gpt-5.2',
deps_type=str,
instructions="Use the customer's name while replying to them.",
)
@agent.instructions
def add_the_users_name(ctx: RunContext[str]) -> str:
return f"The user's name is {ctx.deps}."
@agent.instructions
def add_the_date() -> str:
return f'The date is {date.today()}.'
result = agent.run_sync('What is the date?', deps='Frank')
print(result.output)
#> Hello Frank, the date today is 2032-01-02.
Testing with TestModel
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel
my_agent = Agent('openai:gpt-5.2', instructions='...')
async def test_my_agent():
"""Unit test for my_agent, to be run by pytest."""
m = TestModel()
with my_agent.override(model=m):
result = await my_agent.run('Testing my agent...')
assert result.output == 'success (no tool calls)'
assert m.last_model_request_parameters.function_tools == []
Use Capabilities
Capabilities are reusable, composable units of agent behavior — bundling tools, hooks, instructions, and model settings.
from pydantic_ai import Agent
from pydantic_ai.capabilities import Thinking, WebSearch
agent = Agent(
'anthropic:claude-opus-4-6',
instructions='You are a research assistant. Be thorough and cite sources.',
capabilities=[
Thinking(effort='high'),
WebSearch(),
],
)
Add Lifecycle Hooks
Use Hooks to intercept model requests, tool calls, and runs with decorators — no subclassing needed.
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities.hooks import Hooks
from pydantic_ai.models import ModelRequestContext
hooks = Hooks()
@hooks.on.before_model_request
async def log_request(ctx: RunContext[None], request_context: ModelRequestContext) -> ModelRequestContext:
print(f'Sending {len(request_context.messages)} messages')
return request_context
agent = Agent('openai:gpt-5.2', capabilities=[hooks])
Define Agent from YAML Spec
Use Agent.from_file to load agents from YAML or JSON — no Python agent construction code needed.
from pydantic_ai import Agent
# agent.yaml:
# model: anthropic:claude-opus-4-6
# instructions: You are a helpful research assistant.
# capabilities:
# - WebSearch
# - Thinking:
# effort: high
agent = Agent.from_file('agent.yaml')
Task Routing Table
Load only the most relevant reference first. Read additional references only if the task spans multiple areas.
| I want to... |
Reference |
| Create/configure agents, choose output types, use deps, define specs, or pick run methods |
Agents Core |
| Bundle reusable behavior or intercept lifecycle events |
Capabilities and Hooks |
Decide what should load eagerly vs on demand, apply progressive disclosure, defer capability loading, or explain load_capability |
Capabilities on Demand |
| Add function tools, toolsets, MCP servers, or explicit search tools |
Tools Core |
| Use provider-native web search, web fetch, or code execution |
Native Tools |
Use advanced tool features such as approval, retries, ToolReturn, validators, timeouts, or tool search |
Tools Advanced |
| Work with multimodal input, message history, or context trimming |
Input and History |
| Test or debug agent behavior |
Testing and Debugging |
| Coordinate multiple agents or build graph workflows |
Orchestration and Integrations |
| Call the model directly, expose A2A, use durable execution, embeddings, evals, or third-party integrations |
Orchestration and Integrations |
| Compare abstractions, output modes, decorators, or model-string patterns |
Architecture and Decision Guide |
Follow an older link into COMMON-TASKS.md |
Task Reference Map |
Architecture and Decisions
Load Architecture and Decision Guide only when the user is choosing between abstractions or wants comparison tables and decision trees:
| Topic |
What it covers |
| Decision Trees |
Tool registration, output modes, multi-agent patterns, capabilities, testing approaches, extensibility |
| Comparison Tables |
Output modes, model provider prefixes, tool decorators, built-in capabilities, agent methods |
| Architecture Overview |
Execution flow, generic types, construction patterns, lifecycle hooks, model string format |
Quick reference — model string format: "provider:model-name" (e.g., "openai:gpt-5.2", "anthropic:claude-sonnet-4-6", "google:gemini-3-pro-preview")
Quick reference — key agent methods: run(), run_sync(), run_stream(), run_stream_sync(), run_stream_events(), iter()
Key Practices
- Python 3.10+ compatibility required
- Progressive disclosure by default: For every capability, explicitly consider whether
defer_loading=True would benefit the agent before choosing eager loading. Do not eagerly load specialist instructions, rarely used tool schemas, or domain context unless the model needs them on most turns. Prefer capabilities on demand for named instruction+tool bundles, and tool search for large flat tool catalogs.
- Observability: Pydantic AI has first-class integration with Logfire for tracing agent runs, tool calls, and model requests. Add it with
logfire.instrument_pydantic_ai(). For deeper HTTP-level visibility, logfire.instrument_httpx(capture_all=True) captures the exact payloads sent to model providers.
- Testing: Use
TestModel for deterministic tests, FunctionModel for custom logic
Common Gotchas
These are mistakes agents commonly make with Pydantic AI. Getting these wrong produces silent failures or confusing errors.
@agent.tool requires RunContext as first param; @agent.tool_plain must not have it. Mixing these up causes runtime errors. Use tool_plain when you don't need deps, usage, or messages.
- Model strings need the provider prefix:
'openai:gpt-5.2' not 'gpt-5.2'. Without the prefix, Pydantic AI can't resolve the provider.
TestModel requires agent.override(): Don't set agent.model directly. Always use the context manager: with agent.override(model=TestModel()):.
str in output_type allows plain text to end the run: If your union includes str (or no output_type is set), the model can return plain text instead of structured output. Omit str from the union to force tool-based output.
- Hook decorator names on
.on don't repeat on_: Use hooks.on.run_error and hooks.on.model_request_error — not hooks.on.on_run_error.
history_processors is deprecated; use capabilities=[ProcessHistory(p), ...], or hook before_model_request directly via capabilities=[Hooks(before_model_request=fn)]. ProcessHistory is a thin wrapper around that hook — the hook itself is the underlying primitive. The kwarg still works in 1.x but emits a PydanticAIDeprecationWarning and will be removed in v2.
Task-Family References
Load exactly one of these unless the task clearly spans multiple families:
| Task family |
Reference |
| Core agent setup, output, deps, specs, models, run methods |
Agents Core |
| Capabilities, hooks, and reusable behavior |
Capabilities and Hooks |
Progressive disclosure, deferred capabilities, capabilities on demand, and load_capability semantics |
Capabilities on Demand |
| Function tools, toolsets, MCP, explicit search tools |
Tools Core |
| Provider-native tools |
Native Tools |
| Approval, retries, validators, timeouts, rich tool returns, tool search, and tool-level deferred loading |
Tools Advanced |
| Multimodal input, message history, history processors |
Input and History |
| Testing, request inspection, and Logfire debugging |
Testing and Debugging |
| Multi-agent patterns, graphs, direct API, A2A, durable execution, embeddings, evals, third-party integrations |
Orchestration and Integrations |
Use Task Reference Map only for compatibility with older links or when you need a pointer from an old section name to the new file.
1---2name: building-pydantic-ai-agents3description: Build AI agents with Pydantic AI — tools, capabilities (including on-demand loading), structured output, streaming, testing, and multi-agent patterns. Use when the user mentions Pydantic AI, imports pydantic_ai, or asks to build an AI agent, add tools/capabilities, defer capability loading, stream output, define agents from YAML, or test agent behavior.4license: MIT5---6
7# Building AI Agents with Pydantic AI
8
9Pydantic AI is a Python agent framework for building production-grade Generative AI applications.
10This skill provides patterns, architecture guidance, and tested code examples for building applications with Pydantic AI.
11
12## When to Use This Skill
13
14Invoke this skill when:
15- User asks to build an AI agent, create an LLM-powered app, or mentions Pydantic AI
16- User wants to add tools, capabilities (thinking, web search), or structured output to an agent
17- User asks to define agents from YAML/JSON specs or use template strings
18- User wants to stream agent events, delegate between agents, or test agent behavior
19- Code imports `pydantic_ai` or references Pydantic AI classes (`Agent`, `RunContext`, `Tool`)
20- User asks about hooks, lifecycle interception, or agent observability with Logfire
21- The agent design includes optional instructions, specialist workflows, long-tail tools, or any context the model does not need on most turns
22
23Do **not** use this skill for:
24- The Pydantic validation library alone (`pydantic`/`BaseModel` without agents)
25- Other AI frameworks (LangChain, LlamaIndex, CrewAI, AutoGen)
26- General Python development unrelated to AI agents
27
28## Quick-Start Patterns
29
30### Create a Basic Agent
31
32```python
33from pydantic_ai import Agent
34
35agent = Agent(
36 'anthropic:claude-sonnet-4-6',
37 instructions='Be concise, reply with one sentence.',
38)
39
40result = agent.run_sync('Where does "hello world" come from?')
41print(result.output)
42"""
43The first known use of "hello, world" was in a 1974 textbook about the C programming language.
44"""
45```
46
47### Add Tools to an Agent
48
49```python
50import random
51
52from pydantic_ai import Agent, RunContext
53
54agent = Agent(
55 'google:gemini-3-flash-preview',
56 deps_type=str,
57 instructions=(
58 "You're a dice game, you should roll the die and see if the number "
59 "you get back matches the user's guess. If so, tell them they're a winner. "
60 "Use the player's name in the response."
61 ),
62)
63
64
65@agent.tool_plain
66def roll_dice() -> str:
67 """Roll a six-sided die and return the result."""
68 return str(random.randint(1, 6))
69
70
71@agent.tool
72def get_player_name(ctx: RunContext[str]) -> str:
73 """Get the player's name."""
74 return ctx.deps
75
76
77dice_result = agent.run_sync('My guess is 4', deps='Anne')
78print(dice_result.output)
79#> Congratulations Anne, you guessed correctly! You're a winner!
80```
81
82### Structured Output with Pydantic Models
83
84```python
85from pydantic import BaseModel
86
87from pydantic_ai import Agent
88
89
90class CityLocation(BaseModel):
91 city: str
92 country: str
93
94
95agent = Agent('google:gemini-3-flash-preview', output_type=CityLocation)
96result = agent.run_sync('Where were the olympics held in 2012?')
97print(result.output)
98#> city='London' country='United Kingdom'
99print(result.usage)
100#> RunUsage(input_tokens=57, output_tokens=8, requests=1)
101```
102
103### Dependency Injection
104
105```python
106from datetime import date
107
108from pydantic_ai import Agent, RunContext
109
110agent = Agent(
111 'openai:gpt-5.2',
112 deps_type=str,
113 instructions="Use the customer's name while replying to them.",
114)
115
116
117@agent.instructions
118def add_the_users_name(ctx: RunContext[str]) -> str:
119 return f"The user's name is {ctx.deps}."
120
121
122@agent.instructions
123def add_the_date() -> str:
124 return f'The date is {date.today()}.'
125
126
127result = agent.run_sync('What is the date?', deps='Frank')
128print(result.output)
129#> Hello Frank, the date today is 2032-01-02.
130```
131
132### Testing with TestModel
133
134```python
135from pydantic_ai import Agent
136from pydantic_ai.models.test import TestModel
137
138my_agent = Agent('openai:gpt-5.2', instructions='...')
139
140
141async def test_my_agent():
142 """Unit test for my_agent, to be run by pytest."""
143 m = TestModel()
144 with my_agent.override(model=m):
145 result = await my_agent.run('Testing my agent...')
146 assert result.output == 'success (no tool calls)'
147 assert m.last_model_request_parameters.function_tools == []
148```
149
150### Use Capabilities
151
152Capabilities are reusable, composable units of agent behavior — bundling tools, hooks, instructions, and model settings.
153
154```python
155from pydantic_ai import Agent
156from pydantic_ai.capabilities import Thinking, WebSearch
157
158agent = Agent(
159 'anthropic:claude-opus-4-6',
160 instructions='You are a research assistant. Be thorough and cite sources.',
161 capabilities=[
162 Thinking(effort='high'),
163 WebSearch(),
164 ],
165)
166```
167
168### Add Lifecycle Hooks
169
170Use `Hooks` to intercept model requests, tool calls, and runs with decorators — no subclassing needed.
171
172```python
173from pydantic_ai import Agent, RunContext
174from pydantic_ai.capabilities.hooks import Hooks
175from pydantic_ai.models import ModelRequestContext
176
177hooks = Hooks()
178
179
180@hooks.on.before_model_request
181async def log_request(ctx: RunContext[None], request_context: ModelRequestContext) -> ModelRequestContext:
182 print(f'Sending {len(request_context.messages)} messages')
183 return request_context
184
185
186agent = Agent('openai:gpt-5.2', capabilities=[hooks])
187```
188
189### Define Agent from YAML Spec
190
191Use `Agent.from_file` to load agents from YAML or JSON — no Python agent construction code needed.
192
193```python
194from pydantic_ai import Agent
195
196# agent.yaml:
197# model: anthropic:claude-opus-4-6
198# instructions: You are a helpful research assistant.
199# capabilities:
200# - WebSearch
201# - Thinking:
202# effort: high
203
204agent = Agent.from_file('agent.yaml')
205```
206
207## Task Routing Table
208
209Load only the most relevant reference first. Read additional references only if the task spans multiple areas.
210
211| I want to... | Reference |
212|---|---|
213| Create/configure agents, choose output types, use deps, define specs, or pick run methods | [Agents Core](./references/AGENTS-CORE.md) |
214| Bundle reusable behavior or intercept lifecycle events | [Capabilities and Hooks](./references/CAPABILITIES-AND-HOOKS.md) |
215| Decide what should load eagerly vs on demand, apply progressive disclosure, defer capability loading, or explain `load_capability` | [Capabilities on Demand](./references/ON-DEMAND-CAPABILITIES.md) |
216| Add function tools, toolsets, MCP servers, or explicit search tools | [Tools Core](./references/TOOLS-CORE.md) |
217| Use provider-native web search, web fetch, or code execution | [Native Tools](./references/NATIVE-TOOLS.md) |
218| Use advanced tool features such as approval, retries, `ToolReturn`, validators, timeouts, or tool search | [Tools Advanced](./references/TOOLS-ADVANCED.md) |
219| Work with multimodal input, message history, or context trimming | [Input and History](./references/INPUT-AND-HISTORY.md) |
220| Test or debug agent behavior | [Testing and Debugging](./references/TESTING-AND-DEBUGGING.md) |
221| Coordinate multiple agents or build graph workflows | [Orchestration and Integrations](./references/ORCHESTRATION-AND-INTEGRATIONS.md#coordinate-multiple-agents) |
222| Call the model directly, expose A2A, use durable execution, embeddings, evals, or third-party integrations | [Orchestration and Integrations](./references/ORCHESTRATION-AND-INTEGRATIONS.md) |
223| Compare abstractions, output modes, decorators, or model-string patterns | [Architecture and Decision Guide](./references/ARCHITECTURE.md) |
224| Follow an older link into `COMMON-TASKS.md` | [Task Reference Map](./references/COMMON-TASKS.md) |
225
226## Architecture and Decisions
227
228Load [Architecture and Decision Guide](./references/ARCHITECTURE.md) only when the user is choosing between abstractions or wants comparison tables and decision trees:
229
230| Topic | What it covers |
231|---|---|
232| Decision Trees | Tool registration, output modes, multi-agent patterns, capabilities, testing approaches, extensibility |
233| Comparison Tables | Output modes, model provider prefixes, tool decorators, built-in capabilities, agent methods |
234| Architecture Overview | Execution flow, generic types, construction patterns, lifecycle hooks, model string format |
235
236**Quick reference — model string format:** `"provider:model-name"` (e.g., `"openai:gpt-5.2"`, `"anthropic:claude-sonnet-4-6"`, `"google:gemini-3-pro-preview"`)
237
238**Quick reference — key agent methods:** `run()`, `run_sync()`, `run_stream()`, `run_stream_sync()`, `run_stream_events()`, `iter()`
239
240## Key Practices
241
242- **Python 3.10+** compatibility required
243- **Progressive disclosure by default**: For every capability, explicitly consider whether `defer_loading=True` would benefit the agent before choosing eager loading. Do not eagerly load specialist instructions, rarely used tool schemas, or domain context unless the model needs them on most turns. Prefer capabilities on demand for named instruction+tool bundles, and tool search for large flat tool catalogs.
244- **Observability**: Pydantic AI has first-class integration with Logfire for tracing agent runs, tool calls, and model requests. Add it with `logfire.instrument_pydantic_ai()`. For deeper HTTP-level visibility, `logfire.instrument_httpx(capture_all=True)` captures the exact payloads sent to model providers.
245- **Testing**: Use `TestModel` for deterministic tests, `FunctionModel` for custom logic
246
247## Common Gotchas
248
249These are mistakes agents commonly make with Pydantic AI. Getting these wrong produces silent failures or confusing errors.
250
251- **`@agent.tool` requires `RunContext` as first param**; `@agent.tool_plain` must **not** have it. Mixing these up causes runtime errors. Use `tool_plain` when you don't need deps, usage, or messages.
252- **Model strings need the provider prefix**: `'openai:gpt-5.2'` not `'gpt-5.2'`. Without the prefix, Pydantic AI can't resolve the provider.
253- **`TestModel` requires `agent.override()`**: Don't set `agent.model` directly. Always use the context manager: `with agent.override(model=TestModel()):`.
254- **`str` in output_type allows plain text to end the run**: If your union includes `str` (or no `output_type` is set), the model can return plain text instead of structured output. Omit `str` from the union to force tool-based output.
255- **Hook decorator names on `.on` don't repeat `on_`**: Use `hooks.on.run_error` and `hooks.on.model_request_error` — not `hooks.on.on_run_error`.
256- **`history_processors` is deprecated; use `capabilities=[ProcessHistory(p), ...]`**, or hook `before_model_request` directly via `capabilities=[Hooks(before_model_request=fn)]`. `ProcessHistory` is a thin wrapper around that hook — the hook itself is the underlying primitive. The kwarg still works in 1.x but emits a `PydanticAIDeprecationWarning` and will be removed in v2.
257
258## Task-Family References
259
260Load exactly one of these unless the task clearly spans multiple families:
261
262| Task family | Reference |
263|---|---|
264| Core agent setup, output, deps, specs, models, run methods | [Agents Core](./references/AGENTS-CORE.md) |
265| Capabilities, hooks, and reusable behavior | [Capabilities and Hooks](./references/CAPABILITIES-AND-HOOKS.md) |
266| Progressive disclosure, deferred capabilities, capabilities on demand, and `load_capability` semantics | [Capabilities on Demand](./references/ON-DEMAND-CAPABILITIES.md) |
267| Function tools, toolsets, MCP, explicit search tools | [Tools Core](./references/TOOLS-CORE.md) |
268| Provider-native tools | [Native Tools](./references/NATIVE-TOOLS.md) |
269| Approval, retries, validators, timeouts, rich tool returns, tool search, and tool-level deferred loading | [Tools Advanced](./references/TOOLS-ADVANCED.md) |
270| Multimodal input, message history, history processors | [Input and History](./references/INPUT-AND-HISTORY.md) |
271| Testing, request inspection, and Logfire debugging | [Testing and Debugging](./references/TESTING-AND-DEBUGGING.md) |
272| Multi-agent patterns, graphs, direct API, A2A, durable execution, embeddings, evals, third-party integrations | [Orchestration and Integrations](./references/ORCHESTRATION-AND-INTEGRATIONS.md) |
273
274Use [Task Reference Map](./references/COMMON-TASKS.md) only for compatibility with older links or when you need a pointer from an old section name to the new file.