In short.
The Pydantic AI Hooks guide helps Python developers add logging, validation and execution controls to AI agents, but correct behavior depends on lifecycle ordering and streaming mode. It covers callback registration, conversation-history changes, tool approval timing, retries and event handling. Its most consequential details concern wrappers that bypass inner checks, approvals raised after tool execution, and request edits that do not automatically update persistent history. The examples were not executed; costs, licensing and release compatibility are unspecified.
Researched and written by an AI model and checked by a second AI model. How it works
Coverage is the complete selected page at [https://pydantic.dev/docs/ai/core-concepts/hooks/index.md], including its examples, lifecycle tables, warnings and deprecation notices. All linked documentation, API references and the documentation index are excluded. The source was captured on 2026-11-23T21:16:28.315Z with source SHA-256 8ba1c7f861f7361bc5a8de06bb5c5e6aea8a59eb083eede0726dca28d48e6a4e. No code was executed. Runtime behavior, performance, release compatibility, costs and licensing remain unverified or unspecified.
The overview
Identity
This is the Hooks documentation page for Pydantic AI at [https://pydantic.dev/docs/ai/core-concepts/hooks/index.md]. It teaches a framework capability that intercepts stages of an agent run without requiring a subclass. The selected resource is the guide itself; it is not a standalone agent application.
Assessment
The guide is useful when an existing Pydantic AI application needs shared logging, metrics, lightweight validation or changes to model and tool behavior. It connects simple registration examples to details that matter in larger applications, including retries, deferred execution and composition across capabilities.
Its main difficulty is that callbacks with similar names have different boundaries. A wrapper can skip inner hooks, an error hook covers only its stage's core operation, and streamed runs have exceptions to the usual node lifecycle. The page documents these distinctions, but provides no measured performance or evidence from production deployments.
Users
The audience is Python developers building or maintaining Pydantic AI agents. Beginners can start with request logging; experienced developers can use the request-history, middleware and retry details to design more complex controls. Reading the examples requires familiarity with Python functions, decorators and asynchronous functions. The page is a feature guide rather than a complete introduction to building an agent.
Capabilities
Hooks cover complete runs, graph nodes, model requests, tool argument validation, tool execution, structured-output validation and output processing. They can observe or change values, surround operations with setup and cleanup, recover from core-operation errors, or skip specific operations through documented exceptions.
The API also supports tool-name filters, callback timeouts, deferred tool-call resolution and event-stream interception. Tool preparation can filter available tools in both the model request and the tool manager, so filtering also blocks their execution. A Hooks capability can load on demand, with its callbacks inactive until that capability is loaded.
Using it
Requirements
The examples require Python and a Pydantic AI installation exposing Agent, Hooks and the relevant context, handler and exception types. Hooks is imported from pydantic_ai.capabilities and attached through the agent's capabilities argument. The page does not specify installation commands, minimum Python version, compatible package releases or provider-credential requirements. Several examples use the 'test' model identifier, so their displayed output does not establish behavior with an external model provider.
Mechanism
The usual lifecycle enters a wrapper, runs before hooks, performs the operation with error-hook recovery, runs after hooks and exits the wrapper. Calling the supplied handler advances that inner lifecycle; returning without calling it skips everything inside. Error hooks recover by returning a result and propagate or transform failures by raising an exception. They do not catch exceptions from the corresponding before, after or wrapper hooks.
Within one Hooks instance, before, after and error callbacks follow registration order; the first registered wrapper is outermost. Across capabilities, before hooks follow capability order, while after and error hooks reverse it. All wrappers are entered before any before hook, which makes capability position consequential.
ModelRequestContext.messages is a separate shallow list for the current request. Editing ctx.messages changes persistent conversation history, while changing the request list normally affects only the current request. Updating both requires explicit changes to both. Nested message objects can still be shared, so isolated edits below the list level require replacement objects.
The guide distinguishes a model turn from an attempt to serve it. Before-model and wrapper hooks run once per turn; preparation, model-error and after-model hooks run per attempt. ModelRetry asks the model to try again and consumes the relevant retry budget. ToolFailed reports a failed tool result without consuming the tool retry budget.
Setup
Create a Hooks instance, register a callback through hooks.on, and pass the instance in Agent(..., capabilities=[hooks]). For request logging, the documented callback accepts RunContext and ModelRequestContext and returns the request context. Constructor keywords provide an alternative registration style. Add timeout values where needed and a tools filter for callbacks targeting particular function tools.
Use asynchronous callbacks when the hook needs an event loop or must set context variables visible to later code. Synchronous callbacks run in worker threads, which changes those behaviors.
Example
The quick-start example registers an asynchronous before_model_request callback that prints the number of outgoing messages and returns the unchanged request context. It attaches the Hooks instance to Agent('test'), then calls run_sync('Hello!'). The page displays a one-message log and a successful response with no tool calls. These are documentation outputs; the example was not executed.
A more advanced example centralizes tool-error handling. It converts upstream server errors and rate limiting into ModelRetry, while other upstream failures become ToolFailed so the model can adapt. Unrelated exceptions are re-raised.
Assessment & evidence
Limitations
Tool validation and execution hooks apply to function tools and skip internal structured-output tools. Output-validation hooks apply to structured output and do not fire for plain text or images. During streaming, validation can occur repeatedly on partial output; processing hooks run when partial validation succeeds and on the final result. The guide recommends checking ctx.partial_output to avoid unnecessary work.
With run_stream(), node wrappers have a narrower boundary for non-final streamed nodes, and the final streamed ModelRequestNode skips its wrapper and after-node hook. A ModelRetry cannot replace output already streamed as final through this API; the guide describes different retry behavior for run_stream_events() and iter().
Approval must occur before tool execution to prevent side effects. A deferral raised after execution discards the result after the tool has already run. Deferred capabilities also leave their hooks inactive until loading, so optional loading is unsuitable for checks that must always apply. The approve_all=True example automatically approves requests and supplies no human decision.
Synchronous hooks cannot propagate context-variable writes back to the run and have no running asyncio event loop in their worker thread. Event listeners observe events before stream wrappers transform or drop them, so listeners may see events absent from the delivered stream.
Reasoning
Hooks is a reasonable architectural fit when application behavior belongs around existing agent operations, such as logging every request or translating tool failures consistently. Its registration model keeps those concerns in one place instead of requiring edits to every tool.
The same interception power requires careful placement of mandatory controls. The guide explicitly warns that a wrapper returning a cached or substitute result can skip authorization in inner before hooks. Authorization should therefore sit in an outer wrapper or outside any short-circuiting cache. This is a design implication of the documented lifecycle, not a verified security guarantee.
Alternatives
The page recommends AbstractCapability for reusable behavior combining hooks with tools, instructions, settings or complex per-run state. For event observation alone, agent.on_event provides direct listener registration. HandleDeferredToolCalls is described as a more concise option when deferred-call handling is the only requirement.
For human approval, the guide points to requires_approval=True, conditional ApprovalRequired and ApprovalRequiredToolset. These are alternatives within Pydantic AI; their linked documentation is outside the selected page. Comparisons with other agent frameworks are not provided.
Evidence
The evidence consists of the complete selected Hooks page at [https://pydantic.dev/docs/ai/core-concepts/hooks/index.md]. It contains lifecycle explanations, callback mappings, examples, displayed outputs and caveats. These establish documented behavior, not independently observed runtime results. No examples were executed, and compatibility, reliability and performance were not assessed.
Access & freshness
Costs
The page provides no pricing for the library, model providers or supporting services, so costs are unknown. Retries and fallback attempts can add model calls, and user-written hooks can perform additional work, but the page supplies no usage estimates or measured overhead. Timeout examples describe execution limits, not financial limits.
Rights
The supplied page does not state a license for its documentation or code examples, or establish the library's license. Permission to redistribute the captured text, reuse examples or package the library is therefore unknown from this evidence. Public availability alone does not establish those rights.
Freshness
The supplied capture is dated 2026-11-23T21:16:28.315Z. That is a capture timestamp, not a publication date or release guarantee; the page does not establish its last update or applicable package version.
Two documented deprecations affect implementation choices: in-place appends to request_context.messages in before_model_request, and returning replacement events from event callbacks. The stated replacements are explicit request/history updates and run_event_stream transformations, respectively.
Actions
Start with one request-logging hook and confirm its signature against the installed Pydantic AI release. Before adding validation or approval controls, map wrapper order and identify any path that returns without calling its handler. Place approval before execution and make request-history changes explicit.
For a streaming application, check the chosen run API's final-node and retry behavior, guard expensive partial-output work with ctx.partial_output, and choose event listeners or stream wrappers according to whether emitted or delivered events matter. Confirm package compatibility, licensing and provider costs before adoption; this page does not establish them.
