In the demo at the bottom of this post, a stuck agent with only max_iterations = 30 runs all 30 iterations and spends about 14,700 estimated prompt tokens. With a small guard in the tool loop, the same run stops at iteration 3 after 152 tokens. The guard knew at iteration 3 what the cap found out at iteration 30.

Stuck loops come in three shapes:

  1. It calls search("rate limit policy"), reads the result, and calls search("rate limit policy") again.
  2. It rephrases: "rate limit policy", "API rate limiting rules", "request quota per key", and gets the same top hit every time.
  3. It alternates: search, read_doc(7), search, read_doc(7), each result identical to the last.

Why the cap is the wrong instrument

max_iterations is a ceiling for legitimate work. You set it high enough that a hard, healthy task can finish, so it ends up at 25 or 50 or 100. A stuck agent gets to burn all of it.

The tail is also the expensive part. Every iteration sends the full transcript back to the model, so iteration N costs more than iteration N-1, and the total grows roughly with N squared. In the repeat run below, the first ten iterations cost 1,580 estimated tokens and the last ten cost 8,230. The 30th call alone costs 973 tokens, about six times the entire guarded run.

The cap also says nothing about progress. It fires at the same point for an agent stuck since iteration 2 and for one that is a step away from a good answer.

Progress means new information came back

In a tool loop, the agent made progress on a turn if the tool returned something it had not seen before. You can measure that without understanding the task: hash the result and count how often each hash shows up.

That one check covers all three shapes. A repeated call returns the same payload. A rephrased query that lands on the same document returns the same payload. An alternating pair returns two payloads that each repeat. Counting identical results over the whole run catches a period-2 loop at about the same point it catches a period-1 loop, so you don't need a separate cycle detector.

Two more checks round it out:

  • Identical call arguments. Some tools return noisy output (a timestamp, a request id, results in random order), so the result hash never matches. Count canonicalized (tool, args) too, with a higher limit, since re-reading a file after editing it is normal.
  • A token budget. An agent that wanders through different calls with different results never repeats anything. The budget is the backstop, measured in the thing you pay for.

The guard works in two stages. The first repeat appends a note to the tool result, telling the model in plain text that it already has this information. The next repeat raises and ends the loop. The note gives the model one cheap chance to change course; the hard stop covers the times it doesn't.

The bug in my first version

My first version of this guard hashed the whole tool result. In testing, the rephrasing agent got straight past it. The fake search echoed the query back in its response, as many search APIs do, so every rephrased call produced a "new" payload even though the hits never changed. The guard was measuring novelty in the echo.

The fix is a per-tool view: hash only the part of the result that would change if the agent learned something.

VIEWS = {"search": lambda r: r["hits"]} # ignore the echoed query 

Echoed requests, request_id, fetched_at, and pagination cursors all cause this. If you hash the whole payload, those fields make every result look new and the result counter never climbs. In the demo, the rephrase run without a view went 11 iterations and was only stopped by the token budget. With the view it stopped at 3.

The guard

Standard library only. Save as stall_guard.py.

import hashlib import json import re from collections import Counter class Stall(Exception): """The loop should stop: the agent is not making progress.""" def _canon(v): # Collapse whitespace, sort keys. No lowercasing: paths and IDs are case-sensitive. if isinstance(v, str): return re.sub(r"\s+", " ", v).strip() if isinstance(v, dict): return {k: _canon(v[k]) for k in sorted(v)} if isinstance(v, (list, tuple)): return [_canon(x) for x in v] return v def _digest(obj): raw = json.dumps(obj, sort_keys=True, default=str).encode() return hashlib.sha256(raw).hexdigest()[:12] def _show(name, args): return f"{name}({json.dumps(_canon(args), sort_keys=True)})" class StallGuard: def __init__(self, same_call_limit=5, same_result_limit=3, token_budget=100_000, views=None): self.same_call_limit = same_call_limit self.same_result_limit = same_result_limit self.token_budget = token_budget # Per-tool projection: the part of the result that changes # when the agent learns something. Default: the whole result. self.views = views or {} self.calls = Counter() self.results = Counter() self.tokens = 0 def charge(self, prompt_tokens): self.tokens += prompt_tokens if self.tokens > self.token_budget: raise Stall(f"token budget exceeded ({self.tokens} > {self.token_budget})") def before_call(self, name, args): key = (name, _digest(_canon(args))) self.calls[key] += 1 n = self.calls[key] if n >= self.same_call_limit: raise Stall(f"{_show(name, args)} called {n} times") if n == self.same_call_limit - 1: return (f"NOTE: this is call #{n} of {name} with the same arguments. " "Calling it again will not produce new information. " "Use the result you already have or try a different approach.") return None def after_call(self, name, args, result, informational=True): if not informational: return None view = self.views.get(name, lambda r: r)(result) key = (name, _digest(view)) self.results[key] += 1 n = self.results[key] if n >= self.same_result_limit: raise Stall(f"{name} returned the same result {n} times " f"(last call: {_show(name, args)})") if n == self.same_result_limit - 1: return (f"NOTE: {name} has now returned this exact result {n} times. " "Repeating or rephrasing the call will not change it.") return None 

Notes on the choices:

  • _canon collapses whitespace and sorts keys, so {"q": "rate limit"} and {"q": "rate limit"} count as the same call. It does not lowercase, because paths and IDs are case-sensitive. Synonyms are the result hash's job.
  • Result keys include the tool name, so two different tools returning [] don't count as the same event.
  • informational=False skips result counting. A write tool that returns {"ok": true} every time is returning an acknowledgement, and ten different writes with the same acknowledgement are not a stall. If you already classify tools as read or write for permissions, reuse that.
  • The Stall message includes the call. search({"q": "request quota per key"}) returned the same result 3 times is a bug report. max iterations reached isn't.

Wiring it into the loop

Three changes to the loop body: charge the budget before calling the model, check arguments before running the tool, check the result after. Append any note to the tool result text, where the model is already looking. This is a trimmed excerpt of run() from the demo:

guard.charge(est_tokens(messages)) action = model(messages) ... notes = [guard.before_call(name, args)] result = TOOLS[name](**args) notes.append(guard.after_call(name, args, result)) content = json.dumps(result) + "".join("\n" + n for n in notes if n) messages.append({"role": "tool", "content": content}) 

Catch Stall outside the loop, return whatever partial answer you have, and count stalls by reason in your metrics. A jump in "returned the same result" after a prompt change is something you want to see on a dashboard before you see it on the bill.

The demo

Save as demo.py next to stall_guard.py and run python3 demo.py. The model is scripted, so the run is deterministic and needs no API key. search echoes the query and returns the same top hit for anything about limits or quotas; read_doc reads three short documents.

import json from stall_guard import StallGuard, Stall DOCS = { 7: "Rate limit: 600 requests per minute per API key, burst of 50.", 8: "Authentication: send the key in the X-Api-Key header.", 9: "Pagination: cursor based, max page size 200.", } def search(q): # Like most search APIs, the response echoes the query. # Anything about limits or quotas returns the same top hit. if any(w in q.lower() for w in ("limit", "quota", "throttl")): hits = [{"id": 7, "title": "API rate limits"}] else: hits = [{"id": None, "title": f"Did you mean: {q}?"}] return {"query": q, "hits": hits} def read_doc(id): return DOCS.get(id, "") TOOLS = {"search": search, "read_doc": read_doc} VIEWS = {"search": lambda r: r["hits"]} # ignore the echoed query def est_tokens(messages): # Rough: 4 characters per token across the whole transcript. return sum(len(m["content"]) for m in messages) // 4 def turn(messages): return sum(1 for m in messages if m["role"] == "assistant") # Scripted stand-ins for the model: transcript in, action out. def repeat_model(messages): return {"tool": "search", "args": {"q": "rate limit policy"}} REPHRASES = ["rate limit policy", "API rate limiting rules", "request quota per key", "throttling limits", "rate-limit docs"] def rephrase_model(messages): return {"tool": "search", "args": {"q": REPHRASES[turn(messages) % 5]}} def alternate_model(messages): steps = [{"tool": "search", "args": {"q": "rate limit policy"}}, {"tool": "read_doc", "args": {"id": 7}}] return steps[turn(messages) % 2] def wander_model(messages): # A different query every time, never finishes. return {"tool": "search", "args": {"q": f"topic {turn(messages)}"}} def listens_model(messages): if messages[-1]["role"] == "tool" and "NOTE:" in messages[-1]["content"]: return {"final": "600 requests per minute per key."} return {"tool": "search", "args": {"q": "rate limit policy"}} def healthy_model(messages): plan = [{"tool": "search", "args": {"q": "rate limit policy"}}, {"tool": "read_doc", "args": {"id": 7}}, {"tool": "read_doc", "args": {"id": 8}}, {"tool": "read_doc", "args": {"id": 9}}, {"final": "600 requests per minute per key."}] return plan[turn(messages)] def run(model, guard=None, max_iterations=30): messages = [{"role": "user", "content": "What is the API rate limit per key?"}] s = {"iters": 0, "calls": 0, "tokens": 0, "stop": "max_iterations"} for _ in range(max_iterations): s["iters"] += 1 prompt = est_tokens(messages) s["tokens"] += prompt try: if guard: guard.charge(prompt) action = model(messages) messages.append({"role": "assistant", "content": json.dumps(action)}) if "final" in action: s["stop"] = "final answer" return s name, args = action["tool"], action["args"] notes = [guard.before_call(name, args)] if guard else [] result = TOOLS[name](**args) s["calls"] += 1 if guard: notes.append(guard.after_call(name, args, result)) content = json.dumps(result) for note in notes: if note: content += "\n" + note messages.append({"role": "tool", "content": content}) except Stall as e: s["stop"] = f"guard: {e}" return s return s if __name__ == "__main__": rows = [("repeat", repeat_model), ("rephrase", rephrase_model), ("alternate", alternate_model), ("wander", wander_model), ("listens", listens_model), ("healthy", healthy_model)] guards = [("none", lambda: None), ("raw", lambda: StallGuard(token_budget=2_000)), ("view", lambda: StallGuard(token_budget=2_000, views=VIEWS))] print("iterations / estimated prompt tokens, per guard") print(f"{'scenario':<10}" + "".join(f"{g:>12}" for g, _ in guards) + " stopped by (view)") for label, model in rows: cells, last = "", None for gname, make in guards: last = run(model, make()) cells += f"{last['iters']:>5} /{last['tokens']:>5}" print(f"{label:<10}{cells} {last['stop']}") 

Output (none = only max_iterations, raw = guard hashing whole results, view = guard with VIEWS):

iterations / estimated prompt tokens, per guard scenario none raw view stopped by (view) repeat 30 /14715 3 / 152 3 / 152 guard: search returned the same result 3 times (last call: search({"q": "rate limit policy"})) rephrase 30 /15093 11 / 2387 3 / 155 guard: search returned the same result 3 times (last call: search({"q": "request quota per key"})) alternate 30 /13087 5 / 426 5 / 426 guard: search returned the same result 3 times (last call: search({"q": "rate limit policy"})) wander 30 /13767 12 / 2130 12 / 2130 guard: token budget exceeded (2130 > 2000) listens 30 /14715 3 / 152 3 / 152 final answer healthy 5 / 320 5 / 320 5 / 320 final answer 

Reading it:

  • repeat and alternate stop on the result hash with or without the view. Alternate takes 5 iterations because each of its two payloads needs three sightings.
  • rephrase is the echo bug. Every argument string is different, so the arguments counter never fires, and without the view every result looks new too. Only the token budget stops it, at iteration 11. With the view it stops at 3.
  • wander never repeats a call or a result, so only the budget stops it. The 2,000 budget is sized for this demo's tiny messages. In your system, look at the token spend of successful runs and set the budget at a multiple of the high end, not at a round number.
  • listens is the two-stage design working. The model repeats once, gets the note on the second result, and answers on iteration 3 without the guard raising.
  • healthy is the false-positive check: four distinct calls and a final answer, identical in every column.

The token numbers are a 4-characters-per-token estimate over a scripted transcript, so read them as shape, not pricing.

Tuning

Polling tools are the common legitimate repeat. An agent that calls job_status(id) and gets pending four times looks stuck to the guard. Usually the right fix is to put the waiting inside the tool, with its own backoff and timeout, so one call returns a terminal state. If you can't, give that tool a higher limit instead of loosening the guard for everything.

Small payloads collide. Empty lists, null, and short status strings from the same tool match each other across unrelated calls. If one read tool legitimately returns [] a lot, give it a view or a higher limit. Don't drop the result check globally because one tool is noisy.

Write the note like an error message for a person: what happened, what to do instead. It goes into the model's context as part of the tool output.

What it doesn't catch

  • Real progress that goes nowhere. An agent paging through 400 search results gets a new result every call. That's a budget problem: the token budget, a per-tool cap, or max_iterations.
  • Loops across runs. The guard lives for one run. If a scheduler restarts a stalled task every minute, it stalls once a minute.
  • Repeated writes. For side-effect tools, a repeated call is a duplicate write, which needs an idempotency key, not a counter.

Keep max_iterations as the last line of defense. It tells you how long you're willing to wait. The guard tells you when waiting stopped being useful, and in a loop whose cost grows with the square of its length, that's the number you want first.

AI-assisted: the first draft of this article was written with an AI model, then edited by hand. All code was run with Python 3, and every number above comes from that run.