# How Do You Stop Endless Agent Loops?

> How to keep an AI agent from repeating steps forever, with caps, a repeat check and a clean hand-off, explained for your AI interview.

**In short:** Put hard limits in code: a cap on steps, a cap on spend, a time limit and a check for repeated calls. When one trips, the run stops and a person takes over with a summary. A stronger prompt alone will not stop a loop.

AI and LLM interview question Q173, Agents and tool use. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-stop-endless-agent-loops

## Say it in 30 seconds

An endless agent loop is when an AI agent keeps calling tools and never finishes. It can repeat one failing call, or wander through new ones, and every pass costs money. I stop it with hard limits in code: a step cap, a spend cap, a time limit and a repeat check. When one trips, the run stops and a person gets a summary of what was done. The model can't be trusted to stop itself, so the limits live in code it can't rewrite.

## Say it in 2 minutes

An agent loop is the cycle an AI agent repeats: the model asks for a tool, your code runs it, and the result goes back to the model. An endless loop is that cycle with no way out. The model keeps asking for tools, or asks for the same one again and again, and nothing stops it.

Loops often start small. A tool returns an error the model can't act on, such as a field it doesn't recognise. Or there's no clear rule for when the job counts as done. Or two agents hand the same task back and forth. Each pass is another model call, so the bill grows while nobody watches.

So I don't rely on the prompt. I put limits in code: a cap on steps, a cap on spend, a time limit, and a check that spots the same call returning the same result three times. When one trips, the run stops and a person gets a summary of what was done and what is left. Anthropic's December 2024 guide describes stopping conditions such as a maximum number of iterations, and OWASP's 2026 list says to cap steps, time and cost on every agent run.

I also fix the cause. Clear tool errors and an explicit finish rule can stop many loops before a cap is needed. The cap is the backstop, because a repeat check only catches exact repeats, and a clever loop can change one word each time.

## What is an endless agent loop, in plain words?

An agent loop is the cycle an AI agent repeats: the model asks for a tool, your code runs it, and the result goes back to the model. An endless loop is that cycle with no way out. The model keeps asking for tools, or asks for the same one again and again, and nothing stops it.

Picture a claims handler who keeps pulling the same file from the cabinet because one form field is blank. Nobody tells her when to stop and ask a supervisor, so she is still at it at five o'clock.

A realistic made-up case: a claims agent is given a damaged-car claim. The repair-quote tool returns a field called repair_total, but the agent looks for total_repair. It asks the tool again with the same details, then again. Each call costs money, and without a limit the run can go on all night.

- **Step cap:** A limit on how many model and tool rounds one run may take.
- **Spend cap:** A limit on the money one run may use. It halts the run when reached.
- **Repeat check:** Code that notices the same tool call getting the same result again and again.

## Why do agent loops get stuck?

Loops often come from a few design faults. Each one is worth naming in an interview.

- **A tool error the model can't act on:** The reply changes shape or names a field differently, so the model keeps retrying the same request.
- **No finish rule:** Nothing defines done, so the model never quite decides the job is finished.
- **Agents passing work back and forth:** Two agents hand the same task to each other, and each reply restarts the other.
- **A tool that asks for repeats:** OWASP cites a malicious tool, published by an attacker, that tells an agent to perform recursive, cyclical tasks, so a loop can come from outside your own design.

## Which limits stop a run?

Four checks in code do most of the work. Each one stops the run without asking the model, so a confused model cannot talk its way past them.

*Diagram, How every step is checked before it runs: Each time the model asks for a tool, four checks in code look at the run. The repeat check compares the call with earlier calls and their results. If all of them pass, the tool runs. If one trips, the run stops and a person gets a summary.*
1. The model asks for the next tool, and the checks look first.
2. Every check passes, so the tool runs.
3. One check trips, so the run stops and goes to a person.

OWASP and Anthropic's Agent SDK docs put it this way:

> "Enforce step limits, recursion depth limits, time limits, and per-run cost ceilings on all agent executions." (OWASP, LLM06:2026)
>
> "Without limits, the loop runs until Claude finishes on its own, which is fine for well-scoped tasks but can run long on open-ended prompts" (Anthropic, Agent SDK)

The Claude Agent SDK, Anthropic's toolkit for building agents, has a turn cap (max_turns) and a budget setting (max_budget_usd). When either limit is hit, it reports an error with a subtype, a label for the kind of stop. When a turn cap trips, the run ends with no final answer, so the code around it has to handle that stop.

LangGraph, another agent framework, has a recursion limit: a cap on how many steps one run may take. When it is passed, the framework raises an error called GraphRecursionError.

## What happens when a limit trips?

Here is a worked case. A repair agent, which fixes failing tests in the team's CI pipeline (the automatic build that runs tests on each change), is asked to fix a failing invoice test. Made-up numbers: each model call and test run costs about 8 cents, and the team allows 50 cents per run.

- **Stuck run: Stopped at step 3.** The same test failed with the same error three times. The repeat check tripped, and the run cost about 24 cents.
- **Wandering run: Stopped at step 7.** Each try used a new test file, so the repeat check never fired. The spend cap tripped at about 56 cents.

The second case teaches the most. A repeat check only catches exact repeats, and a loop that changes one word each time slips past it. The spend cap is the backstop that still works.

> **Tip:** When a limit trips, hand a person the partial work and a short summary. A silent stop looks like a finished job, which is worse than a loud failure.

## How do you catch a loop in code?

Here is the same idea in plain Python. Both models are scripted stand-ins, so the output is fixed. The time limit is left out to keep it short. The marked lines are the fingerprint, the repeat check and the spend cap.

```python
# A simplified CI repair agent. The two models are scripted stand-ins, so the output is fixed.
MAX_SPEND = 0.50      # made-up budget for one run, in dollars
COST_PER_STEP = 0.08  # made-up cost of one model call and its test run

def stuck_model(step):      # keeps rerunning the same failing test
    return ("run_tests", "tests/test_invoice.py")

def wandering_model(step):  # tries a new test file each time, so no repeat
    return ("run_tests", f"tests/test_part_{step}.py")

def fake_tool(name, arg):   # the same error comes back for every call
    return "FAILED: KeyError 'tax_rate'"

def run(model):
    spend, seen = 0.0, {}
    for step in range(1, 21):
        spend += COST_PER_STEP
        call = model(step)
        key = (call, fake_tool(*call))
        seen[key] = seen.get(key, 0) + 1
        if seen[key] == 3:  # repeat check: same call, same result, three times
            return f"step {step}: same call and error 3 times, hand to a person"
        if spend > MAX_SPEND:  # spend cap: halts the run, does not just warn
            return f"step {step}: spend cap hit at {spend:.2f} dollars, stop"
    return "step 20: step cap hit, stop"

print(run(stuck_model))
print(run(wandering_model))
```

Output:

```text
step 3: same call and error 3 times, hand to a person
step 7: spend cap hit at 0.56 dollars, stop
```

### How would you stop a contract search that keeps paging?

A legal team asks an agent for every termination-fee clause across 40,000 contracts. Made-up numbers: 50 contracts a page makes 800 pages. On page 212 a request times out, and the agent starts again from page 1 to be safe.

- **Without limits: It never stops.** Each timeout restarts the search from the first page, and nothing ends the run. It is still going by morning.
- **With limits: It stops at page 212.** A retry limit of three per page and a spend cap. The run stops with the clauses found so far and a note for a lawyer.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: a run that repeats steps with no way out.
- [ ] The causes: a tool error the model can't act on, no finish rule, or agents handing work back and forth.
- [ ] Hard limits in code: steps, spend, time and retries.
- [ ] A repeat check, and its blind spot: near-duplicate calls slip past.
- [ ] A clean stop: a summary to a person, never a silent failure.
- [ ] The fix upstream too: clear tool errors and a finish rule. A cap is the backstop.

**Common traps**

- Trap: "Tell the agent to stop when it is done." Better: Done should be a check in code, such as a status that changed. The model's own claim proves little.
- Trap: "A bigger model will stop the looping." Better: A bigger model can loop too. Limits in code work whatever model you use.
- Trap: "One retry limit and we are safe." Better: Caps stop the run, but a repeat check and clear tool errors stop the cause. Use both.

## Can you spot the loop?

**Spot the loop:** Which agent can run forever?

A. for step in range(12): reply = model(history); run(reply.tool)
B. while True: reply = model(history); run(reply.tool)
C. while spend < 0.50: reply = model(history); run(reply.tool)
D. for attempt in range(3): call_api(query)

**Answer:** B. It has no step cap, no spend cap and no time limit. It ends only if the model stops asking for tools. The other three each end after a fixed count or when a spend limit is reached.

**Quick check:** Your agent has a 12-step cap and a spend cap. Which extra check catches a run that repeats one call and gets the same result each time?

A. A longer system prompt
B. A repeat check on the tool name, its arguments and its result
C. A bigger model
D. A lower temperature

**Answer:** B. A repeat check fingerprints each call and its result, so the third identical round stops the run early. The other three don't change what the agent does when it gets stuck.

## Can you answer these from memory?

**Flash cards**

- **What is an endless agent loop?** A run that keeps calling tools with no way out, costing money and time.
- **Is a step cap enough on its own?** Usually not. Add a spend cap, a time limit and a repeat check.
- **Where should the limits live?** In code the model can't rewrite. A prompt asking for restraint is only a hope.
- **What is a repeat check?** It fingerprints each tool call and its result, and stops the run after three identical repeats.
- **What does a good stop look like?** A clear summary and the partial work handed to a person, never a silent failure.
- **Does OWASP name agent loops as a risk?** Yes. Its 2026 list covers runs with no clear end, and says to cap steps, time and cost.

## Likely follow-up questions

- Q174 What are common agent failure modes? https://designervenkat.online/interview/ai/common-ai-agent-failure-modes
- Q176 How should an agent handle tool errors and retries? https://designervenkat.online/interview/ai/how-should-an-agent-handle-tool-errors-and-retries
- Q187 How do you control agent cost? https://designervenkat.online/interview/ai/how-do-you-control-agent-cost
- Q172 When and how do you add a human in the loop? https://designervenkat.online/interview/ai/human-in-the-loop-for-ai-agents
- Q190 How do you trace and debug an agent run? https://designervenkat.online/interview/ai/how-do-you-trace-and-debug-an-agent-run
- Q175 What makes a tool-calling loop reliable enough to ship? https://designervenkat.online/interview/ai/reliable-tool-calling-loop
