Overview
An agent loop is the cycle that turns a stateless model into an agent: send the conversation, run any tool the model requests, append the result, and call the model again until it replies without a tool call. With the Claude API the loop continues while stop_reason is "tool_use" and ends on "end_turn".
Set the exits before writing the prompt. Cap iterations and total tokens, and require human approval for destructive tool calls; without caps an agent can retry a failing tool until the budget is gone. Long loops fill the context-window, so clear or summarize old tool results before the window fills. For a task with many steps, split planning from execution with planner-executor.
Example
“Fix the failing test”: read file (tool call), run tests (fail), edit file (tool call), run tests (pass), final answer. That is five model calls and three tool calls.
Related
- tool-use: the request and result messages the loop exchanges.
- planner-executor: a two-phase variant of the loop.
- agent-architecture-patterns: loop designs and when to use each.
- reliable-agents-in-production: limits, retries, and approval gates.
- multi-agent: loops that orchestrate other loops.