Building AI Agents from Scratch with Python · Tools and Real-World Robustness
The Tool-Calling Pattern
Tool calling is how you let the model trigger real code instead of just generating text. You describe each tool's name, purpose, and parameters; the model can then respond with a request to call one instead of a plain-text reply. Your code executes the actual function, and feeds the result back into the loop as the next observation.
Perceive: user asks "what's 47 * 892?"
Think: model decides: this needs the calculator tool
Act: your code runs calculator(47, 892) → 41924
Perceive: tool result (41924) is added to the conversation
Think: model now has enough info to answer directly
Act: model replies "47 × 892 = 41,924"
Note that the loop ran through Perceive→Think→Act twice for one user question — once to decide it needed a tool, once to use the tool's result. This is exactly the branching Chapter 1 talked about: the number of iterations isn't fixed in code, it depends on what the model decides at each step.
A tool definition, in Anthropic's API shape, is just a JSON Schema description:
tools = [
{
"name": "calculator",
"description": "Evaluate a basic arithmetic expression.",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "e.g. '47 * 892'",
}
},
"required": ["expression"],
},
}
]
The description fields aren't documentation for humans — they're the only information the model has about when and how to use the tool. Vague descriptions are the single most common cause of an agent calling the wrong tool, or the right tool with bad arguments.