TL;DR: Normalise each call (tool name plus arguments lower-cased, sorted, with volatile values such as timestamps and page tokens removed and word order ignored), keep a sliding window of recent signatures, and flag three patterns: the same signature repeated, near-duplicates above a similarity threshold, and short cycles (A, B, A, B). Return an action (continue, warn the model with evidence, or stop with a reason) rather than a boolean, and test each pattern with scripted sequences.
How to approach it
Define the signature, then the three patterns, then the response policy, with a test for each pattern and for a legitimate sequence that must not trigger.
A strong answer
import re
from collections import deque
VOLATILE = {"page_token", "request_id", "timestamp"}
def signature(tool, args):
parts = []
for k in sorted(args):
if k in VOLATILE:
continue
words = re.findall(r"[a-z0-9]+", str(args[k]).lower())
parts.append((k, frozenset(words)))
return tool, tuple(parts)
def similar(a, b, threshold=0.8):
if a[0] != b[0] or [k for k, _ in a[1]] != [k for k, _ in b[1]]:
return False
for (_, wa), (_, wb) in zip(a[1], b[1]):
union = wa | wb
if union and len(wa & wb) / len(union) < threshold:
return False
return True
class LoopDetector:
def __init__(self, window=6, max_similar=3):
self.recent, self.max_similar = deque(maxlen=window), max_similar
self.warned = False
def observe(self, tool, args):
sig = signature(tool, args)
hits = sum(similar(sig, s) for s in self.recent)
cycle = len(self.recent) >= 3 and sig == self.recent[-2] \
and self.recent[-1] == self.recent[-3]
self.recent.append(sig)
if hits + 1 >= self.max_similar or cycle:
if self.warned:
return "stop: repeating without progress"
self.warned = True
return "warn: similar calls repeated; change approach or answer"
return "continue"
d = LoopDetector()
calls = [("search", {"q": "battery recycling cost 2026"}),
("search", {"q": "2026 battery recycling cost", "page_token": "x1"}),
("search", {"q": "Battery recycling COST 2026"}),
("search", {"q": "cost 2026 recycling battery"})]
actions = [d.observe(t, a).split(":")[0] for t, a in calls]
print(actions) # => ['continue', 'continue', 'warn', 'stop']
legit = LoopDetector()
steps = [("read_file", {"path": f"src/mod{i}.py"}) for i in range(5)]
print({legit.observe(t, a) for t, a in steps}) # => {'continue'}
Rewordings and a changed page token normalise to the same signature, so the third similar search warns and the fourth stops. Reading five different files does not trigger.
What to say.
- "The detector returns an action so the loop can inject a warning observation first and stop only if it continues."
- "Thresholds differ by task type; debugging legitimately repeats similar test runs, so I would scope or relax it there."
- "Progress signals (new findings, completed tasks) would reset the count in a fuller version."
What interviewers probe next
"Why word sets instead of embeddings?" Fast, deterministic and good enough for rewordings in an interview; embeddings help in production for semantic paraphrases.
"How do you avoid false positives on paginated reads?" Page tokens are volatile and removed, but the detector should still allow successive pages; include the page number in the signature if paging forward is progress.
"Where does it sit?" In the dispatcher, before execution, so a stop prevents the call.
How it's scored
Weak: Checks whether the exact same call appeared before.
Hire: Normalised signatures and a repeat threshold in a sliding window.
Strong Hire: Removes volatile fields, compares by similarity, detects short cycles, returns warn-then-stop actions, tests both triggering and legitimate sequences, and discusses thresholds by task type and progress-based resets.
Common mistakes
- Exact matching only.
- Including volatile values such as timestamps in signatures.
- Stopping on the first similarity, with no warning step.
- No test that legitimate varied work does not trigger.