Selector Group Chat#

The SelectorGroupChat implements a team coordination pattern where participants take turns publishing messages, with the next speaker selected by a generative model (LLM) based on the conversation context. This enables dynamic and context-aware multi-agent conversations.

SelectorGroupChat provides several key features:

  • Dynamic speaker selection using an LLM to analyze conversation context

  • Configurable participant roles and descriptions

  • Optional prevention of consecutive turns by the same speaker

  • Customizable selection prompting

Speaker Selection Process#

The chat uses an LLM to select the next speaker by:

  1. Analyzing the conversation history

  2. Evaluating participant roles and descriptions

  3. Using a configurable prompt template to make the selection

  4. Validating that exactly one participant is selected

import asyncio
from typing import List, Sequence

from autogen_agentchat.agents import (
    BaseChatAgent,
    CodingAssistantAgent,
    ToolUseAssistantAgent,
)
from autogen_agentchat.base import Response
from autogen_agentchat.messages import ChatMessage, StopMessage, TextMessage
from autogen_agentchat.task import TextMentionTermination
from autogen_agentchat.teams import SelectorGroupChat
from autogen_core.base import CancellationToken
from autogen_core.components.tools import FunctionTool
from autogen_ext.models import OpenAIChatCompletionClient

Defining Agents#

The UserProxyAgent allows the user to input messages directly. This agent waits for user input and returns a text message or a stop message if the user decides to terminate the conversation.

class UserProxyAgent(BaseChatAgent):
    def __init__(self, name: str) -> None:
        super().__init__(name, "A human user.")

    @property
    def produced_message_types(self) -> List[type[ChatMessage]]:
        return [TextMessage, StopMessage]

    async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> Response:
        user_input = await asyncio.get_event_loop().run_in_executor(None, input, "Enter your response: ")
        if "TERMINATE" in user_input:
            return Response(chat_message=StopMessage(content="User has terminated the conversation.", source=self.name))
        return Response(chat_message=TextMessage(content=user_input, source=self.name))

    async def on_reset(self, cancellation_token: CancellationToken) -> None:
        pass
async def flight_search(start: str, destination: str, date: str) -> str:
    return "\n".join(
        [
            f"AC24 from {start} to {destination} on {date} is $500",
            f"UA23 from {start} to {destination} on {date} is $450",
            f"AL21 from {start} to {destination} on {date} is $400",
        ]
    )


async def flight_booking(flight: str, date: str) -> str:
    return f"Booked flight {flight} on {date}"

The ToolUseAssistantAgent is responsible for calling external tools. In this example, two tools are defined: flight_search and flight_booking.

Additionally, the CodingAssistantAgent serves as a general travel assistant with predefined behavior specified in the system_message.

user_proxy = UserProxyAgent("User")
flight_broker = ToolUseAssistantAgent(
    "FlightBroker",
    description="An assistant for booking flights",
    model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
    registered_tools=[
        FunctionTool(flight_search, description="Search for flights"),
        FunctionTool(flight_booking, description="Book a flight"),
    ],
)
travel_assistant = CodingAssistantAgent(
    "TravelAssistant",
    description="A travel assistant",
    model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
    system_message="You are a travel assistant.",
)

termination = TextMentionTermination("TERMINATE")
team = SelectorGroupChat(
    [user_proxy, flight_broker, travel_assistant],
    model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
    termination_condition=termination,
)
await team.run(task="Help user plan a trip and book a flight.")
--------------------------------------------------------------------------- 
[2024-10-08T20:35:30.283450]:

Help user plan a trip and book a flight.
--------------------------------------------------------------------------- 
[2024-10-08T20:35:48.275743], User:


--------------------------------------------------------------------------- 
[2024-10-08T20:35:50.795496], TravelAssistant:

I'd be happy to help you plan your trip! To get started, could you please provide me with the following details:

1. Your departure city and the destination city.
2. Your travel dates (departure and return).
3. The number of travelers and their ages (if any children are involved).
4. Your budget for flights and accommodations, if you have one in mind.
5. Any specific activities or attractions you're interested in at the destination.

Once I have this information, I can help you find the best options!
--------------------------------------------------------------------------- 
[2024-10-08T20:35:59.701486], User:

Traveling to toronto from new york
--------------------------------------------------------------------------- 
[2024-10-08T20:36:02.325330], TravelAssistant:

Great choice! Toronto is a vibrant city with a lot to offer. Now, could you please provide the following additional details to help me assist you better?

1. What are your travel dates (departure and return)?
2. How many travelers will be going, and what are their ages?
3. Do you have a budget for the flight and accommodations?
4. Are there any specific activities or attractions you’re interested in while in Toronto?

Once I have this information, I can help you find the best flights and suggestions for your trip!
--------------------------------------------------------------------------- 
[2024-10-08T20:36:20.633004], User:

leaving on december 7 and returning on 12
--------------------------------------------------------------------------- 
[2024-10-08T20:36:23.202871], TravelAssistant:

Thank you for the details! Here's what I have so far:

- **Departure City:** New York
- **Destination City:** Toronto
- **Departure Date:** December 7
- **Return Date:** December 12

Now, could you please provide:

1. The number of travelers and their ages.
2. Your budget for flights and accommodations (if applicable).
3. Any specific activities or attractions you're interested in while in Toronto.

This will help me provide more tailored options for your trip!
--------------------------------------------------------------------------- 
[2024-10-08T20:36:38.096554], User:

just myself one adult
--------------------------------------------------------------------------- 
[2024-10-08T20:36:40.307824], FlightBroker:

Thanks for the information! Here's what I have:

- **Departure City:** New York
- **Destination City:** Toronto
- **Departure Date:** December 7
- **Return Date:** December 12
- **Number of Travelers:** 1 Adult

Could you let me know if you have a budget for flights and accommodations? Additionally, are there any specific activities or attractions you're interested in while in Toronto? This will help me provide the best options for your trip!
--------------------------------------------------------------------------- 
[2024-10-08T20:36:45.875280], User:

that's it
--------------------------------------------------------------------------- 
[2024-10-08T20:36:50.925624], FlightBroker:

Your flights have been successfully booked! Here are the details:

- **Departure:** New York to Toronto
  - **Flight:** AL21
  - **Date:** December 7, 2023

- **Return:** Toronto to New York
  - **Flight:** AL21
  - **Date:** December 12, 2023

If you need help with accommodations, activities, or anything else for your trip, feel free to let me know! 

TERMINATE
TeamRunResult(messages=[TextMessage(source='user', content='Help user plan a trip and book a flight.'), TextMessage(source='User', content=''), TextMessage(source='TravelAssistant', content="I'd be happy to help you plan your trip! To get started, could you please provide me with the following details:\n\n1. Your departure city and the destination city.\n2. Your travel dates (departure and return).\n3. The number of travelers and their ages (if any children are involved).\n4. Your budget for flights and accommodations, if you have one in mind.\n5. Any specific activities or attractions you're interested in at the destination.\n\nOnce I have this information, I can help you find the best options!"), TextMessage(source='User', content='Traveling to toronto from new york'), TextMessage(source='TravelAssistant', content='Great choice! Toronto is a vibrant city with a lot to offer. Now, could you please provide the following additional details to help me assist you better?\n\n1. What are your travel dates (departure and return)?\n2. How many travelers will be going, and what are their ages?\n3. Do you have a budget for the flight and accommodations?\n4. Are there any specific activities or attractions you’re interested in while in Toronto?\n\nOnce I have this information, I can help you find the best flights and suggestions for your trip!'), TextMessage(source='User', content='leaving on december 7 and returning on 12'), TextMessage(source='TravelAssistant', content="Thank you for the details! Here's what I have so far:\n\n- **Departure City:** New York\n- **Destination City:** Toronto\n- **Departure Date:** December 7\n- **Return Date:** December 12\n\nNow, could you please provide:\n\n1. The number of travelers and their ages.\n2. Your budget for flights and accommodations (if applicable).\n3. Any specific activities or attractions you're interested in while in Toronto.\n\nThis will help me provide more tailored options for your trip!"), TextMessage(source='User', content='just myself one adult'), TextMessage(source='FlightBroker', content="Thanks for the information! Here's what I have:\n\n- **Departure City:** New York\n- **Destination City:** Toronto\n- **Departure Date:** December 7\n- **Return Date:** December 12\n- **Number of Travelers:** 1 Adult\n\nCould you let me know if you have a budget for flights and accommodations? Additionally, are there any specific activities or attractions you're interested in while in Toronto? This will help me provide the best options for your trip!"), TextMessage(source='User', content="that's it"), StopMessage(source='FlightBroker', content='Your flights have been successfully booked! Here are the details:\n\n- **Departure:** New York to Toronto\n  - **Flight:** AL21\n  - **Date:** December 7, 2023\n\n- **Return:** Toronto to New York\n  - **Flight:** AL21\n  - **Date:** December 12, 2023\n\nIf you need help with accommodations, activities, or anything else for your trip, feel free to let me know! \n\nTERMINATE'), StopMessage(source='StopMessageTermination', content='Stop message received')])