Infinite Agent Loops
An infinite loop occurs when an agent keeps running steps without making progress toward its goal. This wastes resources, costs money, and can trigger security alerts.
8 min•By Priygop Team•Updated 2026
Loop Detection
Loop Detection
# Comprehensive loop detection for agent execution
class LoopDetector:
def __init__(self, max_steps: int = 15, max_repeated_action: int = 3):
self.max_steps = max_steps
self.max_repeated = max_repeated_action
self.history = []
def check(self, action: str, args: dict) -> dict:
"""
Check for loop conditions before executing a step.
Returns a result indicating if the agent should continue or stop.
"""
self.history.append({"action": action, "args": str(args)})
step = len(self.history)
# Check 1: Absolute step limit
if step > self.max_steps:
return {
"should_stop": True,
"reason": f"Step limit exceeded: {step}/{self.max_steps}"
}
# Check 2: Repeated identical action + args (exact loop)
current = f"{action}:{args}"
recent = [f"{h['action']}:{h['args']}" for h in self.history[-5:]]
if recent.count(current) >= self.max_repeated:
return {
"should_stop": True,
"reason": f"Exact loop detected: '{action}' with same args repeated {self.max_repeated}x"
}
# Check 3: Same action type repeated too many times (even with different args)
recent_actions = [h["action"] for h in self.history[-6:]]
if recent_actions.count(action) >= self.max_repeated + 1:
return {
"should_stop": True,
"reason": f"Action '{action}' repeated {self.max_repeated+1}x in last 6 steps — possible loop"
}
# Check 4: No progress — state data hasn't grown in last 5 steps
return {"should_stop": False, "step": step}
detector = LoopDetector(max_steps=10, max_repeated_action=3)
# Simulate a loop
actions = ["web_search", "web_search", "web_search", "web_search"]
for a in actions:
result = detector.check(a, {"query": "same query"})
print(f" Step {result.get('step','?')}: {a} → {'STOP: ' + result['reason'] if result['should_stop'] else 'continue'}")
if result["should_stop"]:
break