Skip to main content
Hooks let you register middleware callbacks that fire at key points in the agent execution lifecycle. Register once with WithHooks — the SDK calls your functions automatically across Run and Stream. Every hook can inspect, mutate, or abort the operation it wraps. Return an error from any hook to abort the run immediately.

Register hooks

Call WithHooks multiple times to register independent groups. Each group runs under its own name in RunMeta.HooksGroup:
Hook group names participate in the Temporal agent config fingerprint. The agent and worker processes must register the same hook group names — implementations are not hashed, only the names.

Hook points

Every hook receives RunMeta with RunID, Iteration, and HooksGroup for correlation.

Use cases

Guardrails and safety

Block unsafe inputs before they reach the LLM and filter toxic outputs before they reach the user:
Hooks: BeforeLLM, AfterLLM

PII and data privacy

Scrub sensitive data before it leaves your system or gets persisted:
Hooks: BeforeLLM, AfterLLM, BeforeTool, AfterTool, BeforeRetrieve, AfterRetrieve, BeforeMemoryStore, AfterMemoryLoad

Token budget and cost tracking

Enforce a per-run or per-user token budget across LLM calls:
Hooks: BeforeLLM (cache read / short-circuit), AfterLLM (token tracking, cache write, model fallback)

Tenant isolation for memory

Enforce that each tenant only reads and writes their own memories:
Hooks: BeforeMemoryLoad, BeforeMemoryStore

Audit logging

Log every operation for observability without touching business logic:
Hooks: BeforeLLM, AfterLLM, BeforeTool, AfterTool, BeforeRetrieve, AfterRetrieve, AfterMemoryLoad, AfterMemoryStore

Retrieval query rewriting and re-ranking

Modify the query before search and filter or re-rank results after:
Hooks: BeforeRetrieve (query rewriting), AfterRetrieve (filtering, re-ranking)

Use case reference

Example

Hooks

PII scrubbing, retrieval filtering, memory tenant isolation — every hook point registered

Memory

BeforeMemoryLoad and BeforeMemoryStore hooks

Retrieval

BeforeRetrieve and AfterRetrieve hooks