Before you start
3- Python 3 installed and a terminal you can run python3 from
- Basic familiarity with how an agent loop works: the model picks a tool, the runner executes it, the result goes back to the model
- An agent runner you control, so you can add checks around its loop and its tool calls
An agent that keeps calling tools, rewriting the same file or retrying the same failing command is rarely "broken" in an exotic way. Recursive agents fail when autonomy outruns stop rules. Nothing tells the loop when it is finished, so it keeps going.
Four causes show up again and again:
- The exit condition is ambiguous. Under uncertainty, the agent defaults to doing more.
- Shared state is not updated correctly. The agent never sees that the work is already done, so it repeats it.
- The finish mechanism itself fails. One reported case traced a loop to a bug in a
task.finishtool, which left the model forced to keep responding. - Model limitations. In another reported case, an assistant repeated itself because of the model it ran on, not because of the surrounding setup.
The first two you fix in your own runner. The third you check by testing that your finish path really ends the run. The fourth you can only contain, which is why budgets matter even when the logic is right.
This guide builds a small guard in plain Python. It does not depend on any agent framework, so you can copy the pattern into whatever runner you use. The guard gives the agent a measurable finish line, enforces budgets, requires an explicit stop-or-continue decision, and blocks new tool calls once the run is over.
Step 1 of 6: Define a measurable finish line
Write down one check that returns true or false when the task is done, for example "the test suite passes". In the script below this is the goal_met function.
A measurable finish line removes the ambiguity that pushes an agent to do more. "Make it better" never ends. "Tests pass" does.
Step 2 of 6: Set budgets for attempts, time and repeated errors
Set three constants: MAX_ATTEMPTS, MAX_SECONDS and MAX_SAME_ERROR. The script uses 5, 30 seconds and 2. These are starting values you tune, not recommendations from any vendor.
A cap of five stops the agent after five attempts whether or not anything changed between them. A same-error rule stops it earlier, as soon as the failure repeats, so you do not spend four more attempts on a problem the agent has already shown it cannot solve.
Step 3 of 6: Require an explicit stop or continue decision
Make every agent turn return a decision that is exactly stop or continue, plus a result. Treat anything else as a stop.
When the exit condition is unclear, an agent drifts toward more work. Treating an unclear answer as a stop reverses that default, so uncertainty ends the run instead of extending it.
Step 4 of 6: Block new tool calls at the executor
Route every tool call through one executor object with a halted flag. Call halt() as soon as the run ends for any reason.
Blocking at the executor works even if the model keeps asking for tools, because the refusal does not depend on the model cooperating. The executor also records each write, so you can check afterwards whether the last write already committed before you retry or roll back.
Step 5 of 6: Run the guard against three scenarios
Save the script as loop_guard.py. It runs a simulated agent that finishes, one that never finishes, and one that fails the same way every time. Run it with the command below the script.
The simulated steps stand in for your real agent turn. Replace step with a function that calls your agent and returns (decision, result).
import time
MAX_ATTEMPTS = 5
MAX_SECONDS = 30.0
MAX_SAME_ERROR = 2
class ToolExecutor:
def __init__(self):
self.halted = False
self.writes = []
def call(self, name, payload):
if self.halted:
raise RuntimeError("tool executor halted: new calls are blocked")
if name == "write":
self.writes.append(payload)
return "ok: " + name
def halt(self):
self.halted = True
def run_guarded(step, goal_met, executor):
started = time.monotonic()
last_error = None
same_error = 0
reason = "attempt cap reached"
for attempt in range(1, MAX_ATTEMPTS + 1):
if time.monotonic() - started > MAX_SECONDS:
reason = "time budget exhausted"
break
try:
decision, result = step(attempt, executor)
except Exception as exc:
error = type(exc).__name__ + ": " + str(exc)
same_error = same_error + 1 if error == last_error else 1
last_error = error
print("attempt", attempt, "failed:", error)
if same_error >= MAX_SAME_ERROR:
reason = "same error repeated"
break
continue
print("attempt", attempt, decision + ":", result)
if decision == "stop":
if goal_met(result):
reason = "goal met"
else:
reason = "agent stopped without meeting the goal"
break
if decision != "continue":
reason = "unclear decision treated as stop"
break
executor.halt()
return reason
def goal_met(result):
return result == "tests pass"
def finishing_step(attempt, executor):
executor.call("write", "draft " + str(attempt))
if attempt < 3:
return "continue", "tests still failing"
return "stop", "tests pass"
def looping_step(attempt, executor):
executor.call("write", "draft " + str(attempt))
return "continue", "tests still failing"
def failing_step(attempt, executor):
raise ValueError("file not found")
scenarios = [
("finishing", finishing_step),
("looping", looping_step),
("failing", failing_step),
]
for name, step in scenarios:
print("==", name, "==")
executor = ToolExecutor()
reason = run_guarded(step, goal_met, executor)
last = executor.writes[-1] if executor.writes else None
print("RESULT", name, "|", reason, "| writes:", len(executor.writes), "| last write:", last)
try:
executor.call("write", "late write")
except RuntimeError as exc:
print("blocked:", exc)
python3 loop_guard.py
Step 6 of 6: Read the result and check the last write
Compare each RESULT line with the scenario. The reason tells you which rule ended the run, and the write count tells you what the agent changed before it stopped.
After a forced stop, check whether the last write already committed before you restart. Restarting blindly can repeat a change that already landed.
Expected result
== finishing == attempt 1 continue: tests still failing attempt 2 continue: tests still failing attempt 3 stop: tests pass RESULT finishing | goal met | writes: 3 | last write: draft 3 blocked: tool executor halted: new calls are blocked == looping == attempt 1 continue: tests still failing attempt 2 continue: tests still failing attempt 3 continue: tests still failing attempt 4 continue: tests still failing attempt 5 continue: tests still failing RESULT looping | attempt cap reached | writes: 5 | last write: draft 5 blocked: tool executor halted: new calls are blocked == failing == attempt 1 failed: ValueError: file not found attempt 2 failed: ValueError: file not found RESULT failing | same error repeated | writes: 0 | last write: None blocked: tool executor halted: new calls are blocked
Frequently asked questions
Why does my AI agent keep retrying instead of stopping?
The exit condition is usually ambiguous, and under uncertainty an agent defaults to doing more. A measurable finish line, budgets and an explicit stop decision remove that default.
How do I stop an agent that is already looping?
Block new calls at the tool executor, stop the outer runner, and check whether the last write already committed before you restart.
How many retries should I allow?
There is no universal number. A cap of five is a common starting point: it stops the agent after five attempts whether or not anything changed. Add a same-error rule to end the run sooner.
Can a loop be caused by the model and not my code?
Yes. One reported case was attributed to the limitations of a specific model. Budgets contain this kind of loop even when you cannot fix the cause.
Can a broken finish tool cause a loop?
Yes. One reported case involved a bug in a task.finish tool that left the model forced to keep responding. Test that your finish path ends the run.
From Grokem: https://www.grokem.com/ai-and-machine-learning/ai-agents/agent-workflows/ai-agent-stuck-in-a-loop-why-it-happens-and-how-to-stop-it-in-python






