Deployed Lab

Module 2 · Agentic architecture and orchestration · Chapter 3 · Free

Build the agentic loop: stop_reason, tool results and when to stop

20 min1 clickable picture1 break-it lab1 predict, 2 quick quizzes, 5-question final quiz5-min video review
In 30 seconds

The picture: a kitchen ticket. The cook (Claude) asks for salt, the runner (your code) fetches it, and "plate is ready" means done.

Exam objective: Task statement 1.1

Domain 1, Agentic Architecture and Orchestration (27 percent). Design and implement agentic loops. You should be able to:

The cold open Harbor & Pine Outfitters is a made-up gear shop. Kavish builds "Pine", a support agent, and it handles 2,100 chats over one weekend. The loop stopped at the first text, and Claude often writes a friendly sentence beside its tool request.
The plan for this chapter
  1. Follow one trip around the loop.
  2. Read stop_reason, shape the history.
  3. Who picks the next step: Claude or your script.
  4. Three stop rules that fail.
  5. 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:

The agentic loop Send the history to Claude, read stop_reason, run any tools asked for, append the reply and results, and send again. On end_turn, return the final answer. Historygrows every turn Claudeone reply per request stop_reason?your code reads it Run the toolsin your code Final answer tool_use end_turn append reply, then results
  1. "Refund my trail jacket, order 48213" becomes the first user message. The list is Claude's whole memory.
  2. Send system prompt, tool definitions and the full list. Each request stands alone.
  3. The reply holds content blocks plus a stop_reason. Here: a sentence and a get_customer request, reason "tool_use".
  4. The API sets this field. It is the signal you can trust; wording is not.
  5. Your code runs the real function and captures its output. Claude only asked.
  6. Add Claude's whole reply as an assistant message, then one user message with the results.
  7. Repeat with lookup_order, then process_refund. Each request grows.
  8. 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

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:

  1. A user message with the question.
  2. An assistant message: Claude's full reply, text and tool requests. Each request has an id.
  3. A user message with one result per request, each naming its tool_use_id.
  4. 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

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

Scenario (a made-up story) Owen Brandt asks Kavish for a loop in a developer helper exploring the old 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.

Scenario (at a customer) Imran Qureshi, the security reviewer, asks: "What stops the agent from looping forever and spending money?" Kavish answers: healthy runs stop on 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.

Field note, November 2026

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

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.

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".