feat: Add LoopDetector middleware for agent loop detection (#4682)#4684
feat: Add LoopDetector middleware for agent loop detection (#4682)#4684sicmundu wants to merge 1 commit intocrewAIInc:mainfrom
Conversation
…#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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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)
| self._history.append(record) | ||
| self._total_actions += 1 | ||
|
|
||
| def is_looping(self, current_action: Optional[str] = None) -> bool: |
There was a problem hiding this comment.
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)
|
This PR is stale because it has been open for 45 days with no activity. |


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
Key classes
LoopDetector— core detection engine with configurable parametersActionRecord— dataclass for tracking individual agent actionsLoopDetectionStrategy— enum for exit strategies (RAISE, SUMMARIZE, CALLBACK)Tests
Includes comprehensive test suite covering:
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_detectormodule 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.