Skip to course content
Free CrewAI course

CrewAI for Multi-Agent Automation

Unit 07.03: Spotting a loop before the bill does

Delegation loops are the most expensive failure in a multi-agent system and the easiest to detect.

Two detectors, because one misses cases

A hop ceiling catches drift that never repeats exactly. A repeat count on (agent, action) pairs catches a tight loop well before the ceiling.

The code runs both over a five-event delegation sequence.

events = [
    ("Researcher", "delegate to Writer"),
    ("Writer", "delegate to Researcher"),
    ("Researcher", "delegate to Writer"),
    ("Writer", "delegate to Researcher"),
    ("Researcher", "delegate to Writer"),
]

MAX_HOPS = 4
seen = []
for i, (agent, action) in enumerate(events, 1):
    seen.append((agent, action))
    repeated = seen.count((agent, action))
    flag = ""
    if i > MAX_HOPS:
        flag = "  <- HOP CEILING EXCEEDED, stop the run"
    elif repeated > 1:
        flag = f"  <- seen {repeated}x"
    print(f"{i}. {agent:11} {action}{flag}")

print(f"\nTwo independent detectors: a hop ceiling ({MAX_HOPS}), and a repeat")
print("count on (agent, action) pairs. Either one alone misses a case.")

# The ceiling catches a slow drift that never repeats exactly. The repeat count
# catches a tight loop well before the ceiling. Run both.

The repeat detector fires at event three - the second time Researcher delegates to Writer - while the ceiling would not fire until event five. On a tight loop that difference is two model calls saved.

The ceiling still earns its place for the other shape: agents that pass work along a slowly widening path, never repeating a pair exactly, and never converging. The repeat detector never fires on that one.

The mistake this prevents

The mistake is setting only a ceiling because it is simpler. A ceiling of six lets a tight two-agent loop run six times, which is six model calls to learn something detectable at the third. Run both.

Takeaway

Detect loops with a hop ceiling and a repeat count on (agent, action) pairs. Each catches a shape the other misses, and both are a few lines.