r/AgentsOfAI • u/ClickOk5811 • 8h ago
Discussion A small loop guard for agents: step budget plus a repeated-call detector (and the case it misses)
A failure mode I think is common in tool-calling agents is the loop: the model calls the same tool with the same arguments, gets the same result, and tries again. A cheap guard sits between the model’s decision and the tool execution. Here’s a minimal version I tested with a simulated sequence of calls:
import hashlib
import json
from collections import Counter
class LoopGuard:
def __init__(self, max_steps=25, max_repeats=3):
self.max_steps = max_steps
self.max_repeats = max_repeats
self.steps = 0
self.seen = Counter()
def check(self, tool_name: str, args: dict) -> str | None:
"""Return a reason to stop, or None to continue."""
self.steps += 1
if self.steps > self.max_steps:
return f"step budget exceeded ({self.max_steps})"
key = hashlib.sha256(
json.dumps([tool_name, args], sort_keys=True).encode()
).hexdigest()
self.seen[key] += 1
if self.seen[key] > self.max_repeats:
return f"same call repeated {self.seen[key]} times: {tool_name}({args})"
return NoneCall check() before executing each tool call. If it returns a reason, stop the loop and return control (to a human, a fallback, or a summary step) instead of executing.
What happened in my test (max_repeats=2): the first two identical search("refund policy") calls passed, a third identical call was blocked with a message naming the tool and arguments. A call with a slightly different string ("refund policy", two spaces) was not caught, because the hash is of the exact arguments.
What it catches:
Exact repeated calls (same tool, same args).
Runaway loops in general, via the step budget, whatever the cause.
What it doesn’t catch:
Near-duplicates: rephrased queries, reordered arguments that aren’t normalized, small variations that go nowhere. You could normalize arguments (lowercase, trim, collapse whitespace) or compare results, but that adds false positives.
Loops that span several tools (A, then B, then A, then B).
Agents that make progress on paper but not in substance, such as steady calls that never get closer to the goal.
Design questions I’d weigh:
What should happen on a stop: ask a human, return a partial answer, or try a different strategy? Stopping silently can look like success.
Should repeated results count, not just repeated calls? An identical result from a different query may mean the same thing.
The right budget depends on the task. A fixed number can be too tight for research-style work and too loose for simple lookups.
I haven’t tested this in a real agent framework, only with the simulated sequence above, so treat it as a starting point, not a solution.
What do you use for loop detection in your agents: step caps, argument hashing, result similarity, or something else? And what do you do when the guard fires?