Claude API Tool Calling Tutorial with Python
On this page
Learning Objective
Implement a real agent loop with the Claude Messages API: define tools with JSON Schema, read tool_use blocks, return tool_result blocks with matching ids, handle parallel tool calls and errors, and check stop reasons correctly.
Concept Explanation
The Claude Messages API supports tool calling directly on the single messages endpoint. You pass a tools array where each tool has a name, a description and an input_schema written in JSON Schema. When the model wants to use a tool, the response contains one or more content blocks of type tool_use, each with a unique id, the tool name and an input object that matches the schema. The response's stop_reason is tool_use, which tells your loop that work is pending.
Your code then runs each requested tool and sends a new user message containing tool_result blocks. Each result carries the tool_use_id it answers, the content, and optionally is_error set to true when the tool failed. The pairing by id is strict: every tool_use in the assistant turn must be answered by a tool_result in the next user turn. The assistant message itself must be appended to the history exactly as returned, including any thinking blocks, because the API validates that the conversation is consistent.
Modern models frequently request several tools at once, for example looking up two customers in parallel. All the results must go back in a single user message, one tool_result per tool_use. Splitting them across several messages is technically allowed in some cases but teaches the model to stop calling tools in parallel, which slows every future task. Run independent calls concurrently and return them together.
You can control how the model chooses tools with tool_choice. The default, auto, lets the model decide whether to call a tool. On the current Claude models, forcing a specific tool is no longer supported, so you steer through the system prompt and tool descriptions instead, and you can set strict to true on a tool definition so the arguments are guaranteed to validate against its schema. Strict mode removes a whole class of bugs where the model sends a string where you expected a number.
Stop reasons drive the loop. end_turn means the model finished. tool_use means it wants tools run. max_tokens means the output was truncated, so increase the limit or stream rather than treating the partial text as an answer. refusal means a safety classifier declined the request. pause_turn appears when server-side tools ran for a long time and the turn should be resumed by sending the conversation back.
| Field | Where | Purpose |
|---|---|---|
| tools[].input_schema | Request | JSON Schema the arguments must satisfy |
| tools[].strict | Request | Guarantees arguments validate exactly against the schema |
| tool_use block (id, name, input) | Response | The model's request to run a tool |
| tool_result block (tool_use_id, content, is_error) | Next request | Your answer to one tool_use |
| stop_reason | Response | end_turn, tool_use, max_tokens, refusal, pause_turn |
Worked Example: A Complete Agent with Two Tools
This agent answers questions about orders. It runs parallel tool calls concurrently, returns all results in one message, reports failures with is_error, and refuses to treat truncated output as an answer.
import json
from concurrent.futures import ThreadPoolExecutor
import anthropic
client = anthropic.Anthropic()
ORDERS = {"A-100": {"status": "shipped", "carrier": "UPS", "eta": "2026-10-09"}}
def get_order(order_id: str) -> dict:
if order_id not in ORDERS:
raise KeyError(f"No order {order_id}. Order ids look like A-100.")
return ORDERS[order_id]
def get_refund_policy() -> str:
return "Refunds within 30 days of delivery. Shipping is not refundable."
HANDLERS = {"get_order": get_order, "get_refund_policy": get_refund_policy}
TOOLS = [
{"name": "get_order", "strict": True,
"description": "Look up one order by id (format A-123). Returns status, carrier and ETA.",
"input_schema": {"type": "object", "additionalProperties": False,
"properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}},
{"name": "get_refund_policy", "strict": True,
"description": "Return the refund policy text. Use before answering any refund question.",
"input_schema": {"type": "object", "additionalProperties": False, "properties": {}, "required": []}},
]
def run_tool(block) -> dict:
try:
out = HANDLERS[block.name](**block.input)
return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(out)}
except Exception as exc:
return {"type": "tool_result", "tool_use_id": block.id, "content": str(exc), "is_error": True}
def agent(question: str, max_steps: int = 8) -> str:
messages = [{"role": "user", "content": question}]
for _ in range(max_steps):
resp = client.messages.create(
model="claude-opus-5-5", max_tokens=16000,
system="You are a support agent. Use tools for facts; never guess order data.",
tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": resp.content}) # keep every block
if resp.stop_reason == "end_turn":
return "".join(b.text for b in resp.content if b.type == "text")
if resp.stop_reason != "tool_use":
raise RuntimeError(f"Unexpected stop: {resp.stop_reason}") # max_tokens, refusal
calls = [b for b in resp.content if b.type == "tool_use"]
with ThreadPoolExecutor() as pool: # parallel calls
results = list(pool.map(run_tool, calls))
messages.append({"role": "user", "content": results}) # one message, all results
return "Stopped after the step limit."
print(agent("Where is order A-100, and could I still get a refund?"))On this question the model typically calls get_order and get_refund_policy in the same turn, receives both results together, and answers in the second turn. Try asking about order 100 without the prefix: the error message tells the model the expected format, and it retries with A-100.
Real-World Examples
- Anthropic's tool use documentation recommends returning all parallel tool results in a single user message, noting that splitting them reduces the model's future use of parallel calls.
- The Anthropic Python and TypeScript SDKs include a tool runner helper that implements this exact loop from decorated functions, which is the recommended starting point once you understand what it does underneath.
Review Questions & Answers
Each tool_use block has a unique id, and each tool_result block must carry that id in its tool_use_id field. Every tool_use in an assistant turn must be answered by a matching tool_result in the following user turn.
The API expects all results for one assistant turn together, and splitting them teaches the model to stop making parallel calls, which makes later tasks slower. Running them concurrently and returning them together keeps both behaviour and latency good.
Treat the output as incomplete. Increase max_tokens, use streaming for long outputs, or continue the turn, but never present the truncated text as a finished answer or try to run a partially generated tool call.
It guarantees the model's arguments validate exactly against the input schema, removing bugs such as a missing required field or a string where a number was expected, so your handler can trust the input shape.