Skip to content

1.1 Agentic Loops

An agentic loop is the core execution cycle behind every Claude-based agent. It’s deterministic control flow, defined in code. Not a prompt trick, not a retry loop, not a chatbot turn. Get this lifecycle right and most of Domain 1 falls into place; get it wrong and your agent stops halfway through a task in production.

The loop follows four steps, repeated until completion:

  1. Send a request to Claude via the Messages API. This includes the conversation history (system prompt, prior messages, and any tool results from the previous iteration).

  2. Inspect the stop_reason field in the response. This field is the authoritative signal for what happens next. It has two values relevant to agentic loops:

    • "tool_use" — Claude wants to call one or more tools. The loop continues.
    • "end_turn" — Claude has finished its work. The loop terminates.
  3. If stop_reason is "tool_use": execute the requested tool(s), append the tool results to the conversation history as a new message, and send the updated conversation back to Claude.

  4. If stop_reason is "end_turn": the agent has finished. Present the final response to the user.

Step 3 is where loops break. Tool results must be appended to conversation history. Miss that, and Claude can’t reason about the new information on the next iteration — the model never sees what the tool returned, so it has nothing new to act on.

In an agentic loop, Claude decides which tool to call from the current context. That’s model-driven decision-making — the model reads the task, weighs the available tools, and picks one. Compare that to pre-configured decision trees or fixed tool sequences, where the developer hard-codes which tool runs when.

The exam favours model-driven approaches because they flex. Claude adapts to situations the developer never mapped out, handles edge cases, and chains tools in orders nobody planned. There’s one exception worth memorising: when business logic demands deterministic compliance — financial operations, security checks, regulatory requirements — programmatic enforcement overrides that flexibility. Task Statement 1.4 covers this in detail.

Three anti-patterns show up again and again for loop termination. Learn to spot all three.

Anti-Pattern 1: Parsing natural language signals. Checking if Claude said “I’m done” or “task complete” to determine whether the loop should end. This is wrong because natural language is inherently ambiguous. Claude might say “I’ve finished analysing the first file” while intending to continue with more files. The stop_reason field exists precisely to eliminate this ambiguity.

Anti-Pattern 2: Arbitrary iteration caps as the primary stopping mechanism. Setting “stop after 10 loops” as the main way to terminate the agent. This is wrong because it either cuts off useful work (if the task genuinely needs 12 iterations) or runs unnecessary iterations (if the task finishes in 3). The model signals completion via stop_reason — use that signal. Iteration caps are acceptable as a safety net (a maximum bound to prevent runaway agents), but never as the primary control mechanism.

Anti-Pattern 3: Checking for assistant text content as a completion indicator. Using response.content[0].type == "text" to decide the loop is finished. This is wrong because Claude can return text alongside tool_use blocks. A response might contain explanatory text (“I’ll now search for the customer’s order history”) immediately followed by a tool call. Checking for text presence does not tell you whether the agent is finished.

Practical Example: The Premature Termination Bug

Section titled “Practical Example: The Premature Termination Bug”

A developer builds a customer support agent. It works for simple queries but sometimes stops mid-task on complex requests. The code checks if response.content[0].type == "text" to determine completion.

The bug: Claude returns a text explanation (“Let me look up your order”) alongside a tool_use block requesting the lookup_order tool. The code sees text in position [0], concludes the agent is finished, and returns the incomplete response to the user.

The fix: replace the content-type check with a stop_reason check. Continue the loop when stop_reason == "tool_use", terminate when stop_reason == "end_turn". This works regardless of what content types appear in the response.

A developer’s agent sometimes terminates prematurely when Claude returns text alongside a tool call. Their loop checks response.content[0].type == ‘text’ to determine if the agent is finished. Users report incomplete responses on complex queries. What should the developer change?

  • A. Add an iteration cap of 15 loops to ensure the agent runs long enough for complex queries
  • B. Set tool_choice to any so Claude always calls a tool instead of returning text
  • C. Parse the assistant text for completion phrases like I have finished before terminating the loop
  • D. Check the stop_reason field instead of content type — continue when stop_reason is tool_use, terminate when end_turn
Answer & explanation

Correct: D

  • A — Arbitrary caps do not address the root cause. The agent exits because it misidentifies the response type, not because it loops insufficient times. A cap of 15 would still terminate prematurely if the text-check bug triggers on iteration 2.
  • B — This forces tool use even when the agent is genuinely finished, creating an infinite loop. The issue is not that Claude returns text — the issue is that the code misinterprets text presence as a completion signal.
  • C — Natural language parsing is ambiguous and unreliable. Claude might say it has finished one step while intending to continue with the next. The stop_reason field already provides an unambiguous signal.
  • D — The stop_reason field is the deterministic, authoritative signal for loop control. It correctly distinguishes between responses where Claude wants to call more tools (tool_use) and responses where Claude has finished (end_turn), regardless of whether text content appears alongside tool calls.

Five exam-style multiple-choice questions on Agentic Loops. Pick an answer, then open the explanation.

A developer’s agent sometimes terminates prematurely when Claude returns text alongside a tool call. Their loop checks response.content[0].type == "text" to determine if the agent is finished. Users report incomplete responses on complex queries. What should the developer change?

  • A. Add an iteration cap of 15 loops to ensure the agent runs long enough for complex queries
  • B. Parse the assistant’s text for completion phrases like “I have finished” before terminating the loop
  • C. Check the stop_reason field instead of content type — continue when stop_reason is “tool_use”, terminate when “end_turn”
  • D. Set tool_choice to “any” so Claude always calls a tool instead of returning text, and treat a text-only reply as the end of the run
Answer & explanation

Correct: C

  • C is correct because stop_reason is the deterministic, authoritative signal for loop control. It correctly distinguishes between responses where Claude wants to call more tools (tool_use) and responses where Claude has finished (end_turn), regardless of whether text content appears alongside tool calls.
  • A is wrong because arbitrary caps do not address the root cause. The agent exits because it misidentifies the response type, not because it loops insufficient times. A cap of 15 would still terminate prematurely if the text-check bug triggers on iteration 2.
  • B is wrong because natural language parsing is ambiguous and unreliable. Claude might say it has finished one step while intending to continue with the next. The stop_reason field already provides an unambiguous signal.
  • D is wrong because this forces tool use even when the agent is genuinely finished, creating an infinite loop. The issue is not that Claude returns text — the issue is that the code misinterprets text presence as a completion signal.

Which of the following correctly describes the agentic loop lifecycle?

  • A. Send request, inspect stop_reason, if “tool_use” execute tools and append results to history, if “end_turn” finish
  • B. Send request, check if response contains text, parse text for instructions, execute any tools mentioned in text
  • C. Send request, execute all available tools in sequence, check if any returned errors, retry failed tools
  • D. Send request, count tokens in response, if tokens exceed threshold then tools are needed, otherwise finish
Answer & explanation

Correct: A

  • A is correct because the agentic loop lifecycle follows four deterministic steps: send request via Messages API, inspect stop_reason, execute tools and append results if tool_use, terminate if end_turn.
  • B is wrong because it relies on parsing natural language text for instructions, which is ambiguous. The stop_reason field, not text content, determines what happens next.
  • C is wrong because an agentic loop does not execute all tools in sequence. Claude selects which tool to call based on context (model-driven decision-making). Tools are not retried automatically.
  • D is wrong because token count has no bearing on loop control. The stop_reason field is the sole authoritative signal for whether to continue or terminate.

An agent completes simple tasks correctly but enters an infinite loop on complex queries. The developer’s fix is to add an iteration cap of 10. What is wrong with this approach?

  • A. The iteration cap is too low — it should be at least 50 for complex queries
  • B. Iteration caps only work with synchronous APIs, not with streaming responses
  • C. The agent needs more tools to handle complex queries, not an iteration cap
  • D. Caps are a safety net, but the real bug is an unchecked stop_reason
Answer & explanation

Correct: D

  • D is correct because the infinite loop indicates stop_reason is not being used correctly as the primary control mechanism. An iteration cap masks the underlying bug rather than fixing it. Caps are acceptable only as a safety net (maximum bound) to prevent runaway agents, not as primary loop control.
  • A is wrong because increasing the cap does not fix the root cause. If the loop is infinite because stop_reason is not being checked, no cap value solves the underlying problem — it just delays termination.
  • B is wrong because iteration caps can apply to any execution mode. The issue is using them as primary control rather than checking stop_reason.
  • C is wrong because the number of tools is unrelated to infinite loop behaviour. The loop continues or terminates based on stop_reason, not on whether the right tools are available.

Why must tool results be appended to the conversation history before sending the next request to Claude?

  • A. To reduce API costs by caching previous responses
  • B. So Claude can reason about what the tool returned before deciding what to do next
  • C. To enable streaming of partial results to the user interface
  • D. Because the Messages API rejects requests that do not include complete conversation history
Answer & explanation

Correct: B

  • B is correct because the model needs to see what the tool returned in order to decide its next action. Without tool results in the conversation history, Claude cannot incorporate tool output into its reasoning chain and cannot make informed decisions about whether to call another tool or finish.
  • A is wrong because appending tool results is about enabling reasoning continuity, not cost reduction. The model needs the data to think, not to save money.
  • C is wrong because tool result appending is about the model’s reasoning chain, not about streaming partial results to users. These are separate concerns.
  • D is wrong because the API does not reject incomplete histories as a technical constraint. The issue is that without tool results, the model lacks information needed for correct reasoning.

A customer support agent uses model-driven decision-making to select tools. Under what circumstance should this approach be overridden with programmatic enforcement?

  • A. When the task requires deterministic compliance for financial, security, or regulatory operations
  • B. When the agent is handling more than 3 concurrent conversations, because parallel sessions make model-driven tool selection unreliable
  • C. When the user requests a specific tool by name in their message
  • D. When the agent has access to more than 5 tools, since a wider tool surface makes the model’s selection harder to predict
Answer & explanation

Correct: A

  • A is correct because model-driven decision-making is probabilistic. For operations where a single failure causes financial loss, security breach, or compliance violation, programmatic enforcement provides deterministic guarantees that override model flexibility.
  • B is wrong because the number of concurrent conversations does not determine whether to use model-driven or programmatic approaches. Enforcement type is determined by the stakes of the operation.
  • C is wrong because user requests do not override the architectural decision between model-driven and programmatic enforcement. The stakes of the operation determine the approach.
  • D is wrong because the number of available tools is irrelevant to the enforcement decision. Whether the agent has 2 tools or 20, high-stakes operations require programmatic enforcement.