Skip to content
be-human.ai
← Back to the journal

Testing & reliability

AI Agent Stuck in a Loop: Stop Conditions That Actually Work

An AI agent stuck in a loop needs layered stops: step limits, repeat detection and cost caps that end a run cleanly and hand the decision to a person.

Be Human typographic cover with the title: AI Agent Stuck in a Loop: Stop Conditions That Actually Work
Conceptual illustration created with AI · Be Human

An AI agent gets stuck in a loop when nothing around it can tell that repeating an action is no longer making progress. The fix is not a cleverer prompt. It is a set of stop conditions enforced outside the model: a step limit, a repeat detector and a cost and time ceiling, each ending the run in a defined state that a person can review.

Key takeaways

  • Enforce stops in the code that runs the agent, not in the instructions the agent reads. A model asked to stop itself may not.
  • Use three layers together: a step limit for the run, a repeat detector for identical or circular behavior, and a budget for cost and time.
  • Judge progress by changes in state (a record updated, a new fact found), not by activity. Many loops look busy.
  • A stop is only clean if it leaves a reason code, a short state summary and a named person who decides what happens next.
  • Review the limits on a schedule. Workflows, tools and models change, and a limit that fit last quarter may now be too tight or too loose.

What does an AI agent stuck in a loop look like?

The obvious version is the same tool call made again and again with identical arguments. That one is easy to catch. The versions that cost more are quieter.

One is oscillation: the agent checks a record, edits a field, checks the record again, reverts the edit, and starts over. Another is the reworded retry, where each attempt differs slightly (a search phrased five ways) but none of them changes the outcome. A third is the retry storm, where a tool returns an ambiguous error and the agent treats it as a reason to try again, forever. In setups with more than one agent, two agents can hand a task back and forth, each convinced the other should finish it.

The causes are usually ordinary:

  • A tool returns an empty result or vague error, and the agent has no instruction for what to do next.
  • The success criterion is unclear, so the agent cannot tell that it is done.
  • Earlier attempts have scrolled out of the working context, so the agent no longer knows it already tried.
  • A step depends on something only a human can supply, such as a missing approval, and the agent keeps looking for a workaround.

None of these is fixed by asking the model to try harder. They are fixed by making the loop visible and bounded. Published guidance on agent design, including [Anthropic's notes on building effective agents](https://www.anthropic.com/engineering/building-effective-agents), recommends stopping conditions such as a maximum number of iterations for the same reason: autonomy needs a boundary somebody chose in advance.

How do you set a step limit that makes sense?

A step limit is the simplest stop and the one most often set badly. Too low, and legitimate work gets cut off. Too high, and it only limits the damage after the loop has already done its harm.

Start from observed behavior, not from a guess. Run the workflow on realistic cases (the shadow mode approach is a good way to gather them) and note how many model turns and tool calls a normal, successful run takes. Set the ceiling comfortably above the slowest legitimate run, not above the average. If your golden test set includes hard cases, use those to calibrate.

Then apply limits at more than one level:

  • Per run: a maximum number of model turns and a maximum number of tool calls.
  • Per tool: a lower ceiling on calls to any single tool, especially ones that write data, send messages or cost money.
  • Per task: a limit across restarts, so a failed run that is automatically requeued cannot start a fresh count each time.

The third one is the most commonly missing. A loop that restarts itself is still a loop, only with a clean counter.

Also decide what happens before the hard stop. A soft threshold, reached at a point well before the ceiling, can trigger one useful action: ask the agent to write a short summary of what it has tried and what is blocking it. That summary becomes the handoff note if the hard limit is reached. Keep the hard limit non-negotiable: the code ends the run, regardless of what the model says.

How can you detect repeated behavior?

Step limits catch long runs. Repeat detection catches runs that are going nowhere, often much earlier. It works by fingerprinting what the agent does and watching for patterns.

A workable fingerprint combines the tool name with normalized arguments (lowercased, whitespace trimmed, volatile values such as timestamps removed). Keep a short window of recent fingerprints for the run. Then check for these signals:

  • Exact repeat: the same fingerprint appears again with no change in state between the two calls.
  • Near repeat: arguments differ only trivially, such as a reordered search phrase, and the result is the same or equally empty.
  • Oscillation: a pattern like A, B, A, B across a few steps.
  • Same result, different route: several different calls return identical content, which suggests the agent is circling the same missing fact.
  • Error echo: the same error category returned repeatedly from one tool.

The important design choice is the progress signal. A repeated call is not a problem if something changed in between, for example a record was updated and the check is a legitimate verification. So the detector should ask: since the last time this action ran, did any relevant state change? If not, the second occurrence is a warning and the third is a stop. Allow one repeat before acting, because a single retry after a transient failure is reasonable. Your retry policy should define exactly which errors earn a retry and how long to wait, so the detector and the policy agree.

This only works if you log the right things. Tool name, normalized arguments, result category and state change flag per step are enough to build the detector and to investigate afterward. The article on what to log for agent observability covers the wider picture.

Which cost and time stops end a run cleanly?

Step limits and repeat detection watch behavior. Budgets watch consequences. A looping agent can stay under a step limit and still be expensive if each step is large, or it can hammer an external system in a short time.

Use budgets at three levels:

  • Per run: a ceiling on model usage and elapsed time for one attempt. Tie the time limit to the latency budget the workflow was designed around, since a run far past it is rarely still useful.
  • Per task or customer: a ceiling across all attempts at the same piece of work, so repeated restarts add up to something visible.
  • Per agent per day: a circuit breaker that pauses the agent and alerts a person when total usage is unusual. This catches the case where many runs each look fine but something upstream is flooding the queue.

External limits matter too. A looping agent can exhaust a partner's quota or trigger throttling that affects other systems, which is covered in API rate limits and AI agents. Put a cap on calls per minute to each connected system, separate from the model budget.

To make budgets meaningful, compare them against what a completed task normally costs. The approach in measuring cost per completed task gives you a baseline, so a ceiling can be set as a multiple of normal rather than an arbitrary figure. Unbounded resource use is also a recognized risk category in the [OWASP Top 10 for LLM Applications](https://genai.owasp.org/llm-top-10/), which is a useful reference when someone asks why these caps are not optional.

For actions with direct financial effect, the limits should be stricter and sit alongside the ones described in safe limits for agent payments.

What should happen when a stop condition fires?

A stop that simply kills the process can leave a half-finished action behind: an email sent but not logged, a record updated but not confirmed. A clean stop is a short, predictable sequence. Build it once and reuse it for every stop condition.

  • First, block new actions. The harness refuses further tool calls the moment a limit is hit.
  • Second, settle anything in flight. Complete or roll back the current write using idempotent operations, so a later retry cannot duplicate it.
  • Third, record a reason code. Use a small fixed set, such as step limit, repeat detected, cost ceiling, time ceiling or external limit, so patterns are easy to count later.
  • Fourth, save a state summary: what the agent was asked to do, what it did, what it tried last and what it believes is blocking it.
  • Fifth, mark the task as stopped so no automatic requeue runs it again. Only a person or an explicit rule should restart it.
  • Sixth, notify the named owner with a decision to make, not a log dump. The principle in human escalation for AI agent failures applies: send the decision, not the mess.
  • Seventh, review the stop. Was the limit right, the tool unclear or the task badly specified? Feed the answer back into the runbook.

If stops start to repeat across many tasks, treat that as an incident rather than a string of unrelated events, and follow the incident response playbook. Keeping the stop reasons and the owner's usual response in a runbook saves time the next time it happens.

Illustrative scenario: a loop caught on the third attempt

This is an illustrative scenario, not a real case.

An agent helps an accounts payable team match supplier invoices to purchase orders. For one supplier, the purchase order number on the invoice includes a prefix that the ERP lookup does not recognize. The lookup returns an empty result. Without a stop, the agent might rephrase the query repeatedly, try a supplier name search, then try the original query again.

With stop conditions in place, the sequence is different. The first empty result is allowed. The second, a near repeat with no change in state, raises a warning, and the agent is prompted to summarize what it has tried. The third near repeat triggers the repeat detector. The harness blocks further lookups, writes the reason code, and sends the accounts payable owner a short note: the invoice, the number searched, the three variants tried and the empty result each time.

The owner recognizes the prefix issue in a minute and either matches the invoice by hand or adds a normalization rule to the lookup. The task stays marked as stopped until then, so nothing runs it again behind anyone's back. The cost of the loop is three lookups rather than an open-ended search, and the team learns something about the data. If your agent touches an ERP, the integration checks for ERP connections list the kinds of lookup behavior worth testing before launch.

How does Be Human handle runaway loops?

Be Human treats stop conditions as part of the first engagement, alongside the role, the memory and tools it needs, the approval boundaries and an observable success criterion. Step limits, repeat detection, budgets and the stop sequence are configured in the agent's operating layer, not left to the prompt, and the owner who receives a stopped task is named in advance. In managed operations, stop events are monitored, recurring evaluations include looping scenarios, and limits are revisited during permission and integration reviews and after model or tool changes, following the routine in the weekly maintenance checklist. Changes to limits go through the same controlled process described in updating a live agent safely.

Frequently asked questions

Why does my AI agent keep repeating the same action? Usually because the tool result gave it no clear next step, the success criterion is vague, or earlier attempts fell out of its working context. Check the tool's error messages and the definition of done before changing the model or the prompt.

Can I just tell the agent in its instructions to stop after a few tries? You can add the instruction, but do not rely on it. The model may miscount, forget or decide one more attempt is justified, so the hard limit must be enforced by the code that runs the agent.

What is a good first stop condition if I can only add one? A per-run limit on tool calls, enforced in code, with a reason code and a notification to a named person when it fires. It is simple, it bounds the worst case, and it gives you the data to add repeat detection and budgets next.

How often should stop conditions be reviewed? Review them on a regular schedule and whenever the workflow, a connected tool or the underlying model changes. Stop reasons are the best input: if one limit fires often on legitimate work, loosen it with evidence, and if loops slip through, tighten the detector. A related approach is covered in AI model update regression checks.

Be Human editorial guidance. Examples are illustrative unless explicitly attributed. Sources provide background; implementation choices depend on your workflow.

Less busywork. More room for you.

Bring us the work you wish you had time for.

Try a personalized AI agent free for 7 days on WhatsApp ↗