Skip to content

feat: Add LoopDetector middleware for agent loop detection (#4682)#4684

Open
sicmundu wants to merge 1 commit intocrewAIInc:mainfrom
sicmundu:feature/loop-detector-middleware
Open

feat: Add LoopDetector middleware for agent loop detection (#4682)#4684
sicmundu wants to merge 1 commit intocrewAIInc:mainfrom
sicmundu:feature/loop-detector-middleware

Conversation

@sicmundu
Copy link
Copy Markdown

@sicmundu sicmundu commented Mar 3, 2026

Summary

Implements a LoopDetector middleware that detects when agents get stuck in repetitive action loops and provides graceful exit strategies.

Related Issue

Addresses #4682 — [FEATURE] Agent Loop Detection

What it does

  • Tracks agent actions using a sliding window approach
  • Detects repetition patterns via similarity hashing (exact match + fuzzy n-gram)
  • Configurable thresholds: window size, similarity threshold, max consecutive repeats
  • Multiple exit strategies: raise exception, return summary, trigger callback
  • Lightweight: no external dependencies beyond Python stdlib

Key classes

  • LoopDetector — core detection engine with configurable parameters
  • ActionRecord — dataclass for tracking individual agent actions
  • LoopDetectionStrategy — enum for exit strategies (RAISE, SUMMARIZE, CALLBACK)

Tests

Includes comprehensive test suite covering:

  • No false positives with varied actions
  • Detection of exact repetition loops
  • Detection of similar (fuzzy) action loops
  • Configurable threshold behavior
  • Callback strategy execution
  • Edge cases (empty actions, single actions)

Why this matters

Agents in production frequently get stuck in repetitive loops — retrying the same failed action, oscillating between two states, or generating nearly-identical outputs. This middleware provides a clean, pluggable detection mechanism that can be integrated into CrewAI's agent execution pipeline.

Built with real-world loop detection experience. 🔄


Note

Medium Risk
Adds new loop-detection logic and a new test module; while largely additive, it introduces behavioral heuristics (similarity/cycle detection) and the included tests use a nonstandard import/path setup that could affect CI reliability.

Overview
Introduces a new crewai.utilities.loop_detector module that records recent agent actions in a sliding window and detects looping via exact repeats, high text similarity (SequenceMatcher), and short cyclic action-type patterns, emitting loop events and optional callbacks.

Adds APIs to suggest an exit strategy (suggest_exit_strategy), report metrics (get_stats), and reset state, plus a new test file covering loop detection modes, strategy selection, stats/reset, and callback invocation.

Written by Cursor Bugbot for commit 7c8ddd9. This will update automatically on new commits. Configure here.

…#4682)

Implements a LoopDetector utility that detects when agents get stuck in
repetitive action loops. Addresses issue crewAIInc#4682.

Features:
- Exact repetition detection (same action repeated N times)
- Similarity-based loop detection (near-identical actions)
- Cyclic pattern detection (A->B->C->A->B->C patterns)
- Configurable thresholds and window sizes
- Exit strategy suggestions (force different action, increase temperature,
  break cycle, escalate to human)
- Callback support for custom loop handling
- Statistics tracking

Includes 10 unit tests covering all detection modes, exit strategies,
stats tracking, reset, and callback functionality.

All tests pass.
Copy link
Copy Markdown

@cursor cursor Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Bugbot Free Tier Details

Your team is on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle for each member of your team.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

return False

avg_similarity = sum(similarities) / len(similarities)
return avg_similarity >= self.similarity_threshold
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarity check always co-fires with exact repetition detection

Medium Severity

_check_similarity_loop always returns True when _check_exact_repetition returns True, because SequenceMatcher.ratio() yields 1.0 for identical strings, which exceeds any similarity_threshold ≤ 1.0. This means pattern_types always contains both "exact" and "similarity" for exact matches, triggering the len(pattern_types) > 1 escalation logic in suggest_exit_strategy. The "force_different_action" strategy is effectively unreachable as a primary recommendation — every exact repetition gets "escalate" instead.

Additional Locations (1)

Fix in Cursor Fix in Web

self._history.append(record)
self._total_actions += 1

def is_looping(self, current_action: Optional[str] = None) -> bool:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parameter current_action in is_looping is unused

Low Severity

The current_action parameter in is_looping is accepted but never read or used in the method body. The module docstring demonstrates calling detector.is_looping(current_action), suggesting the parameter was meant to be incorporated into the detection logic. Callers passing a value will have it silently ignored, leading to a misleading API contract.

Additional Locations (1)

Fix in Cursor Fix in Web

@github-actions
Copy link
Copy Markdown
Contributor

This PR is stale because it has been open for 45 days with no activity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant