Skip to content

Loop Detection

Translation in Progress

This page is being translated. Content below is a placeholder.

The Problem

Agents can get stuck in infinite loops:

  • Repeating the same actions
  • Failing and retrying endlessly
  • Never reaching completion

Detection Strategies

1. Turn Limit

Simple but effective:

typescript
const MAX_TURNS = 10

let turns = 0
while (turns < MAX_TURNS) {
  turns++
  // Agent logic...
}

if (turns >= MAX_TURNS) {
  return 'Maximum turns reached'
}

2. Action Pattern Detection

Detect repeated action sequences:

typescript
class LoopDetector {
  private history: string[] = []

  addAction(action: string) {
    this.history.push(action)
    if (this.history.length > 10) {
      this.history.shift()
    }
  }

  isLooping(): boolean {
    if (this.history.length < 4) return false

    // Check if last 2 actions repeat previous 2
    const recent = this.history.slice(-2).join('|')
    const before = this.history.slice(-4, -2).join('|')

    return recent === before
  }
}

3. Error Tracking

Detect repeated failures:

typescript
class ErrorTracker {
  private errors: string[] = []

  addError(error: string) {
    this.errors.push(error)
  }

  hasTooManyErrors(): boolean {
    // More than 3 consecutive same errors
    if (this.errors.length < 3) return false

    const recent = this.errors.slice(-3)
    return recent.every(e => e === recent[0])
  }
}

Summary

  • Turn limits prevent runaway loops
  • Pattern detection catches repetition
  • Error tracking prevents failure spirals

Next

See the full project structure: Project Structure →

Learn AI Agent development through real source code