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.
11 min readIntermediateCommon · estimateFacts checked 26 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
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.
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.
Key words
- 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.
How every step is checked before it runs
Model asks for a tool
one step, chosen by the model
Checks in code
Step cap
stops after a set number of steps
Spend cap
halts when the budget is used up
Time limit
stops a run that takes too long
Repeat check
same call and result, three times
Tool runs
only if every check passes
Person takes over
gets a summary of what was done
- 1The model asks for the next tool, and the checks look first.
- 2Every check passes, so the tool runs.
- 3One 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.
# 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
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."
BetterDone 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."
BetterA bigger model can loop too. Limits in code work whatever model you use.
Trap"One retry limit and we are safe."
BetterCaps 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?
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?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
- Q174What are common agent failure modes?12 min
- Q176How should an agent handle tool errors and retries?14 min
- Q187How do you control agent cost?13 min
- Q172When and how do you add a human in the loop?12 min
- Q190How do you trace and debug an agent run?11 min
- Q175What makes a tool-calling loop reliable enough to ship?13 min
Last updated on 26 November 2026
Building an agent that could get stuck in a loop?
Venkat designs and builds AI agents and the interface around them. Book a short call and say what your agent needs to do.