How to detect an AI agent stuck in a loop
On this page
To detect an agent stuck in a loop, put a hard step limit inside the agent so a loop ends as an error, then add an outside check for the two loops your code can't see from inside: a run that never finishes, and an agent that keeps getting restarted. A start ping with a time limit catches the first. A count of runs per time window catches the second. Report cost as the run goes, and a daily cost cap catches a loop that is burning money before either limit trips.
The three loops, and which check catches each
| What loops | What it looks like | What catches it |
|---|---|---|
| The model inside one run (calls the same tool, re-plans, retries forever) | One run that keeps going and keeps spending | A step limit in your code, then a Stuck run alert if the run never reports a finish |
| The run itself (a queue retries the job, a webhook re-fires, a supervisor restarts a crashing agent) | Many short runs, close together | Stallbell's Loop rule, which counts runs per window |
| Spend, in either case | Cost climbing far past a normal day | A Per-day cost cap on the cost each run reports |
Layer 1: cap the steps inside the agent
Every agent framework has a limit. Check what yours defaults to, because the default may be far higher than any sane run:
- CrewAI: an
Agenttakesmax_iter, the maximum iterations before the agent must give its best answer. The default is 20. It also takesmax_execution_time, a time limit in seconds, which is off unless you set it. - LangGraph (and agents built on it): the recursion limit caps how many super-steps one run may execute, and raises
GraphRecursionErrorwhen it's exceeded. From LangGraph 1.1.4 the default is 10,007 super-steps. Pass a smallerrecursion_limitin the run's config. - Your own loop: count iterations and raise when the count passes a limit you choose.
A step limit turns an endless loop into an error. The next layer makes sure that error, or the silence of a run that never got that far, reaches you.
Layer 2: an outside check on each run
Send a start ping with a run_id when the agent begins, a progress ping with the cost so far every few steps, and a finish ping with the exit code. This uses only the Python standard library:
# agent_run.py: step limit inside, start, progress and finish pings outside.
import json, sys, uuid, urllib.request
PING = "https://stallbell.com/p/TOKEN"
MAX_STEPS = 25
run_id = str(uuid.uuid4())
def ping(path, **fields):
body = json.dumps({"run_id": run_id, **fields}).encode()
req = urllib.request.Request(PING + path, data=body, method="POST",
headers={"content-type": "application/json"})
try:
urllib.request.urlopen(req, timeout=10).read()
except Exception as exc: # never let monitoring break the agent
print("stallbell ping failed:", exc, file=sys.stderr)
def agent_step(step):
# Your agent's next step. Return (done, answer, cost_usd_of_this_step).
return step >= 3, "Summary: 3 new leads", 0.002
ping("/start")
try:
for step in range(1, MAX_STEPS + 1):
done, answer, step_cost = agent_step(step)
if step % 5 == 0 or done:
ping("/progress", cost_usd=step_cost)
if done:
break
else:
raise RuntimeError(f"step limit hit: {MAX_STEPS} steps without an answer")
ping("/0", output=answer[:2000])
except Exception as exc:
ping("/fail", msg=str(exc)[:500])
raiseWhat each ping does in Stallbell:
/startopens a run. If no finish or progress arrives within the monitor's Stuck after time (1 hour by default), Stallbell opens a Stuck run alert. A loop that ignores your step limit, or a process that hangs, ends up here./progresskeeps a long, healthy run from looking stuck, and adds itscost_usd(or its model and token counts) to the run and to the day's total./0or/failfinishes the run. Hitting the step limit raises, so it's reported as a Failed run with the messagestep limit hit.
Set Stuck after a little above your slowest normal run. Note that each progress ping restarts the stuck timer, so a loop that keeps sending progress pings won't look stuck. That's what the step limit and the cost cap are for.
Layer 3: catch an agent that keeps restarting
Some loops live outside the agent: a queue that redelivers a job that crashed, a webhook that fires again on every retry, a supervisor that restarts the process the moment it dies. Each run is short, so nothing looks stuck. What gives it away is the number of runs.
Stallbell's Loop rule counts runs in a sliding window: each start ping is a run, and so is a finish ping that arrives without a start. It alerts when the count goes over a threshold, which by default is the larger of 5 runs or 3 times the pace your schedule expects in the window. The window is 10 minutes by default. For an agent that runs hourly, that means more than 5 runs in 10 minutes raises a Loop alert.
You can change all of it under the monitor's thresholds: Loop window, Runs over the expected pace, Minimum runs in the window, and an optional Hourly run cap. The alert stays open until the rate drops back under the threshold and stays quiet for 10 minutes, so a short pause in a burst doesn't look like a recovery.
Layer 4: cap the spend
Turn on Per-day cost cap in the monitor settings. Cost you send on progress pings counts toward the day's total, so the cap can fire while a looping run is still going. The day is counted in the project's timezone. See how to get alerted on runaway LLM cost for the cost fields and the other two cost rules.
What this doesn't do
- It doesn't read your agent's steps. Stallbell sees the pings you send. It doesn't count tool calls or model calls inside a run, so the step limit has to live in your code.
- It doesn't stop the agent. Every rule sends an alert. None of them cancels a run or touches your model provider account.
- It doesn't judge the answer. The output checks are empty, a required phrase, and valid JSON.
FAQ
Will the Loop rule fire on a busy but healthy agent? Only if it runs more often than the threshold allows. If an agent is meant to run 20 times in 10 minutes, raise Minimum runs in the window or give it a fixed interval that matches, so the expected pace covers it.
What happens when the step limit is hit? The script raises, reports /fail with the message, and exits with an error, so you get a Failed run alert that says step limit hit. The run's cost so far is already recorded from the progress pings.
Does this work with LangChain or CrewAI? Yes. Wrap the call that starts the agent. See how to monitor LangChain and CrewAI agents.
Related: Runaway LLM cost alerts · Detect stuck jobs · How to monitor AI agents that run on a schedule
Sources
Framework behaviour on this page comes from each framework's own docs, read on 9 November 2026:
- CrewAI Agents (
max_iter, default 20, andmax_execution_time) - LangGraph Graph API: recursion limit (
GraphRecursionErrorand the default limit)
Stallbell's side comes from the docs.