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

tools.md docs/

1
# Tools and Function Calling
2
3
Flexible tool system enabling agents to call Python functions, access APIs, execute code, and perform web searches. Supports both built-in tools and custom function definitions with full type safety.
4
5
## Capabilities
6
7
### Tool Definition and Creation
8
9
Create custom tools from Python functions with automatic schema generation and type safety.
10
11
```python { .api }
12
class Tool[AgentDepsT]:
13
"""
14
Tool implementation with typed dependencies.
15
"""
16
def __init__(
17
self,
18
function: ToolFuncEither[AgentDepsT, Any],
19
*,
20
name: str | None = None,
21
description: str | None = None,
22
prepare: ToolPrepareFunc[AgentDepsT] | None = None
23
):
24
"""
25
Create a tool from a function.
26
27
Parameters:
28
- function: Function to wrap as a tool
29
- name: Override tool name (defaults to function name)
30
- description: Override tool description (defaults to docstring)
31
- prepare: Function to prepare tool before use
32
"""
33
34
def tool(
35
function: ToolFuncEither[AgentDepsT, Any] | None = None,
36
*,
37
name: str | None = None,
38
description: str | None = None,
39
prepare: ToolPrepareFunc[AgentDepsT] | None = None
40
) -> Tool[AgentDepsT]:
41
"""
42
Decorator to create a tool from a function.
43
44
Parameters:
45
- function: Function to wrap as a tool
46
- name: Override tool name
47
- description: Override tool description
48
- prepare: Function to prepare tool before use
49
50
Returns:
51
Tool instance that can be used with agents
52
"""
53
```
54
55
### Run Context
56
57
Context object passed to tools providing access to dependencies and run metadata.
58
59
```python { .api }
60
class RunContext[AgentDepsT]:
61
"""
62
Runtime context for tools and system prompt functions.
63
"""
64
deps: AgentDepsT
65
retry: int
66
tool_name: str
67
68
def set_messages(self, messages: list[ModelMessage]) -> None:
69
"""
70
Set messages in the conversation history.
71
72
Parameters:
73
- messages: List of messages to add to conversation
74
"""
75
```
76
77
### Built-in Web Search Tool
78
79
Search the web and retrieve search results for agents.
80
81
```python { .api }
82
class WebSearchTool:
83
"""
84
Web search functionality using DuckDuckGo.
85
"""
86
def __init__(
87
self,
88
*,
89
max_results: int = 5,
90
request_timeout: float = 10.0
91
):
92
"""
93
Initialize web search tool.
94
95
Parameters:
96
- max_results: Maximum number of search results to return
97
- request_timeout: Request timeout in seconds
98
"""
99
100
def search(
101
self,
102
query: str,
103
*,
104
user_location: WebSearchUserLocation | None = None
105
) -> list[dict[str, Any]]:
106
"""
107
Search the web for the given query.
108
109
Parameters:
110
- query: Search query string
111
- user_location: User location for localized results
112
113
Returns:
114
List of search result dictionaries with title, url, and snippet
115
"""
116
117
class WebSearchUserLocation(TypedDict):
118
"""Configuration for user location in web search."""
119
country: str
120
city: str | None
121
```
122
123
### Built-in Code Execution Tool
124
125
Execute Python code safely in a controlled environment.
126
127
```python { .api }
128
class CodeExecutionTool:
129
"""
130
Code execution functionality with safety controls.
131
"""
132
def __init__(
133
self,
134
*,
135
timeout: float = 30.0,
136
allowed_packages: list[str] | None = None
137
):
138
"""
139
Initialize code execution tool.
140
141
Parameters:
142
- timeout: Maximum execution time in seconds
143
- allowed_packages: List of allowed package imports (None = all allowed)
144
"""
145
146
def execute(
147
self,
148
code: str,
149
*,
150
globals_dict: dict[str, Any] | None = None
151
) -> dict[str, Any]:
152
"""
153
Execute Python code and return results.
154
155
Parameters:
156
- code: Python code to execute
157
- globals_dict: Global variables available to code
158
159
Returns:
160
Dictionary with 'result', 'output', and 'error' keys
161
"""
162
```
163
164
### Built-in URL Context Tool
165
166
Fetch and process content from URLs for agents.
167
168
```python { .api }
169
class UrlContextTool:
170
"""
171
URL content access functionality.
172
"""
173
def __init__(
174
self,
175
*,
176
request_timeout: float = 10.0,
177
max_content_length: int = 100000
178
):
179
"""
180
Initialize URL context tool.
181
182
Parameters:
183
- request_timeout: Request timeout in seconds
184
- max_content_length: Maximum content length to fetch
185
"""
186
187
def fetch_url(
188
self,
189
url: str
190
) -> dict[str, Any]:
191
"""
192
Fetch content from a URL.
193
194
Parameters:
195
- url: URL to fetch content from
196
197
Returns:
198
Dictionary with content, title, and metadata
199
"""
200
```
201
202
### Tool Function Types
203
204
Type definitions for different kinds of tool functions.
205
206
```python { .api }
207
ToolFuncContext[AgentDepsT, ToolParams] = Callable[
208
[RunContext[AgentDepsT], ToolParams],
209
Awaitable[Any] | Any
210
]
211
212
ToolFuncPlain[ToolParams] = Callable[
213
[ToolParams],
214
Awaitable[Any] | Any
215
]
216
217
ToolFuncEither[AgentDepsT, ToolParams] = (
218
ToolFuncContext[AgentDepsT, ToolParams] |
219
ToolFuncPlain[ToolParams]
220
)
221
222
SystemPromptFunc[AgentDepsT] = Callable[
223
[RunContext[AgentDepsT]],
224
str | Awaitable[str]
225
]
226
227
ToolPrepareFunc[AgentDepsT] = Callable[
228
[RunContext[AgentDepsT]],
229
Any | Awaitable[Any]
230
]
231
232
ToolsPrepareFunc[AgentDepsT] = Callable[
233
[RunContext[AgentDepsT]],
234
list[Tool[AgentDepsT]] | Awaitable[list[Tool[AgentDepsT]]]
235
]
236
```
237
238
### Tool Schema Generation
239
240
Utilities for generating JSON schemas for tools.
241
242
```python { .api }
243
class GenerateToolJsonSchema:
244
"""JSON schema generator for tools."""
245
246
def generate_schema(
247
self,
248
function: Callable,
249
*,
250
docstring_format: DocstringFormat = 'auto'
251
) -> ObjectJsonSchema:
252
"""
253
Generate JSON schema for a tool function.
254
255
Parameters:
256
- function: Function to generate schema for
257
- docstring_format: Format of function docstring
258
259
Returns:
260
JSON schema object describing the function
261
"""
262
263
ObjectJsonSchema = dict[str, Any]
264
265
class DocstringFormat(str, Enum):
266
"""Docstring format options."""
267
GOOGLE = 'google'
268
NUMPY = 'numpy'
269
SPHINX = 'sphinx'
270
AUTO = 'auto'
271
```
272
273
### Tool Definition Objects
274
275
Low-level tool definition objects for advanced use cases.
276
277
```python { .api }
278
class ToolDefinition:
279
"""
280
Tool definition for models.
281
"""
282
name: str
283
description: str | None
284
parameters_json_schema: ObjectJsonSchema
285
outer_typed_dict_key: str | None
286
287
class ToolKind(str, Enum):
288
"""Tool types."""
289
FUNCTION = 'function'
290
OUTPUT = 'output'
291
DEFERRED = 'deferred'
292
```
293
294
## Usage Examples
295
296
### Basic Function Tool
297
298
```python
299
from pydantic_ai import Agent, RunContext, tool
300
301
# Simple tool without dependencies
302
@tool
303
def get_weather(location: str) -> str:
304
"""Get weather information for a location."""
305
# In real implementation, call weather API
306
return f"Weather in {location}: Sunny, 22°C"
307
308
agent = Agent(
309
model='gpt-4',
310
tools=[get_weather],
311
system_prompt='You can help with weather queries.'
312
)
313
314
result = agent.run_sync('What is the weather in Paris?')
315
```
316
317
### Tool with Dependencies
318
319
```python
320
from pydantic_ai import Agent, RunContext, tool
321
from dataclasses import dataclass
322
323
@dataclass
324
class DatabaseDeps:
325
database_url: str
326
api_key: str
327
328
@tool
329
def get_user_info(ctx: RunContext[DatabaseDeps], user_id: int) -> str:
330
"""Get user information from database."""
331
# Access dependencies through ctx.deps
332
db_url = ctx.deps.database_url
333
api_key = ctx.deps.api_key
334
335
# Mock database query
336
return f"User {user_id}: John Doe, email: john@example.com"
337
338
agent = Agent(
339
model='gpt-4',
340
tools=[get_user_info],
341
deps_type=DatabaseDeps,
342
system_prompt='You can help with user queries.'
343
)
344
345
deps = DatabaseDeps('postgresql://localhost', 'secret-key')
346
result = agent.run_sync('Get info for user 123', deps=deps)
347
```
348
349
### Built-in Tools Usage
350
351
```python
352
from pydantic_ai import Agent
353
from pydantic_ai.builtin_tools import WebSearchTool, CodeExecutionTool
354
355
# Agent with web search capability
356
search_tool = WebSearchTool(max_results=3)
357
agent = Agent(
358
model='gpt-4',
359
tools=[search_tool],
360
system_prompt='You can search the web for current information.'
361
)
362
363
result = agent.run_sync('What are the latest Python releases?')
364
365
# Agent with code execution capability
366
code_tool = CodeExecutionTool(timeout=30.0)
367
agent = Agent(
368
model='gpt-4',
369
tools=[code_tool],
370
system_prompt='You can execute Python code to solve problems.'
371
)
372
373
result = agent.run_sync('Calculate the factorial of 10')
374
```
375
376
### Multiple Tools
377
378
```python
379
from pydantic_ai import Agent, tool
380
from pydantic_ai.builtin_tools import WebSearchTool, CodeExecutionTool
381
382
@tool
383
def calculate_tax(income: float, tax_rate: float = 0.25) -> float:
384
"""Calculate tax amount based on income and tax rate."""
385
return income * tax_rate
386
387
# Agent with multiple tools
388
agent = Agent(
389
model='gpt-4',
390
tools=[
391
WebSearchTool(),
392
CodeExecutionTool(),
393
calculate_tax
394
],
395
system_prompt='You are a financial assistant with web search and calculation capabilities.'
396
)
397
398
result = agent.run_sync(
399
'Search for current tax rates and calculate tax on $50,000 income'
400
)
401
```
402
403
### Tool with Preparation
404
405
```python
406
from pydantic_ai import Agent, RunContext, tool
407
408
def prepare_database_connection(ctx: RunContext) -> dict:
409
"""Prepare database connection before tool use."""
410
return {'connection': 'database-connection-object'}
411
412
@tool
413
def query_database(
414
ctx: RunContext,
415
query: str,
416
prepared_data: dict = None
417
) -> str:
418
"""Query the database with prepared connection."""
419
connection = prepared_data['connection']
420
# Use connection to query database
421
return f"Query result for: {query}"
422
423
database_tool = Tool(
424
query_database,
425
prepare=prepare_database_connection
426
)
427
428
agent = Agent(
429
model='gpt-4',
430
tools=[database_tool],
431
system_prompt='You can query the database.'
432
)
433
```