Detect a repeating tool-call loop

EasyAgents

Why it matters Agent harnesses stop runaway loops with guards like this to save tokens and money.

Agents sometimes call the same tool with the same arguments over and over.

Write detect_loop(calls, k). calls is a list of (tool, args_string). Return True if the last k calls are identical, else False. If fewer than k calls, return False.

Signaturedef detect_loop(calls, k)

Example

detect_loop([("search", "a"), ("search", "a"), ("search", "a")], 3) is True.

Understand the idea

Agents sometimes get stuck calling the same tool with the same arguments again and again, burning tokens without progress. A simple guard checks whether the last k calls are all identical in both tool name and arguments. The arguments must match too: calling search with page=1, then page=2, then page=3 is normal paging, not a loop. Worked example: calls [('search', 'q=a'), ('read', 'x'), ('read', 'x'), ('read', 'x')]. With k = 3, the last three are all ('read', 'x'), so the answer is True. With k = 4, the first call differs, so False. Calls [('search', 'page=1'), ('search', 'page=2'), ('search', 'page=3')] with k = 3 give False because the arguments differ. Rule: if len(calls) < k, return False; else take calls[-k:] and return True only if every tuple equals the first one in that window. Compare whole (tool, args) tuples, not just the tool name. Used in: agent frameworks that stop or nudge a model after repeated identical tool calls, and in cost guards for long-running agents.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampledetect_loop([('search', 'a'), ('search', 'a'), ('search', 'a')], 3)
  • Sample 2: different argsdetect_loop([('search', 'a'), ('search', 'b'), ('search', 'a')], 3)
  • Test 3: shortdetect_loop([('x', '1')], 2)
  • Test 4: loop at enddetect_loop([('read', 'f'), ('ls', '.'), ('ls', '.')], 2)