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