pydantic_ai.capabilities
AbstractCapability
dataclass
Bases: ABC, Generic[AgentDepsT]
Abstract base class for agent capabilities.
A capability is a reusable, composable unit of agent behavior that can provide instructions, model settings, tools, and request/response hooks.
Lifecycle: capabilities are passed to an Agent at construction time, where
most get_* methods are called to collect static configuration (instructions, model
settings, toolsets, builtin tools). The exception is
get_wrapper_toolset,
which is called per-run during toolset assembly. Then, on each model request during a
run, the before_model_request
and after_model_request
hooks are called to allow dynamic adjustments.
See the capabilities documentation for built-in capabilities.
get_serialization_name
and from_spec support
YAML/JSON specs (via [Agent.from_spec][pydantic_ai.Agent.from_spec]); they have
sensible defaults and typically don't need to be overridden.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
has_wrap_node_run
property
has_wrap_node_run: bool
Whether this capability (or any sub-capability) overrides wrap_node_run.
get_serialization_name
classmethod
get_serialization_name() -> str | None
Return the name used for spec serialization (CamelCase class name by default).
Return None to opt out of spec-based construction.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
85 86 87 88 89 90 91 | |
from_spec
classmethod
from_spec(
*args: Any, **kwargs: Any
) -> AbstractCapability[Any]
Create from spec arguments. Default: cls(*args, **kwargs).
Override when __init__ takes non-serializable types.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
93 94 95 96 97 98 99 | |
for_run
async
for_run(
ctx: RunContext[AgentDepsT],
) -> AbstractCapability[AgentDepsT]
Return the capability instance to use for this agent run.
Called once per run, before get_*() re-extraction and before any hooks fire.
Override to return a fresh instance for per-run state isolation.
Default: return self (shared across runs).
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
101 102 103 104 105 106 107 108 | |
get_instructions
get_instructions() -> AgentInstructions[AgentDepsT] | None
Return instructions to include in the system prompt, or None.
This method is called once at agent construction time. To get dynamic
per-request behavior, return a callable that receives
RunContext or a
[TemplateStr][pydantic_ai.TemplateStr] — not a dynamic string.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
110 111 112 113 114 115 116 117 118 | |
get_model_settings
get_model_settings() -> (
AgentModelSettings[AgentDepsT] | None
)
Return model settings to merge into the agent's defaults, or None.
This method is called once at agent construction time. Return a static
ModelSettings dict when the settings don't change between requests.
Return a callable that receives RunContext
when settings need to vary per step (e.g. based on ctx.run_step or ctx.deps).
When the callable is invoked, ctx.model_settings contains the merged
result of all layers resolved before this capability (model defaults and
agent-level settings). The returned dict is merged on top of that.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
120 121 122 123 124 125 126 127 128 129 130 131 132 | |
get_toolset
get_toolset() -> AgentToolset[AgentDepsT] | None
Return a toolset to register with the agent, or None.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
134 135 136 | |
get_builtin_tools
get_builtin_tools() -> (
Sequence[AgentBuiltinTool[AgentDepsT]]
)
Return builtin tools to register with the agent.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
138 139 140 | |
get_wrapper_toolset
get_wrapper_toolset(
toolset: AbstractToolset[AgentDepsT],
) -> AbstractToolset[AgentDepsT] | None
Wrap the agent's assembled toolset, or return None to leave it unchanged.
Called per-run with the combined non-output toolset (after agent-level
prepare_tools wrapping).
Output tools are added separately and are not included.
Unlike the other get_* methods which are called once at agent construction,
this is called each run (after for_run).
When multiple capabilities provide wrappers, each receives the already-wrapped
toolset from earlier capabilities (first capability wraps innermost).
Use this to apply cross-cutting toolset wrappers like
PreparedToolset,
FilteredToolset,
or custom WrapperToolset subclasses.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
prepare_tools
async
prepare_tools(
ctx: RunContext[AgentDepsT],
tool_defs: list[ToolDefinition],
) -> list[ToolDefinition]
Filter or modify tool definitions visible to the model for this step.
The list contains all tool kinds (function, output, unapproved) distinguished
by tool_def.kind. Return a filtered
or modified list. Called after the agent-level
prepare_tools has already run.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
163 164 165 166 167 168 169 170 171 172 173 174 175 | |
before_run
async
before_run(ctx: RunContext[AgentDepsT]) -> None
Called before the agent run starts. Observe-only; use wrap_run for modification.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
179 180 181 182 183 | |
after_run
async
after_run(
ctx: RunContext[AgentDepsT],
*,
result: AgentRunResult[Any]
) -> AgentRunResult[Any]
Called after the agent run completes. Can modify the result.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
185 186 187 188 189 190 191 192 | |
wrap_run
async
wrap_run(
ctx: RunContext[AgentDepsT], *, handler: WrapRunHandler
) -> AgentRunResult[Any]
Wraps the entire agent run. handler() executes the run.
If handler() raises and this method catches the exception and
returns a result instead, the error is suppressed and the recovery
result is used.
If this method does not call handler() (short-circuit), the run
is skipped and the returned result is used directly.
Note: if the caller cancels the run (e.g. by breaking out of an
iter() loop), this method receives an :class:asyncio.CancelledError.
Implementations that hold resources should handle cleanup accordingly.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
on_run_error
async
on_run_error(
ctx: RunContext[AgentDepsT], *, error: BaseException
) -> AgentRunResult[Any]
Called when the agent run fails with an exception.
This is the error counterpart to
after_run:
while after_run is called on success, on_run_error is called on
failure (after wrap_run
has had its chance to recover).
Raise the original error (or a different exception) to propagate it.
Return an AgentRunResult to suppress
the error and recover the run.
Not called for GeneratorExit or KeyboardInterrupt.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
before_node_run
async
before_node_run(
ctx: RunContext[AgentDepsT],
*,
node: AgentNode[AgentDepsT]
) -> AgentNode[AgentDepsT]
Called before each graph node executes. Can observe or replace the node.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
239 240 241 242 243 244 245 246 | |
after_node_run
async
after_node_run(
ctx: RunContext[AgentDepsT],
*,
node: AgentNode[AgentDepsT],
result: NodeResult[AgentDepsT]
) -> NodeResult[AgentDepsT]
Called after each graph node succeeds. Can modify the result (next node or End).
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
248 249 250 251 252 253 254 255 256 | |
wrap_node_run
async
wrap_node_run(
ctx: RunContext[AgentDepsT],
*,
node: AgentNode[AgentDepsT],
handler: WrapNodeRunHandler[AgentDepsT]
) -> NodeResult[AgentDepsT]
Wraps execution of each agent graph node (run step).
Called for every node in the agent graph (UserPromptNode,
ModelRequestNode, CallToolsNode). handler(node) executes
the node and returns the next node (or End).
Override to inspect or modify nodes before execution, inspect or modify
the returned next node, call handler multiple times (retry), or
return a different node to redirect graph progression.
Note: this hook fires when using [agent.run()][pydantic_ai.Agent.run],
[agent.run_stream()][pydantic_ai.Agent.run_stream], and when manually driving
an [agent.iter()][pydantic_ai.Agent.iter] run with
[next()][pydantic_ai.result.AgentRun.next], but it does not fire when
iterating over the run with bare async for (which yields stream events, not
node results).
When using agent.run() with event_stream_handler, the handler wraps both
streaming and graph advancement (i.e. the model call happens inside the wrapper).
When using agent.run_stream(), the handler wraps only graph advancement — streaming
happens before the wrapper because run_stream() must yield the stream to the caller
while the stream context is still open, which cannot happen from inside a callback.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
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 | |
on_node_run_error
async
on_node_run_error(
ctx: RunContext[AgentDepsT],
*,
node: AgentNode[AgentDepsT],
error: Exception
) -> NodeResult[AgentDepsT]
Called when a graph node fails with an exception.
This is the error counterpart to
after_node_run.
Raise the original error (or a different exception) to propagate it.
Return a next node or End to recover and continue the graph.
Useful for recovering from
UnexpectedModelBehavior
by redirecting to a different node (e.g. retry with different model settings).
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 | |
wrap_run_event_stream
async
wrap_run_event_stream(
ctx: RunContext[AgentDepsT],
*,
stream: AsyncIterable[AgentStreamEvent]
) -> AsyncIterable[AgentStreamEvent]
Wraps the event stream for a streamed node. Can observe or transform events.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
313 314 315 316 317 318 319 320 321 | |
before_model_request
async
before_model_request(
ctx: RunContext[AgentDepsT],
request_context: ModelRequestContext,
) -> ModelRequestContext
Called before each model request. Can modify messages, settings, and parameters.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
325 326 327 328 329 330 331 | |
after_model_request
async
after_model_request(
ctx: RunContext[AgentDepsT],
*,
request_context: ModelRequestContext,
response: ModelResponse
) -> ModelResponse
Called after each model response. Can modify the response before further processing.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
333 334 335 336 337 338 339 340 341 | |
wrap_model_request
async
wrap_model_request(
ctx: RunContext[AgentDepsT],
*,
request_context: ModelRequestContext,
handler: WrapModelRequestHandler
) -> ModelResponse
Wraps the model request. handler() calls the model.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
343 344 345 346 347 348 349 350 351 | |
on_model_request_error
async
on_model_request_error(
ctx: RunContext[AgentDepsT],
*,
request_context: ModelRequestContext,
error: Exception
) -> ModelResponse
Called when a model request fails with an exception.
This is the error counterpart to
after_model_request.
Raise the original error (or a different exception) to propagate it.
Return a ModelResponse to suppress
the error and use the response as if the model call succeeded.
Not called for SkipModelRequest.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
before_tool_validate
async
before_tool_validate(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: RawToolArgs
) -> RawToolArgs
Modify raw args before validation.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
375 376 377 378 379 380 381 382 383 384 | |
after_tool_validate
async
after_tool_validate(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs
) -> ValidatedToolArgs
Modify validated args. Called only on successful validation.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
386 387 388 389 390 391 392 393 394 395 | |
wrap_tool_validate
async
wrap_tool_validate(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: RawToolArgs,
handler: WrapToolValidateHandler
) -> ValidatedToolArgs
Wraps tool argument validation. handler() runs the validation.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
397 398 399 400 401 402 403 404 405 406 407 | |
on_tool_validate_error
async
on_tool_validate_error(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: RawToolArgs,
error: ValidationError | ModelRetry
) -> ValidatedToolArgs
Called when tool argument validation fails.
This is the error counterpart to
after_tool_validate.
Fires for [ValidationError][pydantic.ValidationError] (schema mismatch) and
ModelRetry (custom validator rejection).
Raise the original error (or a different exception) to propagate it.
Return validated args to suppress the error and continue as if validation passed.
Not called for SkipToolValidation.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 | |
before_tool_execute
async
before_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs
) -> ValidatedToolArgs
Modify validated args before execution.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
434 435 436 437 438 439 440 441 442 443 | |
after_tool_execute
async
after_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
result: Any
) -> Any
Modify result after execution.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
445 446 447 448 449 450 451 452 453 454 455 | |
wrap_tool_execute
async
wrap_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
handler: WrapToolExecuteHandler
) -> Any
Wraps tool execution. handler() runs the tool.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
457 458 459 460 461 462 463 464 465 466 467 | |
on_tool_execute_error
async
on_tool_execute_error(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
error: Exception
) -> Any
Called when tool execution fails with an exception.
This is the error counterpart to
after_tool_execute.
Raise the original error (or a different exception) to propagate it.
Return any value to suppress the error and use it as the tool result.
Not called for control flow exceptions
(SkipToolExecution,
CallDeferred,
ApprovalRequired)
or retry signals (ToolRetryError
from ModelRetry).
Use wrap_tool_execute
to intercept retries.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | |
prefix_tools
prefix_tools(prefix: str) -> PrefixTools[AgentDepsT]
Returns a new capability that wraps this one and prefixes its tool names.
Only this capability's tools are prefixed; other agent tools are unaffected.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/abstract.py
499 500 501 502 503 504 505 506 | |
AgentNode
module-attribute
AgentNode: TypeAlias = (
"_agent_graph.AgentNode[AgentDepsT, Any]"
)
Type alias for an agent graph node (UserPromptNode, ModelRequestNode, CallToolsNode).
NodeResult
module-attribute
NodeResult: TypeAlias = (
"_agent_graph.AgentNode[AgentDepsT, Any] | End[FinalResult[Any]]"
)
Type alias for the result of executing an agent graph node: either the next node or End.
RawToolArgs
module-attribute
RawToolArgs: TypeAlias = 'str | dict[str, Any]'
Type alias for raw (pre-validation) tool arguments.
ValidatedToolArgs
module-attribute
ValidatedToolArgs: TypeAlias = 'dict[str, Any]'
Type alias for validated tool arguments.
WrapModelRequestHandler
module-attribute
WrapModelRequestHandler: TypeAlias = (
"Callable[[ModelRequestContext], Awaitable[ModelResponse]]"
)
Handler type for wrap_model_request.
WrapNodeRunHandler
module-attribute
WrapNodeRunHandler: TypeAlias = (
"Callable[[_agent_graph.AgentNode[AgentDepsT, Any]], Awaitable[_agent_graph.AgentNode[AgentDepsT, Any] | End[FinalResult[Any]]]]"
)
Handler type for wrap_node_run.
WrapRunHandler
module-attribute
WrapRunHandler: TypeAlias = (
"Callable[[], Awaitable[AgentRunResult[Any]]]"
)
Handler type for wrap_run.
WrapToolExecuteHandler
module-attribute
WrapToolExecuteHandler: TypeAlias = (
"Callable[[dict[str, Any]], Awaitable[Any]]"
)
Handler type for wrap_tool_execute.
WrapToolValidateHandler
module-attribute
WrapToolValidateHandler: TypeAlias = (
"Callable[[str | dict[str, Any]], Awaitable[dict[str, Any]]]"
)
Handler type for wrap_tool_validate.
BuiltinOrLocalTool
dataclass
Bases: AbstractCapability[AgentDepsT]
Capability that pairs a provider builtin tool with a local fallback.
When the model supports the builtin natively, the local fallback is removed. When the model doesn't support the builtin, it is removed and the local tool stays.
Can be used directly by providing builtin and local arguments, or subclassed
to set defaults via _default_builtin, _default_local, and _requires_builtin.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/builtin_or_local.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 | |
builtin
class-attribute
instance-attribute
builtin: AgentBuiltinTool[AgentDepsT] | bool = True
Configure the provider builtin tool.
True(default): use the default builtin tool configuration (subclasses only).False: disable the builtin; always use the local tool.- An
AbstractBuiltinToolinstance: use this specific configuration. - A callable (
BuiltinToolFunc): dynamically create the builtin per-run viaRunContext.
local
class-attribute
instance-attribute
Configure the local fallback tool.
None(default): auto-detect a local fallback via_default_local.False: disable the local fallback; only use the builtin.- A
ToolorAbstractToolsetinstance: use this specific local tool. - A bare callable: automatically wrapped in a
Tool.
BuiltinTool
dataclass
Bases: AbstractCapability[AgentDepsT]
A capability that registers a builtin tool with the agent.
Wraps a single AgentBuiltinTool — either a static
AbstractBuiltinTool instance or a callable
that dynamically produces one.
When builtin_tools is passed to [Agent.__init__][pydantic_ai.Agent.__init__], each item is
automatically wrapped in a BuiltinTool capability.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/builtin_or_local.py
19 20 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 51 52 53 54 | |
from_spec
classmethod
from_spec(
tool: AbstractBuiltinTool | None = None, **kwargs: Any
) -> BuiltinTool[Any]
Create from spec.
Supports two YAML forms:
- Flat:
{BuiltinTool: {kind: web_search, search_context_size: high}} - Explicit:
{BuiltinTool: {tool: {kind: web_search}}}
Source code in pydantic_ai_slim/pydantic_ai/capabilities/builtin_or_local.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
CombinedCapability
dataclass
Bases: AbstractCapability[AgentDepsT]
A capability that combines multiple capabilities.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/combined.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 317 318 319 320 321 322 323 324 325 326 327 328 329 330 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 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
HistoryProcessor
dataclass
Bases: AbstractCapability[AgentDepsT]
A capability that processes message history before model requests.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/history_processor.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
Hooks
Bases: AbstractCapability[AgentDepsT]
Register hook functions via decorators or constructor kwargs.
For extension developers building reusable capabilities, subclass
:class:AbstractCapability directly. For application code that needs
a few hooks without the ceremony of a subclass, use Hooks.
Example using decorators::
hooks = Hooks()
@hooks.on.before_model_request
async def log_request(ctx, request_context):
print(f'Request: {request_context}')
return request_context
agent = Agent('openai:gpt-5', capabilities=[hooks])
Example using constructor kwargs::
agent = Agent('openai:gpt-5', capabilities=[
Hooks(before_model_request=log_request)
])
Source code in pydantic_ai_slim/pydantic_ai/capabilities/hooks.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 | |
on
cached
property
on: _HookRegistration[AgentDepsT]
Decorator namespace for registering hook functions.
HookTimeoutError
Bases: TimeoutError
Raised when a hook function exceeds its configured timeout.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/hooks.py
57 58 59 60 61 62 63 64 | |
ImageGeneration
dataclass
Bases: BuiltinOrLocalTool[AgentDepsT]
Image generation capability.
Uses the model's builtin image generation when available. No default local
fallback — provide a custom local tool if needed.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/image_generation.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | |
MCP
dataclass
Bases: BuiltinOrLocalTool[AgentDepsT]
MCP server capability.
Uses the model's builtin MCP server support when available, connecting directly via HTTP when it isn't.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/mcp.py
20 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
id
instance-attribute
id: str | None = id
Unique identifier for the MCP server. Defaults to a slug derived from the URL.
authorization_token
instance-attribute
authorization_token: str | None = authorization_token
Authorization header value for MCP server requests. Passed to both builtin and local.
headers
instance-attribute
HTTP headers for MCP server requests. Passed to both builtin and local.
allowed_tools
instance-attribute
Filter to only these tools. Applied to both builtin and local.
description
instance-attribute
description: str | None = description
Description of the MCP server. Builtin-only; ignored by local tools.
PrefixTools
dataclass
Bases: WrapperCapability[AgentDepsT]
A capability that wraps another capability and prefixes its tool names.
Only the wrapped capability's tools are prefixed; other agent tools are unaffected.
from pydantic_ai import Agent
from pydantic_ai.capabilities import PrefixTools, Toolset
from pydantic_ai.toolsets import FunctionToolset
toolset = FunctionToolset()
agent = Agent(
'openai:gpt-5',
capabilities=[
PrefixTools(
wrapped=Toolset(toolset),
prefix='ns',
),
],
)
Source code in pydantic_ai_slim/pydantic_ai/capabilities/prefix_tools.py
13 14 15 16 17 18 19 20 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
from_spec
classmethod
Create from spec with a nested capability specification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
The prefix to add to tool names (e.g. |
required |
capability
|
dict[str, Any] | str
|
A capability spec (same format as entries in the |
required |
Source code in pydantic_ai_slim/pydantic_ai/capabilities/prefix_tools.py
44 45 46 47 48 49 50 51 52 53 54 55 | |
PrepareTools
dataclass
Bases: AbstractCapability[AgentDepsT]
Capability that filters or modifies tool definitions using a callable.
Wraps a ToolsPrepareFunc as a capability,
allowing it to be composed with other capabilities via the capability system.
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import PrepareTools
from pydantic_ai.tools import ToolDefinition
async def hide_admin_tools(
ctx: RunContext[None], tool_defs: list[ToolDefinition]
) -> list[ToolDefinition] | None:
return [td for td in tool_defs if not td.name.startswith('admin_')]
agent = Agent('openai:gpt-5', capabilities=[PrepareTools(hide_admin_tools)])
Source code in pydantic_ai_slim/pydantic_ai/capabilities/prepare_tools.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | |
Thinking
dataclass
Bases: AbstractCapability[AgentDepsT]
Enables and configures model thinking/reasoning.
Uses the unified thinking setting in
ModelSettings to work portably across providers.
Provider-specific thinking settings (e.g., anthropic_thinking,
openai_reasoning_effort) take precedence when both are set.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/thinking.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
effort
class-attribute
instance-attribute
effort: ThinkingLevel = True
The thinking effort level.
True: Enable thinking with the provider's default effort.False: Disable thinking (silently ignored on always-on models).'minimal'/'low'/'medium'/'high'/'xhigh': Enable thinking at a specific effort level.
Toolset
dataclass
Bases: AbstractCapability[AgentDepsT]
A capability that provides a toolset.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/toolset.py
9 10 11 12 13 14 15 16 17 18 19 20 | |
WebFetch
dataclass
Bases: BuiltinOrLocalTool[AgentDepsT]
URL fetching capability.
Uses the model's builtin URL fetching when available. No default local
fallback — provide a custom local tool if needed.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/web_fetch.py
13 14 15 16 17 18 19 20 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
allowed_domains
instance-attribute
Only fetch from these domains. Requires builtin support.
blocked_domains
instance-attribute
Never fetch from these domains. Requires builtin support.
max_uses
instance-attribute
max_uses: int | None = max_uses
Maximum number of fetches per run. Requires builtin support.
enable_citations
instance-attribute
enable_citations: bool | None = enable_citations
Enable citations for fetched content. Builtin-only; ignored by local tools.
max_content_tokens
instance-attribute
max_content_tokens: int | None = max_content_tokens
Maximum content length in tokens. Builtin-only; ignored by local tools.
WebSearch
dataclass
Bases: BuiltinOrLocalTool[AgentDepsT]
Web search capability.
Uses the model's builtin web search when available, falling back to a local function tool (DuckDuckGo by default) when it isn't.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/web_search.py
14 15 16 17 18 19 20 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
search_context_size
instance-attribute
search_context_size: (
Literal["low", "medium", "high"] | None
) = search_context_size
Controls how much context is retrieved from the web. Builtin-only; ignored by local tools.
user_location
instance-attribute
user_location: WebSearchUserLocation | None = user_location
Localize search results based on user location. Builtin-only; ignored by local tools.
blocked_domains
instance-attribute
Domains to exclude from results. Requires builtin support.
allowed_domains
instance-attribute
Only include results from these domains. Requires builtin support.
max_uses
instance-attribute
max_uses: int | None = max_uses
Maximum number of web searches per run. Requires builtin support.
WrapperCapability
dataclass
Bases: AbstractCapability[AgentDepsT]
A capability that wraps another capability and delegates all methods.
Analogous to WrapperToolset for toolsets.
Subclass and override specific methods to modify behavior while delegating the rest.
Source code in pydantic_ai_slim/pydantic_ai/capabilities/wrapper.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 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 | |
CAPABILITY_TYPES
module-attribute
CAPABILITY_TYPES: dict[
str, type[AbstractCapability[Any]]
] = {
name: cls
for cls in (
BuiltinTool,
HistoryProcessor,
ImageGeneration,
MCP,
PrefixTools,
PrepareTools,
Thinking,
Toolset,
WebFetch,
WebSearch,
)
if (name := (get_serialization_name())) is not None
}
Registry of all capability types that have a serialization name, mapping name to class.