BasicsGuardrailsLoop DetectionOpenAIAnthropicGoogle
Problem
Implement has_tool_loop(calls, max_repeats=2) where calls is a list of (tool_name, arg_str) tuples. Return True if any identical (tool_name, arg_str) pair appears strictly more than max_repeats times, otherwise False.
Why It Matters: Stuck agents often call the exact same failing tool with identical arguments over and over; loop detectors break the cycle and force a replan or escalation.
Function Signature
from collections import Counter
def has_tool_loop(calls: list[tuple[str, str]], max_repeats: int = 2) -> bool:
"""Return True if any identical (tool, arg) call repeats > max_repeats times."""
Sample Input & Output
Example 1: Stuck Repeat Loop Detected
Input:
calls = [("search", "q=ai"), ("read", "1"), ("search", "q=ai"), ("search", "q=ai")], max_repeats = 2
Expected Output:
True
Explanation: ('search', 'q=ai') occurs 3 times (3 > 2), triggering the loop detector.
Example 2: At Threshold (Allowed) & Different Args
Input:
calls = [("search", "q=ai"), ("search", "q=ai"), ("search", "q=ml")], max_repeats = 2
Expected Output:
False
Explanation: ('search', 'q=ai') occurs 2 times (2 <= 2) and q=ml has different args, so no loop.
Constraints & Edge Cases
- Return a Python
bool. - Check strictly greater (
count > max_repeats), not>=. - Empty
callsreturnsFalse.
Constraints & Evaluation Criteria
- Return a Python `bool`.
Hints
Learn the Concept First
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
3x ('search','q'), max=2Expected Output / Criteria
True