Lesson 33.2 · 2 of 6 · 7 min read · Reviewed 24 Nov 2026
The request, tool_use, tool_result cycle
By the end, you can
- Run the full tool use loop until stop_reason is end_turn.
- Return tool results in the right shape, matched by tool_use_id.
The diagram above walks through one full cycle. In code, the loop looks like this:
messages = [{"role": "user", "content": question}]
for turn in range(10): # always cap the loop
response = client.messages.create(model=MODEL, max_tokens=1024, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
results = []
for block in response.content:
if block.type == "tool_use":
output, failed = run_tool(block.name, block.input)
results.append({"type": "tool_result", "tool_use_id": block.id, "content": output, "is_error": failed})
messages.append({"role": "user", "content": results})
const messages: Anthropic.MessageParam[] = [{ role: 'user', content: question }];
for (let turn = 0; turn < 10; turn++) { // always cap the loop
const response = await client.messages.create({ model: MODEL, max_tokens: 1024, tools: TOOLS, messages });
messages.push({ role: 'assistant', content: response.content });
if (response.stop_reason !== 'tool_use') break;
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of response.content) {
if (block.type === 'tool_use') {
const { output, failed } = await runTool(block.name, block.input);
results.push({ type: 'tool_result', tool_use_id: block.id, content: output, is_error: failed });
}
}
messages.push({ role: 'user', content: results });
}
The rules that matter
- The API is stateless. Every request carries the whole conversation, including earlier tool calls and results.
- Keep the assistant turn intact. Append Claude’s full
content, including any text before thetool_useblock. - Match ids. Each
tool_resultnames thetool_use_idit answers. All results for one assistant turn go in the next single user message. - Report failures, don’t hide them. Set
is_error: truewith a useful message. Claude can retry, choose another route or explain the problem. - Stop deliberately. End on
end_turn, and also cap the number of iterations so a confused loop cannot run up cost.
On other providers
Not every API is fully stateless. OpenAI’s Responses API can store a conversation on the server, so the next call passes only previous_response_id and the new input. That saves bandwidth, not tokens: the model still reads the whole history and you are still billed for it. It also moves conversation data onto the provider, which matters for retention and residencyData residency: A requirement that data is stored or processed in a particular country or region. rules (70.4).
Key points
- Claude returns tool_use blocks with stop_reason tool_use; your code runs the tool.
- Results go back as tool_result blocks in a user message, matched by tool_use_id.
- Loop until stop_reason is end_turn, with a cap on iterations.
Run the tool loop until end_turn
Complete the request, tool_use, tool_result cycle with a capped loop.
You will have: A loop that runs the tool, returns results matched by tool_use_id, and stops on end_turn.
Steps
- Run the starter: it stops after the first tool_use.
- For each tool_use block, run the tool and build a tool_result with block.id.
- Append all results in one user message and remove the early break.
- Run it and check the final answer and stop reason.
Done when
- The tool runs once, for Lisbon.
- The final stop_reason is end_turn.
- The loop uses 2 turns, under its cap of 5.
Open in the Playground No API key needed.
Starter code (Python)
# Run the full tool use loop: call, run the tool, return the result, until end_turn.
import json
import anthropic
client = anthropic.Anthropic()
WEATHER = {"Lisbon": {"temp_c": 19, "conditions": "sunny"}}
tools = [{
"name": "get_weather",
"description": "Current weather for one city: temperature in Celsius and conditions. Use when asked about the weather now.",
"input_schema": {"type": "object", "properties": {"city": {"type": "string", "description": "City name, e.g. Lisbon"}}, "required": ["city"]},
}]
def run_tool(name, args):
if name == "get_weather" and args.get("city") in WEATHER:
return json.dumps(WEATHER[args["city"]]), False
return json.dumps({"error": f"no data for {args}"}), True
messages = [{"role": "user", "content": "What's the weather in Lisbon?"}]
for turn in range(1, 6): # always cap the loop
response = client.messages.create(model="claude-sonnet-5-5", max_tokens=500, tools=tools, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
# TODO: for each tool_use block, call run_tool(block.name, block.input)
# TODO: append ONE user message whose content is a list of tool_result blocks,
# each with "tool_use_id": block.id, the output as "content", and "is_error".
break # TODO: remove this once results go back
print("answer:", "".join(b.text for b in response.content if b.type == "text"))
print("stop_reason:", response.stop_reason)
print("turns used:", turn)
Show a solution
# Run the full tool use loop: call, run the tool, return the result, until end_turn.
import json
import anthropic
client = anthropic.Anthropic()
WEATHER = {"Lisbon": {"temp_c": 19, "conditions": "sunny"}}
tools = [{
"name": "get_weather",
"description": "Current weather for one city: temperature in Celsius and conditions. Use when asked about the weather now.",
"input_schema": {"type": "object", "properties": {"city": {"type": "string", "description": "City name, e.g. Lisbon"}}, "required": ["city"]},
}]
def run_tool(name, args):
if name == "get_weather" and args.get("city") in WEATHER:
return json.dumps(WEATHER[args["city"]]), False
return json.dumps({"error": f"no data for {args}"}), True
messages = [{"role": "user", "content": "What's the weather in Lisbon?"}]
for turn in range(1, 6): # always cap the loop
response = client.messages.create(model="claude-sonnet-5-5", max_tokens=500, tools=tools, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break
results = []
for block in response.content:
if block.type == "tool_use":
output, failed = run_tool(block.name, block.input)
print(f"turn {turn}: ran {block.name}({block.input['city']})")
results.append({"type": "tool_result", "tool_use_id": block.id, "content": output, "is_error": failed})
messages.append({"role": "user", "content": results})
print("answer:", "".join(b.text for b in response.content if b.type == "text"))
print("stop_reason:", response.stop_reason)
print("turns used:", turn)
Do it Build the loop in the Playground in the Playground. No API key needed.