Skip to content

A programming framework for agentic AI

Max turn parameter for group chats (#4143)

Eric Zhu233e482c7b44
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py b/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py
index 604ef5b5b..c5a9ac21e 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py
@@ -62,10 +62,6 @@ class ToolCallResultMessage(BaseMessage):
"""The tool call results."""
-InnerMessage = ToolCallMessage | ToolCallResultMessage
-"""Messages for intra-agent monologues."""
-
-
ChatMessage = TextMessage | MultiModalMessage | StopMessage | HandoffMessage
"""Messages for agent-to-agent communication."""
@@ -83,6 +79,5 @@ __all__ = [
"ToolCallMessage",
"ToolCallResultMessage",
"ChatMessage",
- "InnerMessage",
"AgentMessage",
]
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py
index 6eb659d7c..612c94b4b 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py
@@ -38,6 +38,7 @@ class BaseGroupChat(Team, ABC):
participants: List[ChatAgent],
group_chat_manager_class: type[BaseGroupChatManager],
termination_condition: TerminationCondition | None = None,
+ max_turns: int | None = None,
):
if len(participants) == 0:
raise ValueError("At least one participant is required.")
@@ -46,6 +47,7 @@ class BaseGroupChat(Team, ABC):
self._participants = participants
self._base_group_chat_manager_class = group_chat_manager_class
self._termination_condition = termination_condition
+ self._max_turns = max_turns
# Constants for the group chat.
self._team_id = str(uuid.uuid4())
@@ -78,6 +80,7 @@ class BaseGroupChat(Team, ABC):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None,
) -> Callable[[], BaseGroupChatManager]: ...
def _create_participant_factory(
@@ -123,6 +126,7 @@ class BaseGroupChat(Team, ABC):
participant_topic_types=self._participant_topic_types,
participant_descriptions=self._participant_descriptions,
termination_condition=self._termination_condition,
+ max_turns=self._max_turns,
),
)
# Add subscriptions for the group chat manager.
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py
index 43bda969c..e28f46a8c 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat_manager.py
@@ -35,6 +35,7 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None = None,
+ max_turns: int | None = None,
):
super().__init__(description="Group chat manager")
self._group_topic_type = group_topic_type
@@ -49,6 +50,10 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):
self._participant_descriptions = participant_descriptions
self._message_thread: List[AgentMessage] = []
self._termination_condition = termination_condition
+ if max_turns is not None and max_turns <= 0:
+ raise ValueError("The maximum number of turns must be greater than 0.")
+ self._max_turns = max_turns
+ self._current_turn = 0
@event
async def handle_start(self, message: GroupChatStart, ctx: MessageContext) -> None:
@@ -105,8 +110,27 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):
await self.publish_message(
GroupChatTermination(message=stop_message), topic_id=DefaultTopicId(type=self._output_topic_type)
)
- # Stop the group chat and reset the termination condition.
+ # Stop the group chat and reset the termination conditions and turn count.
await self._termination_condition.reset()
+ self._current_turn = 0
+ return
+
+ # Increment the turn count.
+ self._current_turn += 1
+ # Check if the maximum number of turns has been reached.
+ if self._max_turns is not None:
+ if self._current_turn >= self._max_turns:
+ stop_message = StopMessage(
+ content=f"Maximum number of turns {self._max_turns} reached.",
+ source="Group chat manager",
+ )
+ await self.publish_message(
+ GroupChatTermination(message=stop_message), topic_id=DefaultTopicId(type=self._output_topic_type)
+ )
+ # Stop the group chat and reset the termination conditions and turn count.
+ if self._termination_condition is not None:
+ await self._termination_condition.reset()
+ self._current_turn = 0
return
# Select a speaker to continue the conversation.
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py
index 9638051e7..8e3a262a8 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py
@@ -16,6 +16,7 @@ class RoundRobinGroupChatManager(BaseGroupChatManager):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None = None,
) -> None:
super().__init__(
group_topic_type,
@@ -23,10 +24,12 @@ class RoundRobinGroupChatManager(BaseGroupChatManager):
participant_topic_types,
participant_descriptions,
termination_condition,
+ max_turns,
)
self._next_speaker_index = 0
async def reset(self) -> None:
+ self._current_turn = 0
self._message_thread.clear()
if self._termination_condition is not None:
await self._termination_condition.reset()
@@ -50,6 +53,7 @@ class RoundRobinGroupChat(BaseGroupChat):
participants (List[BaseChatAgent]): The participants in the group chat.
termination_condition (TerminationCondition, optional): The termination condition for the group chat. Defaults to None.
Without a termination condition, the group chat will run indefinitely.
+ max_turns (int, optional): The maximum number of turns in the group chat before stopping. Defaults to None, meaning no limit.
Raises:
ValueError: If no participants are provided or if participant names are not unique.
@@ -114,12 +118,16 @@ class RoundRobinGroupChat(BaseGroupChat):
"""
def __init__(
- self, participants: List[ChatAgent], termination_condition: TerminationCondition | None = None
+ self,
+ participants: List[ChatAgent],
+ termination_condition: TerminationCondition | None = None,
+ max_turns: int | None = None,
) -> None:
super().__init__(
participants,
group_chat_manager_class=RoundRobinGroupChatManager,
termination_condition=termination_condition,
+ max_turns=max_turns,
)
def _create_group_chat_manager_factory(
@@ -129,6 +137,7 @@ class RoundRobinGroupChat(BaseGroupChat):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None,
) -> Callable[[], RoundRobinGroupChatManager]:
def _factory() -> RoundRobinGroupChatManager:
return RoundRobinGroupChatManager(
@@ -137,6 +146,7 @@ class RoundRobinGroupChat(BaseGroupChat):
participant_topic_types,
participant_descriptions,
termination_condition,
+ max_turns,
)
return _factory
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 7e8f35832..f618c0d38 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
@@ -33,6 +33,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None,
model_client: ChatCompletionClient,
selector_prompt: str,
allow_repeated_speaker: bool,
@@ -44,6 +45,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):
participant_topic_types,
participant_descriptions,
termination_condition,
+ max_turns,
)
self._model_client = model_client
self._selector_prompt = selector_prompt
@@ -52,6 +54,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):
self._selector_func = selector_func
async def reset(self) -> None:
+ self._current_turn = 0
self._message_thread.clear()
if self._termination_condition is not None:
await self._termination_condition.reset()
@@ -178,6 +181,7 @@ class SelectorGroupChat(BaseGroupChat):
to select the next speaker.
termination_condition (TerminationCondition, optional): The termination condition for the group chat. Defaults to None.
Without a termination condition, the group chat will run indefinitely.
+ 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
@@ -309,6 +313,7 @@ class SelectorGroupChat(BaseGroupChat):
model_client: ChatCompletionClient,
*,
termination_condition: TerminationCondition | None = None,
+ max_turns: int | None = None,
selector_prompt: str = """You are in a role play game. The following roles are available:
{roles}.
Read the following conversation. Then select the next role from {participants} to play. Only return the role.
@@ -321,7 +326,10 @@ Read the above conversation. Then select the next role from {participants} to pl
selector_func: Callable[[Sequence[AgentMessage]], str | None] | None = None,
):
super().__init__(
- participants, group_chat_manager_class=SelectorGroupChatManager, termination_condition=termination_condition
+ participants,
+ group_chat_manager_class=SelectorGroupChatManager,
+ termination_condition=termination_condition,
+ max_turns=max_turns,
)
# Validate the participants.
if len(participants) < 2:
@@ -345,6 +353,7 @@ Read the above conversation. Then select the next role from {participants} to pl
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None,
) -> Callable[[], BaseGroupChatManager]:
return lambda: SelectorGroupChatManager(
group_topic_type,
@@ -352,6 +361,7 @@ Read the above conversation. Then select the next role from {participants} to pl
participant_topic_types,
participant_descriptions,
termination_condition,
+ max_turns,
self._model_client,
self._selector_prompt,
self._allow_repeated_speaker,
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py
index f3116d75f..d37684feb 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py
@@ -20,6 +20,7 @@ class SwarmGroupChatManager(BaseGroupChatManager):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None,
) -> None:
super().__init__(
group_topic_type,
@@ -27,10 +28,12 @@ class SwarmGroupChatManager(BaseGroupChatManager):
participant_topic_types,
participant_descriptions,
termination_condition,
+ max_turns,
)
self._current_speaker = participant_topic_types[0]
async def reset(self) -> None:
+ self._current_turn = 0
self._message_thread.clear()
if self._termination_condition is not None:
await self._termination_condition.reset()
@@ -59,6 +62,7 @@ class Swarm(BaseGroupChat):
participants (List[ChatAgent]): The agents participating in the group chat. The first agent in the list is the initial speaker.
termination_condition (TerminationCondition, optional): The termination condition for the group chat. Defaults to None.
Without a termination condition, the group chat will run indefinitely.
+ max_turns (int, optional): The maximum number of turns in the group chat before stopping. Defaults to None, meaning no limit.
Examples:
@@ -96,10 +100,16 @@ class Swarm(BaseGroupChat):
"""
def __init__(
- self, participants: List[ChatAgent], termination_condition: TerminationCondition | None = None
+ self,
+ participants: List[ChatAgent],
+ termination_condition: TerminationCondition | None = None,
+ max_turns: int | None = None,
) -> None:
super().__init__(
- participants, group_chat_manager_class=SwarmGroupChatManager, termination_condition=termination_condition
+ participants,
+ group_chat_manager_class=SwarmGroupChatManager,
+ termination_condition=termination_condition,
+ max_turns=max_turns,
)
# The first participant must be able to produce handoff messages.
first_participant = self._participants[0]
@@ -113,6 +123,7 @@ class Swarm(BaseGroupChat):
participant_topic_types: List[str],
participant_descriptions: List[str],
termination_condition: TerminationCondition | None,
+ max_turns: int | None,
) -> Callable[[], SwarmGroupChatManager]:
def _factory() -> SwarmGroupChatManager:
return SwarmGroupChatManager(
@@ -121,6 +132,7 @@ class Swarm(BaseGroupChat):
participant_topic_types,
participant_descriptions,
termination_condition,
+ max_turns,
)
return _factory
diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.py
index cd792f73d..11eb2c925 100644
--- a/python/packages/autogen-agentchat/tests/test_group_chat.py
+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py
@@ -349,6 +349,40 @@ async def test_round_robin_group_chat_with_resume_and_reset() -> None:
assert result.stop_reason is not None
+async def test_round_group_chat_max_turn() -> None:
+ agent_1 = _EchoAgent("agent_1", description="echo agent 1")
+ agent_2 = _EchoAgent("agent_2", description="echo agent 2")
+ agent_3 = _EchoAgent("agent_3", description="echo agent 3")
+ agent_4 = _EchoAgent("agent_4", description="echo agent 4")
+ team = RoundRobinGroupChat(participants=[agent_1, agent_2, agent_3, agent_4], max_turns=3)
+ result = await team.run(
+ task="Write a program that prints 'Hello, world!'",
+ )
+ assert len(result.messages) == 4
+ assert result.messages[1].source == "agent_1"
+ assert result.messages[2].source == "agent_2"
+ assert result.messages[3].source == "agent_3"
+ assert result.stop_reason is not None
+
+ # Resume.
+ result = await team.run()
+ assert len(result.messages) == 3
+ assert result.messages[0].source == "agent_4"
+ assert result.messages[1].source == "agent_1"
+ assert result.messages[2].source == "agent_2"
+ assert result.stop_reason is not None
+
+ # Reset.
+ await team.reset()
+ result = await team.run(task="Write a program that prints 'Hello, world!'")
+ assert len(result.messages) == 4
+ assert result.messages[1].source == "agent_1"
+ assert result.messages[2].source == "agent_2"
+ assert result.messages[3].source == "agent_3"
+ assert result.stop_reason is not None
+
+
@pytest.mark.asyncio
async def test_selector_group_chat(monkeypatch: pytest.MonkeyPatch) -> None:
model = "gpt-4o-2024-05-13"
diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb
index 3f567fce2..08986bfe3 100644
--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb
+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/teams.ipynb
@@ -599,7 +599,45 @@
"### Pause for User Input\n",
"\n",
"Often times, team needs additional input from the application (i.e., user)\n",
- "to continue processing the task.\n",
+ "to continue processing the task. We will show two possible ways to do it:\n",
+ "\n",
+ "- Set the maximum number of turns such that the team stops after the specified number of turns.\n",
+ "- Use the {py:class}`~autogen_agentchat.task.HandoffTermination` termination condition.\n",
+ "\n",
+ "You can also use custom termination conditions, see [Termination Conditions](./termination.ipynb)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Maximum Number of Turns\n",
+ "\n",
+ "This is the simplest way to pause the team for user input. For example,\n",
+ "you can set the maximum number of turns to 1 such that the team stops right\n",
+ "after the first agent responds. This is useful when you want the user\n",
+ "to constantly engage with the team, such as in a chatbot scenario.\n",
+ "\n",
+ "Simply set the `max_turns` parameter in the {py:meth}`~autogen_agentchat.teams.RoundRobinGroupChat` constructor.\n",
+ "\n",
+ "```python\n",
+ "team = RoundRobinGroupChat([...], max_turns=1)\n",
+ "```\n",
+ "\n",
+ "Once the team stops, the turn count will be reset. When you resume the team,\n",
+ "it will start from 0 again.\n",
+ "\n",
+ "Note that `max_turn` is specific to the team class and is currently only supported by\n",
+ "{py:class}`~autogen_agentchat.teams.RoundRobinGroupChat`, {py:class}`~autogen_agentchat.teams.SelectorGroupChat`, and {py:class}`~autogen_agentchat.teams.Swarm`.\n",
+ "When used with termination conditions, the team will stop when either condition is met."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Using Handoff to Pause Team\n",
+ "\n",
"You can use the {py:class}`~autogen_agentchat.task.HandoffTermination` termination condition\n",
"to stop the team when an agent sends a {py:class}`~autogen_agentchat.messages.HandoffMessage` message.\n",
"\n",
@@ -744,7 +782,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.11.5"
+ "version": "3.12.6"
}
},
"nbformat": 4,