pypi-pydantic-ai

Description
Agent Framework / shim to use Pydantic with LLMs
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-pydantic-ai@0.8.0

agent.md docs/

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