页面简介
Add lifecycle hooks to a Pydantic AI agent to log, modify, retry or skip model requests, tool calls, output and stream events, without subclassing.
正文摘录
Hooks Hooks let you intercept and modify agent behavior at every stage of a run — model requests, tool calls, streaming events — using simple decorators or constructor arguments. No subclassing needed. The Hooks capability is the recommended way to add lifecycle hooks for application-level concerns like logging, metrics, and lightweight validation. For reusable capabilities that combine hooks with tools, instructions, or model settings, subclass AbstractCapability instead — see Building custom capabilities. Hook lifecycle Every stage of a run (the run itself, each node, model request, tool call, and output) has the same hook lifecycle: wrap_* enter → before_* → operation (on_*_error if it fails) → after_* → wrap_* exit A wrap_* hook that returns without calling its handler skips everything inside it. run_stream() handles node hooks differently, and Hook ordering covers how several hooks and capabilities combine. Quick start Create a Hooks instance, register hooks via @hooks.on.* decorators, and pass it to your agent: hooks_decorator.pyfrom pydantic_ai import Agent, ModelRequestContext, RunContext from pydantic_ai.capabilities import Hooks hooks = Hooks() @hooks.on.before_model_request async def log_request(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext: print(f'Sending {len(request_context.messages)} messages to the model') #> Sending 1 messages to the model return request_context agent = Agent('test', capabilities=[hooks]) result = agent.run_sync('Hello!') print(result.output) #> success (no tool calls) Registering hooks Decorator registration The hooks.on namespace provides decorator methods for every lifecycle hook. Use them as bare decorators or with parameters: # Bare decorator @hooks.on.before_model_request async def my_hook(ctx, request_context): return request_context # With parameters (timeout, tool filter) @hooks.on.before_model_request(timeout=5.0) async def my_timed_hook(ctx, request_context): return request_context Multiple hooks can be registered for the same event — they fire in registration order. Constructor kwargs You can also pass hook functions directly to the Hooks constructor: hooks_constructor.pyfrom pydantic_ai import Agent, ModelRequestContext, RunContext from pydantic_ai.capabilities import Hooks async def log_request(ctx: RunContext, request_context: ModelRequestContext) -> ModelRequestContext: print(f'Sending {len(request_context.messages)} messages to the model') #> Sending 1 messages to the model return request_context agent = Agent('test', capabilities=[Hooks(before_model_request=log_request)]) result = agent.run_sync('Hello!') print(result.output) #> success (no tool calls) Both sync and async hook functions are accepted. Sync functions are run in a thread pool, so a slow one won’t hold up the rest of the run. On-demand hooks Hooks is a capability, so it can be loaded on demand just like any other capability. This is useful for optional, user-requested behavior such as verbose request logging: deferred_hooks_capability.pyfrom pydantic_ai import Agent, ModelRequestContext, RunContext from pydantic_ai.capabilities import Hooks request_logging_hooks = Hooks( id='request-logging', description='Use when the user asks for verbose request diagnostics.', defer_loading=True, ) @request_logging_hooks.on.before_model_request async def log_request( ctx: RunContext, request_context: ModelRequestContext, ) -> ModelRequestContext: print(f'Model request at step {ctx.run_step}: {len(request_context.messages)} messages') return request_context agent = Agent('openai-responses:gpt-6.1-sol', capabilities=[request_logging_hooks]) Pydantic AI skips hooks owned by a deferred Hooks instance until its capability is loaded. Use on-demand hooks for optional behavior that only applies after the capability is loaded. For human-in-the-loop tool approval, pass requires_approval=True when registering a tool, raise ApprovalRequired for conditional approval, or wrap a toolset with ApprovalRequiredToolset. Hook types Run hooks hooks.on.Constructor kwargAbstractCapability methodbefore_runbefore_run=before_runafter_runafter_run=after_runrunrun=wrap_runrun_errorrun_error=on_run_error The run lifecycle is dispatched once per agent run. wrap_run (registered via hooks.on.run) runs once and encloses before_run, graph iteration with on_run_error recovery, and after_run; a wrapper that does not call its handler skips those inner hooks. A realtime session is a run: the same four hooks fire once around the session, with wrap_run recovery and after_run result transformation applied when the session closes. So is compact_history(), which ends after its compaction step without a model response: wrap_run, after_run and the final AgentRunResultEvent get a result whose output is None, whatever the agent’s output_type. A hook that reads result.output, say to log, validate or store the answer, should allow for None there. Its one model request step compacts inside the wrap_model_request chain and then ends without sending the request, by raising a BaseException that isn’t an Exception out of handler(): let it propagate, as except Exception does. Node hooks hooks.on.Constructor kwargAbstractCapability methodbefore_node_runbefore_node_run=before_node_runafter_node_runafter_node_run=after_node_runnode_runnode_run=wrap_node_runnode_run_errornode_run_error=on_node_run_error Node hooks fire for each graph step (UserPromptNode, ModelRequestNode, CallToolsNode). Node hooks fire no matter how the run is driven: agent.run(), agent_run.next(), and async for node in agent_run: over agent.iter() all advance the run the same way. Model request hooks hooks.on.Constructor kwargAbstractCapability methodbefore_model_requestbefore_model_request=before_model_requestprepare_model_requestprepare_model_request=prepare_model_requestafter_model_requestafter_model_request=after_model_requestmodel_requestmodel_request=wrap_model_requestmodel_request_errormodel_request_error=on_model_request_error Model request hooks fire around each model request step, which usually makes one LLM call, and more when a hook asks for another attempt. ModelRequestContext bundles model, messages, model_settings, and model_request_parameters. To swap the model for a given request, set request_context.model to a different Model instance. before_model_request and model_request (wrap) use the same message-persistence rules. Each receives two top-level views of the messages: Mutating or assigning request_context.messages changes only the current model request (except for the deprecated appends below). Mutating the ctx.messages list changes persistent history returned by all_messages() and used by later requests, but not the current model request. To change both, update both explicitly. ProcessHistory and compaction deliberately update both, preserving their existing history-rewriting contract. Because a history processor transforms the current request view and makes its whole result persistent, its position relative to other message hooks remains significant. To skip the model call entirely, raise SkipModelRequest(response) from before_model_request or model_request (wrap). before_model_request runs once per request step. prepare_model_request runs before every attempt at the request, with request_context.model set to the model about to serve it, which differs from the step’s model when a hook moves the request to another model by raising RetryModelRequest. Use it for preparation that depends on the model; see Retrying and falling back. Tool validation hooks hooks.on.Constructor kwargAbstractCapability methodbefore_tool_validatebefore_tool_validate=before_tool_validateafter_tool_validateafter_tool_validate=after_tool_validatetool_validatetool_validate=wrap_tool_validatetool_validate_errortool_validate_error=on_tool_validate_error Validation hooks fire when the model’s JSON arguments are parsed and validated. All tool hooks receive call (ToolCallPart) and tool_def (ToolDefinition) parameters. To skip validation, raise SkipToolValidation(args) from before_tool_validate or tool_validate (wrap). A tool call can only be deferred once its arguments have been validated, so a call with invalid arguments is retried instead of reaching whoever resolves the deferral. So ApprovalRequired and CallDeferred can be raised from after_tool_validate (and from tool_validate after its handler() has returned), but raising them from before_tool_validate, from tool_validate before it calls handler(), or from tool_validate_error is a UserError. A deferral from a tool’s args_validator is held until after_tool_validate has checked the validated arguments; a deferral raised by tool_validate after its handler returns happens after that gate has already run. An external tool is executed outside the run, which therefore can’t approve its calls, so raising ApprovalRequired while validating one is a UserError. Raise CallDeferred instead, with any metadata the code that executes the call needs to approve it. Whoever resolves the deferral can see the arguments as these hooks rewrote them in validated_args, while the deferred ToolCallPart keeps the model’s. If they approve the call, the hooks run again on the model’s arguments. Human-in-the-Loop Tool Approval covers a hook whose rewrite can differ the second time. Tool execution hooks hooks.on.Constructor kwargAbstractCapability methodbefore_tool_executebefore_tool_execute=before_tool_executeafter_tool_executeafter_tool_execute=after_tool_executetool_executetool_execute=wrap_tool_executetool_execute_errortool_execute_error=on_tool_execute_error Execution hooks fire when the tool function runs. args is always the validated dict[str, Any]. To skip execution, raise SkipToolExecution(result) from before_tool_execute or tool_execute (wrap). Every execution hook can defer the call — the arguments are validated by this point — but raise ApprovalRequired/CallDeferred from before_tool_execute (or from tool_execute before it calls handler()). A def