# How to stop an AI agent from looping (agent loop design)

> An agent loop is the cycle of a model call, tool calls and observations. This playbook covers where that cycle fails to stop, the budgets and guards that end it, and what the person should hear when they fire.

---

**The short version**

- End on a reply with no tool call, and fence the rest with step, time and cost budgets.
- A doom loop is the same work again, with an observation that did not change.
- Hash the tool and the normalised arguments. Stop on the third identical call.
- When a stop fires, return the partial and one next step. Do not return the exception.
- Fit the step budget to tasks that finished, one cohort at a time.

## How does an agent loop work?

A loop that never stops spends patience and tokens on a task that is not moving. Agent loop design is the rules for when a tool-calling agent calls the model again, and when that cycle ends.

The loop is one part of an [agent harness](https://tryabracadabra.com/blog/what-is-an-agent-harness/): the control flow around the model, not the model. Changing a stop, a budget or a repeat guard is a [harness change](https://tryabracadabra.com/blog/harness-engineering/), and it should ship as one change.

**Short answer.** An agent loop should stop when the model returns no tool call or when a done tool fires. It should also stop when a step, time or cost budget is hit. Also stop when the same call repeats. Say what finished, what did not, and the next useful step. Do not return a raw iteration error.

The example is the assistant inside a CRM. It is the illustrative worked example used across this blog (the step figures are in [AI agent failure detection](https://tryabracadabra.com/blog/ai-agent-failure-detection/)). Every figure in the example is illustrative. The task is “update these contacts from the trade-show list”. The 3 steps are find the contacts, update them, and log the activity. The tools are `find_contacts`, `update_contacts` and `log_activity`. The `update_contacts` tool takes all 9 contacts in 1 call, updates 3, skips the 6 whose emails do not match, and returns success.

One pass is four moves. The harness sends the instructions, the tool descriptions and the conversation. The model returns text, or one or more tool calls. The harness runs those calls and appends the observations. The model is called again. Text and no tool call ends the loop. That is natural completion.

The [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/running_agents/) uses that same exit: text of the desired type, and no tool calls. The cycle still fails to terminate in a few places. Name the place before you pick a guard.

- **A tool call on every pass.** Natural completion never fires.
- **A retry with no cap.** The same timeout is called again, and nothing counts it.
- **An unchanged observation.** Success, 3 written and 6 skipped, is treated as news.
- **A planner that routes to itself.** The plan text changes. The CRM does not.
- **“Try again” as a new order.** Turn 9 repeats the last call.
- **A handoff that returns.** The second agent hands the same tool list back.
- **A partial parallel batch.** Two calls succeeded, and the retry restarts all three.

*The loop, and the checks that can end it*

A reply with no tool call leaves to the side. Any other reply runs the tools, stores the observation, and meets the stop checks before the model is called again.

## When should an agent loop stop?

A stop condition ends the loop even when the model would take another pass. Natural completion is the happy stop. The rest are fences for when that stop never comes. Use more than one. Each fence misses a different failure.

**Natural completion** never fires while the model keeps requesting `update_contacts`. **A done tool** such as `finish` ends the loop when called. The model can forget it, or call it while 6 contacts are unwritten. `log_activity` is not a done tool.

**A step budget.** A cap on how many laps one run may take. Two framework knobs count different units, and their defaults sit at opposite ends.

[LangGraph](https://docs.langchain.com/oss/python/langgraph/graph-api) calls the cap `recursion_limit`: how many super-steps one run may execute. Pass it as a top-level config key, not under `configurable`. From version 1.1.4 the default is 10,007 super-steps. Between 1.0.6 and 1.1.3 the default is 10,000. `LANGGRAPH_DEFAULT_RECURSION_LIMIT` overrides it. Past the limit, LangGraph raises `GraphRecursionError`. A super-step is not a model call. Parallel nodes share one super-step. A model node and a tools node are separate super-steps, so one lap is more than one. 10,007 is a crash fence, not a product budget. In Python, `RemainingSteps` tells the graph how many steps remain, so it can route to a completion path before the error. That path is on the [control-flow page](https://docs.langchain.com/oss/python/langgraph/graph-api-control-flow).

The [OpenAI Agents SDK](https://openai.github.io/openai-agents-python/running_agents/) calls the cap `max_turns`, on `Runner.run`, `Runner.run_sync` and `Runner.run_streamed`. A turn is one model invocation, including any tool calls that invocation makes. The default is `DEFAULT_MAX_TURNS`, which is 10 in [`run_config.py`](https://github.com/openai/openai-agents-python/blob/main/src/agents/run_config.py). The [JavaScript SDK](https://openai.github.io/openai-agents-js/guides/running-agents/) documents the same default for `maxTurns`. Past the limit, Python raises `MaxTurnsExceeded` unless an error handler for `"max_turns"` returns a final output. `max_turns=None` disables the limit. Ten turns will cut a task that searches, writes, looks the misses up by name, and writes again. Raise it from data. Do not delete it.

Too low, and a long task dies on the lap that would have finished it. Too high, and a loop burns tokens while the person waits. Neither default is the step budget for this CRM task.

**Time** catches a stuck tool someone is waiting on, and misses a fast loop. Set it inside the wait where people on this task rephrase. That wait is not in the example’s figures, so measure it. **Cost** catches spend after the result stops changing, and misses a cheap loop. Read unit prices on the [AI model pricing](https://tryabracadabra.com/ai-pricing/) pages, and judge the cap as the cost of a finished task. **A human handoff** is a stop on the open step, not a new task. A loop that never asks never reaches it. Escalation as a signal is in [AI agent failure detection](https://tryabracadabra.com/blog/ai-agent-failure-detection/).

A step budget will catch a doom loop only after the tokens are spent. The repeat guard fires while the observation is still the same.

| Stop | Catches | Misses | Tradeoff | Sensible default |
| --- | --- | --- | --- | --- |
| Natural completion | Text, and no tool call | A model that always calls a tool | Ends finished work. Never ends a loop | Required. Not a budget |
| Done tool | An explicit finish call | The model forgets to call it | Clear signal. Easy to skip | One tool, and it does no other work |
| Step budget | A run that never converges | A long task that is still progressing | Too low cuts real work. Too high burns cost | A high percentile of steps on finished tasks |
| Time budget | A stuck run someone is waiting on | A fast loop inside the clock | Too low aborts a live write | Shorter than the wait where people rephrase |
| Cost budget | Spend after the result stops changing | A cheap loop that still wastes the person | Needs a price that stays current | A cap per attempt, as cost per finished task |
| Human handoff | The person asked, or a guard fired | A loop that never asks | Stops the burn. Adds a queue | A stop on the open step, not a new task |
| Repeat guard | The same call, K times | Oscillation across two tools | Stops a doom loop. A real retry needs new arguments | The third identical call |

## Why do agents get stuck repeating the same step?

A doom loop keeps going while the task does not move. Five shapes need different detectors. A check against only the previous call misses three of them.

- **Repeated identical calls.** `update_contacts` on the same 9 contacts. Every row is a success.
- **Oscillation.** `find_contacts`, then `update_contacts`, then `find_contacts` again. A “same as previous” check stays quiet.
- **Re-planning without progress.** A new plan, then `update_contacts` with the same arguments. The text changed. The 3 written contacts did not.
- **A retry storm.** A timeout, retried with the same arguments and no per-tool cap. Unlike the skip, the status is an error.
- **An apology loop.** “Sorry, trying again”, then the same call. The person sees the apology. The trace sees another success.

Four detectors cover those shapes. The numbers are illustrative settings for a short task, not a measured budget for the illustrative example’s 2,400 attempts.

- **Repeated-call counts.** Hash the tool and the arguments, object keys sorted, list order kept. Stop at K. An illustrative K is 3: the first call is the attempt, the second can be a retry, the third is the loop.
- **No-progress detection.** Hash the world, here “3 written, 6 skipped”. If it is unchanged over N steps, stop even when the tool name alternates. An illustrative N is 3. This catches oscillation and re-planning.
- **A sliding window.** Keep the last W hashes. Stop when one hash fills K of them. An illustrative window is the last 6 calls, stopping at 3. Pick any similarity threshold on your own repeats.
- **A per-tool retry cap.** One retry of `update_contacts` after a timeout. The second identical error stops. An error cap never sees a success-with-skips. A retry after a lookup by name is a different call.

Different ids, or a different list, are a new attempt. The key is the arguments, not the tool name alone.

## How do you stop an agent that repeats the same call?

The guard hashes `(tool, arguments)` with object keys sorted, counts identical calls, and enforces a step budget and a time budget. It returns `"repeat"`, `"step_budget"`, `"time_budget"`, or `None`. It does not hash the observation, so put the no-progress check beside it. `max_steps=8`, `max_seconds=12` and `repeat_limit=3` are illustrative for a short task.

A timeout and a 401 are not the same repeat. Classifying the error, backing off inside a budget, and replaying a write with a stable key are covered in [agent tool retries and idempotency](https://tryabracadabra.com/blog/tool-errors-retries-idempotency/).

```python
import hashlib, json, time

def call_key(tool, args):
    raw = json.dumps([tool, args], sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(raw.encode()).hexdigest()

class LoopGuard:
    def __init__(self, max_steps, max_seconds, repeat_limit):
        self.max_steps = max_steps
        self.repeat_limit = repeat_limit
        self.deadline = time.monotonic() + max_seconds
        self.steps = 0
        self.counts = {}

    def observe(self, tool, args):
        self.steps += 1
        if self.steps > self.max_steps:
            return "step_budget"
        if time.monotonic() >= self.deadline:
            return "time_budget"
        key = call_key(tool, args)
        self.counts[key] = self.counts.get(key, 0) + 1
        if self.counts[key] >= self.repeat_limit:
            return "repeat"
        return None
```

`sort_keys=True` makes key order irrelevant. List order stays, so a different set of ids is a different call. Non-JSON arguments throw: coerce them first. On this task the first `update_contacts` returns `None`, the second with keys swapped returns `None`, and the third returns `"repeat"`. `max_steps=2` returns `"step_budget"` on the third lap. A deadline already past returns `"time_budget"` on the first. Call `observe` once per tool call, before the tool runs. `max_turns` still counts model invocations.

## What should the user see when the agent stops?

A stop is a product event. The person is mid-task. The worst exit is the framework’s exception in the chat, or a silence. The best exit says what finished, what did not, why the loop stopped, and one next step.

The hooks exist. On the Agents SDK, the `"max_turns"` handler described earlier swaps the exception for a reply. The [running-agents guide](https://openai.github.io/openai-agents-python/running_agents/) shows that handler. On LangGraph, route on `RemainingSteps` before `GraphRecursionError`, or catch the error and read the last checkpoint. That checkpoint is the partial. Throwing it away is the bug.

Pick one exit from the reason the stop fired.

- **A partial result.** The default when a budget or a repeat fires and some work is real. Name the 3 updated and the 6 skipped.
- **A clarifying question.** Right at turn 2, when the scope is unclear. Wrong once the result is known. “Want me to try again?” feeds the apology loop.
- **A handoff.** The person asked, or the guard cannot choose a safe write. Do not open a second task.
- **The exception text.** Log `MaxTurnsExceeded` or `GraphRecursionError`. The chat gets the partial.

The two turns below are illustrative. They are the same facts, 3 written and 6 skipped, said two ways. They are not a transcript from the illustrative example’s 2,400 attempts.

The good turn states the partial, the gap, and a next step that is not the same call.

| Exit | What the person sees | What they can do next |
| --- | --- | --- |
| Raw max iterations | Max turns (10) exceeded. | Nothing. The task looks broken, and the 3 updates are unmentioned. |
| Partial | 3 of the 9 contacts are updated. The same 6 emails still do not match, and a second update returned the same result, so I stopped. | Look those 6 up by name, or send the emails that match. |

## Friction, loops and fallbacks in a conversation

Keep three layers separate. Friction is what the person does. A loop is the agent repeating work. A fallback is a second strategy after a partial or failed result. A green trace can contain all three, or only the loop.

The excerpt is illustrative. Turns 8 and 9 are the example transcript. Turns 10 to 14 are a continuation, not a counted conversation and not a split of the illustrative example’s 528 stops. The log can mark every call a success.

Every tool row can be a success. The person’s side is the loop. Treat these as friction on the same task, and never as a new task. The signs are “you already tried that”, “try again”, “that’s the same answer”, a rephrase (“update all 9, including the ones you skipped”), then silence. Turn 9 of the example transcript is already the first of those. A second task called “try again” counts one failure twice.

- **Friction.** A rephrase, dissatisfaction, or a last turn. Turn 2 is not friction: the person answers, and find the contacts continues.
- **A loop.** The call hash repeats, or the written set stays at 3 of 9. The status says success. That is the wrong field.
- **A fallback.** A new tool or new arguments after a partial result, such as a lookup by name. The same ids on `update_contacts` are the loop, wearing a new sentence.

Spans will not show turn 11. [AI agent observability](https://tryabracadabra.com/blog/ai-agent-observability/) tells you the run happened. [Failure detection](https://tryabracadabra.com/blog/ai-agent-failure-detection/) compares the tool result with the next person turn. The finish rate is in [how to measure agent performance](https://tryabracadabra.com/blog/how-to-measure-ai-agent-performance/).

A repeated call is one symptom. The same chat can also be a fact the context dropped, or a tool result treated as done. Which symptom belongs to which part is the [symptom-to-harness map](https://tryabracadabra.com/blog/symptom-to-harness-component/).

Start from the turns. The [workspace](https://tryabracadabra.com/product/) keeps the topic, the task, the intent and the signal on the conversation, and an annotated replay pins dissatisfaction to the turn. [Search](https://tryabracadabra.com/features/) takes plain English, so “it tried the same thing again” or “try again” is a real query, matched on intent. Repeated intents are a signal you can count. Open the person and read what they asked across sessions.

| Turn | Who | Says | Trace |
| --- | --- | --- | --- |
| 8 | Agent | Done. 3 contacts updated and logged. | `update_contacts` success. 3 written, 6 skipped |
| 9 | Person | Where are the rest? Can you try that again? | Dissatisfaction. Same task |
| 10 | Agent | Sorry. Trying the update again. | Same 9 ids, success, same 3 written |
| 11 | Person | You already tried that. | Friction. The call did not change |
| 12 | Agent | Let me look them up, then update again. | `find_contacts`, then the same write, same result |
| 13 | Person | That’s the same answer. | Rephrase of the same ask |
| 14 | Person | No further message. | The attempt ends. Abandonment |

## How many steps should an agent be allowed to take?

A step budget copied from a framework default is a guess. 10,007 super-steps will not save the person at turn 11. Ten turns may cut the lookup by name that would have written the 6 skips. The budget you want sits just above the laps that finished tasks used. The example’s figures do not include that distribution. Do not invent a percentile.

1. Count model calls, or super-steps, on attempts that finished the task. Keep attempts that stopped in a separate distribution.
2. Set the step budget near a high percentile of the finished attempts. A finished task then still fits, and the long tail is what you cut.
3. Read the tail before you cut it. Some of it is a real name lookup. Some of it is the third identical write. The conversations, not the percentile alone, say which.
4. Ship one change. Then compare task success on that task and that cohort with the previous period.

In the illustrative example, cohorts do not share one finish rate: self-serve 71%, enterprise 66%, returning users 61%, EMEA 58%, enterprise EMEA 52%. A budget fitted on self-serve can truncate enterprise EMEA if that cohort’s finished tasks take more laps. Check the percentile on the cohort you are changing.

Too low, and the second write after a name lookup never runs. Too high, and the third `update_contacts` still runs before the budget fires. The repeat guard catches the identical call. The step budget is the backstop for calls that change a little and move nothing.

The [workspace](https://tryabracadabra.com/product/) holds that before-and-after comparison. In the illustrative example, halving the 528 stops would finish 264 more attempts, and 64% of 2,400 would become 75%. That arithmetic is not a promise about the guard, and it only holds when the guard is the one edit in the period.

## When is a stop rule not enough?

A fence can end a run that should have continued, or miss the run you meant to catch. Name that before you trust the guard.

- **No finished-task distribution yet.** A percentile you cannot plot is a guess. Start wide, keep the repeat guard, and tighten after the distribution exists.
- **A healthy poll.** The same call is how you read a status. Hash a progress field, or exempt that tool.
- **Time as the only stop.** A fast loop finishes inside the clock. Pair it with the repeat hash.
- **The guard as the fix for the 6 skips.** It ends the burn. It does not write the rows. The tool still has to return the skips with a reason.
- **A guard that only watches errors.** This task returns success. An error cap never sees it.
- **Turn 2 treated as a loop.** A clarifying question the person answers is find the contacts working.

A stop that fires, and a finish rate that moves, are two facts. Only the second one says the fence was worth it.

## Key points

1. Natural completion never ends a model that always calls a tool, so a budget has to.
2. Name the fence. LangGraph counts super-steps and the Agents SDK counts model turns, and neither default is a product budget.
3. Guard on 2 hashes: the call, and the written state. The second one catches oscillation between tools.
4. Treat a stop as a turn the person reads. The exception belongs in the log.
5. “You already tried that”, “try again”, and “that’s the same answer” are a loop a green trace can still miss.
6. Judge a guard by the finish rate on the cohort it changed, not by how often it fires.

## Common questions about agent loops

### How do you detect friction, loops, and fallbacks in AI agent conversations?

Read 3 places. The person’s turns show friction. A repeated call hash or a count stuck at 3 written out of 9 shows a loop. A lookup by name after the partial shows a fallback. The section on friction, loops and fallbacks above walks through an example where every call is green.

### What is an agent stop condition?

It is any rule that ends the tool-calling loop before the model asks for another pass. A reply with no tool call is the happy case. The table in “When should an agent loop stop?” compares the 6 fences for every other case.

### What is a doom loop in an AI agent?

It is an agent spending laps without changing anything in the CRM. Here that means `update_contacts` sent again on the same 9 contacts, each time writing 3 and skipping 6. The section on why agents get stuck lists the 5 shapes it takes and a detector for each.

### Why does an agent keep looping when every tool call succeeds?

Success means the tool ran, not that the step finished. `update_contacts` returns success after writing 3 and skipping 6. If that status counts as done, or the person saying “try again” repeats the call, the loop continues on a green trace. Compare arguments and records written, not the status flag.

### What is a sensible max iterations or step budget?

No single number fits every task. Plot the laps that finished attempts used, per cohort, and cap just above the top of that range. Framework defaults are crash fences, not product budgets.

## Related guides

- [What is an agent harness? The parts you can change without retraining](https://tryabracadabra.com/blog/what-is-an-agent-harness/)
- [Harness engineering: how to test a harness change before it reaches everyone](https://tryabracadabra.com/blog/harness-engineering/)
- [AI agent failure detection: catch silent failures](https://tryabracadabra.com/blog/ai-agent-failure-detection/)
- [AI agent observability: how to monitor agents in production](https://tryabracadabra.com/blog/ai-agent-observability/)
- [How to measure AI agent performance in production: 6 steps](https://tryabracadabra.com/blog/how-to-measure-ai-agent-performance/)
- [Which part of the agent is failing? Symptom-to-harness map](https://tryabracadabra.com/blog/symptom-to-harness-component/)

To see where tasks stop in your own agent, read how [the workspace](https://tryabracadabra.com/product/) works, what it [can show](https://tryabracadabra.com/features/), and what each [plan includes](https://tryabracadabra.com/pricing/).
