Task statement 1.1 · Agentic architecture and orchestration

Design and implement agentic loops for autonomous task execution

The coordinator runs an agentic loop while it delegates, and each subagent runs its own while it searches, reads or writes. Each loop decides whether to continue by reading one field on the API response, stop_reason, and not by reading what the model wrote. A loop that decides any other way ships a report that reads as complete but stopped partway through a subtopic.

watch the video

Part 1 of 5 · What is an agentic loop? · 2:12

Agentic loops: 5 parts · 11 min, with chapters

Why it's tested

The tempting stopping conditions all look sensible. Stopping when the reply says "done", or when any text comes back, fails because Claude often narrates one step in the same reply that asks for the next tool, so the loop quits with a search still pending. A fixed turn count feels safe, but on a broad subtopic it cuts the run off mid-search, and the half-finished findings look exactly like finished ones.

KnowledgeOne turn of the loop

An agentic loop is your code calling the Messages API until Claude has nothing left to ask for. Each request sends messages[], the whole conversation so far, and each response carries stop_reason, a field that says why Claude stopped. The value tool_use means Claude wants tools run, and the reply then holds tool_use blocks that each name a tool, its input and an id. Your code runs each tool and sends back its output, and a tool_result is the block that carries that output. The value end_turn means Claude finished its response naturally, so the loop returns the answer. Because the API sets this field, the loop never has to guess from the wording of the reply.

  1. Your code sends messages[].
  2. Claude replies with content blocks, which may include text and tool_use blocks.
  3. Your code reads response.stop_reason.
  4. On "tool_use", your code runs every tool the reply asked for.
  5. Your code appends the assistant reply verbatim, then a user message with one tool_result per tool_use block.
  6. The loop returns to step 1. It exits at step 3 on "end_turn".

Interactive · two passes of the web-search subagent's loop

Vertical flow of one agentic loop iteration: messages array is sent, Claude replies, stop_reason is read, tool_use runs the tool and appends a tool_result before looping back, end_turn exits with the final answer loop — full history messages[] every turn so far POST /v1/messages Claude decides: ask for a tool, or answer response.stop_reason your code reads one field "tool_use" "end_turn" run every tool it asked for results append 2 messages assistant, then user with tool_result loop exits final answer is written

Press Step to follow the loop from the first request to the exit.

Step 1 · The web-search subagent sends messages[], every turn so far.

Step 2 · Claude replies with a sentence and a web_search request in the same turn.

Step 3 · Your code reads stop_reason. It is "tool_use".

Step 4 · The search runs.

Step 5 · Two messages appended: the assistant turn, then a user turn with the tool_result.

Step 6 · Back to step 1, carrying the whole history.

Step 2 again · Claude reads the results and writes its answer.

Step 3 again · stop_reason is "end_turn", so the loop exits with that answer.

Time reads downward. The first six states are steps 1–6 of the list, and the last two are a second pass through steps 2 and 3 that ends on "end_turn". The dashed rail carries the whole history back to the top, never a summary.

KnowledgeWhat each stop_reason tells your loop to do

The API documents seven stop_reason values. Four matter to a research loop: two mean send another request, one means done, and one means the answer is incomplete. The value pause_turn means a server tool, such as the web_search tool that Anthropic runs for you, reached its limit of 10 iterations per request, so you send the assistant content back and Claude carries on. The value max_tokens means the reply reached the output limit in your request, so the answer is cut off, and the docs say to raise the limit or continue the response.

"tool_use"send again

Your moveRun every requested tool, append the reply and the results, send.

"pause_turn"send again

Your moveAppend the reply as returned and send. Run nothing.

"end_turn"loop ends

Your moveReturn the answer. This is the normal exit.

"max_tokens"incomplete

Your moveRaise the limit and continue the reply. If it ends inside a tool_use block, resend the request instead.

More precise than the guide. The guide names only "tool_use" (continue) and "end_turn" (terminate). The API also returns "pause_turn", "max_tokens", "stop_sequence", "refusal" and "model_context_window_exceeded", so a loop that continues only on "tool_use" can return an unfinished search as its answer (checked 2026-09-30). Exam answer: continue on "tool_use", terminate on "end_turn".

KnowledgeHow tool results re-enter the conversation

Claude keeps no memory between requests, so a search result can shape the next step only if it is in messages[] when the next request goes out. Your code appends the assistant reply exactly as it came back, then one user message holding every tool_result for that reply, before any text. Each result carries a tool_use_id, the field that names the id of the tool_use block it answers. Because the whole history travels every time, Claude can see which queries already ran and what they found, so it can fill a gap instead of repeating a search. Here is one turn of the web-search subagent's loop.

What comes back
// response
{
  "stop_reason": "tool_use",
  "content": [
    { "type": "text",
      "text": "Starting with recent coverage." },
    { "type": "tool_use",
      "id": "toolu_01A09q90qw90lq9",
      "name": "web_search",
      "input": { "query": "AI in film scoring" } }
  ]
}

The reply holds a text block and a tool_use block in the same turn, so "did any text come back?" cannot tell you the turn is finished.

What you append
// two messages, in this order
{ "role": "assistant",
  "content": [ /* the array above, verbatim */ ] },

{ "role": "user",
  "content": [
    { "type": "tool_result",
      "tool_use_id": "toolu_01A09q90qw90lq9",
      "content": "[{\"url\":\"…\"}]" }
  ] }

The results travel in a user message. Four parallel searches would get four results, each matched by its own tool_use_id.

KnowledgeWho picks the next step

That growing history is what lets the loop be model-driven. In a pre-configured decision tree, your code fixes the sequence of tool calls before the run starts. In model-driven decision-making, Claude reads the latest results and decides which tool to call next. Suppose web_search("AI in film scoring") returns a 2024 composers' guild survey that mentions licensing disputes. A fixed sequence moves on to its next hard-coded step, but the model-driven subagent can call web_search("AI music licensing disputes"), a query nobody wrote in advance. When the model chooses each step, only the model can say that no step is left, and stop_reason is how it says so. Anthropic's definitions draw the same line.

Pre-configured decision tree

A workflow

"Orchestrated through predefined code paths." Fits when the steps are known before the input arrives.

Model-driven decision-making

An agent

"Dynamically direct their own processes and tool usage." Fits when the next step depends on what the last tool returned.

SkillA loop that stops on the wrong signal

The web-search subagent is asked for "AI in film scoring" and returns three sources with a summary that reads as complete. The log shows the loop stopped at turn 3, when Claude wrote "Festival coverage done, now checking studio deals" beside a tool_use block for the studio search, so the search never ran. On the broad subtopic "AI in music", the same loop used up its ten turns with seven of twelve planned queries finished, and returned those findings as final. The code shows the three anti-patterns the guide names: parsing natural language signals to decide termination, checking for assistant text content as a completion indicator, and an arbitrary iteration cap as the primary stopping mechanism.

Before

The prose or the count ends the loop

for i in range(10):
    r = client.messages.create(**kw)
    if "done" in text_of(r).lower():
        break
    run_tools_and_append(r, kw)
return findings(kw)  # looks finished

Turn 3: "done" matches while a search is pending. Turn 10: the range ends mid-search.

After

stop_reason ends the loop

MAX_TURNS = 40  # a guard, not the exit
msgs = kw["messages"]
for turn in range(MAX_TURNS):
    r = client.messages.create(**kw)
    if r.stop_reason == "end_turn":
        return final_text(r)
    msgs.append(assistant_turn(r))
    if r.stop_reason == "tool_use":
        msgs.append(tool_results(r))
    elif r.stop_reason == "max_tokens":
        kw["max_tokens"] *= 2  # continue
    elif r.stop_reason != "pause_turn":
        raise StoppedEarly(r.stop_reason)
raise LoopCapExceeded(MAX_TURNS)

The same two runs now continue after turn 3 and finish on "end_turn" at turns 7 and 22.

The fix reads stop_reason and nothing else, so a reply that narrates "done" beside a pending search simply goes round again. The iteration cap stays, because a runaway loop costs tokens on every turn, but it becomes a secondary guard. Hitting it now raises LoopCapExceeded, so the coordinator sees a failure instead of a half-finished report. A cap that no healthy run reaches is doing its job, while a cap that ends most runs has become the primary stopping mechanism again.

Before your loop sends or returns, ask: What does stop_reason say about this reply?
"tool_use" or "pause_turn"Append, then send another request.
"end_turn"Return the answer. This is the only normal exit.
Anything else, or the turn cap is reachedThe work is unfinished. Continue it or raise an error, but never return it as the report.
Takeaway
  • Control flow comes from the response metadata, never from the words Claude wrote.
  • Each iteration appends the assistant reply verbatim, then a user message with one tool_result per tool_use_id.
  • An iteration cap is a safety net: when it trips, the run has failed and should say so.

check yourself

0 / 3 answered

The document analysis subagent's loop is for turn in range(8), and it returns whatever findings exist when the range runs out. On batches of 40 PDFs, a third of runs end this way, and the synthesis subagent treats their partial findings as complete. Finance requires a hard turn ceiling on every run, because each turn costs about $0.30.Which change best stops partial findings from reaching synthesis while preserving the turn ceiling?

Select one.

Two research runs shipped unfinished reports. In one, the web search subagent's loop ended on stop_reason: "pause_turn" after its web_search server tool reached the per-request limit. In the other, the report generation subagent's loop ended on "max_tokens" mid-sentence. Both loops continue only while stop_reason is "tool_use". The team wants the fix inside the loops themselves.Which TWO changes best stop both loops from returning unfinished work?

Select two.

The document analysis subagent calls load_document on the same three PDFs again and again until its turn ceiling. To save tokens, its loop rebuilds messages on each turn from the original prompt, the latest assistant turn and that turn's tool_result blocks. Every request is accepted without an error, and the log for turn 9 shows three entries in messages.What is the most likely root cause?

Select one.

sources

  1. Claude Platform Docs, "Stop reasons and fallback": the seven stop_reason values; end_turn as "the most common stop reason"; pause_turn when a server-tool loop reaches its limit (default 10 iterations), handled by sending the assistant content back; "Raise max_tokens or continue the response" on max_tokens, including resending with a higher limit when a tool_use block was cut off. Checked 2026-10-01.
  2. Claude Platform Docs, "Handle tool calls": the tool_result fields (tool_use_id, content, is_error), the user role that carries them, and results placed first and immediately after the tool_use message. Checked 2026-09-30.
  3. Claude Platform Docs, "Parallel tool use": one tool_result per tool_use block, all together in the next user message. Checked 2026-09-30.
  4. Anthropic Engineering, "Building effective agents": workflows "orchestrated through predefined code paths" versus agents that "dynamically direct their own processes and tool usage", and stopping conditions such as a maximum number of iterations. Checked 2026-09-30.
  5. The loop lifecycle, the "tool_use"/"end_turn" control flow and the three anti-patterns: Claude Certified Architect — Foundations Exam Guide v1.0, Domain 1.1. Scenario: the guide's Scenario 3. The film-scoring queries and turn counts are this course's illustration.