Velamuvi AIAcademy
AutoGen

Lesson 3 of 6 · AutoGen

Group Chats

Run AutoGen agent teams: RoundRobinGroupChat, SelectorGroupChat with a model picking speakers, selector_func rules, Swarm handoffs and termination conditions.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain how a group chat decides who speaks next
  • Use RoundRobinGroupChat and SelectorGroupChat
  • Override speaker selection with selector_func
  • Let agents hand off to each other in a Swarm
  • Combine termination conditions to end runs safely

Teams of agents

In AutoGen, several agents working together form a team, usually a group chat: one shared conversation where agents take turns.

AutoGen's main team types differ only in how the next speaker is chosen:

TeamWho speaks next
RoundRobinGroupChatEach agent in a fixed order (lesson 2 used it)
SelectorGroupChatA model reads the conversation and the agents' descriptions, and chooses
SwarmWhoever the current agent hands off to
MagenticOneGroupChatAn orchestrator agent that plans, tracks progress and assigns steps
GraphFlowA directed graph of agents you define, including branches and loops

A model chooses the speaker

import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.messages import TextMessage
from autogen_agentchat.teams import SelectorGroupChat
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

async def main():
    model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
    researcher = AssistantAgent(
        "researcher", model_client=model_client,
        description="Finds facts: distances, opening times, prices.",          # the selector reads this
        system_message="Give short, factual notes for the trip.",
    )
    planner = AssistantAgent(
        "planner", model_client=model_client,
        description="Turns facts into a day plan with times.",
        system_message="Write a short day plan from the facts gathered so far.",
    )
    critic = AssistantAgent(
        "critic", model_client=model_client,
        description="Checks plans for problems and approves good ones.",
        system_message="Check the plan is realistic. Reply APPROVE if it is, or say what to fix.",
    )
    team = SelectorGroupChat(
        [researcher, planner, critic],
        model_client=model_client,                  # this model chooses who speaks next
        termination_condition=TextMentionTermination("APPROVE", sources=["critic"]) | MaxMessageTermination(10),
    )
    result = await team.run(task="Plan a cycling day trip from Lisbon to Cascais.")
    for m in result.messages:
        if isinstance(m, TextMessage):
            print(f"{m.source}: {m.content}")
    await model_client.close()

asyncio.run(main())
Output
user: Plan a cycling day trip from Lisbon to Cascais.
researcher: Lisbon to Cascais along the coast is about 30 km, mostly flat; trains back run every 20 minutes.
planner: 9:00 leave Belém; 11:30 arrive Cascais; lunch; 15:00 train back with the bike.
critic: APPROVE

Before each turn, the selector model sees a prompt listing the agents' names and descriptions plus the conversation, and replies with a name. That's why each agent's description matters: it's how the selector knows who does what. Here it chose the researcher, then the planner, then the critic, whose “APPROVE” ended the run.

Selection costs a model call per turn. When the next speaker is obvious, decide it in code with selector_func: a function that receives the messages and returns a name, or None to let the model choose. The exercise below writes one.

Handoffs in a Swarm

In a Swarm, agents pass control directly. Each agent lists who it can hand off to; AutoGen turns those into tools, and calling one transfers the conversation:

import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.messages import HandoffMessage, TextMessage
from autogen_agentchat.teams import Swarm
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

async def main():
    model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
    triage = AssistantAgent(
        "triage", model_client=model_client,
        handoffs=["billing", "repairs"],            # becomes tools: transfer_to_billing, transfer_to_repairs
        system_message="Work out what the customer needs and hand off to billing or repairs.",
    )
    billing = AssistantAgent(
        "billing", model_client=model_client,
        system_message="Solve payment problems. End your final reply with DONE.",
    )
    repairs = AssistantAgent(
        "repairs", model_client=model_client,
        system_message="Help with bike faults. End your final reply with DONE.",
    )
    team = Swarm([triage, billing, repairs],
                 termination_condition=TextMentionTermination("DONE") | MaxMessageTermination(8))
    result = await team.run(task="I was charged twice for my order A-881.")
    for m in result.messages:
        if isinstance(m, (TextMessage, HandoffMessage)):
            print(f"{type(m).__name__:<14} {m.source}: {m.content}")
    await model_client.close()

asyncio.run(main())
Output
TextMessage    user: I was charged twice for my order A-881.
HandoffMessage triage: Transferred to billing, adopting the role of billing immediately.
TextMessage    billing: I can see two payments of 39 EUR for order A-881. I've refunded the duplicate; it will reach your card in 3 to 5 days. DONE

This is the triage-and-specialists design from the Multi-Agent Systems course: the triage agent called transfer_to_billing, and billing took over the conversation.

Ending the conversation

Every team needs a termination condition, or it runs until something breaks. AutoGen's conditions include:

  • MaxMessageTermination(n): a hard limit on messages; always include one.
  • TextMentionTermination("APPROVE", sources=[...]): a stop word, ideally only from certain agents.
  • TokenUsageTermination and TimeoutTermination: limits on tokens and time.
  • HandoffTermination: stop when control is handed to a particular target, such as a person.

Conditions combine with | (stop when either is true) and & (stop when both are). Here's how such combinable conditions work, in plain Python:

Try it yourselfPython
# AutoGen-style termination conditions in plain Python: small rules you can combine
# with | (stop if either is true) and & (stop only if both are true).
class Condition:
    def __or__(self, other): return Either(self, other)
    def __and__(self, other): return Both(self, other)

class TextMention(Condition):
    def __init__(self, text, sources=None): self.text, self.sources = text, sources
    def check(self, msgs):
        src, content = msgs[-1]
        return self.text in content and (self.sources is None or src in self.sources)

class MaxMessages(Condition):
    def __init__(self, n): self.n = n
    def check(self, msgs): return len(msgs) >= self.n

class Either(Condition):
    def __init__(self, a, b): self.a, self.b = a, b
    def check(self, msgs): return self.a.check(msgs) or self.b.check(msgs)

class Both(Condition):
    def __init__(self, a, b): self.a, self.b = a, b
    def check(self, msgs): return self.a.check(msgs) and self.b.check(msgs)

stop = TextMention("APPROVE", sources=["critic"]) | MaxMessages(6)
conversations = {
    "critic approves":   [("user", "task"), ("writer", "draft"), ("critic", "APPROVE")],
    "writer says it":    [("user", "task"), ("writer", "I APPROVE of my own draft")],
    "too long":          [("user", "task")] + [("writer", "draft"), ("critic", "fix it")] * 3,
}
for name, msgs in conversations.items():
    print(f"{name:<16} -> stop: {stop.check(msgs)}")

The writer's “I APPROVE of my own draft” didn't end the run, because only the critic's approval counts. And the long conversation stopped at the message limit.

Common mistakes

Practice exercise

Write a selector_func for a SelectorGroupChat: fixed rules where the order is obvious, and None to let the model decide otherwise.

Your solutionPython
def selector_func(messages):
    # messages is a list of (source, content). Rules for who speaks next:
    # - after "executor", the "reviewer" speaks
    # - after "coder", the "executor" speaks
    # - otherwise return None (let the model choose)
    pass

for last in [("coder", "def add(a, b): ..."), ("executor", "3 tests passed"), ("user", "Write add()")]:
    print(last[0], "->", selector_func([last]))
Knowledge check

In a SelectorGroupChat, how does the selector model know which agent should speak?

Summary

  • A group chat shares one conversation; teams differ in how the next speaker is chosen.
  • RoundRobinGroupChat uses a fixed order; SelectorGroupChat lets a model choose from descriptions; selector_func adds code rules.
  • Swarm agents hand off with tools such as transfer_to_billing.
  • Combine termination conditions with | and &, and always include a message limit.

Next: running code safely.

Finished reading? Tick it off to track your progress.