What is an agentic loop?
The agentic loop is the control structure underneath every AI agent. The model receives the task and the current state, responds with either an answer or a request to call a tool, the harness runs the tool and appends the result, and the model decides again. One pass is a turn. The loop ends when the model replies with no tool calls, or when something outside the model ends it.
The vendors describe the same mechanism in nearly the same words. Anthropic's engineering team summarises the Claude Agent SDK as "gather context, take action, verify work, repeat" (September 2025). OpenAI's Agents SDK runner calls the model, ends if the output is final, switches agent on a handoff, or runs the requested tools and loops again (OpenAI docs). The code that runs this cycle, with its tools, permissions and context management, is what people now call the agent harness.
What happens in each phase of the loop?
A useful mental model is four phases. The table maps them to Anthropic's wording and lists what tends to break in each one.
| Phase | What the agent does | Anthropic's term | Typical failure |
|---|---|---|---|
| Observe | Reads the prompt, the history and the latest tool results | Gather context | Context fills up; older instructions get summarised away |
| Plan | Decides the next action, or decides it is finished | (model turn) | The model declares success early, or never does |
| Act | Calls a tool: edit a file, run a command, call an API, hand off to another agent | Take action | Side effects outside the sandbox; repeated calls after a crash |
| Verify | Checks the result against something other than its own opinion | Verify work | Skipped entirely, or done by the same context that wrote the code |
The observe phase has a cost most teams notice late. Context does not reset between turns: the system prompt, tool definitions, every tool input and every tool output accumulate. When the window fills, the Claude Agent SDK compacts older history into a summary, and its documentation warns that instructions from early in the conversation may not survive (agent loop docs). Rules that must hold for the whole run belong in a file the harness re-injects every turn, not in the first prompt.
Which stop conditions should every loop have?
The model's own "I'm done" is one exit, and the least reliable one. Production loops need at least one hard cap and one check the model cannot talk its way past. This is what the three most-used harnesses give you out of the box, as documented in November 2026.
| Exit | Mechanism | Claude Agent SDK | OpenAI Agents SDK | LangGraph | Use it as |
|---|---|---|---|---|---|
| Natural completion | Model returns a response with no tool calls | Result subtype success | Final output with no tool calls | Graph reaches END | Necessary, never sufficient |
| Turn cap | Stop after N tool-use round trips | max_turns (no limit by default) | max_turns, raises MaxTurnsExceeded | Recursion limit on graph steps | The cheapest safety net |
| Budget cap | Stop at a spend threshold | max_budget_usd, covers subagents | Track usage yourself | Track usage yourself | Set one on every unattended run |
| Goal check | An external test decides whether the goal is met | Stop hook; /goal in Claude Code | Output guardrails | Conditional edge on state | Strongest when the check is deterministic |
| Human interrupt | Pause for approval, then resume | canUseTool callback, permission modes | needs_approval, RunState resume | interrupt() with a checkpointer | Reserve for irreversible actions |
Two defaults deserve attention. In the Claude Agent SDK, both the turn cap and the budget cap default to no limit, so an unattended agent with neither set runs until it decides it is finished. LangGraph's recursion-limit error fires when a graph "reached the maximum number of steps before hitting a stop condition", which the docs say is often an infinite loop and sometimes just a large graph. Raise it deliberately, not by reflex.
How should you budget an agent loop?
Budget in three units, because each one fails differently. Turns bound how long the agent can wander. Dollars
bound what a wandering agent costs, including the subagents it spawns; the Claude Agent SDK counts subagent
spend toward max_budget_usd and refuses to spawn more once the cap is reached. Wall-clock time
bounds how long a person waits before someone notices the run is stuck.
Anthropic's own guidance on loops in Claude Code is a reasonable checklist: match the model and effort level to the task, define success and stop criteria before starting, pilot a large run on a small slice first, push deterministic steps into scripts instead of reasoning through them, and do not schedule a loop more often than the data it watches changes (Claude blog, June 2026). The binding constraint is usually not the per-token price. It is the number of turns spent re-discovering context the agent already had.
How do you verify what the loop produced?
Verification is the phase teams skip, and it is the one that decides whether a loop converges. Anthropic lists three methods in order of reliability: rules with clear failure messages (tests, type checks, linters), visual feedback (screenshots checked against the spec), and a model acting as judge, which it calls "generally not a very robust method". The ranking matches the mechanism. A failing test returns a precise error the next turn can act on; a judge model returns an opinion shaped by the same blind spots as the author.
- Prefer deterministic checks. Test counts, a type-checker exit code, a performance score threshold. If you cannot write the check, the task is probably not ready for an unattended loop.
- Separate the verifier's context. A reviewer agent that starts fresh does not inherit the author's assumptions. Claude Code's goal mode uses a separate evaluator that sends work back each time the agent tries to stop.
- Fix the system, not the instance. When a result misses the bar, update the instructions or the check so the next run benefits.
For how to build evaluation suites around agents before rollout, see how to test and evaluate AI agents.
Where does a human belong in the loop?
Put people on irreversible actions and trust boundaries: sending email, moving money, deleting records, deploying, using production credentials. Everything reversible should run under budgets and come back as a reviewable diff. Approving every tool call looks safe and is not, because reviewers stop reading by the twentieth prompt.
All three harnesses support pause and resume. The Claude Agent SDK routes unresolved tool calls to a
canUseTool callback after hooks, deny rules, ask rules and the permission mode have had their say
(permissions docs).
The OpenAI Agents SDK marks tools with needs_approval, returns interruptions, and lets you
serialise the run state and resume it later. LangGraph's interrupt() pauses a node and needs a
checkpointer and thread ID to resume. One detail from OpenAI's documentation applies to all of them:
"Approval permits a tool call to execute; it does not guarantee exactly-once execution." Tools with external
side effects need idempotency keys.
Why do agent loops run away?
Runaway loops have a small number of causes, and each has a specific counter.
- No exit except the model's opinion. The agent keeps "improving" an open-ended goal. Counter: a hard cap plus a deterministic completion check.
- Retrying the same failure. An unreachable service or missing permission produces the same error each turn, and the agent tries variations forever. Counter: detect repeated identical errors in a hook and stop the run.
- Oscillation. Fixing test A breaks test B, and back again. Counter: a turn cap and a rule that the agent reports a blocker instead of trying a third approach.
- Context decay. Compaction drops the original constraint, and the agent drifts. Counter: persistent rules in a re-injected file, and short runs that start from clean context.
- Fan-out. An orchestrator spawns subagents that spawn more. Counter: a budget that covers the whole tree and a limit on subagent depth.
Restarting a loop from a clean context on every iteration, with state kept in files and git, is one deliberate answer to context decay. That is the core of the Ralph loop technique for coding agents.
When should you use a loop at all?
Use an agent loop when the path to the result cannot be written down in advance but the result can be checked. Use a workflow when you can write the steps. Anthropic's own advice on loops opens with the same caution: start with the simplest solution and add loop patterns selectively. The agentic workflows explainer covers when deterministic control wins, and our partner site compares the three main loop harnesses on exactly these controls.
Decision rule: if you cannot name the check that proves the task is done, and the turn and spend caps that end it if the check never passes, the task is not ready to run unattended.
Related questions
Frequently asked questions
What is an agentic loop?
An agentic loop is the cycle an AI agent runs to finish a task: the model looks at the current state, decides on an action, calls a tool, reads the result and decides again. It repeats until the model returns an answer with no further tool calls or until an external limit stops it. Anthropic describes the cycle as gather context, take action, verify work, repeat; OpenAI's Agents SDK and LangGraph implement the same idea with different control surfaces.
What is the difference between an agent loop and a workflow?
In a workflow, your code decides the sequence of steps and the model fills in individual steps. In an agent loop, the model decides the next step each time. Workflows are more predictable and cheaper to test; loops handle tasks whose path you cannot write down in advance. Many production systems are workflows with one or two bounded loops inside them.
How do you stop an AI agent from looping forever?
Set at least two independent exits: a hard cap (maximum turns, a dollar budget or a graph recursion limit) and a completion check the model cannot fake, such as tests passing or a measurable threshold. The Claude Agent SDK exposes max_turns and max_budget_usd, the OpenAI Agents SDK raises MaxTurnsExceeded at its max_turns limit, and LangGraph raises a recursion-limit error when a graph exceeds its step limit.
Where should a human be in the loop?
At the points where an action cannot be undone or crosses a trust boundary: sending messages, moving money, deleting data, deploying, or touching production credentials. All three major SDKs can pause a run for approval and resume it. Approving every step trains people to click yes without reading, which is worse than a well-placed gate.
Is an agent loop the same as recursive self-improvement?
No. An agent loop iterates on a task while the model's weights and core instructions stay fixed. Recursive self-improvement refers to systems that improve their own capabilities or training. Our separate explainer on recursive self-improvement covers that topic.
Sources
- Anthropic, Building agents with the Claude Agent SDK (29 September 2025).
- Anthropic, How the agent loop works and Configure permissions (Claude Agent SDK docs, accessed November 2026).
- Delba de Oliveira and Michael Segner, Loop engineering: getting started with loops (Claude blog, 30 June 2026).
- OpenAI, Running agents and Human-in-the-loop (Agents SDK docs, accessed November 2026).
- LangChain, Interrupts and GRAPH_RECURSION_LIMIT (LangGraph docs, accessed November 2026).