liveBook · Manning

Before_tool_callback

As explained in Build an AI Agent (From Scratch)

A before-tool callback is a hook invoked before a tool executes that can bypass execution by supplying a result.

A before-tool callback is an interception point before tool execution. It can approve, validate, or replace a tool call; returning a value skips the tool and uses that value as the result, while returning None allows execution. section 5.5.1 section 5.5.2

Implement the callback flow in three stages:

  • Run registered callbacks in order, passing ExecutionContext and the ToolCall. section 5.5.2
  • Stop at the first non-None result, applying the Early Exit pattern; otherwise execute the tool. section 5.5.2
  • Support asynchronous callbacks by checking awaitable results before continuing. section 5.5.2

Approval and cache interception

Register an approval callback in before_tool_callbacks alongside tools such as search_web, list_files, read_file, and delete_file. The callback can request approval for a dangerous operation or return a cached result, preventing execution. Pair it with an after-tool callback when postprocessing is also required. section 5.5.1 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().

Use the execution-flow diagram to locate before_tool_callback between the agent's reasoning step and each tool execution. section 5.5.1

How Build an AI Agent (From Scratch) covers it

How deep it goes
Explains registration, ordered early exit, asynchronous handling, and the three-stage act flow, but defers asynchronous human approval to later treatment.
Examples
Demonstrates dangerous-operation approval, cached results, and an Agent configured with search and file-management tools.
What it assumes
Assumes Python agent, tool-call, and execution-context structures while teaching callback behavior from its execution contract.
What you can do after
Build it from scratch by adding callback lists and refactoring act() to intercept, bypass, or permit each tool call.
How it connects
Connects callbacks with tool execution, ExecutionContext, HITL approval, caching, input validation, and after_tool_callback.

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.