Loop Detection and Prevention

Medium
Agents

Implement loop detection for agent safety:

  1. add_action(action, state_fingerprint): Record step
    • action: string representation
    • state_fingerprint: hashable state summary
  2. detect_repetition_loop(): Same action repeated consecutively >= max_repetitions
  3. detect_state_cycle(): State fingerprint seen before in history
    • Return cycle length (current_pos - previous_pos) or 0
  4. should_terminate(): True if either loop detected

State Fingerprint: Hashable representation of agent state (e.g., tuple of key values)

Window: Only look at last window_size actions for repetition

Return Values:

  • Repetition: boolean
  • Cycle: integer length (0 if none)

Examples

Example 1:
Input: ld = LoopDetector(max_repetitions=3); [ld.add_action('search', i) for i in range(3)]; ld.detect_repetition_loop()
Output: True
Explanation: Same action 3 times >= max_repetitions

Starter Code

class LoopDetector:
    """
    Detect and prevent infinite loops in agent execution.
    """
    
    def __init__(self, max_repetitions=3, window_size=5):
        self.max_repetitions = max_repetitions
        self.window_size = window_size
        self.action_history = []
        self.state_fingerprints = []
    
    def add_action(self, action, state_fingerprint):
        """Record action and state"""
        # Your implementation here
        pass
    
    def detect_repetition_loop(self):
        """
        Detect if same action repeated max_repetitions times consecutively.
        Returns bool.
        """
        # Your implementation here
        pass
    
    def detect_state_cycle(self):
        """
        Detect if agent returned to previous state (cycle).
        Returns cycle length if detected, 0 otherwise.
        """
        # Your implementation here
        pass
    
    def should_terminate(self):
        """Check all loop conditions"""
        # Your implementation here
        pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews