Example: Adding a Calculator to Our Agent › Understanding the Tool Use Flow
AI Agent HandbookAll chapters Example: Adding a Calculator to Our Agent › Understanding the Tool Use FlowOne section · Sections in this chapter9 / 16 ↓
Let's trace through exactly what happens when you ask "What's ?":
Step 1: User Input
User: What's 1234 times 5678?Step 2: Agent Analyzes the Question
Claude receives:
- The user's message
- The calculator tool description
- Instructions to use tools when appropriate
Claude thinks: "This is a multiplication problem with large numbers. I should use the calculate tool to get the exact answer."
Step 3: Agent Requests Tool Use
Claude returns a response indicating it wants to use a tool:
{
"stop_reason": "tool_use",
"content": [
{
"type": "tool_use",
"name": "calculate",
"input": {"expression": "1234 * 5678"}
}
]
}{'stop_reason': 'tool_use',
'content': [{'type': 'tool_use',
'name': 'calculate',
'input': {'expression': '1234 * 5678'}}]}Step 4: We Call the Tool
Our code extracts the tool name and input, then calls:
calculate(expression="1234 * 5678"){'success': True, 'result': 7006652, 'expression': '1234 * 5678'}Which returns:
{'success': True, 'result': 7006652, 'expression': '1234 * 5678'}{'success': True, 'result': 7006652, 'expression': '1234 * 5678'}Step 5: We Send the Result Back
We add the tool result to the conversation and send it back to Claude:
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": "...",
"content": "{'success': True, 'result': 7006652, 'expression': '1234 * 5678'}"
}]
})Step 6: Agent Formulates Final Response
Claude receives the tool result and generates a natural response:
1,234 times 5,678 equals 7,006,652.This entire flow happens in milliseconds. From the user's perspective, they just asked a question and got an accurate answer.