Loop Limits for AI Agents: How to Stop Runaway Tool Calls
An AI agent infinite loop ends with hard caps on steps, time and spend per task, plus progress signals that halt the run and escalate to a person.

An AI agent infinite loop is a run where the agent keeps calling tools, rereading the same records or retrying the same failed step without getting closer to a finished result. The dependable fix is not a cleverer prompt. It is three hard caps per task (a step cap, a wall clock cap and a spend cap) plus progress signals that halt the run early and hand it to a named person with enough context to decide. Caps make the worst case bounded. Progress signals make most halts happen long before any cap is reached.
Key takeaways
- Every agent task needs a step cap, a time cap and a spend cap, and each cap needs a defined behavior when it is hit: stop, save state, escalate.
- Caps are the floor, not the plan. Progress signals (repeated identical calls, unchanged state, the same error class twice) should stop a stuck run much earlier.
- A halt is only useful if the handoff carries the goal, what was attempted, the last good checkpoint and the one decision a person must make.
- Loops become expensive when writes are not idempotent, because a retried step can duplicate real business actions.
- Review halts weekly. A rising halt rate is a design signal, not just an operations annoyance.
Why do AI agents get stuck in loops?
Loops are rarely a sign that the model is broken. They are a sign that the agent cannot tell the difference between work and progress. A tool returns an ambiguous error, so the agent tries again with slightly different arguments. A search returns nothing useful, so the agent broadens the query, then narrows it, then broadens it again. A planning step rewrites the same plan with new wording. Each action looks reasonable on its own, and nothing in the run says stop.
Four patterns cover most of what you will see in business agents. The retry spiral, where a flaky integration produces a loop of attempts because the failure is reported as temporary. The oscillation, where the agent alternates between two states because two rules disagree. The search widening loop, where the agent keeps fetching context because the answer is not in the data at all. And the perfectionist loop, where the goal has no clear finish condition, so the agent keeps refining a draft it has already finished.
Notice what these share: the task has no definition of done that the agent can check. Before you tune limits, write the finish condition in one sentence a person could verify. Many loops disappear at that step. For the ones that remain, see the companion piece on stop conditions that actually work.
The three caps every agent task needs
Set all three. Each one catches a failure the others miss.
A step cap limits tool calls and model turns inside a single task. It catches tight loops that are cheap per call but endless. Derive the number from observed runs: look at how many steps your successful runs take at the upper end, then set the cap somewhat above that, not at a round number you invented. If the cap is near the normal maximum, you will halt healthy work. If it is many times higher, it stops being a guard.
A wall clock cap limits elapsed time. It catches slow loops where each call waits on a timeout before failing. Without it, a run can sit for a long stretch doing almost nothing while a customer waits. Pair a per task cap with a per step cap so a single hanging call cannot consume the whole budget. The detail work is covered in agent run timeouts.
A spend cap limits tokens and tool cost per task. It catches loops that are neither tight nor slow, just large: long contexts reread on every turn, repeated document fetches, retried generations. Spend caps also protect you from the one loop class that is hardest to notice, the overnight scheduled job that nobody is watching. Alerting on aggregate usage is the matching control, described in usage alerts and hard stops.
Caps must be enforced outside the agent's own reasoning. A limit stated in a prompt is a request. A limit enforced by the runtime that executes tool calls is a limit. The runtime counts steps, watches the clock, totals the cost and terminates the run regardless of what the agent intends to do next.
Which signals should halt a loop before the caps do?
Caps are blunt by design. The signals below are sharper, because they measure progress rather than consumption. Any of them should halt the run and escalate.
- The same tool is called with the same arguments twice in a row, or three times within the run.
- The agent's working state is unchanged after a full cycle: no new record fetched, no field written, no fact added.
- Two consecutive failures share the same error class from the same tool.
- A retrieval step returns results the agent has already seen, twice.
- The plan or the draft is rewritten without the finish condition being met.
- Context length grows while the set of distinct facts does not.
- A tool reports an unknown outcome (the call timed out, so the result is neither success nor failure) on a step that writes data.
- The task has crossed a defined share of its spend budget while no checkpoint has been reached.
That last pair matters most for money and trust. An unknown write outcome should never be retried blindly. Make writes idempotent so a repeat is safe, as described in idempotent tool calls for agents, and treat an unknown result as a halt reason rather than a retry reason.
A step-by-step plan to add loop limits this week
- Pick one agent task that touches real systems, ideally one that already produced a confusing run.
- Write its finish condition in one sentence, and write the one thing that makes the task unfinishable (missing data, a closed account, a tool that is down).
- Pull the step count, elapsed time and token cost for a set of recent successful runs. Use the upper end of normal, not the average, as your baseline.
- Set the three caps above that baseline with room to breathe, and record the numbers where a non technical owner can read them.
- Implement the halt behavior: terminate the loop, persist the partial state, write a structured halt record, notify the owner.
- Add the progress signals from the previous section as explicit checks in the loop, starting with repeated identical calls and repeated error classes.
- Verify that every write the task can perform is idempotent, or that it is gated behind an approval.
- Force a halt on purpose in a test environment and confirm the person who receives it can act without opening logs.
- Put halts on the weekly review list alongside your other reliability panels, as in the five panel dashboard.
- Revisit the caps after a few weeks of real traffic and adjust once, with the change written down.
For long tasks, add checkpoints before you tighten caps. A run that can resume from its last good state turns a halt from lost work into a pause. The practical shape of that is in checkpoints for long agent tasks.
An illustrative scenario: the invoice agent that would not stop
The following is illustrative, not a client account.
A distribution company runs an agent that reconciles supplier invoices against delivery records. Normal runs read an invoice, fetch the matching delivery, compare line items and either post a match or raise an exception for a buyer. One morning a supplier changes its reference format. The delivery lookup now returns nothing. The agent widens the search by date, finds several candidate deliveries, cannot choose, narrows the search again, returns to the original query and starts over. Each cycle costs a handful of tool calls and a long context read. No error is raised, because nothing failed. The agent is working, visibly and expensively, on an unfinishable task.
With caps and signals in place, the run ends on the second identical lookup. The halt record says: goal was to reconcile this invoice, the delivery lookup returned no match for this reference, three candidate deliveries were found by date, the agent could not choose, no write occurred. The buyer sees a single item in a queue with one decision: confirm the correct delivery or reject the invoice. The pattern repeats on other invoices from the same supplier, so the owner adds a reference format rule, and the loop class is gone. Without caps, the same morning produces a large usage bill, a late reconciliation and no explanation anyone can read.
What should a halt hand to the person?
A halt that produces a cryptic alert just moves the problem. Send the decision, not the mess. A good halt record is short, structured and consistent across tasks, and it includes the goal in business language, the reason for the halt, the sequence of attempts in summary form, the last checkpoint, whether any write happened and whether it was idempotent, the records touched, and the single question the person must answer.
A halt is a handoff, so write it for the person who has to act, not for the engineer who will debug it later.
Route halts to a named owner with a response window rather than to a shared channel. Keep the queue small enough to read. If halts arrive faster than they are cleared, the queue becomes a second place where work gets stuck. The escalation design is covered in human escalation for AI agents.
How managed operations keep caps honest
Caps drift out of usefulness as tasks change. A new tool adds steps, a larger document set adds tokens, a model change alters pacing, and the limit you set months ago starts halting good work or stops catching bad runs. Be Human's managed operations include monitoring of halts and run costs, recurring evaluations against test cases drawn from real work, integration maintenance when a tool's behavior changes, incident response when a run goes wrong, and controlled changes to limits and permissions that are written into a change log the owner can read. The aim is a bounded worst case that stays bounded as the work evolves.
If you are not sure which task to put under these limits first, the free Be Human AI diagnostic helps you identify the first task worth handing to an agent.
Frequently asked questions
What is the difference between a loop guard and a timeout? A timeout measures elapsed time and ends a run that is taking too long, including runs that are simply slow rather than stuck. A loop guard measures progress and ends a run that is repeating itself, even when each individual step is fast. You want both, because a tight loop can finish thousands of fast calls well inside a generous timeout, and a single hanging call can waste a long window without looping at all.
Won't strict caps break legitimate long tasks? They will if you set them from intuition instead of observation. Derive caps from the upper end of your real successful runs, add room, and add checkpoints so a long task can resume rather than restart. If a task genuinely needs a wide budget, give it one and watch it more closely, with per step limits and a mid run progress check rather than a single limit at the end.
Should the agent be told about its own limits? It helps to tell the agent the budget remains, because a well designed agent can then summarize its state and stop cleanly rather than being cut off mid action. Do not rely on that cooperation. Enforce the caps in the runtime that executes tool calls, and treat anything the agent says about its own restraint as advisory.
How do we know whether our caps are working? Track three things each week: how many runs halted, why they halted, and how long halts waited before a person acted. Halts clustered on one tool or one task type point to a design fix rather than a limit change. Zero halts over a long period usually means the caps are set too loosely to catch anything, so test them deliberately.
Your next step
See where an AI agent fits in your company first.
Take the free Be Human AI diagnostic. A few questions about your work show which task to hand to an agent first, what it needs to know and where a person approves.
Be Human editorial guidance. Examples are illustrative unless explicitly attributed. Sources provide background; implementation choices depend on your workflow.


