Skip to content

A programming framework for agentic AI

fix: improve speaker selection in SelectorGroupChat for weaker models (#5454)

Eric Zhu426b8984854f
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
index de0ef3247..70de57138 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py
@@ -3,7 +3,7 @@ import re
from typing import Any, Callable, Dict, List, Mapping, Sequence
from autogen_core import Component, ComponentModel
-from autogen_core.models import ChatCompletionClient, ModelFamily, SystemMessage, UserMessage
+from autogen_core.models import AssistantMessage, ChatCompletionClient, ModelFamily, SystemMessage, UserMessage
from pydantic import BaseModel
from typing_extensions import Self
@@ -39,6 +39,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):
selector_prompt: str,
allow_repeated_speaker: bool,
selector_func: Callable[[Sequence[AgentEvent | ChatMessage]], str | None] | None,
+ max_selector_attempts: int,
) -> None:
super().__init__(
group_topic_type,
@@ -53,6 +54,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):
self._previous_speaker: str | None = None
self._allow_repeated_speaker = allow_repeated_speaker
self._selector_func = selector_func
+ self._max_selector_attempts = max_selector_attempts
async def validate_group_state(self, messages: List[ChatMessage] | None) -> None:
pass
@@ -131,41 +133,72 @@ class SelectorGroupChatManager(BaseGroupChatManager):
# Select the next speaker.
if len(participants) > 1:
- select_speaker_prompt = self._selector_prompt.format(
- roles=roles, participants=str(participants), history=history
- )
- select_speaker_messages: List[SystemMessage | UserMessage]
- if self._model_client.model_info["family"] in [
- ModelFamily.GPT_4,
- ModelFamily.GPT_4O,
- ModelFamily.GPT_35,
- ModelFamily.O1,
- ModelFamily.O3,
- ]:
- select_speaker_messages = [SystemMessage(content=select_speaker_prompt)]
- else:
- # Many other models need a UserMessage to respond to
- select_speaker_messages = [UserMessage(content=select_speaker_prompt, source="selector")]
-
- response = await self._model_client.create(messages=select_speaker_messages)
-
- assert isinstance(response.content, str)
- mentions = self._mentioned_agents(response.content, self._participant_topic_types)
- if len(mentions) != 1:
- raise ValueError(f"Expected exactly one agent to be mentioned, but got {mentions}")
- agent_name = list(mentions.keys())[0]
- if (
- not self._allow_repeated_speaker
- and self._previous_speaker is not None
- and agent_name == self._previous_speaker
- ):
- trace_logger.warning(f"Selector selected the previous speaker: {agent_name}")
+ agent_name = await self._select_speaker(roles, participants, history, self._max_selector_attempts)
else:
agent_name = participants[0]
self._previous_speaker = agent_name
trace_logger.debug(f"Selected speaker: {agent_name}")
return agent_name
+ async def _select_speaker(self, roles: str, participants: List[str], history: str, max_attempts: int) -> str:
+ select_speaker_prompt = self._selector_prompt.format(
+ roles=roles, participants=str(participants), history=history
+ )
+ select_speaker_messages: List[SystemMessage | UserMessage | AssistantMessage]
+ if self._model_client.model_info["family"] in [
+ ModelFamily.GPT_4,
+ ModelFamily.GPT_4O,
+ ModelFamily.GPT_35,
+ ModelFamily.O1,
+ ModelFamily.O3,
+ ]:
+ select_speaker_messages = [SystemMessage(content=select_speaker_prompt)]
+ else:
+ # Many other models need a UserMessage to respond to
+ select_speaker_messages = [UserMessage(content=select_speaker_prompt, source="user")]
+
+ num_attempts = 0
+ while num_attempts < max_attempts:
+ num_attempts += 1
+ response = await self._model_client.create(messages=select_speaker_messages)
+ assert isinstance(response.content, str)
+ select_speaker_messages.append(AssistantMessage(content=response.content, source="selector"))
+ mentions = self._mentioned_agents(response.content, self._participant_topic_types)
+ if len(mentions) == 0:
+ trace_logger.debug(f"Model failed to select a valid name: {response.content} (attempt {num_attempts})")
+ feedback = f"No valid name was mentioned. Please select from: {str(participants)}."
+ select_speaker_messages.append(UserMessage(content=feedback, source="user"))
+ elif len(mentions) > 1:
+ trace_logger.debug(f"Model selected multiple names: {str(mentions)} (attempt {num_attempts})")
+ feedback = (
+ f"Expected exactly one name to be mentioned. Please select only one from: {str(participants)}."
+ )
+ select_speaker_messages.append(UserMessage(content=feedback, source="user"))
+ else:
+ agent_name = list(mentions.keys())[0]
+ if (
+ not self._allow_repeated_speaker
+ and self._previous_speaker is not None
+ and agent_name == self._previous_speaker
+ ):
+ trace_logger.debug(f"Model selected the previous speaker: {agent_name} (attempt {num_attempts})")
+ feedback = (
+ f"Repeated speaker is not allowed, please select a different name from: {str(participants)}."
+ )
+ select_speaker_messages.append(UserMessage(content=feedback, source="user"))
+ else:
+ # Valid selection
+ trace_logger.debug(f"Model selected a valid name: {agent_name} (attempt {num_attempts})")
+ return agent_name
+
+ if self._previous_speaker is not None:
+ trace_logger.warning(f"Model failed to select a speaker after {max_attempts}, using the previous speaker.")
+ return self._previous_speaker
+ trace_logger.warning(
+ f"Model failed to select a speaker after {max_attempts} and there was no previous speaker, using the first participant."
+ )
+ return participants[0]
+
def _mentioned_agents(self, message_content: str, agent_names: List[str]) -> Dict[str, int]:
"""Counts the number of times each agent is mentioned in the provided message content.
Agent names will match under any of the following conditions (all case-sensitive):
@@ -210,6 +243,7 @@ class SelectorGroupChatConfig(BaseModel):
selector_prompt: str
allow_repeated_speaker: bool
# selector_func: ComponentModel | None
+ max_selector_attempts: int = 3
class SelectorGroupChat(BaseGroupChat, Component[SelectorGroupChatConfig]):
@@ -226,13 +260,17 @@ class SelectorGroupChat(BaseGroupChat, Component[SelectorGroupChatConfig]):
max_turns (int, optional): The maximum number of turns in the group chat before stopping. Defaults to None, meaning no limit.
selector_prompt (str, optional): The prompt template to use for selecting the next speaker.
Must contain '{roles}', '{participants}', and '{history}' to be filled in.
- allow_repeated_speaker (bool, optional): Whether to allow the same speaker to be selected
- consecutively. Defaults to False.
+ allow_repeated_speaker (bool, optional): Whether to include the previous speaker in the list of candidates to be selected for the next turn.
+ Defaults to False. The model may still select the previous speaker -- a warning will be logged if this happens.
+ max_selector_attempts (int, optional): The maximum number of attempts to select a speaker using the model. Defaults to 3.
+ If the model fails to select a speaker after the maximum number of attempts, the previous speaker will be used if available,
+ otherwise the first participant will be used.
selector_func (Callable[[Sequence[AgentEvent | ChatMessage]], str | None], optional): A custom selector
function that takes the conversation history and returns the name of the next speaker.
If provided, this function will be used to override the model to select the next speaker.
If the function returns None, the model will be used to select the next speaker.
+
Raises:
ValueError: If the number of participants is less than two or if the selector prompt is invalid.
@@ -368,6 +406,7 @@ Read the following conversation. Then select the next role from {participants} t
Read the above conversation. Then select the next role from {participants} to play. Only return the role.
""",
allow_repeated_speaker: bool = False,
+ max_selector_attempts: int = 3,
selector_func: Callable[[Sequence[AgentEvent | ChatMessage]], str | None] | None = None,
):
super().__init__(
@@ -390,6 +429,7 @@ Read the above conversation. Then select the next role from {participants} to pl
self._model_client = model_client
self._allow_repeated_speaker = allow_repeated_speaker
self._selector_func = selector_func
+ self._max_selector_attempts = max_selector_attempts
def _create_group_chat_manager_factory(
self,
@@ -411,6 +451,7 @@ Read the above conversation. Then select the next role from {participants} to pl
self._selector_prompt,
self._allow_repeated_speaker,
self._selector_func,
+ self._max_selector_attempts,
)
def _to_config(self) -> SelectorGroupChatConfig:
@@ -421,6 +462,7 @@ Read the above conversation. Then select the next role from {participants} to pl
max_turns=self._max_turns,
selector_prompt=self._selector_prompt,
allow_repeated_speaker=self._allow_repeated_speaker,
+ max_selector_attempts=self._max_selector_attempts,
# selector_func=self._selector_func.dump_component() if self._selector_func else None,
)
@@ -435,6 +477,7 @@ Read the above conversation. Then select the next role from {participants} to pl
max_turns=config.max_turns,
selector_prompt=config.selector_prompt,
allow_repeated_speaker=config.allow_repeated_speaker,
+ max_selector_attempts=config.max_selector_attempts,
# selector_func=ComponentLoader.load_component(config.selector_func, Callable[[Sequence[AgentEvent | ChatMessage]], str | None])
# if config.selector_func
# else None,
diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.py
index c04d73440..098d68349 100644
--- a/python/packages/autogen-agentchat/tests/test_group_chat.py
+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py
@@ -740,6 +740,68 @@ async def test_selector_group_chat_two_speakers_allow_repeated(monkeypatch: pyte
assert result2 == result
+async def test_selector_group_chat_succcess_after_2_attempts() -> None:
+ model_client = ReplayChatCompletionClient(
+ ["agent2, agent3", "agent2"],
+ )
+ agent1 = _StopAgent("agent1", description="echo agent 1", stop_at=1)
+ agent2 = _EchoAgent("agent2", description="echo agent 2")
+ agent3 = _EchoAgent("agent3", description="echo agent 3")
+ team = SelectorGroupChat(
+ participants=[agent1, agent2, agent3],
+ model_client=model_client,
+ max_turns=1,
+ )
+ result = await team.run(task="Write a program that prints 'Hello, world!'")
+ assert len(result.messages) == 2
+ assert result.messages[0].content == "Write a program that prints 'Hello, world!'"
+ assert result.messages[1].source == "agent2"
+
+
+async def test_selector_group_chat_fall_back_to_first_after_3_attempts() -> None:
+ model_client = ReplayChatCompletionClient(
+ [
+ "agent2, agent3", # Multiple speakers
+ "agent5", # Non-existent speaker
+ "agent3, agent1", # Multiple speakers
+ ]
+ )
+ agent1 = _StopAgent("agent1", description="echo agent 1", stop_at=1)
+ agent2 = _EchoAgent("agent2", description="echo agent 2")
+ agent3 = _EchoAgent("agent3", description="echo agent 3")
+ team = SelectorGroupChat(
+ participants=[agent1, agent2, agent3],
+ model_client=model_client,
+ max_turns=1,
+ )
+ result = await team.run(task="Write a program that prints 'Hello, world!'")
+ assert len(result.messages) == 2
+ assert result.messages[0].content == "Write a program that prints 'Hello, world!'"
+ assert result.messages[1].source == "agent1"
+
+
+async def test_selector_group_chat_fall_back_to_previous_after_3_attempts() -> None:
+ model_client = ReplayChatCompletionClient(
+ ["agent2", "agent2", "agent2", "agent2"],
+ )
+ agent1 = _StopAgent("agent1", description="echo agent 1", stop_at=1)
+ agent2 = _EchoAgent("agent2", description="echo agent 2")
+ agent3 = _EchoAgent("agent3", description="echo agent 3")
+ team = SelectorGroupChat(
+ participants=[agent1, agent2, agent3],
+ model_client=model_client,
+ max_turns=2,
+ )
+ result = await team.run(task="Write a program that prints 'Hello, world!'")
+ assert len(result.messages) == 3
+ assert result.messages[0].content == "Write a program that prints 'Hello, world!'"
+ assert result.messages[1].source == "agent2"
+ assert result.messages[2].source == "agent2"
+
+
@pytest.mark.asyncio
async def test_selector_group_chat_custom_selector(monkeypatch: pytest.MonkeyPatch) -> None:
model = "gpt-4o-2024-05-13"
diff --git a/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py b/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py
index fcd3b8839..301c2f21d 100644
--- a/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py
+++ b/python/packages/autogen-agentchat/tests/test_group_chat_endpoint.py
@@ -4,10 +4,29 @@ import pytest
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import SelectorGroupChat
from autogen_agentchat.ui import Console
-from autogen_core.models import ModelFamily
+from autogen_core.models import ChatCompletionClient, ModelFamily
from autogen_ext.models.openai import OpenAIChatCompletionClient
+async def _test_selector_group_chat(model_client: ChatCompletionClient) -> None:
+ assistant = AssistantAgent(
+ "assistant",
+ description="A helpful assistant agent.",
+ model_client=model_client,
+ system_message="You are a helpful assistant.",
+ )
+
+ critic = AssistantAgent(
+ "critic",
+ description="A critic agent to provide feedback.",
+ model_client=model_client,
+ system_message="Provide feedback.",
+ )
+
+ team = SelectorGroupChat([assistant, critic], model_client=model_client, max_turns=2)
+ await Console(team.run_stream(task="Draft a short email about organizing a holiday party for new year."))
+
+
@pytest.mark.asyncio
async def test_selector_group_chat_gemini() -> None:
try:
@@ -26,20 +45,18 @@ async def test_selector_group_chat_gemini() -> None:
"family": ModelFamily.GEMINI_1_5_FLASH,
},
)
+ await _test_selector_group_chat(model_client)
- assistant = AssistantAgent(
- "assistant",
- description="A helpful assistant agent.",
- model_client=model_client,
- system_message="You are a helpful assistant.",
- )
- critic = AssistantAgent(
- "critic",
- description="A critic agent to provide feedback.",
- model_client=model_client,
- system_message="Provide feedback.",
- )
+async def test_selector_group_chat_openai() -> None:
+ try:
+ api_key = os.environ["OPENAI_API_KEY"]
+ except KeyError:
+ pytest.skip("OPENAI_API_KEY not set in environment variables.")
- team = SelectorGroupChat([assistant, critic], model_client=model_client, max_turns=2)
- await Console(team.run_stream(task="Draft a short email about organizing a holiday party for new year."))
+ model_client = OpenAIChatCompletionClient(
+ model="gpt-4o-mini",
+ api_key=api_key,
+ )
+ await _test_selector_group_chat(model_client)