Skip to main content

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_reasonMeaningLoop action
tool_useClaude emitted one or more tool_use blocksExecute them, append results, iterate
end_turnClaude finished naturallyTerminate, return the final text
max_tokensOutput cap hitNot a completion signal — raise max_tokens or stream
pause_turnServer-tool turn pausedResume by sending the response back
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 });
}

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.input as JSON (JSON.parse, json.loads). Never string-match the serialized input.
  • Return all tool_result blocks 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 — with is_error: true. Dropping it leaves a dangling tool_use.

Model-driven vs pre-configured control flow​

Model-drivenPre-configured decision tree
Claude reasons about which tool to call next from contextFixed tool sequence encoded in application code
Adapts to unanticipated request shapesDeterministic, auditable, no adaptability
Correct default for high-ambiguity work (support, research)Correct when compliance ordering is mandatory (see 1.4)

Anti-patterns​

Loop termination anti-patterns
  • Parsing natural language for completion signals ("if the reply contains 'done'…"). stop_reason is 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 text content as a completion indicator. A turn can contain both text and tool_use blocks.

Preparation exercise 1 — Multi-tool agent with escalation logic​

Objective: an agentic loop with tool integration, structured error handling, and escalation patterns.

  1. 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.
  2. Implement an agentic loop that checks stop_reason to decide between continuing tool execution and presenting the final response. Handle both "tool_use" and "end_turn" correctly.
  3. 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.
  4. 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.
  5. 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

What to notice

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​

  1. 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?

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

  3. 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?

  4. 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?