A callback is a user-defined function invoked at a specified point in an agent’s execution. It lets you add behavior—such as tool approval or result compression—without changing the agent’s core logic. section 5.5 section 5.5.1
Choose the intervention point according to the job:
- Before or after an LLM call: change context, check a cache, or validate a response. section 5.5.1
- Before or after a tool call: approve execution, supply a cached result, compress output, or mask sensitive information. section 5.5.1 section 5.5.4
- After an agent run: save the conversation or generate a summary. section 5.5.1
To implement tool callbacks, give the agent lists of before-tool and after-tool functions, defaulting to empty lists. For each tool call, run the before callbacks first. A non-None return value becomes the tool result and skips execution; None lets execution proceed. Then run the tool if needed, followed by the after callbacks. An after callback’s non-None ToolResult replaces the result; None preserves it. When several callbacks are registered, stop at the first non-None return value. Await a callback result when it is awaitable. section 5.5.2
Approve a dangerous tool
Register an approval function in before_tool_callbacks. It returns None immediately for safe tools. For delete_file, it displays the tool and arguments and asks the user to confirm. Approval returns None, allowing execution; denial returns a rejection message instead, so the tool is skipped and the LLM can respond on its next step. The demonstration delete_file tool only reports deletion—it does not delete a file. section 5.5.3
Compress a search result
Register a search compressor in after_tool_callbacks alongside the approval callback. For a long search_web result, it finds the matching query through the tool-call ID, chunks the result, embeds the chunks, and uses vector search to retain relevant content. Unrelated or short results pass through unchanged. This reduces search-result noise and token use without changing the agent loop. section 5.5.4
The approval example waits on synchronous input, blocking the program. That is suitable for local testing, not for a web service or API server; an asynchronous approval flow must request a response and resume later. section 5.5.4


















