AutoGen Essentials

Course Content

AutoGen Essentials

7 sections · 28 lessons

What strategies do you use to prevent infinite loops or repetitive agent-to-agent chatter?


Three layers against a looping group chatHard caps: messages, tokens, timeoutDesigned exit: tests pass, two reviews maxDetection: repeats and cap-hit stop_reason
The semantic stop word is the outcome you want, but only the caps are guaranteed to fire when the model never says it.

What you need to know

Why group chats loop

A loop needs only two things: an agent that always has something to say, and no condition that says "done". Common causes:

  • A critic with no limit keeps finding small issues.
  • Two agents politely thank each other ("Great, anything else?" "No, thanks!").
  • The stop word is never produced, because the model phrases it differently ("Approved." vs APPROVED).
  • A tool keeps failing and the agent retries the same call.

Layer 1: hard caps

Python
from autogen_agentchat.conditions import (    MaxMessageTermination, TextMentionTermination,    TimeoutTermination, TokenUsageTermination,)from autogen_agentchat.teams import RoundRobinGroupChatstop = (TextMentionTermination("APPROVED", sources=["reviewer"])        | MaxMessageTermination(20)        | TokenUsageTermination(max_total_token=60_000)        | TimeoutTermination(timeout_seconds=180))team = RoundRobinGroupChat([author, reviewer], termination_condition=stop)result = await team.run(task=diff_text)print(result.stop_reason)  # which condition fired

| means "stop when any fires"; & means "stop when all have fired". The sources=["reviewer"] argument matters: without it, the author quoting "not yet APPROVED" would end the run.

Legacy 0.2 equivalents: GroupChat(max_round=12), max_consecutive_auto_reply on each agent, and is_termination_msg=lambda m: "APPROVED" in (m.get("content") or "").

Layer 2: design the loop to end

  • A verifiable exit. "Tests pass" or "JSON validates" is checkable. "Until it's good" never ends.
  • Cap revisions in the prompt too. "After two review rounds, approve the best version and list remaining issues."
  • Bound tool retries with max_tool_iterations, and make a tool say "failed twice, do not retry" after repeated errors.

Layer 3: detect and alert

  • Repetition check. Hash each message, or compare embeddings; if an agent repeats itself or the last few messages add nothing new, end the run and escalate.
  • Watch stop_reason. Record whether each run ended on the semantic condition or on a cap. A rising cap-hit rate is your loop detector.

About allow_repeated_speaker=False in SelectorGroupChat (it is the default): it only stops the same agent speaking twice in a row. It does not stop two agents ping-ponging A, B, A, B.

A real-life example

A code-review agent pair (author and reviewer) at a SaaS company ran happily in testing. In production, 9% of runs hit MaxMessageTermination(20). The logs showed the reviewer asking for docstring changes, the author changing them, and the reviewer asking for different ones, for 20 messages.

The team made three changes:

  • The reviewer's prompt now says: "Only list issues that change behaviour or security. Style is out of scope."
  • After two reviews, the reviewer must approve and add remaining notes as comments.
  • Runs that end on the cap are marked needs_human and posted to a Slack channel instead of being treated as done.

Cap-hit runs fell to under 1%, and token cost per review dropped by about a third.

Follow-up questions to expect

  • "What should happen when the cap fires?" — Treat it as a failure: return the best result so far with a clear "incomplete" flag, or hand it to a human. Never present it as a finished answer.
  • "How do you stop a run from outside?" — ExternalTermination lets your application call .set() (for example, a user presses Stop); a CancellationToken aborts immediately.
  • "Is max_turns the same as MaxMessageTermination?" — Not quite. max_turns on a team counts agent turns and is often used to pause for user input; termination conditions look at message content, counts, tokens or time.