liveBook · Manning

After_tool_callback

As explained in Build an AI Agent (From Scratch)

An after-tool callback is a hook invoked after a tool executes that can replace the tool's original result.

An after-tool callback runs after a tool executes and can transform or replace its result without changing the agent’s core tool logic. It is useful for postprocessing such as compressing search output or masking sensitive information. section 5.5.1 section 5.6

The callback receives an ExecutionContext and ToolResult. Returning None preserves the original result; returning a value replaces it. With multiple callbacks, processing stops at the first non-None return. section 5.5.2

Implement the tool path in three stages:

  • Run the tool and obtain its ToolResult. section 5.5.2
  • Invoke each after_tool_callback, awaiting asynchronous results when necessary. section 5.5.2
  • Replace the result when a callback returns a new ToolResult; otherwise pass the original result onward. section 5.5.2

Compressing web-search output

A search_compressor checks whether the tool is search_web and whether its content exceeds 2,000 characters. For long results, it matches the search query by tool_call_id, chunks the content, performs vector search, and returns the top three chunks in a new ToolResult. Other tools and short results pass through unchanged. section 5.5.4

Figure 5.7 Points where callbacks are inserted into the agent execution flow. LLM callbacks are called before and after think(), and tool callbacks are called before and after each tool execution within act().

Trace callback placement around each tool execution within the agent’s act phase, alongside the before- and after-LLM extension points. section 5.5.1

How Build an AI Agent (From Scratch) covers it

How deep it goes
Implements callback registration, asynchronous dispatch, early exit, and ToolResult replacement inside Agent.act.
Examples
Demonstrates compressing long search_web results into three relevant chunks while preserving short and unrelated tool results.
What it assumes
Assumes familiarity with agents, tools, ToolResult, callbacks, and vector search; teaches the callback contract from its execution stages.
What you can do after
Build it from scratch by registering callbacks that intercept and replace tool results during asynchronous agent execution.
How it connects
Connects callbacks with tool execution, before_tool_callback, ExecutionContext, vector search, and token reduction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build an AI Agent (From Scratch). The section links point to the parts of the book it draws on.