pydantic_ai.tools
AgentDepsT
module-attribute
AgentDepsT = TypeVar(
"AgentDepsT", default=None, contravariant=True
)
Type variable for agent dependencies.
RunContext
dataclass
Bases: Generic[AgentDepsT]
Information about the current call.
Source code in pydantic_ai_slim/pydantic_ai/_run_context.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
|
prompt
class-attribute
instance-attribute
The original user prompt passed to the run.
messages
class-attribute
instance-attribute
messages: list[ModelMessage] = field(default_factory=list)
Messages exchanged in the conversation so far.
tracer
class-attribute
instance-attribute
tracer: Tracer = field(default_factory=NoOpTracer)
The tracer to use for tracing the run.
trace_include_content
class-attribute
instance-attribute
trace_include_content: bool = False
Whether to include the content of the messages in the trace.
retries
class-attribute
instance-attribute
Number of retries for each tool so far.
tool_call_id
class-attribute
instance-attribute
tool_call_id: str | None = None
The ID of the tool call.
tool_name
class-attribute
instance-attribute
tool_name: str | None = None
Name of the tool being called.
ToolParams
module-attribute
ToolParams = ParamSpec('ToolParams', default=...)
Retrieval function param spec.
SystemPromptFunc
module-attribute
SystemPromptFunc = Union[
Callable[[RunContext[AgentDepsT]], str],
Callable[[RunContext[AgentDepsT]], Awaitable[str]],
Callable[[], str],
Callable[[], Awaitable[str]],
]
A function that may or maybe not take RunContext
as an argument, and may or may not be async.
Usage SystemPromptFunc[AgentDepsT]
.
ToolFuncContext
module-attribute
ToolFuncContext = Callable[
Concatenate[RunContext[AgentDepsT], ToolParams], Any
]
A tool function that takes RunContext
as the first argument.
Usage ToolContextFunc[AgentDepsT, ToolParams]
.
ToolFuncPlain
module-attribute
ToolFuncPlain = Callable[ToolParams, Any]
A tool function that does not take RunContext
as the first argument.
Usage ToolPlainFunc[ToolParams]
.
ToolFuncEither
module-attribute
ToolFuncEither = Union[
ToolFuncContext[AgentDepsT, ToolParams],
ToolFuncPlain[ToolParams],
]
Either kind of tool function.
This is just a union of ToolFuncContext
and
ToolFuncPlain
.
Usage ToolFuncEither[AgentDepsT, ToolParams]
.
ToolPrepareFunc
module-attribute
ToolPrepareFunc: TypeAlias = (
"Callable[[RunContext[AgentDepsT], ToolDefinition], Awaitable[ToolDefinition | None]]"
)
Definition of a function that can prepare a tool definition at call time.
See tool docs for more information.
Example — here only_if_42
is valid as a ToolPrepareFunc
:
from typing import Union
from pydantic_ai import RunContext, Tool
from pydantic_ai.tools import ToolDefinition
async def only_if_42(
ctx: RunContext[int], tool_def: ToolDefinition
) -> Union[ToolDefinition, None]:
if ctx.deps == 42:
return tool_def
def hitchhiker(ctx: RunContext[int], answer: str) -> str:
return f'{ctx.deps} {answer}'
hitchhiker = Tool(hitchhiker, prepare=only_if_42)
Usage ToolPrepareFunc[AgentDepsT]
.
ToolsPrepareFunc
module-attribute
ToolsPrepareFunc: TypeAlias = (
"Callable[[RunContext[AgentDepsT], list[ToolDefinition]], Awaitable[list[ToolDefinition] | None]]"
)
Definition of a function that can prepare the tool definition of all tools for each step. This is useful if you want to customize the definition of multiple tools or you want to register a subset of tools for a given step.
Example — here turn_on_strict_if_openai
is valid as a ToolsPrepareFunc
:
from dataclasses import replace
from typing import Union
from pydantic_ai import Agent, RunContext
from pydantic_ai.tools import ToolDefinition
async def turn_on_strict_if_openai(
ctx: RunContext[None], tool_defs: list[ToolDefinition]
) -> Union[list[ToolDefinition], None]:
if ctx.model.system == 'openai':
return [replace(tool_def, strict=True) for tool_def in tool_defs]
return tool_defs
agent = Agent('openai:gpt-4o', prepare_tools=turn_on_strict_if_openai)
Usage ToolsPrepareFunc[AgentDepsT]
.
DocstringFormat
module-attribute
DocstringFormat = Literal[
"google", "numpy", "sphinx", "auto"
]
Supported docstring formats.
'google'
— Google-style docstrings.'numpy'
— Numpy-style docstrings.'sphinx'
— Sphinx-style docstrings.'auto'
— Automatically infer the format based on the structure of the docstring.
Tool
dataclass
Bases: Generic[AgentDepsT]
A tool function for an agent.
Source code in pydantic_ai_slim/pydantic_ai/tools.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
|
__init__
__init__(
function: ToolFuncEither[AgentDepsT],
*,
takes_ctx: bool | None = None,
max_retries: int | None = None,
name: str | None = None,
description: str | None = None,
prepare: ToolPrepareFunc[AgentDepsT] | None = None,
docstring_format: DocstringFormat = "auto",
require_parameter_descriptions: bool = False,
schema_generator: type[
GenerateJsonSchema
] = GenerateToolJsonSchema,
strict: bool | None = None,
function_schema: FunctionSchema | None = None
)
Create a new tool instance.
Example usage:
from pydantic_ai import Agent, RunContext, Tool
async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
return f'{ctx.deps} {x} {y}'
agent = Agent('test', tools=[Tool(my_tool)])
or with a custom prepare method:
from typing import Union
from pydantic_ai import Agent, RunContext, Tool
from pydantic_ai.tools import ToolDefinition
async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
return f'{ctx.deps} {x} {y}'
async def prep_my_tool(
ctx: RunContext[int], tool_def: ToolDefinition
) -> Union[ToolDefinition, None]:
# only register the tool if `deps == 42`
if ctx.deps == 42:
return tool_def
agent = Agent('test', tools=[Tool(my_tool, prepare=prep_my_tool)])
Parameters:
Name | Type | Description | Default |
---|---|---|---|
function
|
ToolFuncEither[AgentDepsT]
|
The Python function to call as the tool. |
required |
takes_ctx
|
bool | None
|
Whether the function takes a |
None
|
max_retries
|
int | None
|
Maximum number of retries allowed for this tool, set to the agent default if |
None
|
name
|
str | None
|
Name of the tool, inferred from the function if |
None
|
description
|
str | None
|
Description of the tool, inferred from the function if |
None
|
prepare
|
ToolPrepareFunc[AgentDepsT] | None
|
custom method to prepare the tool definition for each step, return |
None
|
docstring_format
|
DocstringFormat
|
The format of the docstring, see |
'auto'
|
require_parameter_descriptions
|
bool
|
If True, raise an error if a parameter description is missing. Defaults to False. |
False
|
schema_generator
|
type[GenerateJsonSchema]
|
The JSON schema generator class to use. Defaults to |
GenerateToolJsonSchema
|
strict
|
bool | None
|
Whether to enforce JSON schema compliance (only affects OpenAI).
See |
None
|
function_schema
|
FunctionSchema | None
|
The function schema to use for the tool. If not provided, it will be generated. |
None
|
Source code in pydantic_ai_slim/pydantic_ai/tools.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
function_schema
instance-attribute
function_schema: FunctionSchema = (
function_schema
or function_schema(
function,
schema_generator,
takes_ctx=takes_ctx,
docstring_format=docstring_format,
require_parameter_descriptions=require_parameter_descriptions,
)
)
The base JSON schema for the tool's parameters.
This schema may be modified by the prepare
function or by the Model class prior to including it in an API request.
from_schema
classmethod
from_schema(
function: Callable[..., Any],
name: str,
description: str | None,
json_schema: JsonSchemaValue,
) -> Self
Creates a Pydantic tool from a function and a JSON schema.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
function
|
Callable[..., Any]
|
The function to call. This will be called with keywords only, and no validation of the arguments will be performed. |
required |
name
|
str
|
The unique name of the tool that clearly communicates its purpose |
required |
description
|
str | None
|
Used to tell the model how/when/why to use the tool. You can provide few-shot examples as a part of the description. |
required |
json_schema
|
JsonSchemaValue
|
The schema for the function arguments |
required |
Returns:
Type | Description |
---|---|
Self
|
A Pydantic tool that calls the function |
Source code in pydantic_ai_slim/pydantic_ai/tools.py
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
|
prepare_tool_def
async
prepare_tool_def(
ctx: RunContext[AgentDepsT],
) -> ToolDefinition | None
Get the tool definition.
By default, this method creates a tool definition, then either returns it, or calls self.prepare
if it's set.
Returns:
Type | Description |
---|---|
ToolDefinition | None
|
return a |
Source code in pydantic_ai_slim/pydantic_ai/tools.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
|
ObjectJsonSchema
module-attribute
Type representing JSON schema of an object, e.g. where "type": "object"
.
This type is used to define tools parameters (aka arguments) in ToolDefinition.
With PEP-728 this should be a TypedDict with type: Literal['object']
, and extra_parts=Any
ToolDefinition
dataclass
Definition of a tool passed to a model.
This is used for both function tools and output tools.
Source code in pydantic_ai_slim/pydantic_ai/tools.py
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
|
parameters_json_schema
class-attribute
instance-attribute
parameters_json_schema: ObjectJsonSchema = field(
default_factory=lambda: {
"type": "object",
"properties": {},
}
)
The JSON schema for the tool's parameters.
description
class-attribute
instance-attribute
description: str | None = None
The description of the tool.
outer_typed_dict_key
class-attribute
instance-attribute
outer_typed_dict_key: str | None = None
The key in the outer [TypedDict] that wraps an output tool.
This will only be set for output tools which don't have an object
JSON schema.
strict
class-attribute
instance-attribute
strict: bool | None = None
Whether to enforce (vendor-specific) strict JSON schema validation for tool calls.
Setting this to True
while using a supported model generally imposes some restrictions on the tool's JSON schema
in exchange for guaranteeing the API responses strictly match that schema.
When False
, the model may be free to generate other properties or types (depending on the vendor).
When None
(the default), the value will be inferred based on the compatibility of the parameters_json_schema.
Note: this is currently only supported by OpenAI models.
kind
class-attribute
instance-attribute
kind: ToolKind = field(default='function')
The kind of tool:
'function'
: a tool that can be executed by Pydantic AI and has its result returned to the model'output'
: a tool that passes through an output value that ends the run'deferred'
: a tool that will be executed not by Pydantic AI, but by the upstream service that called the agent, such as a web application that supports frontend-defined tools provided to Pydantic AI via e.g. AG-UI. When the model calls a deferred tool, the agent run ends with aDeferredToolCalls
object and a new run is expected to be started at a later point with the message history and newToolReturnPart
s corresponding to each deferred call.