Over 40% of agentic AI projects will be canceled by the end of 2027, according to Gartner's June 2025 prediction, driven by escalating costs, unclear business value or inadequate risk controls. Look inside most of those projects and you find the same small piece of code: the agent loop.
The agent loop is easy to write. It is a dozen lines. What is hard is deciding when it stops, and who gets to say no halfway through. Every runaway bill, every stuck retry and every "the agent did something nobody approved" story is, at its root, a stop-condition failure.
This guide walks through one iteration of the loop, then the five independent exits every production loop needs: goal reached, max steps, budget cap, no-progress detection and a human approval that blocks. You will also get the failure modes, the math on what a runaway loop costs, and a checklist you can copy.
In a hurry? Try a free 5-day trial of Rerun, where the loop's guardrails are an operations layer instead of code you maintain.
What Is the Agent Loop?
The agent loop is the cycle that turns a language model into something that acts. The model reads its context, decides on a step, a tool runs, the result is appended to the context, and the cycle repeats until a final answer or a limit ends it.
Anthropic describes agents in Building effective agents in nearly the same terms: they are typically "just LLMs using tools based on environmental feedback in a loop." That sentence is the whole architecture. Everything else (planning, memory, subagents) is built on top of it.
Building effective AI agentsPractical guidance from Anthropic on building reliable AI agents, from simple composable patterns to fully autonomous systems.Here is the skeleton in framework-neutral pseudo-code:
def run_agent(goal, tools, limits):
context = [system_prompt, goal]
for step in range(limits.max_steps): # exit 2: max steps
decision = model(context) # THINK
if decision.is_final_answer:
if verify(decision.answer, goal): # exit 1: goal reached, verified
return Done("success", decision.answer)
context.append(feedback("answer failed verification"))
continue
if needs_approval(decision.tool_call): # exit 5: human interrupt
verdict = wait_for_human(decision.tool_call)
if verdict.rejected:
return Done("rejected", verdict.reason)
result = tools.run(decision.tool_call) # ACT
context.append(result) # OBSERVE
if spend(context) > limits.budget: # exit 3: budget cap
return Done("budget", partial(context))
if stalled(context): # exit 4: no progress
return Done("stalled", partial(context))
return Done("max_steps", partial(context))Notice what dominates the code. The think-act-observe core is three lines. The other fifteen are about stopping. That ratio is the point of this article.
If you want the reasoning pattern behind the "think" step, our guide to ReAct agents covers it. Here we stay on the mechanics of the cycle itself.
Think: the model decides the next step
On every iteration the model receives the full context so far and returns one of two things: a tool call, or a final answer. It has no memory between iterations other than what you put back into that context. That is why the loop is only as good as what you append to it.
Act: the tool call executes
This is where risk lives. Thinking is free of side effects, acting is not. A tool call can send an email, charge a card or delete a table. Our deep dive on tool calling for AI agents covers how calls are specified and validated. For the loop, the key point is that every "act" step is a place where a limit or an approval can be enforced.
Observe: the result goes back into context
The tool result is appended to the context and the cycle restarts. Two things quietly go wrong here. The context grows with every step, which raises the cost of every later step. And a long, noisy tool output can push the original goal out of the model's effective attention. Managing this is a discipline of its own, covered in context engineering for AI agents and AI agent memory.
One Iteration, Step by Step
Take a support agent triaging a refund request. Three turns of the loop look like this:
| Turn | Think | Act | Observe | Context size |
|---|---|---|---|---|
| 1 | "I need the order first" | get_order(8841) | Order found, delivered 12 days ago | Small |
| 2 | "Check the refund policy window" | search_policy("refund window") | 30-day window, no restocking fee | Medium |
| 3 | "Eligible. Draft the refund and ask for sign-off" | issue_refund(8841) (needs approval) | Paused until a human decides | Larger |
Three things to notice. The model never "decides to stop" in turns 1 and 2, the loop simply continues because there is more to do. Turn 3 is a consequential action, so the loop should pause there rather than trusting the model's confidence. And the context at turn 3 contains everything from turns 1 and 2, which is why cost does not grow in a straight line. For the wider system around the loop, see our overview of AI agent architecture.
How an Agent Loop Knows When to Stop
"The model says it is done" is not a stop condition. It is one of five, and the weakest. A production loop needs several exits that fail independently, so that when the model is wrong, something else is still right.
Exit 1: goal reached, and verified
The model returns a final answer. Accept it only after a check that does not depend on the model's own confidence: a test that passes, a schema that validates, a record that actually exists, or a second pass by a different prompt or model. A hallucinated "success" is one of the most common loop failures, and verification is the cheapest cure.
Exit 2: max steps
Cap the number of iterations. For scoped tasks, 10 to 25 steps is a reasonable starting range, then tune from your own run history. Frameworks expose this directly. In the OpenAI Agents SDK, the runner raises a MaxTurnsExceeded exception when a run exceeds max_turns, and you can register an error handler to return a controlled final output instead. LangGraph has the same idea as a recursion limit that caps how many super-steps one run may execute and raises an error when exceeded.
The behavior on hitting the limit matters more than the number. Fail loudly, return the partial result, and record why. A silent stop looks like success.
Exit 3: token and cost caps
Set a budget per run and per day. Step count alone is not enough, because a few steps with huge tool outputs can cost more than many small ones. We break down where agent spend actually goes in AI agent cost. The short version: every step resends the whole context, so cost compounds. The next section puts numbers on it.
Exit 4: no-progress detection
The loop is still "working" but going nowhere. Common signatures:
- The same tool called with the same arguments three times in a row
- The same error returned repeatedly
- Oscillation between two states (open file, close file, open file)
A simple detector hashes the last few (tool, arguments) pairs and stops when it sees repeats. It is crude and effective.
Exit 5: a human approval that blocks
Before an irreversible action, the loop pauses, saves its state and waits. We cover this in its own section below, because it is the exit that most teams add last and regret most.
Bonus: wall-clock timeouts
Tools hang. APIs stall. A wall-clock limit per tool call and per run catches the failures the other exits cannot see, because no step is completing at all.
The stop condition is the product. Anyone can make an agent keep going. The engineering is in making it stop for the right reason, and in knowing which reason it was.
Agent Loop Failures and Runaway Loops
Most loop incidents fall into a handful of patterns. Here they are with the guard that catches each:
| Symptom | Root cause | Guard |
|---|---|---|
| Same failing tool call, over and over | No retry limit, error not changing the plan | No-progress detection, per-tool retry cap |
| Plan keeps changing, nothing gets done | Re-planning on every observation | Max re-plans, fixed plan with explicit revision points |
| Answers drift from the original goal | Context bloat pushes the goal out of focus | Re-inject the goal each turn, summarize old context |
| Declares success, nothing was done | Model trusts its own output | Independent verification before accepting |
| Behavior suddenly changes mid-run | Tool output contains injected instructions | Treat tool output as untrusted, approvals on risky actions |
| Bill explodes overnight | Subagents each running their own loop | Budget caps per run and in aggregate |
The injection row deserves emphasis. A loop feeds tool output straight back to the model, so a web page or email with hidden instructions can redirect the whole run. Our guides to prompt injection and AI agent security cover the attack, and AI agent guardrails covers the defenses.
What a runaway loop costs
Here is an illustrative calculation for an agent loop, not a benchmark. Assume the context starts at 5,000 tokens and grows by 2,000 tokens per step, with no prompt caching, at an assumed $3 per million input tokens. Because each step resends everything so far:
| Run length | Input tokens consumed | Cost at $3 per million |
|---|---|---|
| 20 steps | about 480,000 | about $1.44 |
| 200 steps (runaway) | about 40.8 million | about $122 |
Ten times more steps cost roughly 85 times more. That is the compounding Anthropic warns about when it says that the autonomous nature of agents means "higher costs, and the potential for compounding errors." Prompt caching lowers the constant, not the shape of the curve.
Recovery: when the loop stops halfway
A loop that stops mid-task leaves the world half-changed. Plan for it: write checkpoints, make tools idempotent so a retry does not double-charge anyone, and know how to undo what already happened. We cover the patterns in AI agent rollback strategies.
Human Approval as a Blocking Interrupt Inside the Loop
A human approval is not a notification. It is a blocking interrupt. The difference is whether the action has already happened by the time the human reads about it.
Implemented correctly, it works like this. Before a consequential tool call, the loop pauses and persists its state. A human sees the exact action, its arguments and the reasoning behind it, then chooses one of three outcomes: approve, edit or reject. On approve, the loop resumes exactly where it paused. On reject, the loop receives the reason as an observation and replans, or ends with a typed "rejected" stop reason.
Both major SDKs support this pattern. LangGraph documents interrupt and resume as a human-in-the-loop primitive, and the OpenAI Agents SDK has a human-in-the-loop guide for tool approvals. The mechanism exists. The harder questions are policy questions.
Which actions get gated? Tier by reversibility and blast radius, not by tool name:
- ✅ Read-only actions: no approval
- ⚠️ Reversible writes (drafts, internal notes): sampled or batched review
- ❌ Irreversible or external actions (sending, paying, deleting): always approve
What if nobody answers? Decide in advance. A pending approval needs a timeout and a default, and the default should be "do not act."
What if the human says no? The loop needs a path for that, not a crash. Feed the reason back, let the model propose a safer alternative, and cap how many times it may ask again.
For the full treatment of approval design, see human-in-the-loop AI agents. This section is only about the mechanics inside the loop.
Planning Inside the Agent Loop
A loop can run with no explicit plan at all, deciding one step at a time. That is flexible and fragile. The alternative is a plan the model writes first and then executes, revising it when an observation breaks an assumption.
The trade-off is re-planning frequency. Re-plan on every observation and you get plan thrash. Never re-plan and the agent follows a dead plan to the end. A middle path works well: fixed plan, with explicit revision points after failures. Our article on AI agent planning goes much deeper on this.
Where the Loop Lives: Harness vs. Operations Layer
There are three layers around a loop, and teams regularly confuse them:
| Layer | What it owns | Example |
|---|---|---|
| The loop | Think, act, observe, repeat | The for loop above |
| The harness | Tools, prompts, context assembly, memory | Everything that feeds the model each turn |
| The operations layer | Limits, approvals, audit, cost, alerts | What decides whether the loop is allowed to continue |
The harness is covered in our guide to the agent harness.

What Is an Agent Harness? The Software That Turns a Model Into an AI Agent
An agent harness is everything around the model that lets it act: loop, tools, environment, memory, context, guardrails and logs. Learn the 7 components, why the harness matters as much as the model, and how it differs from a framework.
The reason to keep the operations layer separate is simple. A model cannot police itself. If your max-steps limit lives in the prompt ("stop after 20 steps"), it is a suggestion. If it lives in code outside the model, it is a rule. Limits, budgets and approvals should be enforced from outside the loop, where the model cannot talk its way past them.
Operating Agent Loops in Production with Rerun
Rerun is not a framework and does not ask you to write agent logic in it. It is a framework-agnostic operations layer: where your agents run, where their limits live, and where humans stay in the loop. On Rerun, these agents are called coworkers.
In practice, that maps onto the exits above. Each coworker has a step limit setting. Every action it takes is written to a log with time, tokens and tools used, and cost, run count and tokens are tracked over 24 hours, 7 days, 30 days and 90 days. When a coworker reaches a consequential action it can ask a question or wait for approval, and you answer from the app or from Slack, and it resumes exactly where it paused. Paid data lookups show their cost and ask before they spend.
Be clear about the boundary. Rerun does not decide what a good answer looks like, and it does not replace the verification step in exit 1. That check is yours to design. What it gives you is the layer around the loop: the visible log, the blocking approval and the limits, without maintaining that plumbing yourself.
This is also where Rerun differs from the tools people reach for first. A chatbot waits to be asked and has no loop to govern. A Zapier, Make or n8n flowchart has no loop at all: it is a fixed path that runs the same way every time, with no judgment to supervise. A coworker has the loop, so it needs the stop conditions, and Rerun is built around them. If you want the broader picture, read our guides to AI agent observability and AI agent governance.
| Chatbot | Zapier, Make or n8n flowchart | Coworker (agent loop) | |
|---|---|---|---|
| Has an agent loop? | No | No | Yes |
| Decides its own next step? | No | No | Yes |
| What you supervise | Answers | A fixed path | Every step and its actions |
| Stop conditions needed | None | Error handling | Five exits, enforced outside the model |
Agent Loop Checklist
Use this before any loop goes near production:
Typed stop reasons deserve a final word. When a run ends, "it stopped" is not enough information. Knowing it stopped because of a budget cap rather than a stall tells you whether to raise a limit or fix a bug.
Build the Loop, Then Govern It
The agent loop itself is the easy part, and every framework gives you one. The work that separates a demo from a dependable system is everything around it: five independent exits, honest cost math, and a human who can say no before the action lands, not after.
If you would rather not build and maintain that layer yourself, you can run coworkers on Rerun with the guardrails already in place. 3,000+ integrations plus any MCP server, runs 24/7, and the free 5-day trial lets you watch a full loop work before you commit.
Frequently asked questions
What is an agent loop?
An agent loop is the cycle at the core of every AI agent: the model reads its context, decides on a step, a tool executes, the result is added back to the context, and the cycle repeats until the agent returns a final answer or a limit stops it. Anthropic describes agents as LLMs using tools based on environmental feedback in a loop.
How many steps should an agent be allowed to take?
For scoped tasks, 10 to 25 steps is a reasonable starting range. Tune the number from your own run history, and always decide what happens at the limit: return a partial result and a typed stop reason rather than failing silently. Open-ended tasks need a budget cap and no-progress detection alongside the step limit.
Why does an agent loop get stuck?
The usual causes are a failing tool that gets retried with the same arguments, re-planning after every observation, a context so bloated that the goal drifts, and a model that trusts its own output. Each has a guard: a retry cap, a limited number of re-plans, goal re-injection, and independent verification of results.
How do you stop an AI agent from burning money?
Set a token or cost budget per run and per day, enforce it in code outside the prompt, and cap steps. Costs compound because every step resends the growing context, so a run ten times longer can cost far more than ten times as much. Monitoring cost per run makes runaway loops visible early.
Is human approval part of the agent loop?
It should be. A blocking approval pauses the loop before an irreversible action, saves its state and resumes when a human approves, edits or rejects. A notification sent after the action is not an approval. Gate actions by reversibility and blast radius, and give every pending approval a timeout whose default is to not act.
Where should loop limits live: in the prompt or in code?
In code, outside the model. A limit written in the prompt is a suggestion the model can ignore or reason around. Step caps, budgets, timeouts and approvals enforced by an operations layer around the loop are rules. On Rerun, coworkers run inside that layer, with logs and approvals around every run.
What is the difference between an agent loop and a workflow?
A workflow follows a predefined path written in code, so it runs the same way every time. An agent loop lets the model decide the next step on each iteration, which is more flexible and also needs stop conditions. Tools like Zapier, Make and n8n build workflows, and an agent loop is a different thing to supervise.






