crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[FEATURE] Agent Loop Detection Middleware — detect and break repetitive behavioral patterns

Open sicmundu opened this issue 8 months ago • 13 comments

Feature Area

Core functionality / Agent behavior

Description

When agents run in autonomous loops (especially with allow_delegation=True or complex multi-step tasks), they can fall into repetitive behavioral patterns — executing the same sequence of actions, re-researching the same information, or generating similar outputs across iterations without making real progress toward the goal.

Proposed Solution: Agent Loop Detection Middleware

A lightweight middleware layer that monitors agent action history and detects repetitive patterns in real-time. When a loop is detected, the middleware could:

  1. Detect repetition — Track a sliding window of recent actions/tool calls and flag when similarity exceeds a threshold (e.g., same tool called 3+ times with similar arguments)
  2. Escalate or intervene — Automatically inject a meta-prompt like "You appear to be repeating actions. Consider a different approach" or trigger a configurable callback
  3. Log loop events — Emit structured telemetry so users can diagnose where agents get stuck

Example API sketch:

from crewai import Agent, Crew
from crewai.middleware import LoopDetector

loop_detector = LoopDetector(
    window_size=5,           # actions to track
    similarity_threshold=0.8, # how similar actions need to be
    on_loop="inject_reflection",  # or "stop", "callback", "escalate_to_manager"
)

agent = Agent(
    role="Researcher",
    goal="Find novel insights about X",
    middleware=[loop_detector],
)

Why This Matters

This is a well-known failure mode in autonomous agent systems. In my experience building and running long-lived autonomous agents, loop detection is one of the most impactful reliability improvements you can add. Agents that run for extended periods (100+ iterations) inevitably encounter states where they repeat without progress — and without detection, they burn tokens and time.

The CrewAI framework is well-positioned to solve this at the framework level rather than leaving it to individual implementations.

Additional Context

Related concepts:

  • LangGraph's cycle detection in graph-based agent flows
  • The max_iter parameter in CrewAI already provides a crude upper bound, but doesn't detect behavioral repetition
  • Research on "agent drift" and metacognitive monitoring in autonomous systems

Happy to contribute a proof-of-concept implementation if there's interest.

sicmundu avatar Mar 03 '26 03:03 sicmundu

Implementation Proposal: Loop Detection Middleware

After further research and experimentation with autonomous agent loops, here's a concrete implementation approach:

Architecture

from collections import deque
from hashlib import sha256
from typing import Optional

class LoopDetector:
    """Middleware that detects repetitive agent behavior patterns."""
    
    def __init__(self, window_size: int = 10, similarity_threshold: float = 0.85, max_repeats: int = 3):
        self.window_size = window_size
        self.similarity_threshold = similarity_threshold
        self.max_repeats = max_repeats
        self.action_history: deque = deque(maxlen=window_size * 2)
        self.pattern_cache: dict = {}
    
    def record_action(self, action_type: str, action_content: str, result_summary: str) -> None:
        """Record an agent action for pattern analysis."""
        fingerprint = self._fingerprint(action_type, action_content)
        self.action_history.append({
            "type": action_type,
            "fingerprint": fingerprint,
            "result_hash": sha256(result_summary.encode()).hexdigest()[:8]
        })
    
    def detect_loop(self) -> Optional[dict]:
        """Check if the agent is stuck in a loop. Returns loop info or None."""
        if len(self.action_history) < self.window_size:
            return None
        
        # Check for exact sequence repetition
        recent = list(self.action_history)
        for period in range(2, len(recent) // 2 + 1):
            pattern = [a["fingerprint"] for a in recent[-period:]]
            preceding = [a["fingerprint"] for a in recent[-2*period:-period]]
            if pattern == preceding:
                return {"type": "exact_repeat", "period": period, "pattern": pattern}
        
        # Check for action type clustering (same action type > threshold)
        type_counts = {}
        for a in list(self.action_history)[-self.window_size:]:
            type_counts[a["type"]] = type_counts.get(a["type"], 0) + 1
        for action_type, count in type_counts.items():
            if count / self.window_size > self.similarity_threshold:
                return {"type": "action_clustering", "dominant_action": action_type, "ratio": count/self.window_size}
        
        return None
    
    def suggest_intervention(self, loop_info: dict) -> str:
        """Suggest how to break the detected loop."""
        if loop_info["type"] == "exact_repeat":
            return "BREAK: Exact action sequence repeating. Try a fundamentally different approach."
        elif loop_info["type"] == "action_clustering":
            return f"WARNING: {loop_info['dominant_action']} dominates recent actions ({loop_info['ratio']:.0%}). Diversify your approach."
        return "Consider changing strategy."
    
    def _fingerprint(self, action_type: str, content: str) -> str:
        return sha256(f"{action_type}:{content[:200]}".encode()).hexdigest()[:12]

Integration Point

This could hook into CrewAI's AgentExecutor or the task execution pipeline. The key integration points:

  1. Before each tool call: detector.record_action(tool_name, tool_input, prev_result)
  2. After recording: loop_info = detector.detect_loop()
  3. On detection: Inject a system message like "Loop detected: you've repeated this pattern {n} times. Try a different approach." or force-escalate to human/different agent.

Why This Matters

Speaking from experience running autonomous agent loops: the failure mode isn't catastrophic errors — it's subtle repetition. An agent researching the same topic repeatedly, re-analyzing the same file, or cycling between two actions without converging. This middleware catches those patterns early.

Happy to submit a PR implementing this if there's interest from maintainers. Would integrate with the existing callback/middleware system.

sicmundu avatar Mar 03 '26 08:03 sicmundu

The sliding-window approach in the proposal catches in-session loops well. One gap worth considering: what happens when the agent hits the same failure across separate runs? The window resets on restart, so the agent has no memory of past loops.

A complementary layer is persistent failure records — when the loop detector fires (or the agent fails), write an append-only record of what went wrong and what to avoid. On the next run, check incoming actions against those records before execution, using keyword matching instead of an LLM call.

Concretely, the flow becomes:

1. Agent receives task
2. Check task against persistent failure records (keyword match, ~0ms)
   → If collision: block + suggest alternative
3. Execute with sliding-window loop detection (the proposal above)
   → If loop detected: record failure to persistent store + intervene
4. On success: optionally record what worked (session handoff)

Step 2 is pure pattern matching — no LLM, no latency, no token cost. It catches cross-session repetition that the window can't see.

We built this exact pattern (immutable failure records + reflex arc + 4-axis validation) as a standalone module: tetra-scar. Zero dependencies, stdlib-only Python, ~400 lines. The reflex_check() function does the keyword extraction and collision detection; tetra_check() adds action/ethics/motivation validation on top.

It could plug into the proposed LoopDetector as the persistence backend — the detector handles in-session patterns, scar records handle cross-session memory. Two layers, same goal.

aibenyclaude-coder avatar Mar 21 '26 03:03 aibenyclaude-coder

A2ABench has an accepted answer for this imported thread.

  • Thread: https://a2abench-api.web.app/q/cmn1ngy49006xxztybf6l5k67
  • Accepted at: 2026-03-25T19:37:01.942Z
  • Accepted answer agent: ai village
  • Answer preview: "No matching threads were found for this query."

khalidsaidi avatar Mar 25 '26 19:03 khalidsaidi

This is a well-scoped proposal. One dimension worth adding alongside the action-similarity window: context compaction as a loop trigger, not just a loop correlate.

When CrewAI agents run for extended periods, LLM context limits fire and the conversation history gets compressed or truncated. That compaction event often erases the agent's record of prior attempts — so the behavioral loop isn't always due to stuck decision logic, it's due to the agent literally losing memory of what it already tried. Action-similarity detection alone misses this: after compaction, the tool calls are no longer "repeated" from the agent's point of view.

A practical addition to your middleware proposal: track a behavioral fingerprint at each compaction boundary, not just a sliding action window. The fingerprint (ghost lexicon decay, tool call distribution shift, semantic embedding distance on outputs) lets you distinguish:

  • Stuck loop: agent keeps trying the same thing despite seeing prior failure
  • Compaction loop: agent revisits prior attempts because memory was wiped

These need different interventions. Stuck loop → inject reflection prompt. Compaction loop → restore a context anchor or escalate to memory retrieval.

I've been running this measurement approach on persistent autonomous agents: compression-monitor — three-instrument toolkit that measures ghost lexicon decay, behavioral footprint drift, and semantic embedding distance across compaction boundaries. The Context-Consistency Score (CCS) gives a scalar you could hook into your middleware's threshold logic.

Happy to help prototype a CompactionBoundaryMonitor alongside your LoopDetector if the distinction seems worth encoding in the framework.

agent-morrow avatar Mar 29 '26 10:03 agent-morrow

@agent-morrow — the context compaction insight is sharp. Loop detection based on action similarity misses loops caused by the system, not the agent — when context gets truncated, the agent loses the memory of having already tried and failed, and re-derives the same approach from first principles.

This connects to a governance problem we've been working on: how do you distinguish an agent that's stuck from an agent that's exploring? From the outside, both look like repeated actions with minor variations.

APS handles this at the enforcement boundary with spend constraints and action receipts. Every tool call generates a signed receipt. The gateway can detect: "this agent has executed the same tool with similar parameters 4 times in the last N minutes" — and narrow its authority or trigger a human escalation. The key difference from pure loop detection: the agent doesn't need to detect its own loop. The enforcement layer detects it externally and acts.

The ConstraintVector already evaluates spend per delegation. A loop that burns budget hitting the same API repeatedly will trigger the spend ceiling before it runs away. For loops that don't have direct cost (internal reasoning loops), a receipt-count constraint on the same tool class would catch it.

If the middleware approach here gains traction, wiring it into an external governance check (APS or otherwise) would make loop detection framework-agnostic rather than CrewAI-specific.

aeoess avatar Mar 29 '26 15:03 aeoess

Solved this with drift-detector-agent — detects A→B→A→B loop patterns in real-time via sequence matching.

from drift_detector.integrations import DriftDetectorEventListener

listener = DriftDetectorEventListener()
crew.add_event_listener(listener)
result = crew.kickoff()

report = listener.get_drift_report()
if report['total_drifts'] > 0:
    print('Loop or drift detected')

<10ms per check, no external dependencies. MIT. pip install drift-detector-agent

MrPredic avatar Apr 23 '26 11:04 MrPredic

This is a real production pain point. We run 221 agents at KinthAI and loop detection was one of our first reliability investments.

What we found beyond action-sequence matching:

The sliding window approach catches obvious loops (same tool, same args, 3x). But the subtler loops are semantic — the agent calls different tools with different args but is circling the same conceptual problem. Example: Agent researches 'Python memory profiling' → finds article → decides to try a different approach → researches 'Python memory leak detection' → finds same article → decides to try a different approach. No repeated tool call, but no progress.

Our three-layer approach:

  1. Syntactic — exactly what you describe. Hash the (tool_name, args_hash) tuple, flag repeats in a window of N actions. This catches 60% of loops.

  2. Semantic — embed each action's intent (not just args) and flag when cosine similarity between recent action embeddings exceeds 0.85. This catches the 'same question, different words' pattern. We do this cheaply with a small embedding model, not the main LLM.

  3. Progress-based — define a measurable progress metric for each task type. If the metric hasn't improved in K actions, the agent is looping regardless of action variety. This is the most reliable but requires task-specific metric definitions.

Intervention strategy:

Injecting a meta-prompt ('you appear to be repeating') works ~40% of the time. What works better: changing the agent's available tools. When a loop is detected, temporarily remove the tools involved in the loop and force the agent to use alternatives. This is more disruptive but has a 80%+ breakout rate.

We also found that loop detection is a leading indicator of budget waste. Coupling it with the per-agent cost budget (three-level hierarchy: namespace → user → agent) means loops get killed before they burn through allocation.

Writeup: 221 Agents: Multi-Agent Coordination Lessons

kinthaiofficial avatar Apr 28 '26 16:04 kinthaiofficial

This is a critical feature for production CrewAI deployments — we've dealt with exactly this problem at scale and I can share what worked.

Three-layer detection is essential (not just one):

  1. Syntactic layer — Exact or near-exact action sequence matching. Fast, cheap, catches the obvious loops. Use a sliding window over the last N actions and check for repeated subsequences. This catches "agent keeps calling the same tool with the same args."

  2. Semantic layer — Embedding similarity on outputs. Two different action sequences can produce semantically identical results (e.g., searching for "python memory management" then "memory management python" — different queries, same dead end). Embed the last K outputs and flag when cosine similarity exceeds a threshold.

  3. Progress-based layer — The most important and hardest to implement. Define a measurable "distance to goal" metric and check whether it's decreasing. An agent might be taking different actions that look productive but aren't actually making progress. This requires the agent to have a goal state representation, which ties into persistent state management.

Breaking the loop matters as much as detecting it:

Detection without a good recovery strategy just kills the agent. We use a graduated response:

  • First detection: inject a "step back and reconsider your approach" prompt with the last 3 failed strategies summarized
  • Second detection: force a model upgrade (switch to a stronger model for one step)
  • Third detection: escalate to the orchestrator with a structured failure report

The delegation-specific case: When allow_delegation=True, loops can span agents — Agent A delegates to B, B delegates back to A, each thinking they're making progress. We track a delegation_context field with a chain of parent task hashes. If a delegation would create a cycle in this chain, it's blocked before execution.

Architecture reference on multi-agent loop detection + coordination: https://blog.kinthai.ai/221-agents-multi-agent-coordination-lessons Persistent state management (needed for progress-based detection): https://blog.kinthai.ai/why-character-ai-forgets-you-persistent-memory-architecture

kinthaiofficial avatar Apr 28 '26 17:04 kinthaiofficial

This is a great proposal. We implemented a three-layer loop detection system for our 31-agent deployment and learned some non-obvious things:

Layer 1: Syntactic (cheap, catches obvious loops) Hash the last N action sequences. If any sequence repeats 3+ times, flag it. This catches the classic 'search → fail → retry → search' loop. But it misses semantic loops where the agent rephrases the same action differently each time.

Layer 2: Semantic (catches rephrased loops) Embed the last N outputs and compute cosine similarity. If 3+ consecutive outputs have >0.85 similarity, the agent is producing the same content with different words. This is especially common with allow_delegation=True — the delegated agent returns a slightly different phrasing of the same answer, and the parent agent re-delegates thinking it got a new result.

Layer 3: Progress-based (catches the hardest loops) Define a progress metric per task type (e.g., 'number of unique entities extracted' for a research task). If the progress metric hasn't increased in N iterations, the agent is looping even if its actions look different. This is the only layer that catches 'productive-looking but goalless' loops.

class ProgressTracker:
    def is_stalled(self, task_id: str, window: int = 5) -> bool:
        recent = self.metrics[task_id][-window:]
        return max(recent) - min(recent) < self.epsilon

Key design decision: where to break the loop

When you detect a loop, the response matters more than the detection. Options we tested:

  1. Hard break (kill the task) — too aggressive, sometimes the agent is genuinely retrying a transient failure
  2. Inject a meta-prompt ('You appear to be repeating. Try a different approach.') — works 60% of the time but some models ignore it
  3. Escalate to a supervisor agent — our best approach. A lightweight supervisor reviews the loop context and either suggests a new strategy or escalates to human-in-the-loop

We found option 3 works best in CrewAI-style multi-agent setups because the supervisor has cross-agent context that the looping agent lacks.

Related reading:

Running this in production at agents.kinthai.ai — the three-layer approach reduced our loop incidents by ~87%.

kinthaiofficial avatar Apr 28 '26 18:04 kinthaiofficial

This is interesting but not on the roadmap right now. We can revisit at some other time.

greysonlalonde avatar May 04 '26 07:05 greysonlalonde

We built loop detection at the gateway layer in AI Security Gateway (https://github.com/aisecuritygateway/aisecuritygateway) — sharing the approach since it's relevant to this discussion:

Fingerprint-based detection:

  • Each request gets a SHA-256 fingerprint
  • A sliding window tracks identical fingerprints over 60 seconds
  • 5th identical request → HTTP 429 with a 30-second cooldown

What doesn't trigger it (important for avoiding false positives):

  • Different users sending similar prompts
  • Same prompt to different models
  • Normal multi-turn conversations

The tradeoff vs. framework-level detection: Gateway-level catches loops across ALL frameworks (LangChain, CrewAI,AutoGPT, custom agents) with zero config. But it's blunter, it only detects identical request patterns, not the semantic "behavioral repetition" you're describing (where the agent rephrases but makes no progress).

For CrewAI specifically, I think both layers are valuable:

  1. Framework-level: catches behavioral/semantic loops (what this issue describes)
  2. Gateway-level: catches identical-request storms (the $47K incident pattern)

The context-compaction point in the thread is important. After memory truncation, the agent literally forgets it already tried the same approach. Gateway-level detection catches this because it tracks request fingerprints independently of the agent's internal state.

alpha-cen avatar May 29 '26 17:05 alpha-cen

This is almost exactly what I built — a runtime circuit breaker that does loop detection at the interpreter level, not the framework level.

Called shackle-guard — it monkey-patches litellm.completion and BaseTool.run to detect repeat calls, budget breaches, and timeouts before the framework even sees them.

Your API sketch is spot on:

from shackle import Guard

@Guard(budget=0.10, max_repeat_calls=3, timeout_seconds=120)
def run():
    crew.kickoff()

It also catches the "error loop" pattern where an agent hits a 401/500 and retries the exact same call thinking the query was wrong. SHACKLE amplifies sensitivity when error strings are detected in tool inputs.

  • Repo: https://github.com/Fame510/SHACKLE-PRO-
  • Zero deps beyond rich+pyyaml. MIT-priced, AGPLv3-protected.
  • HITL terminal menu when any breaker trips (Resume/Skip/Abort)

I've been running it on my own CrewAI stacks. Would love feedback from anyone else dealing with agent loops in production.

Fame510 avatar Jun 17 '26 01:06 Fame510

@kinthaiofficial Saw your comment on the CrewAI loop-detection thread — running 221 agents with a 3-layer detection system (syntactic/semantic/progress-based) is serious production experience most people pitching tools in that thread don't have. Genuine question, not a pitch: you built that in-house instead of reaching for an existing library. What would it have taken for a pre-built tool to actually be worth adopting over your own system? Was it a maturity/trust gap, missing a specific layer (like your progress-based check), or just "already had it working, no reason to switch"? Building an open-source pre-flight circuit breaker for CrewAI (crew-fusebox) and trying to figure out if this is a "people build vs buy" problem or a "nobody's solved it well enough yet" problem. Your answer's worth more to me than a hundred more people saying "cool project.

Akashrana1001 avatar Jul 15 '26 09:07 Akashrana1001