Claude Agentic Loop: stop_reason, Tool Results and Anti-Patterns
👋 In plain words: A chatbot answers once. An agent keeps working: it asks for a tool, gets the result, and decides what to do next until the job is done. The agentic loop is the small piece of code that keeps this going and knows when to stop.
Every Claude agent — whether you write it yourself or use the Agent SDK — is built on one loop: ask Claude, run the tools it requests, give it the results, repeat. Get the stop condition wrong and your agent either quits mid-task or never finishes. This is Task Statement 1.1 of the exam.
🔑 Key terms
- Agentic loop: Code that repeatedly sends the conversation to Claude, runs any tools it asks for, and sends back the results.
- stop_reason: A field in every Claude response that says why it stopped, for example
tool_useorend_turn. - tool_use: Claude's request to run a tool, including the tool name and inputs.
- tool_result: Your reply that carries the tool's output back to Claude, matched by
tool_use_id. - end_turn: The stop reason meaning Claude has finished its answer.
📖 The story in this lesson
A ShopNest customer asks the support bot: 'Where is order #48213?' To answer, the bot must call lookup_order, read the result, and then reply. That takes two trips to Claude, and the agentic loop manages both.
💡 Think of it like this
The loop is like a manager and an assistant. The manager (Claude) says 'fetch me the order file'. The assistant (your code) fetches it and puts it on the desk. This repeats until the manager says 'done, here is the answer'. The assistant must listen for 'done', not guess from the manager's tone.
🔁 The loop, step by step
- Send the conversation (and tool definitions) to the Messages API.
- Inspect
stop_reasonon the response. - If it is
"tool_use": run each requested tool and append one user message containing everytool_resultblock, matched bytool_use_id. - Call Claude again with the updated history.
- Stop when
stop_reasonis"end_turn".
messages = [{"role": "user", "content": user_question}]
while True:
resp = client.messages.create(model=MODEL, max_tokens=4096,
tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use": # "end_turn" (also handle max_tokens, refusal)
break
results = []
for block in resp.content:
if block.type == "tool_use":
results.append(run_tool(block)) # returns a tool_result dict
messages.append({"role": "user", "content": results}) # ALL results, ONE message
🌍 Real-world example: Two trips to answer one question
Trip 1: Claude replies with stop_reason tool_use and asks for lookup_order with order 48213. Your code runs the lookup and sends back a tool_result. Trip 2: Claude reads 'shipped, arriving Friday', writes the answer, and the stop_reason is end_turn. The loop stops.
trip 1 -> stop_reason: tool_use (run lookup_order)
trip 2 -> stop_reason: end_turn (show the answer)📘 Why the model chooses the next step
In an agent, Claude reasons about which tool to call next from the context, including the results it has just seen. That is the difference from a pre-configured decision tree, where code fixes the sequence. Tool results must be appended to the history, otherwise the model cannot use them and will often request the same tool again.
🌍 Real-world example: The bot adapts to what it finds
The lookup shows order 48213 was delivered yesterday, but the customer says it never arrived. Nobody coded that path. Claude decides by itself to call get_delivery_photo next. That flexibility is what makes it an agent rather than a fixed script.
⚠️ Termination anti-patterns (exam favourites)
- Stopping when the response “contains text” — Claude often writes a sentence and a tool call in the same turn.
- Parsing phrases such as “DONE” or “Is there anything else?” — natural-language signals are brittle.
- A fixed iteration cap — fine as a safety backstop, never as the loop logic.
🌍 Real-world example: The bug that stopped too early
A ShopNest developer stopped the loop whenever Claude's reply contained text. Claude wrote 'Let me check that order for you' and asked for a tool in the same reply. The loop stopped, the tool never ran, and the customer got half an answer. Checking stop_reason fixes it.
🛑 Other stop reasons you should know
| stop_reason | Meaning | What to do |
|---|---|---|
end_turn | Claude finished | Return the answer |
tool_use | Claude wants tools run | Run them, append results, loop |
max_tokens | Output was cut off | Raise the limit or continue |
stop_sequence | A custom stop sequence was hit | Handle per your design |
pause_turn | Long server-tool turn paused | Send the response back to continue |
refusal | Claude declined | Handle gracefully |
🌍 Real-world example: When the answer gets cut off
Asked for a long returns-policy summary, the bot's reply stops mid-sentence. The stop_reason is max_tokens, meaning Claude hit the length limit. The fix is to raise the limit or ask Claude to continue, not to show the customer a broken sentence.
🛠️ Try it yourself (about 10 minutes)
- Install the SDK with
pip install anthropicand set your API key. - Define one fake tool,
get_order_status, that always returns 'shipped'. - Ask Claude 'Where is order 123?' and print
stop_reasonafter each call. - Send the tool result back and call Claude again.
✅ You are done when: your console prints tool_use and then end_turn, and the final answer mentions 'shipped'.
🧪 Exam-Style Practice Questions
Try these before opening the answers. They use the same scenario style as the real exam.
Question 1. Which loop condition is correct for a manual Claude agentic loop?
- A. Loop until the assistant message contains no text
- B. Loop until the model says "DONE"
- C. Loop while
stop_reason == "tool_use", stop on"end_turn" - D. Loop exactly 5 times
Show answer
Answer: C. stop_reason is the structured signal for whether the model wants a tool run. A: Claude often sends text and tool_use in the same turn. B: parsing natural language is brittle. D: a fixed cap can be a safety backstop, but it's never the primary stop condition.
Question 2. After executing the three tool calls Claude requested in one turn, how should you return the results?
- A. Three separate user messages, one per result
- B. Put the results in the system prompt
- C. One assistant message with the results
- D. One user message containing three
tool_resultblocks, each with itstool_use_id
Show answer
Answer: D. All results for a turn go back in one user message, matched by ID. A: splitting them breaks the turn structure and discourages parallel calls. B and C: results are user-role content, not system or assistant content.
Question 3. What best distinguishes an agent from a workflow?
- A. In an agent the model decides the next action from context; in a workflow, code defines the path
- B. Workflows can't use tools
- C. Agents never need a system prompt
- D. Agents use bigger models
Show answer
Answer: A. Model-driven decision-making is what makes it an agent. D: model size doesn't matter here. B: workflows use tools all the time. C: agents need system prompts too.
📝 Assignment
Do these tasks in order. Each one has a Done when check, so you know when it is complete. The stretch task is optional but close to what the exam expects from an architect. Keep your answers in one notes file or Git repository, and revisit them in your final week of revision together with the cheat sheet in the last lesson of this course.
- Task 1: Implement the loop from this lesson with one tool (get_weather returning fixed data) and print stop_reason on every iteration.
✅ Done when: Your script prints tool_use and then end_turn, and the final answer uses the tool's data. - Task 2: Deliberately break it by stopping on 'response contains text'. Find a prompt where Claude writes a sentence and a tool call together and observe the failure.
✅ Done when: You can show a transcript where the broken loop stops early, and explain in one sentence why stop_reason fixes it. - Stretch: add handling for max_tokens and refusal stop reasons with a clear message to the user.
✅ Done when: A response cut off by max_tokens or a refusal produces a clear message instead of a crash or a silent empty answer.
❓ Frequently Asked Questions
🤔 What stop_reason means Claude wants a tool run?
tool_use. Run every tool_use block in the response and send all results back in one user message.
🤔 Why not stop when the response contains text?
Claude often writes a short sentence and a tool call in the same turn, so text alone does not mean the task is finished.
🤔 Is an iteration cap wrong?
A cap is a good safety backstop, but it should never be the main way the loop decides it is done.
🤔 What happens if I forget to append tool results?
Claude cannot see the results, so it usually asks for the same tool again and the loop repeats.
🏁 Summary
- Loop on
stop_reason == "tool_use"; stop on"end_turn". - Return every tool result for a turn in a single user message.
- Never terminate on text content, phrases or a bare iteration count.
Next, continue with Multi-Agent Orchestration with Claude: Coordinators and Subagents.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Mock questions are original practice items, not real exam content. Exam facts checked against Anthropic's official exam guides and certification FAQ on 11 November 2026.