1.1 Agentic loops for autonomous task execution
The loop
An agentic loop is driven by stop_reason, nothing else. It is the finite-state contract between your code and the model.
stop_reason | Meaning | Loop action |
|---|---|---|
tool_use | Claude emitted one or more tool_use blocks | Execute them, append results, iterate |
end_turn | Claude finished naturally | Terminate, return the final text |
max_tokens | Output cap hit | Not a completion signal — raise max_tokens or stream |
pause_turn | Server-tool turn paused | Resume by sending the response back |
- TypeScript
- Python
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: "Refund the damaged item on order 12345." },
];
while (true) {
const response = await client.messages.create({
model: "claude-opus-5",
max_tokens: 16000,
system: SUPPORT_SYSTEM_PROMPT,
tools: SUPPORT_TOOLS,
messages,
});
// The assistant turn goes into history verbatim, including tool_use blocks.
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason !== "tool_use") break; // end_turn -> done
// Execute every tool_use block, then return ALL results in ONE user message.
const toolResults: Anthropic.ToolResultBlockParam[] = await Promise.all(
response.content
.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use")
.map(async (block) => {
try {
return {
type: "tool_result" as const,
tool_use_id: block.id,
content: JSON.stringify(await execute(block.name, block.input)),
};
} catch (err) {
return {
type: "tool_result" as const,
tool_use_id: block.id,
is_error: true,
content: String(err),
};
}
}),
);
messages.push({ role: "user", content: toolResults });
}
import json
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Refund the damaged item on order 12345."}]
while True:
response = client.messages.create(
model="claude-opus-5",
max_tokens=16000,
system=SUPPORT_SYSTEM_PROMPT,
tools=SUPPORT_TOOLS,
messages=messages,
)
# The assistant turn goes into history verbatim, including tool_use blocks.
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason != "tool_use":
break # end_turn -> done
# Execute every tool_use block, then return ALL results in ONE user message.
tool_results = []
for block in response.content:
if block.type != "tool_use":
continue
try:
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(execute(block.name, block.input)),
})
except Exception as err:
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"is_error": True,
"content": str(err),
})
messages.append({"role": "user", "content": tool_results})
Why tool results must be appended
Tool results are appended to conversation history so the model can reason about the next action with the new information in context. Skipping the append — or summarizing results away before the next iteration — breaks the model's ability to chain steps.
Two mechanical rules that items probe:
- Parse
tool_use.inputas JSON (JSON.parse,json.loads). Never string-match the serialized input. - Return all
tool_resultblocks in a single user message. Splitting parallel results across multiple messages trains the model to stop making parallel calls. - A failed tool still needs a
tool_result— withis_error: true. Dropping it leaves a danglingtool_use.
Model-driven vs pre-configured control flow
| Model-driven | Pre-configured decision tree |
|---|---|
| Claude reasons about which tool to call next from context | Fixed tool sequence encoded in application code |
| Adapts to unanticipated request shapes | Deterministic, auditable, no adaptability |
| Correct default for high-ambiguity work (support, research) | Correct when compliance ordering is mandatory (see 1.4) |
Anti-patterns
- Parsing natural language for completion signals ("if the reply contains 'done'…").
stop_reasonis the contract. - Arbitrary iteration caps as the primary stopping mechanism. A cap is a safety net against runaway loops, not a termination condition.
- Checking for assistant
textcontent as a completion indicator. A turn can contain both text andtool_useblocks.
Preparation exercise 1 — Multi-tool agent with escalation logic
Objective: an agentic loop with tool integration, structured error handling, and escalation patterns.
- Define 3–4 MCP tools with detailed descriptions covering purpose, expected inputs, and boundary conditions. Include at least two tools with similar functionality so description quality is what separates them.
- Implement an agentic loop that checks
stop_reasonto decide between continuing tool execution and presenting the final response. Handle both"tool_use"and"end_turn"correctly. - Add structured error responses:
errorCategory(transient / validation / permission),isRetryable, and human-readable descriptions. Verify the agent retries transient errors and explains business errors to the user. - Implement a programmatic hook that intercepts tool calls to enforce a business rule (blocking operations above a threshold amount) and redirects to an escalation workflow.
- Test with multi-concern messages and verify the agent decomposes the request, handles each concern, and synthesises a unified response.
Reinforces: Domain 1, Domain 2, Domain 5
Step 1 and step 4 are the whole exam in miniature: description quality is the fix for selection problems, and a hook is the fix for compliance problems. Confusing the two costs items in every scenario.
Quiz
- Question 1
Your loop executes tools correctly, but on each iteration it rebuilds the messages array from the original customer turn plus a running prose summary of what the tools have returned so far. Resolution quality is acceptable, yet the agent re-calls lookup_order for an order it retrieved two iterations earlier, and it has twice contradicted a refund eligibility it stated itself. What is the underlying defect?
- Question 2Select all that apply (2)
Your loop must handle every stop_reason the API can return for the support agent, which calls client-side MCP tools and one server-side search tool. Which two statements describe correct loop behaviour? Select two.
- Question 3
Your extraction agent loops: request, tool_use, run the extraction tool, append the result, request again. It terminates when a response contains no tool_use block. On documents over 30 pages it sometimes returns a partial extraction and stops, and traces show those final responses carry stop_reason "max_tokens". What is the correct handling?
- Question 4
A colleague proposes replacing the agentic loop with a decision tree: classify each request into one of nine intents, then run the fixed tool sequence registered for that intent. Coverage analysis shows the nine intents account for 93% of historical tickets, and the sequences are derived from what the agent already does. What is the strongest consequence to raise?
Links
- https://code.claude.com/docs/en/agent-sdk/agent-loop
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/how-tool-use-works
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls
- https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/parallel-tool-use
- https://platform.claude.com/docs/en/api/messages
- https://www.anthropic.com/engineering/building-effective-agents
- https://code.claude.com/docs/en/agent-sdk/overview
- https://code.claude.com/docs/en/agent-sdk/quickstart