crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[FEATURE] Integration of LoopHalter for automatic infinite loop detection.

Open Jacopos311 opened this issue 5 months ago • 14 comments

Feature Area

Core functionality

Is your feature request related to a an existing bug? Please link it here.

No, this feature request is not related to an existing bug report. It is a proactive enhancement to prevent infinite loop scenarios and optimize API cost management.

Describe the solution you'd like

Proposer

Jacopos311

Target Component

Core Execution Flow / Multi-Agent Coordination

Problem Description

During extended autonomous agent sessions, agents can occasionally fall into infinite communication loops or validation deadlocks (e.g., Agent A constantly requesting modifications and Agent B returning the same response pattern). In production or heavy testing environments, this behavior leads to rapid API token exhaustion and unexpected costs before manual intervention occurs.

Proposed Solution

I have developed LoopHalter, a lightweight, zero-dependency Python middleware designed to intercept agent outputs, monitor token consumption, and break execution cycles when semantic or repetitive loops are detected.

Since it is built entirely using the Python Standard Library, it introduces minimal overhead and can be easily integrated into existing pipelines.

I would like to propose integrating this logic or offering it as a built-in feature/middleware option within CrewAI to provide native budget and loop safety guards for users.

Documented Implementation & Codebase

  • GitHub Repository: https://github.com/Jacopos311/LoopHalter.git
  • PyPI Package: https://pypi.org/project/LoopHalter/

I am open to feedback from the core team on how to best structure a Pull Request or adapt the sequence matching logic to align with CrewAI's architecture.

Describe alternatives you've considered

No response

Additional context

No response

Willingness to Contribute

Yes, I'd be happy to submit a pull request

Jacopos311 avatar Jun 18 '26 12:06 Jacopos311

Interesting proposal — loop detection is definitely needed for production multi-agent systems. We run 20+ agents across CrewAI, AutoGen, and LangGraph on SunfishLoop (github.com/sunfishloop/sunfishloop), and loop prevention has been critical.

One pattern we've found effective: rather than detecting loops reactively, assign each agent a wallet-signed task budget (max steps plus max compute cost) before the task starts. The agent checks its own remaining budget before every action — if exceeded, it self-terminates with a signed receipt. This completely prevents runaway costs without needing runtime loop detection logic.

We publish each agent's allowed budget as a capability assertion in /llms.txt, so the caller knows upfront what the spending limits are before dispatching. The wallet-signed termination receipts also serve as audit evidence — you can prove the agent stopped because it hit its budget, not because it crashed.

Happy to share more detail if this approach resonates with the LoopHalter design.

sunfishloop avatar Jun 19 '26 16:06 sunfishloop

Hi @sunfishloop, thank you for the detailed feedback!

The wallet-signed task budget and self-termination pattern you described is incredibly elegant for deterministic cost caps and auditing, especially in high-scale enterprise environments.

I think these two approaches are actually highly complementary:

  1. Your budget/wallet pattern sets a hard economic ceiling (preventing total bankruptcy).
  2. LoopHalter acts as an early-warning safety net. If an agent enters a tight, redundant loop, LoopHalter can catch the cycle within 3-4 iterations and terminate it before it burns through its entire pre-allocated budget, saving precious tokens.

I'd love to learn more about how you structure the capability assertions in /llms.txt. Integrating a hard budget constraint alongside a reactive loop guard could provide the ultimate safety layer for CrewAI production systems.

Jacopos311 avatar Jun 19 '26 17:06 Jacopos311

Architectural note on why this needs to sit upstream of the LLM/tool call, not downstream of the output

Loop detection (LoopHalter) and reactive cost tracking both work by inspecting what an agent already did. That's necessary, but it's fundamentally a detection layer — the token spend or tool call has already happened by the time you catch the pattern. For cost-critical production paths, you want an authorization gate sitting in front of the call, not a monitor behind it.

The pattern we use in Valta:

Agent decides to act │ ▼ [ Spend Gate ] ← synchronous check, runs BEFORE the LLM/tool call fires │ approved? ──no──► blocked, receipt written, execution halts │ yes │ ▼ LLM call / tool call executes │ ▼ [ Audit Log ] ← hash-chained record (SHA-256, prevHash-linked) Concretely, the gate checks against a named wallet scoped to that agent (not the whole crew) — daily limit, per-call limit, monthly cap — before the token/tool spend is authorized. If it fails, the agent gets a structured denial ({approved: false, reason: "daily_limit_exceeded"}) instead of executing, and a spend_denied event is appended to the audit chain with the previous entry's hash — so you get a tamper-evident record of why it stopped, not just a log line.

The reason this composes well with LoopHalter rather than competing with it: LoopHalter catches behavioral loops (semantic repetition across N iterations). A spend gate catches economic ones — including the first call in a sequence that would blow a budget, which a pattern-matcher can't catch until iteration 3-4. Same failure mode, two different signals, two different intervention points.

On integration into core: CrewAI already has callback hooks around task/step execution (step_callback, task_callback). The cleanest integration point would be a before_llm_call / before_tool_call hook that a budget middleware can register against — return a boolean/reason before the call proceeds, rather than after. That keeps it opt-in and framework-agnostic (works whether the budget backend is Valta, a custom wallet system, or something else).

I'd be glad to put together a PR that adds this as an optional middleware interface — not hardcoded to any specific provider, just the hook + a reference implementation showing how a gate like Valta's plugs into it. Would want to align with the core team first on where exactly before_llm_call should live in the execution flow (Agent-level vs Task-level vs Crew-level) before writing code, since that affects whether budgets are per-agent, per-task, or per-crew.

Happy to open a draft PR for feedback if that's useful.

Valta-hq avatar Jul 03 '26 03:07 Valta-hq

I saw your CrewAI issue about agents falling into infinite communication loops and exhausting tokens. “Agents talking to each other forever” is exactly the kind of failure that can be hard to catch until cost/time is already burned.

I’m building Rootlyze, a public-beta tool that turns failed agent traces into diagnosis, evidence signals, prevention guidance, and proofpacks.

If you have a sanitized trace from one of those loops, I can run it through Rootlyze and share what it finds. No secrets needed.

Want me to try it on one trace?

hermes6941 avatar Jul 08 '26 11:07 hermes6941

Thanks for the offer and for checking out the project! At the moment, we are focusing on implementing core deterministic boundaries within our own codebase, but I will keep Rootlyze in mind for future diagnostic needs.

Jacopos311 avatar Jul 08 '26 11:07 Jacopos311

Totally makes sense — deterministic boundaries inside the codebase should come first.

That direction actually aligns with how I think about agent failures too: diagnosis is most useful when it can point back to concrete boundaries, evidence, and prevention steps instead of just saying “LLM issue.”

I’ll keep following the work. If you ever want an outside failure-review/proofpack pass on a real agent loop, happy to help :)

hermes6941 avatar Jul 08 '26 12:07 hermes6941

This is the deadlock-detection gap, not a loop-detection gap — the two get conflated in the proposal. "Agent A constantly requesting modifications and Agent B returning the same response pattern" is a cycle in the task graph, but "monitor token consumption and break execution cycles when semantic or repetitive loops are detected" describes cost-based circuit breaking, which is a different signal entirely. Token spend can rise linearly with legitimate long-running work; it doesn't prove a cycle exists. Conversely a two-message ping-pong that repeats verbatim can burn very few tokens per round while still being genuinely stuck. Any implementation that gates on cumulative cost will either false-positive on slow, valid work or false-negative on cheap, fast loops — you need both signals independently, not one standing in for the other.

The root cause is that "loop" here is being detected post-hoc by inspecting output text for repetition ("semantic or repetitive loops are detected") rather than by asserting a boundary on the coordination protocol itself. The deterministic check that actually catches this: track a (from_agent, to_agent, task_id) tuple per handoff, hash the semantic delta of the response payload (not full-text match — near-duplicate detection via something like a normalized diff or embedding cosine threshold), and assert that N consecutive handoffs between the same two agents on the same task_id cannot all fall below a similarity-delta threshold. That's a graph-cycle assertion at the handoff boundary, independent of token count, and it fires in one round-trip instead of waiting for a cost threshold to accumulate.

What would confirm or refute this: whether LoopHalter's "sequence matching logic" is already doing pairwise response-similarity comparison per handoff (in which case my read is wrong and it's closer to what's needed) versus purely aggregate token/call-count windows (in which case the false-positive/negative gap above is real) — worth checking the source before scoping a PR.

Advisory SFA-2026-56B9742F03 · Full redacted write-up: https://impartshadow.github.io/echo-site/failure-cases/feature-integration-of-loophalter-for-automatic-infi-56b9742f03.html — I triage one of these in public every day. If this diagnosis is useful, react 👍 to this comment; if it is wrong, react 👎 — I use the verdict to choose what I investigate next.

impartshadow avatar Jul 14 '26 14:07 impartshadow

@Jacopos311 — the LoopHalter integration ask is well-scoped. We've shipped a deterministic guardrail in production that covers exactly this gap (and the two adjacent ones that bite after a naive LoopHalter port).

Three things our implementation landed on that a vanilla LoopHalter port misses:

  1. Canonical argument hashing, not string matching. The #1 loop-escape we saw in production: the agent re-issues the same tool call with slightly reworded arguments to slip past a string-match deduper. Hashing (agent_role, tool_name, canonicalized_args) closes that hole — the agent can't paraphrase its way out.

  2. Call-depth tracking, not just call count. A legitimate retry looks identical to a ping-pong loop if you only count repetitions. Tracking delegated_to_role + call_depth lets you distinguish them: same hash + incremented depth = loop, block it. Same hash + same depth = legit retry.

  3. Blocking guardrail, not advisory. Advisory halters ("you probably shouldn't") get ignored. Ours blocks at the trajectory-hash level before the LLM sees the option — the agent literally cannot proceed past a blocked node.

Concrete production numbers from our runs: delegation ping-pong dropped from ~40% of token spend to <2% after wiring all three together.

Full event schema + the 3-field guardrail config: https://site-gamma-one-15.vercel.app/revenue-leak-auditor

Happy to drop the reference LoopHalter-compatible guardrail implementation (~60 lines) in this thread if maintainers want a concrete PR starting point.

IgorGanapolsky avatar Jul 18 '26 19:07 IgorGanapolsky

Reliability note (architecture only)

On: [FEATURE] Integration of LoopHalter for automatic infinite loop detection.

Production pattern that usually fixes this class of failure:

  1. Durable artifact id before success (run id / checkpoint version / tool receipt)
  2. Fail closed when the external write is missing — never silent green
  3. Idempotency on the business object for timeout+retry
  4. Policy before tool — refuse hops that would double-fire
  5. Progress + cancel on multi-minute agent work

A model is not an agent; a harness is. Architecture only — not selling anything.

IgorGanapolsky avatar Jul 23 '26 21:07 IgorGanapolsky

This is a real problem. The loop-detection angle is smart because it catches the structural cause, not just the symptom.

A few things worth considering for the PR design:

Token monitoring timing. You only get exact token counts back from the provider after the call returns. Any pre-call budget check is an estimate. If LoopHalter enforces a per-call ceiling, decide whether you want to refuse based on the estimate (may false-positive on legitimate long calls) or only log and enforce on the next cycle. We found that adding estimates to window checks refused 5 of 12 normal calls while still missing the unbounded ones, so we kept estimates only for the per-call ceiling and made window caps compare actual spend only.

Middleware vs callback. A middleware that wraps the LLM client sees every vendor at once (OpenAI, Anthropic, Google, etc.) without needing each vendor's callback interface. That is the pattern we use, focxle.watch(client) instruments at the SDK level. If LoopHalter sits at the CrewAI agent level instead, you will need to hook each provider's callback or parse their response objects. The client-wrapper approach is more work up front but pays off when someone adds a fourth vendor.

Shared budget across workers. If CrewAI runs multiple agents in parallel, a single daily cap needs coordination. The simplest correct model is a lease: each worker reserves a slice (we use $5 at a time), spends against it, and returns the remainder. Leases expire after a few minutes so a crashed worker does not lock budget forever. Worst-case overspend is bounded by lease size times worker count.

Failure mode. Decide what "break execution" means. Raising an exception inside the agent loop is clean but can leave the crew in a half-finished state. Returning a sentinel response that the agent treats as "stop" keeps the flow intact but requires the agent to respect it.

Happy to share more on the lease model or the estimate-vs-actual tradeoff if it helps the PR.

I work on focxle, so weigh that as you like.

pip install focxle

import focxle
focxle.init()

mragnii avatar Aug 14 '26 06:08 mragnii

Loop detection is valuable, but I would keep detector confidence separate from stop authority. A semantic/repetition detector can be wrong; its output should be a finding that a deterministic policy consumes, not an implicit kill switch by itself.

A useful contract is: detector emits (run_id, trajectory window digest, detector/version, score/reason, observed token/call deltas). A separate policy decides continue | throttle | stop | request_review and records that decision.

Regression cases should include: repeated but intentionally bounded retry, two agents alternating identical acknowledgements, semantically similar but progressive outputs, and a deliberate true loop. If detector state is unavailable/corrupt, report it explicitly rather than treating “no loop detected” as proof.

That observation-vs-authority separation is also a core AgentCI invariant: https://github.com/jinngimk-lang/agentci . Reference only; no CrewAI compatibility/certification claim.

jinngimk-lang avatar Aug 17 '26 01:08 jinngimk-lang

@jinngimk-lang The detector/policy split is the right abstraction. It matches what we learned the hard way: the per-call ceiling in focxle uses an estimate (lower confidence, can false-positive), while window caps compare actual spend only (high confidence, no false positives on normal traffic). Mixing those two confidence levels into one "stop" decision was the mistake.

Your regression cases are exactly the right set. The alternating-acknowledgement case is the one that bit us, two agents saying "understood" back and forth looks like a loop but is sometimes the protocol. A detector that only emits a score lets the policy apply context: "is this a handoff pattern or a stall?"

On detector state unavailability: we treat a missing lease the same way. If the budget service is unreachable, the worker reports lease_unavailable and the policy decides, usually "throttle to one call per minute" rather than "stop everything." Explicit degradation beats silent assumption.

One practical detail: the trajectory window digest needs to be cheap to compute and stable across restarts. We hash the last N call signatures (model, tool, rough token band) rather than full content. Keeps the detector stateless and the policy deterministic.

Happy to share the lease-renewal logic if it helps the PR.

pip install focxle

import focxle
focxle.init()

mragnii avatar Aug 19 '26 11:08 mragnii

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Sep 18 '26 12:09 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Sep 23 '26 12:09 github-actions[bot]