Lesson 33 of 39 · Orchestrations
Group Chat and Handoff Orchestration
Let agents take turns with GroupChatBuilder and pass customers between specialists with HandoffBuilder, with termination rules, in Microsoft Agent Framework.
- 12 min read
- Intermediate
- Reviewed
- Explain the difference between a group chat and a handoff
- Run a group chat with a selection function and a termination condition
- Let an agent moderate the chat with orchestrator_agent
- Route customers between specialists with HandoffBuilder and answer their requests
- Control handoffs with handoff rules, autonomous mode and a termination condition
Two ways for agents to take turns
The last lesson's orchestrations had a fixed shape: one agent after another, or all at once. Real teamwork is often less tidy. Sometimes agents need to discuss, and sometimes the right expert depends on what the customer says.
The difference is who decides. In a group chat, a manager outside the conversation picks each speaker. In a handoff, the current agent picks its successor, by calling a handoff tool that the framework adds for it.
Here are both ideas in plain Python, with functions standing in for agents:
# Group chat and handoff in plain Python. Each "agent" is a function here.
def writer(conversation):
return "Ride all day for 35 EUR." if len(conversation) > 2 else "Pedal further, worry less."
def reviewer(conversation):
return "APPROVED" if "EUR" in conversation[-1][1] else "Too vague: mention the price."
participants = {"writer": writer, "reviewer": reviewer}
# Group chat: a selection function picks each speaker, a termination condition ends the chat.
def next_speaker(round_index):
return "writer" if round_index % 2 == 0 else "reviewer"
conversation = [("user", "A slogan for the Velo City E")]
for round_index in range(6): # max_rounds = 6
name = next_speaker(round_index)
conversation.append((name, participants[name](conversation)))
print(f"{name}: {conversation[-1][1]}")
if conversation[-1][1] == "APPROVED": # the termination condition
break
# Handoff: the agent that is talking decides who takes over.
def front_desk(message):
if "refund" in message:
return "refunds"
if "delivery" in message:
return "orders"
return "front_desk"
for message in ["I want a refund for my helmet", "When is my delivery?", "Hello!"]:
print(f"{message!r} -> {front_desk(message)}")A group chat with a selection function
GroupChatBuilder from agent_framework.orchestrations builds the chat. The simplest manager is a selection function: plain Python that receives a GroupChatState and returns the name of the next speaker. A writer and a reviewer take turns until the reviewer approves:
import asyncio
from agent_framework import Agent, Message
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import GroupChatBuilder, GroupChatState
def next_speaker(state: GroupChatState) -> str: # the selection function
return "writer" if state.current_round % 2 == 0 else "reviewer"
def approved(conversation: list[Message]) -> bool: # the termination condition
return any(m.author_name == "reviewer" and m.text.startswith("APPROVED") for m in conversation)
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
writer = Agent(client=client, name="writer", description="Writes slogans",
instructions="Write one slogan. Use the reviewer's feedback if there is any.")
reviewer = Agent(client=client, name="reviewer", description="Checks slogans",
instructions="Review the latest slogan. Reply APPROVED if it is short, clear and "
"names the price; otherwise say what to change.")
workflow = GroupChatBuilder(
participants=[writer, reviewer],
selection_func=next_speaker,
termination_condition=approved,
max_rounds=6, # a safety net
intermediate_output_from="all", # show every reply as it happens
).build()
result = await workflow.run("A slogan for the Velo City E, our rental e-bike at 35 EUR a day")
for reply in result.get_intermediate_outputs():
print(f"{reply.messages[-1].author_name}: {reply.text}")
print(result.get_outputs()[0].text)
asyncio.run(main())writer: Pedal further, worry less. reviewer: Too vague. Please mention the 35 EUR price. writer: Ride all day for 35 EUR. reviewer: APPROVED: short, clear and it names the price. The group chat has reached its termination condition.
What each piece does:
GroupChatStateholdscurrent_round(starting at 0),participants(an ordered mapping of each name to itsdescription) andconversation(everyMessageso far). Your function can use any of them, for example to pick whoever has spoken least.- The termination condition is a
TerminationCondition: a function that receives the conversation and returnsTrueto stop. It may also beasync. max_roundsis a safety net. When it is reached, the chat ends with the message "The group chat has reached the maximum number of rounds."- The final output is only the manager's closing message. To see what the participants said, list them in
intermediate_output_from(here"all") and readresult.get_intermediate_outputs().
Every participant sees the whole conversation, so the writer reads the reviewer's feedback before its second try. That is the point of a group chat: agents build on each other's words.
Under the hood, your function (its type is GroupChatSelectionFunction) runs inside a GroupChatOrchestrator. For complete control, for example to keep scores or skip a busy agent, subclass BaseGroupChatOrchestrator and pass an instance as orchestrator=.
Letting an agent run the meeting
A selection function is predictable, but it cannot understand the conversation. For open-ended discussions, give the chat a moderator agent with orchestrator_agent=. The builder wraps it in an AgentBasedGroupChatOrchestrator, which shows the moderator the conversation and every participant's description, and asks for a structured decision each round: stop or continue, a reason, the next speaker, and a final message when it stops.
import asyncio
from agent_framework import Agent, AgentResponseUpdate
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import GroupChatBuilder, GroupChatRequestSentEvent
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
moderator = Agent(client=client, name="moderator",
instructions="You lead Velo's planning meetings. Let each expert speak once, "
"then end the meeting with a one-line plan.")
experts = [
Agent(client=client, name="route_planner", description="Plans routes and distances",
instructions="You plan bike routes around Porto. Answer in one sentence."),
Agent(client=client, name="safety_officer", description="Checks rider safety",
instructions="You check safety for group rides. Answer in one sentence."),
Agent(client=client, name="marketer", description="Writes announcements",
instructions="You write announcements for Velo's events. Answer in one sentence."),
]
workflow = GroupChatBuilder(participants=experts, orchestrator_agent=moderator, max_rounds=8).build()
async for event in workflow.run("Plan our spring group ride.", stream=True):
if event.type == "group_chat" and isinstance(event.data, GroupChatRequestSentEvent):
print(f"round {event.data.round_index}: moderator picks {event.data.participant_name}")
elif event.type == "output" and isinstance(event.data, AgentResponseUpdate):
print(event.data.text, end="")
print()
asyncio.run(main())round 0: moderator picks route_planner round 1: moderator picks safety_officer round 2: moderator picks marketer Plan: 40 km coast route on 12 April, helmets required, posters from 1 April.
The moderator chose the order itself and wrote the final plan, which became the workflow's output. Good participant descriptions matter here: they are what the moderator reads when it decides who should speak.
Handoff: passing the customer along
A handoff workflow starts with one agent and lets agents pass the conversation on. HandoffBuilder adds a handoff tool to each agent, named like handoff_to_refunds. When the model calls it, the next agent takes over with the full conversation.
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
from agent_framework.orchestrations import HandoffAgentUserRequest, HandoffBuilder
def make_agent(client, name: str, description: str, instructions: str) -> Agent:
return Agent(client=client, name=name, description=description, instructions=instructions,
require_per_service_call_history_persistence=True) # required for handoffs
async def main():
client = OpenAIChatClient(model="MODEL_NAME")
front_desk = make_agent(client, "front_desk", "Greets customers and finds the right specialist",
"You are Velo's front desk. Hand each customer to the right specialist.")
refunds = make_agent(client, "refunds", "Handles refunds and returns",
"You handle refunds for Velo. Ask for the order number, then confirm the refund.")
orders = make_agent(client, "orders", "Answers questions about orders and deliveries",
"You answer questions about orders and deliveries.")
workflow = (
HandoffBuilder(participants=[front_desk, refunds, orders])
.with_start_agent(front_desk)
.add_handoff(front_desk, [refunds, orders]) # who may hand off to whom
.add_handoff(refunds, [front_desk])
.add_handoff(orders, [front_desk])
.build()
)
result = await workflow.run("Hi, I want my money back for a helmet.")
while True:
for event in result:
if event.type == "handoff_sent":
print(f"[handoff: {event.data.source} -> {event.data.target}]")
elif event.type == "output" and event.data.text:
print(f"{event.data.messages[-1].author_name}: {event.data.text}")
requests = result.get_request_info_events() # the agent waits for the customer
if not requests:
break
reply = input("You: ")
if reply:
answer = HandoffAgentUserRequest.create_response(reply)
else:
answer = HandoffAgentUserRequest.terminate() # an empty line ends the chat
result = await workflow.run(responses={requests[0].request_id: answer})
asyncio.run(main())[handoff: front_desk -> refunds] refunds: I can help with that. What is your order number? You: Order A-1042. refunds: Done: 89.00 EUR for order A-1042 is on its way to your card. Anything else? You:
How the conversation flows:
with_start_agent(front_desk)says who answers first. It is required.- The front desk calls
handoff_to_refunds. The workflow sends ahandoff_sentevent whose data is aHandoffSentEventwithsourceandtarget. - The refunds agent replies. Because it did not hand off, the workflow pauses and waits for the customer:
get_request_info_events()returns one request whose data is aHandoffAgentUserRequest. - You answer with
HandoffAgentUserRequest.create_response(text)(a string, a list of strings orMessageobjects), and the same agent continues.HandoffAgentUserRequest.terminate()ends the conversation.
Handoff rules, autonomous mode and ending
- Handoff rules.
add_handoff(source, [targets])decides who may hand off to whom, and stores aHandoffConfigurationfor each target. Without anyadd_handoff()call, every agent may hand off to every other agent. Rules keep specialists focused: here they can only send customers back to the front desk. - Autonomous mode. By default, a reply that is not a handoff hands control back to the user. With autonomous mode, an agent keeps working on its own (each extra turn gets the message "User did not respond. Continue assisting autonomously.") until it hands off or reaches its turn limit.
- Ending by rule.
with_termination_condition()takes the same kind of function as a group chat and ends the workflow when it returnsTrue.
workflow = (
HandoffBuilder(participants=[front_desk, orders])
.with_start_agent(front_desk)
.with_autonomous_mode(agents=[orders], turn_limits={"orders": 2})
.build()
) workflow = (
HandoffBuilder(participants=[front_desk, orders])
.with_start_agent(front_desk)
.with_termination_condition(lambda conversation: any("delivered" in m.text for m in conversation))
.build()
)autonomous: 3 replies, waiting for the customer: True with a termination condition: IDLE, waiting: 0
With a turn limit of 2, the orders agent replied, carried on twice by itself, and then waited for the customer. With the termination condition, the workflow ended as soon as an answer mentioned "delivered", with no request left waiting.
Choosing an orchestration
| Situation | Use |
|---|---|
| Fixed steps, each building on the last | Sequential |
| Independent opinions on the same input | Concurrent |
| Agents should discuss and build on each other | Group chat |
| The right expert depends on the request, and customers talk to them directly | Handoff |
| An open task that needs a plan, with progress tracking | Magentic (next lesson) |
Common mistakes
Write a selection function for a group chat: the writer and the reviewer take turns, and as soon as the reviewer approves, the publisher speaks.
conversation = [] # (speaker, text) pairs, like the group chat's conversation
def next_speaker(round_index, conversation):
# Writer and reviewer take turns, starting with the writer (round 0).
# But if the last message is from the reviewer and starts with "APPROVED",
# return "publisher" instead.
pass
def reply(name, round_index):
return {"writer": f"draft {round_index // 2 + 1}",
"reviewer": "APPROVED" if round_index >= 3 else "too long",
"publisher": "published"}[name]
for round_index in range(6):
name = next_speaker(round_index, conversation)
conversation.append((name, reply(name, round_index)))
print(round_index, name, "->", conversation[-1][1])
if name == "publisher":
break
In a handoff workflow, an agent replies without handing off and autonomous mode is off. What happens next?
Summary
- In a group chat, a manager picks each speaker; in a handoff, the agent that is talking picks who takes over.
GroupChatBuilderneeds a manager: aselection_functhat readsGroupChatState, or anorchestrator_agentthat is wrapped in anAgentBasedGroupChatOrchestrator. Stop it with aTerminationConditionandmax_rounds.- The group chat's output is the manager's closing message; use
intermediate_output_fromto see the participants' replies. HandoffBuilderneedswith_start_agent()and agents withrequire_per_service_call_history_persistence=True. It pauses with aHandoffAgentUserRequestwhenever an agent waits for the user, and reports each handoff as aHandoffSentEvent.add_handoff(),with_autonomous_mode()andwith_termination_condition()control who can hand off, whether agents keep working alone, and when the workflow ends.
Next: Magentic Orchestration.
Finished reading? Tick it off to track your progress.