0
# Core Agent Framework
1
2
The foundational agent system for creating AI agents with typed dependencies, structured outputs, and comprehensive error handling. The Agent class is the central component that orchestrates interactions between users, models, and tools.
3
4
## Capabilities
5
6
### Agent Creation and Configuration
7
8
Create agents with flexible configuration options including model selection, system prompts, result types, tools, and dependency injection.
9
10
```python { .api }
11
class Agent[AgentDepsT, OutputDataT]:
12
"""
13
Main agent class for building AI agents.
14
15
Type Parameters:
16
- AgentDepsT: Type of dependencies passed to tools and system prompt functions
17
- OutputDataT: Type of the agent's output data
18
"""
19
def __init__(
20
self,
21
model: Model | KnownModelName | str | None = None,
22
*,
23
output_type: OutputSpec[OutputDataT] = str,
24
instructions: str | SystemPromptFunc[AgentDepsT] | Sequence[str | SystemPromptFunc[AgentDepsT]] | None = None,
25
system_prompt: str | Sequence[str] = (),
26
deps_type: type[AgentDepsT] = NoneType,
27
name: str | None = None,
28
model_settings: ModelSettings | None = None,
29
retries: int = 1,
30
output_retries: int | None = None,
31
tools: Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] = (),
32
builtin_tools: Sequence[AbstractBuiltinTool] = (),
33
prepare_tools: ToolsPrepareFunc[AgentDepsT] | None = None,
34
prepare_output_tools: ToolsPrepareFunc[AgentDepsT] | None = None,
35
toolsets: Sequence[AbstractToolset[AgentDepsT] | ToolsetFunc[AgentDepsT]] | None = None,
36
defer_model_check: bool = False
37
):
38
"""
39
Initialize an agent.
40
41
Parameters:
42
- model: Model instance, known model name, or string (can be None)
43
- output_type: Expected output specification (replaces result_type)
44
- instructions: Main instruction string or function (replaces system_prompt as primary)
45
- system_prompt: Additional system prompt strings
46
- deps_type: Type of dependencies for type checking
47
- name: Optional name for the agent
48
- model_settings: Default model settings
49
- retries: Number of retries on failure
50
- output_retries: Number of retries for output validation
51
- tools: Sequence of tools available to the agent
52
- builtin_tools: Sequence of built-in tools
53
- prepare_tools: Function to prepare tools before use
54
- prepare_output_tools: Function to prepare output tools
55
- toolsets: Sequence of toolsets for advanced tool management
56
- defer_model_check: Whether to defer model validation
57
"""
58
```
59
60
### Synchronous Execution
61
62
Run agents synchronously for simple use cases and testing.
63
64
```python { .api }
65
def run_sync(
66
self,
67
user_prompt: str,
68
*,
69
message_history: list[ModelMessage] | None = None,
70
deps: AgentDepsT = None,
71
model_settings: ModelSettings | None = None
72
) -> AgentRunResult[OutputDataT]:
73
"""
74
Run the agent synchronously.
75
76
Parameters:
77
- user_prompt: User's input message
78
- message_history: Previous conversation messages
79
- deps: Dependencies to pass to tools and system prompt
80
- model_settings: Model settings for this run
81
82
Returns:
83
AgentRunResult containing the agent's response and metadata
84
"""
85
```
86
87
### Asynchronous Execution
88
89
Run agents asynchronously for production applications and concurrent operations.
90
91
```python { .api }
92
async def run(
93
self,
94
user_prompt: str,
95
*,
96
message_history: list[ModelMessage] | None = None,
97
deps: AgentDepsT = None,
98
model_settings: ModelSettings | None = None
99
) -> AgentRunResult[OutputDataT]:
100
"""
101
Run the agent asynchronously.
102
103
Parameters:
104
- user_prompt: User's input message
105
- message_history: Previous conversation messages
106
- deps: Dependencies to pass to tools and system prompt
107
- model_settings: Model settings for this run
108
109
Returns:
110
AgentRunResult containing the agent's response and metadata
111
"""
112
```
113
114
### Agent Run Management
115
116
Stateful agent runs that can be iterated over for step-by-step execution.
117
118
```python { .api }
119
class AgentRun[AgentDepsT, OutputDataT]:
120
"""
121
Stateful, async-iterable run of an agent.
122
"""
123
def __init__(
124
self,
125
agent: AbstractAgent[AgentDepsT, OutputDataT],
126
user_prompt: str,
127
*,
128
message_history: list[ModelMessage] | None = None,
129
deps: AgentDepsT = None,
130
model_settings: ModelSettings | None = None
131
): ...
132
133
async def __anext__(self) -> None:
134
"""Advance the run by one step."""
135
136
async def final_result(self) -> AgentRunResult[OutputDataT]:
137
"""Get the final result after completion."""
138
```
139
140
### Result Handling
141
142
Comprehensive result objects containing agent responses, usage metrics, and execution metadata.
143
144
```python { .api }
145
class AgentRunResult[OutputDataT]:
146
"""
147
Result from completed agent run.
148
"""
149
data: OutputDataT
150
usage: RunUsage
151
messages: list[ModelMessage]
152
cost: float | None
153
timestamp: datetime
154
155
def is_complete(self) -> bool:
156
"""Check if the run completed successfully."""
157
158
def new_messages(self) -> list[ModelMessage]:
159
"""Get only new messages from this run."""
160
```
161
162
### Agent Variants
163
164
Specialized agent implementations for specific use cases.
165
166
```python { .api }
167
class WrapperAgent[AgentDepsT, OutputDataT]:
168
"""
169
Agent wrapper implementation for extending functionality.
170
"""
171
def __init__(
172
self,
173
wrapped_agent: AbstractAgent[AgentDepsT, OutputDataT]
174
): ...
175
176
class AbstractAgent[AgentDepsT, OutputDataT]:
177
"""
178
Abstract base class for all agent implementations.
179
"""
180
def model_name(self) -> str: ...
181
def deps_type(self) -> type[AgentDepsT]: ...
182
def result_type(self) -> type[OutputDataT]: ...
183
```
184
185
### Message Capture
186
187
Utilities for capturing and analyzing agent run messages for debugging and monitoring.
188
189
```python { .api }
190
def capture_run_messages(
191
agent: Agent[AgentDepsT, OutputDataT],
192
user_prompt: str,
193
*,
194
deps: AgentDepsT = None,
195
model_settings: ModelSettings | None = None
196
) -> list[ModelMessage]:
197
"""
198
Capture messages from an agent run for debugging.
199
200
Parameters:
201
- agent: Agent to run
202
- user_prompt: User's input message
203
- deps: Dependencies to pass to the agent
204
- model_settings: Model settings for the run
205
206
Returns:
207
List of all messages from the agent run
208
"""
209
```
210
211
### End Strategies
212
213
Configuration for handling tool calls when a final result is found.
214
215
```python { .api }
216
class EndStrategy(str, Enum):
217
"""
218
Strategy for handling tool calls when final result found.
219
"""
220
EARLY = 'early' # End immediately when result found
221
EXHAUST_TOOLS = 'exhaust_tools' # Complete all pending tool calls
222
```
223
224
## Usage Examples
225
226
### Basic Agent
227
228
```python
229
from pydantic_ai import Agent
230
from pydantic_ai.models import OpenAIModel
231
232
# Create a simple agent
233
agent = Agent(
234
model=OpenAIModel('gpt-4'),
235
system_prompt='You are a helpful math tutor.'
236
)
237
238
# Run synchronously
239
result = agent.run_sync('What is 15 * 23?')
240
print(result.data) # "345"
241
```
242
243
### Agent with Dependencies
244
245
```python
246
from pydantic_ai import Agent, RunContext
247
from dataclasses import dataclass
248
249
@dataclass
250
class DatabaseDeps:
251
database_url: str
252
api_key: str
253
254
def get_user_info(ctx: RunContext[DatabaseDeps], user_id: int) -> str:
255
# Access dependencies through ctx.deps
256
db_url = ctx.deps.database_url
257
api_key = ctx.deps.api_key
258
# Fetch user info from database
259
return f"User {user_id} info from {db_url}"
260
261
agent = Agent(
262
model=OpenAIModel('gpt-4'),
263
system_prompt='You help with user queries.',
264
tools=[get_user_info],
265
deps_type=DatabaseDeps
266
)
267
268
deps = DatabaseDeps('postgresql://...', 'secret-key')
269
result = agent.run_sync('Get info for user 123', deps=deps)
270
```
271
272
### Structured Output Agent
273
274
```python
275
from pydantic_ai import Agent
276
from pydantic import BaseModel
277
278
class WeatherInfo(BaseModel):
279
location: str
280
temperature: float
281
condition: str
282
humidity: int
283
284
agent = Agent(
285
model=OpenAIModel('gpt-4'),
286
system_prompt='Extract weather information.',
287
result_type=WeatherInfo
288
)
289
290
result = agent.run_sync('The weather in Paris is sunny, 22°C with 65% humidity')
291
print(result.data.location) # "Paris"
292
print(result.data.temperature) # 22.0
293
```