What are lifecycle hooks?
Hooks are functions that run at specific stages of agent execution:on_start- Before agent execution beginson_end- After agent execution completeson_agent_step_start- Before each agent reasoning stepon_agent_step_end- After each agent reasoning stepon_tool_start- Before each tool executionon_tool_end- After each tool execution
Defining hooks
Create hooks using the@hook decorator:
ctx-WorkflowContextwith execution metadatahook_context-HookContextwith current execution state- Returns -
HookResultindicating what action to take
Hook results
Hooks returnHookResult with three options:
1. Continue without changes
2. Continue with modifications
3. Fail and stop execution
Using hooks
Attach hooks to agents:Hook context
Hooks receiveHookContext with execution state:
Multiple hooks
Hooks run in order. If any hook fails, execution stops:validate_input_hook fails, redact_pii_hook and add_metadata_hook never run.