The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
Build the loop that turns Claude's tool calls into an agent: send the messages, read stop_reason, run tools while it says tool_use, stop on end_turn, and see the naive text check quit early and a turn cap catch a stuck loop.
What you will learn
- Write an agent loop that lets stop_reason decide when the work is done
- Let Claude chain several tools on its own, one lap at a time
- Explain why stopping on any text quits too early
- Use a turn cap as a safety net, not as the stop rule
Before you start
- Claude tool use: tool_use and tool_result
- The Claude Messages API: your first call
A customer asks the shop: Where is my order 1042? The person at the counter doesn't know. They have to look it up first, and only then answer.
Claude is in the same spot. It can't see your orders, so one call to the model can't answer: the fact is simply missing. A small loop fills the gap. And the whole job of that loop comes down to one field on every reply: stop_reason.
The single tool round trip (one tool_use, one tool_result) is covered in Claude tool use. This article is about the loop around it: how many laps it runs, who decides when it ends, and the two ways a loop goes wrong.
The manager decides, the assistant runs the errand
Picture a manager and an assistant with a phone.
- The manager says: call the warehouse about order 1042. That's a tool use.
- The assistant writes the answer on a note and hands it back: shipped, arrives Friday. That's the tool result.
- The manager now has everything and says: tell the customer it arrives Friday. That's end turn.
Notice who never decides when the job is done: the assistant. Claude is the manager. Your code is the assistant with the phone.
One loop, one decision
The rule is short: keep turning while stop_reason is tool_use; stop when it is end_turn. On every lap the messages list grows by two entries, Claude's turn and your results. The API remembers nothing between calls, so each request sends the whole list again.
Every turn is a block in the list
After one lap of the order question, the list holds:
- A
usermessage with the question. - An
assistantmessage with Claude'stool_useblock: an id, the namelookup_orderand the input{"order_id": "1042"}. - A
usermessage with atool_resultblock whosetool_use_idis the id Claude gave. That's how Claude matches the answer to the question. Results go back as a user turn, never an assistant one.
Then Claude's second reply is plain text with stop_reason set to end_turn.
agent/loop.py
The project is a support agent with two tools, lookup_order and check_return_policy, reading two small JSON files. It runs against a stand-in model (the Anthropic SDK on an httpx mock transport), so no API key is needed; every reply is scripted and starts with "test model reply". With a real key in a .env file, the same loop calls Claude.
"""The agentic loop: send, read stop_reason, run tools, append results, go round."""
from agent.tools import TOOLS, run_tool
MAX_TURNS = 5
def run_agent(client, task):
messages = [{"role": "user", "content": task}]
for turn in range(1, MAX_TURNS + 1):
response = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024,
tools=TOOLS, messages=messages)
if response.stop_reason == "end_turn":
print(f" turn {turn}: end_turn")
return "".join(b.text for b in response.content if b.type == "text")
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
print(f" turn {turn}: tool_use -> {block.name}")
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": run_tool(block.name, block.input)})
messages.append({"role": "user", "content": results})
return f"stopped by the safety cap after {MAX_TURNS} turns"
- The
forline is the turn cap. It's only a safety net. - Each lap sends the messages list and the tools.
- The one check that matters: if
stop_reasonisend_turn, Claude is done and the loop returns its text. - If not, Claude's turn is kept in the list exactly as it was sent.
- Each
tool_useblock is run, and itstool_resultcopies the block's id. All results go back together in one user message.
Claude picks the next tool
python main.py loop asks two questions:
agent loop: one tool
turn 1: tool_use -> lookup_order
turn 2: end_turn
answer: test model reply: your wireless headphones arrive Friday.
agent loop: two tools
turn 1: tool_use -> lookup_order
turn 2: tool_use -> check_return_policy
turn 3: end_turn
answer: test model reply: arrives Friday, and returns are open for 30 days.
The replies are scripted by the stand-in. The first question takes two laps. The second, Where is my order 1042, and can I return it?, takes three: Claude asks for lookup_order, then, by itself, for check_return_policy, then ends the turn. Nobody told the loop to call the second tool. The loop didn't change; only the list got longer.
The tempting way to stop, and why it breaks
Here is a loop that looks reasonable. It stops as soon as the reply contains any text:
"""The tempting loop that stops when the reply contains any text. Do not copy it."""
from agent.tools import TOOLS, run_tool
def run_naive(client, task):
messages = [{"role": "user", "content": task}]
turn = 0
while True:
turn += 1
response = client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024,
tools=TOOLS, messages=messages)
text = "".join(b.text for b in response.content if b.type == "text")
if text:
print(f" turn {turn}: text found, loop stops")
return text
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
print(f" turn {turn}: tool_use -> {block.name}")
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": run_tool(block.name, block.input)})
messages.append({"role": "user", "content": results})
The bug is if text:. Claude often writes a sentence and asks for a tool in the same reply. This loop sees the sentence and leaves before the tool runs. It also has no cap at all.
python main.py traps runs both traps:
naive loop: one tool
turn 1: tool_use -> lookup_order
turn 2: text found, loop stops
answer: test model reply: your wireless headphones arrive Friday.
naive loop: two tools
turn 1: text found, loop stops
answer: test model reply: let me check that order.
agent loop: order 9999
turn 1: tool_use -> lookup_order
turn 2: tool_use -> lookup_order
turn 3: tool_use -> lookup_order
turn 4: tool_use -> lookup_order
turn 5: tool_use -> lookup_order
answer: stopped by the safety cap after 5 turns
- Quit early. With one tool the naive loop happens to work, only because the text came last. With two tools, the first reply has text and a
tool_use. The loop quits, the customer gets "let me check that order", and the tool never ran. - Never quit. A stuck task (keep checking order 9999 until it shows up) asks for the same lookup again and again. The real loop stops after five turns because of the cap.
The cap is a safety net. The stop rule is stop_reason.
Common mistakes
- Stopping when the text "sounds done". Text and
tool_usecan arrive together. Readstop_reason. - Stopping after a fixed number of turns. That's the cap's job as a safety net, not the stop rule. A fixed count either cuts off real work or wastes calls.
- Always running the same tools in the same order. That takes the choice away from Claude; at that point you've built a workflow (see workflow or agent).
- Dropping Claude's turn. Append the assistant content unchanged before the results, or the
tool_resulthas notool_useto answer. - Forgetting the id. Every
tool_resultcarries thetool_use_idfrom Claude's block. - Treating every other stop reason as "continue". This loop returns only on
end_turn, so any other value (for examplemax_tokens) would go round again with no tool to run. Many loops write the test the other way,if response.stop_reason != "tool_use": return, which leaves on anything that isn't a tool request. Pick one and handle the other values on purpose.
Quick recap
| stop_reason / situation | What the loop does |
|---|---|
tool_use | Append Claude's turn, run each tool, append the tool_result blocks (same ids) as one user message, go round |
end_turn | Return the text and stop |
Text plus tool_use in one reply | Still a tool turn: run the tool |
Never reaches end_turn | The turn cap stops it (here, 5 turns) |
When your loop also needs approval rules, unknown-tool handling and error results, see custom agent loops and harnesses.
Try it yourself
Add a third tool, track_parcel, and a question that needs all three: Where is order 1042, has the courier picked it up, and can I return it? Predict the number of laps and the tool_use lines the loop will print. The stand-in only knows the scripted questions, so run this one with a real key in .env, or add a script for it to the stand-in. Then lower MAX_TURNS to 2 and check what the customer gets back.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.