Module 2 · Agentic architecture and orchestration · Chapter 3 · Free
Build the agentic loop: stop_reason, tool results and when to stop
- An agentic loop is a few lines of your code: send, read
stop_reason, run the tools Claude asked for, append results, repeat. - Loop while
stop_reasonis"tool_use". Stop on"end_turn". That field is the only reliable signal. - Never decide "done" from the text or a turn count. A cap is a safety net only.
The picture: a kitchen ticket. The cook (Claude) asks for salt, the runner (your code) fetches it, and "plate is ready" means done.
Domain 1, Agentic Architecture and Orchestration (27 percent). Design and implement agentic loops. You should be able to:
- Describe the loop and how tool results join the history.
- Tell model-driven decisions from fixed tool sequences.
- Fix three anti-patterns: parsing text for "I'm done", a turn cap as the main stop rule, "some text" as completion.
- By Monday, 340 chats (about 16 percent) ended with: "Let me look up your order for you." Then nothing.
- Each customer wrote back. At a made-up $6 per contact, that is 340 × $6 = $2,040.
- First-contact resolution landed near 64 percent, against a goal of 80.
- Follow one trip around the loop.
- Read
stop_reason, shape the history. - Who picks the next step: Claude or your script.
- Three stop rules that fail.
- The cost of one refund, then a broken loop to fix.
Next: the picture.
Step 1: Follow one trip around the loop
Claude is the cook, your code is the runner, the history is the counter. Press Next to walk the trip.
Where the picture breaks down:
- A cook remembers the kitchen. Claude remembers nothing between requests, so the history is its whole memory.
- A runner can see the dish. Your code only moves requests and results.
- "Refund my trail jacket, order 48213" becomes the first user message. The list is Claude's whole memory.
- Send system prompt, tool definitions and the full list. Each request stands alone.
- The reply holds content blocks plus a
stop_reason. Here: a sentence and aget_customerrequest, reason"tool_use". - The API sets this field. It is the signal you can trust; wording is not.
- Your code runs the real function and captures its output. Claude only asked.
- Add Claude's whole reply as an assistant message, then one user message with the results.
- Repeat with
lookup_order, thenprocess_refund. Each request grows. - The last reply has
"end_turn": "Your $129.00 refund is on its way." Stop, return it.
Next: what stop_reason can say, and what you append.
Step 2: Read stop_reason and shape the history
"tool_use": Claude wants tools run. Keep going."end_turn": Claude finished. Stop.
Other values exist, such as "max_tokens". Log unknown values and fail loudly. The list changes, so check the current docs. (Version-dependent.)
The history follows a strict pattern:
- A user message with the question.
- An assistant message: Claude's full reply, text and tool requests. Each request has an
id. - A user message with one result per request, each naming its
tool_use_id. - Repeat steps 2 and 3 until
end_turn.
Append the whole assistant reply, not just its text. Two tool requests in one reply means both results go in the same user message.
The loop as code (illustrative; model name is a placeholder):
messages = [{"role": "user", "content": user_text}]
MAX_TURNS = 25 # backstop only
for turn in range(MAX_TURNS):
response = client.messages.create(model=MODEL, max_tokens=1024,
system=SYSTEM_PROMPT, tools=TOOLS, messages=messages)
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "end_turn": # the stop rule
break
if response.stop_reason != "tool_use":
raise RuntimeError(response.stop_reason) # log, fail loudly
results = []
for block in response.content:
if block.type == "tool_use":
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": run_tool(block.name, block.input)})
messages.append({"role": "user", "content": results})
else:
escalate_to_human(messages, reason="hit MAX_TURNS")
Predict first:
Text beside a tool request is normal. The loop quit early: the cold-open bug. stop_reason said "tool_use" all along.
Next: who chooses the next tool?
Step 3: Let Claude choose the next step, or script it
- Model-driven. You list the tools. Claude picks the next one, or decides it is done.
- Pre-configured. You fix the order in code:
get_customer,lookup_order,process_refund.
A fixed sequence guarantees the same steps every time, which suits narrow, strict jobs. But a chat mixing a dispute, a return and a wrong address forces you to code every path. A model-driven loop adapts, and cannot promise an order.
Pine's requests are open-ended, so model-driven fits. Rules that must always hold, like "refunds above $500 need a human", belong in code. Chapter 6 covers enforcing order with hooks.
Next: the three wrong stop rules the exam tests.
Step 4: Three stop rules that fail, and why
1. Read the text for "I'm done". Example: if "all set" in reply_text: break. Wording changes. The text is for the customer; the field is for your code.
2. A turn cap as the main stop rule. Example: for _ in range(5). A six-tool dispute gets cut off, maybe after process_refund but before the customer is told. Keep a generous, logged cap as backstop only.
3. Text present means complete. Example: if response.content[0].type == "text": break. Text often sits beside a tool request. This is the cold-open bug.
One rule beats all three: read why the API says it stopped.
Next: what one four-turn refund costs.
Step 5: Worked example, the cost of one refund
Made-up prices: $3 per million input tokens, $15 per million output. The $129.00 refund takes four turns: get_customer (result 200 tokens), lookup_order (1,800 tokens, 40 fields when only 5 matter), process_refund (100 tokens), then the final answer.
Worked example:
1. Call 1: 1,560 input (system prompt, tools, message). Output 80.
2. Call 2 re-sends everything: 1,560 + 80 + 200 = 1,840 input. Output 90.
3. Call 3: 1,840 + 90 + 1,800 = 3,730 input. Output 85. Call 4: 3,730 + 85 + 100 = 3,915 input. Output 70.
4. Totals: 11,045 input, 325 output. Cost: 11,045 ÷ 1,000,000 × $3 = $0.0331, plus 325 ÷ 1,000,000 × $15 = $0.0049, about $0.038.
So one refund costs about 3.8 cents. The driver is the 1,800-token record re-sent in calls 3 and 4. Return only the 5 fields that matter. Chapter 22 covers trimming.
Next: fix the loop Pine shipped, then two stories.
Step 6: Hands-on lab, break the loop Pine shipped
Why this exercise: the exam's favourite loop bug is one line. Finding it in code makes it stick.
Lab: Step 6 ships Pine's broken loop and asks you to build it locally. This lab runs in your browser and needs JavaScript enabled.
Next: two short stories.
Two stories: how it goes in practice
harbor-legacy order service. Version one caps at 10 turns, but one module takes 14 reads.
Decision: raise the cap to 30? Answer: not as the fix. End on end_turn, keep a backstop of 40, log turns, alert past 25. Most runs end by turn 12 to 18, so it never fires.
end_turn; a 25-turn backstop hands any other run to a person; every turn logs stop_reason and tokens.
Result: approved. An alarming cap plus a log is a guarantee.
Teams usually add logging first: one line per turn with stop_reason, tool names and token counts. It turns "the agent seems slow" into a number. Common practice, not a statistic.
The Deployed Lab jobs page (snapshot 15 Nov 2026) lists 367 open roles, median posted base about $243K (base pay only).
Mix-ups to avoid
- Text means done. No: text often sits beside a tool request. Read
stop_reason. - Claude runs the tools. No: Claude asks, your code runs them and appends results.
- A cap is a stop rule. No: a cap is a backstop that fires rarely and alarms.
- Append only the results. No: append Claude's whole reply first, so each
tool_use_idmatches a request. - Model-driven means no rules. No: code still enforces hard limits like the $500 refund rule.
Chapter quiz
Five questions. Score 70% or more to mark this chapter complete.
Review this chapter in 5 minutes
Watch the whole chapter recapped: the loop itself, stop_reason as the only stop signal, history shape, and the stop rules that fail.
- The loop: send, read
stop_reason, run tools, append, repeat. "tool_use"means keep going."end_turn"means stop. Unknown values: log and fail loudly.- Append the whole assistant reply, then one user message with every
tool_result, each matching atool_use_id. - Claude picks the next tool. Fixed sequences only for narrow, strict jobs. Hard rules live in code.
- Anti-patterns: parse text for "done", small cap as stop rule, any text as completion.
- A 4-turn refund re-sends 11,045 input tokens in total, about $0.038 at made-up prices.
Decision rule: decide "done" only from stop_reason. A cap as the normal exit is wrong.
Independent exam preparation. Not affiliated with or endorsed by Anthropic.
Review
Glossary
- Agentic loop
- Code that sends, runs the tools Claude asks for, and repeats until done. Example: the Pine refund flow.
- stop_reason
- The field on a reply saying why Claude stopped:
"tool_use"or"end_turn". - tool_result
- A block in a user message carrying a tool's output back. Example: the order record for 48213.
- tool_use_id
- The id tying a result to its request. Example: result "abc" answers request "abc".
- Conversation history
- The messages list re-sent each turn. Claude has no other memory.
- Model-driven
- Claude picks the next tool from context, not a fixed order in code.
- Backstop cap
- A high turn limit that fires only when something goes wrong, then hands off.
Next: "Coordinator and subagents: hub-and-spoke orchestration that covers the whole topic".