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.
share
watch the video
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.
- Your code sends
messages[]. - Claude replies with content blocks, which may include text and
tool_useblocks. - Your code reads
response.stop_reason. - On
"tool_use", your code runs every tool the reply asked for. - Your code appends the assistant reply verbatim, then a user message with one
tool_resultpertool_useblock. - The loop returns to step 1. It exits at step 3 on
"end_turn".
Interactive · two passes of the web-search subagent's loop
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.
"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.
Your moveRun every requested tool, append the reply and the results, send.
Your moveAppend the reply as returned and send. Run nothing.
Your moveReturn the answer. This is the normal exit.
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.
// 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.
// 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.
A workflow
"Orchestrated through predefined code paths." Fits when the steps are known before the input arrives.
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.
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 finishedTurn 3: "done" matches while a search is pending. Turn 10: the range ends mid-search.
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.
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 reached | The work is unfinished. Continue it or raise an error, but never return it as the report. |
- 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_resultpertool_use_id. - An iteration cap is a safety net: when it trips, the run has failed and should say so.