AI Agents: Loops, Tools, and StoppingAgent Loop Detector
Progress

Agent Loop Detector

medium
Start small, think out loud.

A flight-booking agent in your logs has a bad look: one run spent eleven turns calling the same flight filter with the same options, reading the same empty result each time, until a spending cap killed it. Nothing crashed; the run just stopped being about anything. Detecting that stuck state is not a judgment call, it is a mechanical check, and it belongs in the harness, the code that runs the tools and drives the loop. A trace is the record of one agent run: a list of tool calls in order, each with the tool name and the arguments it was called with. Implement find_loop(calls, threshold): calls is that list, each record a dict with tool and args keys - real traces also stamp ids and timestamps on records, which never participate in the comparison. Two records are equivalent when both the tool and the args match, with args compared as dictionaries, so key order inside args is irrelevant. The loop is detected the moment threshold consecutive equivalent records exist: return the index of the first record of that repeat run. Interleaved calls with different arguments reset the run - same tool, different args is variation, not a loop. If no repeat run that long exists, return -1.

Time:O(number of records)
Space:O(1)
agent-loopsstuck-run-detectionharness-safetyai-track
solution.py
⌘↵ run
Loading...
OUTPUT

Run your code to see output