Skip to content
PaPy

PydanticAI: Hooks — Lifecycle Callbacks

Decorator-based hook registration for agent run lifecycle, model requests, tool calls, and output validation using the Hooks capability.

Verified against pydantic-ai 2.68.0 (checked 2026-11-19) — source module: pydantic_ai.capabilities.hooks.

The Hooks class gives you a decorator-first API for intercepting every phase of an agent run without subclassing AbstractCapability. Register a function once with @hooks.on.<event> and it fires automatically during runs that include this capability.

import asyncio
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
hooks = Hooks()
@hooks.on.before_run
async def log_start(ctx):
print(f'Run starting — prompt: {ctx.prompt!r}')
@hooks.on.after_run
async def log_finish(ctx, *, result):
print(f'Run finished — output: {result.output!r}')
return result
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
async def main():
result = await agent.run('What is 2 + 2?')
print(result.output)
asyncio.run(main())

Both sync and async hook functions are accepted — sync ones are wrapped automatically.

All hooks live on hooks.on.*:

CategoryEvents
Run lifecyclebefore_run, after_run, run (wrap), run_error
Node lifecyclebefore_node_run, after_node_run, node_run (wrap), node_run_error
Model requestbefore_model_request, after_model_request, model_request (wrap), model_request_error
Tool preparationprepare_tools, prepare_output_tools
Tool validationbefore_tool_validate, after_tool_validate, tool_validate (wrap), tool_validate_error
Tool executionbefore_tool_execute, after_tool_execute, tool_execute (wrap), tool_execute_error
Output validationbefore_output_validate, after_output_validate, output_validate (wrap), output_validate_error
Output processingbefore_output_process, after_output_process, output_process (wrap), output_process_error
Event streamrun_event_stream (wrap), event
Deferred toolsdeferred_tool_calls

Each name is also a Hooks(...) constructor keyword. The wrap and error forms map onto AbstractCapability.wrap_* / on_*_error methods (e.g. @hooks.on.model_request implements wrap_model_request), but on hooks.on they have no prefix.

from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import Hooks
from pydantic_ai.run import AgentRunResult
hooks = Hooks()
@hooks.on.before_run
def before(ctx: RunContext) -> None:
print(f'[before_run] conversation_id={ctx.run_id}')
@hooks.on.after_run
async def after(ctx: RunContext, *, result: AgentRunResult) -> AgentRunResult:
print(f'[after_run] tokens used: {result.usage.total_tokens}') # .usage is a @property
return result # must return the result
@hooks.on.run_error
async def on_error(ctx: RunContext, *, error: BaseException) -> AgentRunResult:
print(f'[run_error] {type(error).__name__}: {error}')
raise error # re-raise or return a fallback result
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
from typing import TYPE_CHECKING
from pydantic_ai.capabilities import Hooks
from pydantic_ai.messages import ModelResponse
if TYPE_CHECKING:
from pydantic_ai.models import ModelRequestContext
hooks = Hooks()
_request_log: list[dict] = []
@hooks.on.before_model_request
async def record_request(ctx, request_context: 'ModelRequestContext'):
_request_log.append({'run_id': ctx.run_id, 'messages': len(request_context.messages)})
return request_context # must return (optionally modified) context
@hooks.on.after_model_request
async def record_response(ctx, *, request_context, response: ModelResponse) -> ModelResponse:
print(f' model={response.model_name} tokens={response.usage.total_tokens}')
return response # must return (optionally modified) response
@hooks.on.model_request_error
async def handle_request_error(ctx, *, request_context, error: Exception) -> ModelResponse:
print(f'[model error] {error}')
raise error

Filter which tools a hook applies to with the tools= parameter:

from pydantic_ai import ModelRetry
from pydantic_ai.capabilities import Hooks
from pydantic_ai.tools import ToolDefinition
hooks = Hooks()
@hooks.on.before_tool_execute(tools=['delete_record', 'drop_table'])
async def audit_destructive(ctx, *, call, tool_def: ToolDefinition, args):
print(f'[AUDIT] {tool_def.name} called with {args}')
return args # must return (optionally modified) args
@hooks.on.after_tool_execute
async def cache_tool_result(ctx, *, call, tool_def: ToolDefinition, args, result):
# Could persist result to a cache keyed by (tool_def.name, frozenset(args.items()))
print(f'[cache] {tool_def.name} → {result!r}')
return result # must return (optionally modified) result
@hooks.on.tool_execute_error
async def retry_on_network_error(ctx, *, call, tool_def, args, error: Exception):
if 'timeout' in str(error).lower():
raise ModelRetry(f'Tool {tool_def.name} timed out — please try again.')
raise error

The tools= filter is only available on before_tool_execute, after_tool_execute, tool_execute, tool_execute_error, before_tool_validate, after_tool_validate, tool_validate, tool_validate_error.

from pydantic_ai import ModelRetry
from pydantic_ai.capabilities import Hooks
hooks = Hooks()
@hooks.on.before_output_validate
async def normalise_text(ctx, *, output_context, output):
if isinstance(output, str):
return output.strip()
return output
@hooks.on.after_output_validate
async def enforce_policy(ctx, *, output_context, output):
if hasattr(output, 'confidence') and output.confidence < 0.5:
raise ModelRetry('Confidence too low — provide a more confident answer.')
return output

Pass timeout= (seconds) to any hook decorator. If the hook function takes longer, HookTimeoutError is raised:

import asyncio
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks, HookTimeoutError
hooks = Hooks()
async def some_external_check() -> None:
await asyncio.sleep(5) # stands in for a slow policy service
@hooks.on.before_tool_execute(timeout=2.0)
async def slow_guard(ctx, *, call, tool_def, args):
await some_external_check() # must finish in < 2 s
return args
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
@agent.tool_plain
def transfer(amount: float) -> str:
return f'sent {amount}'
try:
agent.run_sync('Send 10.')
except HookTimeoutError as exc: # an AgentRunError and a TimeoutError
print('hook timed out:', exc)

RetryModelRequest — retry a model request without telling the model

Section titled “RetryModelRequest — retry a model request without telling the model”

ModelRetry asks the model to try again, adding a retry prompt to the history. RetryModelRequest (added in 2.64.0, importable from pydantic_ai) retries the request: the agent stays on the same step, nothing is added to the history, and the model never learns an earlier attempt happened. Raise it from:

  • on_model_request_error, to retry after a failed attempt;
  • after_model_request, to reject a response the model did return;
  • prepare_model_request, to send the attempt to another model before anything is sent.

Raising it from before_model_request or wrap_model_request is a UserError, since those run once per request, not per attempt. Pass a model to switch to it, or nothing to try the same one again. Nothing in the hook bounds the retries except your own condition, so re-raise the error once your budget is spent, as the example does. Each attempt re-runs prepare_model_request for the model serving it. request_context.attempt counts attempts.

from pydantic_ai import Agent, ModelResponse, RetryModelRequest, RunContext
from pydantic_ai.capabilities import AbstractCapability
from pydantic_ai.exceptions import ModelOverloadedError
from pydantic_ai.models import ModelRequestContext
class RetryOnOverload(AbstractCapability[None]):
async def on_model_request_error(
self, ctx: RunContext[None], *, request_context: ModelRequestContext, error: Exception
) -> ModelResponse:
if not isinstance(error, ModelOverloadedError):
raise error
if request_context.attempt == 1:
raise RetryModelRequest() # the same model again
if request_context.attempt == 2:
raise RetryModelRequest('anthropic:claude-sonnet-5-5') # then a different one
raise error # the budget is spent: surface the provider's error
agent = Agent('openai:gpt-6.1-sol', capabilities=[RetryOnOverload()])

For plain failover between models, ModelFallback is built on this mechanism and needs no custom capability.

Wrapping hooks — full control of the call chain

Section titled “Wrapping hooks — full control of the call chain”

wrap_* variants give you a handler callable to invoke the original operation, enabling retry decorators, circuit-breakers, and tracing:

import time
from pydantic_ai.capabilities import Hooks
hooks = Hooks()
@hooks.on.model_request
async def time_model_request(ctx, *, request_context, handler):
t0 = time.perf_counter()
response = await handler(request_context) # call the model
elapsed = time.perf_counter() - t0
print(f'model request took {elapsed:.3f}s')
return response
@hooks.on.tool_execute
async def wrap_tool(ctx, *, call, tool_def, args, handler):
print(f'→ executing {tool_def.name}')
result = await handler(args) # the handler takes only the (possibly modified) validated args
print(f'← {tool_def.name} returned')
return result

Returning without calling handler skips the operation, and the wrap hook’s return value is used instead.

Stack several Hooks objects in the capabilities= list — they run in order:

from collections import Counter
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
audit_hooks = Hooks()
metrics_hooks = Hooks()
metrics: Counter[str] = Counter()
@audit_hooks.on.before_tool_execute(tools=['write_db'])
async def audit_write(ctx, *, call, tool_def, args):
print(f'AUDIT: {ctx.run_id} — {tool_def.name}')
return args
@metrics_hooks.on.after_run
async def record_metric(ctx, *, result):
metrics['agent.run.completed'] += 1
return result
agent = Agent('openai:gpt-6.1-sol', capabilities=[audit_hooks, metrics_hooks])

Hooks can also be passed at run() time for one-shot observability:

from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
agent = Agent('openai:gpt-6.1-sol')
one_time = Hooks()
@one_time.on.before_model_request
async def debug_this_request(ctx, request_context):
print('DEBUG:', len(request_context.messages), 'messages')
return request_context
result = agent.run_sync('test prompt', capabilities=[one_time]) # only this run is hooked

@hooks.on.event observes every event in the run’s stream — model deltas, tool calls and results, custom events — whether the run is streamed or not. Pass event classes to receive only those; @hooks.on.run_event_stream instead wraps the whole stream when you need to transform or drop events.

from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
from pydantic_ai.messages import AgentStreamEvent, FunctionToolCallEvent, FunctionToolResultEvent
hooks = Hooks()
sent: list[dict] = [] # stands in for a websocket or message queue
@hooks.on.event
async def forward_events(ctx, event: AgentStreamEvent) -> None:
sent.append({'type': type(event).__name__})
@hooks.on.event(FunctionToolCallEvent, FunctionToolResultEvent)
async def audit_tools(ctx, event) -> None:
print('tool event:', event.part.tool_name)
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
@agent.tool_plain
def lookup(city: str) -> str:
return f'Sunny in {city}'
agent.run_sync('Weather in Leeds?')
print(sent[:3])
import time
import logging
from dataclasses import dataclass, field
from typing import Any
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
logger = logging.getLogger(__name__)
@dataclass
class RunMetrics:
model_calls: int = 0
tool_calls: dict[str, int] = field(default_factory=dict)
total_tokens: int = 0
errors: list[str] = field(default_factory=list)
wall_time_s: float = 0.0
def make_observability_hooks() -> tuple[Hooks, RunMetrics]:
hooks = Hooks()
m = RunMetrics()
_t0: list[float] = []
@hooks.on.before_run
def start_timer(ctx):
_t0.append(time.perf_counter())
@hooks.on.after_run
def stop_timer(ctx, *, result):
m.wall_time_s = time.perf_counter() - _t0[0]
logger.info('run finished in %.3fs tokens=%d', m.wall_time_s, m.total_tokens)
return result
@hooks.on.after_model_request
def count_tokens(ctx, *, request_context, response):
m.model_calls += 1
m.total_tokens += response.usage.total_tokens if response.usage else 0
return response
@hooks.on.after_tool_execute
def count_tool(ctx, *, call, tool_def, args, result):
m.tool_calls[tool_def.name] = m.tool_calls.get(tool_def.name, 0) + 1
return result
@hooks.on.run_error
def capture_error(ctx, *, error):
m.errors.append(f'{type(error).__name__}: {error}')
raise error
return hooks, m
obs_hooks, metrics = make_observability_hooks()
agent = Agent('openai:gpt-6.1-sol', capabilities=[obs_hooks])

deferred_tool_calls — intercept deferred tool batches

Section titled “deferred_tool_calls — intercept deferred tool batches”

Fires whenever the agent produces a DeferredToolRequests (i.e. some tool called CallDeferred or ApprovalRequired). Use it for logging, queuing, or automatically resolving deferrals in tests:

import asyncio
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import Hooks
from pydantic_ai.exceptions import CallDeferred
from pydantic_ai.tools import DeferredToolRequests, DeferredToolResults
hooks = Hooks()
@hooks.on.deferred_tool_calls
async def log_and_auto_resolve(ctx, *, requests: DeferredToolRequests):
"""Log every deferred call and automatically resolve them with a placeholder."""
print(f'[deferred] {len(requests.calls)} call(s) deferred this step')
for call in requests.calls:
print(f' → {call.tool_name}({call.args})')
# Return resolved results to continue the run automatically;
# each value is what the tool would have returned
return DeferredToolResults(calls={
call.tool_call_id: f'Auto-resolved: {call.tool_name}'
for call in requests.calls
})
agent = Agent(
'openai:gpt-6.1-sol',
output_type=[str, DeferredToolRequests],
capabilities=[hooks],
)
@agent.tool_plain
def slow_job(task: str) -> str:
raise CallDeferred(metadata={'task': task})
async def main():
# With the hook, deferred calls are auto-resolved — no manual loop needed
result = await agent.run('Run slow_job for task "data-export".')
print(result.output)
asyncio.run(main())

run_error (the on_run_error capability method) fires when an exception escapes the run. It can either re-raise the original error or return a fallback AgentRunResult:

import asyncio
import logging
from pydantic_ai import Agent, RunContext
from pydantic_ai.capabilities import Hooks
from pydantic_ai.run import AgentRunResult
from pydantic_ai.exceptions import UsageLimitExceeded
log = logging.getLogger(__name__)
hooks = Hooks()
@hooks.on.run_error
async def handle_error(ctx: RunContext, *, error: BaseException) -> AgentRunResult:
if isinstance(error, UsageLimitExceeded):
# Return a graceful fallback instead of crashing
log.warning('Usage limit exceeded for run %s', ctx.run_id)
raise error # re-raise so caller can handle it
log.error('Unexpected run failure', exc_info=error)
raise error # always re-raise unknown errors
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])

Bundling tools and instructions — Capability

Section titled “Bundling tools and instructions — Capability”

Hooks covers behaviour; Capability is the no-subclass way to package content — instructions, function tools and toolsets — into one reusable unit you can attach to many agents. With defer_loading=True (an id is then required) the model initially sees only the capability’s description and a load_capability tool; the tools and instructions appear once the model loads it, which keeps large tool sets out of the context until needed.

The example also shows OutputContext, which output hooks receive: it tells you how the output was produced (mode — 'tool', 'native', 'prompted', 'text', 'image' — plus output_type, tool_call, tool_def, allows_text, allows_image, allows_deferred_tools). @agent.output_validator does not get it; use the before_/after_output_validate or output_process hooks.

from pydantic import BaseModel
from pydantic_ai import Agent, ModelRetry, RunContext
from pydantic_ai.capabilities import Capability, Hooks
from pydantic_ai.output import OutputContext
finance = Capability(
id='finance',
description='Stock prices and portfolio maths.',
instructions='Quote prices in USD with two decimal places.',
defer_loading=True,
)
@finance.tool
def get_stock_price(ctx: RunContext[object], ticker: str) -> float:
"""Latest closing price for a ticker."""
return {'ACME': 151.2}.get(ticker.upper(), 0.0)
class Quote(BaseModel):
ticker: str
price: float
hooks = Hooks()
@hooks.on.after_output_validate
async def check_quote(ctx, *, output_context: OutputContext, output):
via = output_context.tool_def.name if output_context.tool_def else 'text'
print(f'output arrived in {output_context.mode!r} mode via {via}')
if isinstance(output, Quote) and output.price <= 0:
raise ModelRetry('The price must be positive; look it up with get_stock_price.')
return output
agent = Agent('openai:gpt-6.1-sol', output_type=Quote, capabilities=[finance, hooks])
result = agent.run_sync('What is ACME trading at?')
print(result.output)

Until the model calls load_capability('finance'), the request’s instructions only list the capability (“The following capabilities are deferred and can be loaded using the load_capability tool…”) and get_stock_price is sent with defer_loading=True.

For anything more involved — state across hooks, configuration, serialisation into an AgentSpec — subclass AbstractCapability and override the before_* / after_* / wrap_* / on_*_error methods, get_instructions, get_toolset or get_model_settings.

agent.run(prompt)
│
├─ before_run
│ │
│ └─ [loop per model step]
│ ├─ before_node_run
│ ├─ node_run (wrap)
│ │ ├─ before_model_request ← modify messages before sending
│ │ ├─ model_request (wrap)
│ │ │ └─ [model API call]
│ │ ├─ after_model_request ← inspect/modify response
│ │ │
│ │ └─ [for each tool call in response]
│ │ ├─ before_tool_validate ← inspect raw args JSON
│ │ ├─ tool_validate (wrap)
│ │ ├─ after_tool_validate ← inspect validated typed args
│ │ │
│ │ ├─ before_tool_execute ← last chance to skip/modify
│ │ ├─ tool_execute (wrap)
│ │ │ └─ [tool function runs]
│ │ └─ after_tool_execute ← inspect/modify result
│ │
│ └─ after_node_run
│
├─ after_run (or run_error on failure)
└─ AgentRunResult returned

Skip exceptions — short-circuit the pipeline

Section titled “Skip exceptions — short-circuit the pipeline”

Three exception classes let hook functions completely bypass the normal execution step and inject a synthetic result. Raise them inside before_* or wrap-style hooks.

SkipModelRequest — inject a cached response

Section titled “SkipModelRequest — inject a cached response”
import asyncio
import hashlib
import json
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
from pydantic_ai.exceptions import SkipModelRequest
from pydantic_ai.messages import ModelMessagesTypeAdapter, ModelResponse, TextPart
from pydantic_ai.usage import RequestUsage
import datetime
_cache: dict[str, ModelResponse] = {}
def _cache_key(messages) -> str:
# Messages are dataclasses, not Pydantic models: serialise them with the type adapter.
# Drop timestamps / ids so identical prompts produce identical keys.
dumped = ModelMessagesTypeAdapter.dump_python(
list(messages),
mode='json',
exclude={'__all__': {'timestamp': True, 'run_id': True, 'conversation_id': True,
'parts': {'__all__': {'timestamp'}}}},
)
return hashlib.sha256(json.dumps(dumped, sort_keys=True, default=str).encode()).hexdigest()
def _make_response(text: str) -> ModelResponse:
return ModelResponse(
parts=[TextPart(content=text)],
model_name='cache',
usage=RequestUsage(input_tokens=0, output_tokens=0),
timestamp=datetime.datetime.now(datetime.timezone.utc),
)
hooks = Hooks()
@hooks.on.before_model_request
async def serve_from_cache(ctx, request_context):
key = _cache_key(request_context.messages)
if key in _cache:
raise SkipModelRequest(_cache[key]) # ← bypass the model API call
return request_context
@hooks.on.after_model_request
async def populate_cache(ctx, *, request_context, response):
_cache[_cache_key(request_context.messages)] = response
return response
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
async def main():
r1 = await agent.run('What is 2 + 2?') # API call
r2 = await agent.run('What is 2 + 2?') # cache hit — no API call
print(r1.output, r2.output)
asyncio.run(main())

SkipModelRequest takes a single ModelResponse argument. Any message history modifications made by earlier capabilities in the same before_model_request call are not persisted when this exception is raised.

SkipToolValidation — bypass Pydantic validation

Section titled “SkipToolValidation — bypass Pydantic validation”
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
from pydantic_ai.exceptions import SkipToolValidation
hooks = Hooks()
@hooks.on.before_tool_validate(tools=['search'])
async def normalise_query(ctx, *, call, tool_def, args):
"""Lowercase the query and skip validation (args here are the raw, unvalidated arguments)."""
if isinstance(args, dict) and 'query' in args:
raise SkipToolValidation({**args, 'query': args['query'].lower()})
return args
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
@agent.tool_plain
def search(query: str) -> list[str]:
return [f'Result: {query}']
from pydantic_ai import Agent
from pydantic_ai.capabilities import Hooks
from pydantic_ai.exceptions import SkipToolExecution
DRY_RUN = True
hooks = Hooks()
@hooks.on.before_tool_execute(tools=['delete_record', 'send_email'])
async def dry_run_guard(ctx, *, call, tool_def, args):
if DRY_RUN:
raise SkipToolExecution(f'[DRY RUN] {tool_def.name}({args})')
return args
agent = Agent('openai:gpt-6.1-sol', capabilities=[hooks])
@agent.tool_plain
def delete_record(record_id: str) -> bool:
return True # never runs in dry-run mode

SkipToolExecution takes the result to return to the model as its sole argument. The tool function is never called.

  • Hooks class — capabilities/hooks.py
  • HookTimeoutError — raised when timeout= is exceeded
  • AbstractCapability — base class for custom capabilities (capabilities/abstract.py)
  • Hook function protocols (type annotations) — all *HookFunc classes in capabilities/hooks.py
  • deferred_tool_calls hook (AbstractCapability.handle_deferred_tool_calls) — capabilities/hooks.py; the standalone HandleDeferredToolCalls capability is in capabilities/deferred_tool_handler.py
  • SkipModelRequest, SkipToolValidation, SkipToolExecution — exceptions.py