Skip to content

Commit 75b00e7

Browse files
authored
Agentchat move termination (microsoft#3992)
1 parent 0f4dd0c commit 75b00e7

File tree

6 files changed

+40
-28
lines changed

6 files changed

+40
-28
lines changed

python/packages/autogen-agentchat/src/autogen_agentchat/task/_terminations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ async def __call__(self, messages: Sequence[ChatMessage]) -> StopMessage | None:
4848
self._message_count += len(messages)
4949
if self._message_count >= self._max_messages:
5050
return StopMessage(
51-
content=f"Maximal number of messages {self._max_messages} reached, current message count: {self._message_count}",
51+
content=f"Maximum number of messages {self._max_messages} reached, current message count: {self._message_count}",
5252
source="MaxMessageTermination",
5353
)
5454
return None

python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,20 @@ class BaseGroupChat(Team, ABC):
2828
create a subclass of :class:`BaseGroupChat` that uses the group chat manager.
2929
"""
3030

31-
def __init__(self, participants: List[ChatAgent], group_chat_manager_class: type[BaseGroupChatManager]):
31+
def __init__(
32+
self,
33+
participants: List[ChatAgent],
34+
group_chat_manager_class: type[BaseGroupChatManager],
35+
termination_condition: TerminationCondition | None = None,
36+
):
3237
if len(participants) == 0:
3338
raise ValueError("At least one participant is required.")
3439
if len(participants) != len(set(participant.name for participant in participants)):
3540
raise ValueError("The participant names must be unique.")
3641
self._participants = participants
3742
self._team_id = str(uuid.uuid4())
3843
self._base_group_chat_manager_class = group_chat_manager_class
44+
self._termination_condition = termination_condition
3945

4046
@abstractmethod
4147
def _create_group_chat_manager_factory(
@@ -109,7 +115,7 @@ async def run(
109115
group_topic_type=group_topic_type,
110116
participant_topic_types=participant_topic_types,
111117
participant_descriptions=participant_descriptions,
112-
termination_condition=termination_condition,
118+
termination_condition=termination_condition or self._termination_condition,
113119
),
114120
)
115121
# Add subscriptions for the group chat manager.

python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_round_robin_group_chat.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,12 @@ class RoundRobinGroupChat(BaseGroupChat):
8282
8383
"""
8484

85-
def __init__(self, participants: List[ChatAgent]):
86-
super().__init__(participants, group_chat_manager_class=RoundRobinGroupChatManager)
85+
def __init__(self, participants: List[ChatAgent], termination_condition: TerminationCondition | None = None):
86+
super().__init__(
87+
participants,
88+
termination_condition=termination_condition,
89+
group_chat_manager_class=RoundRobinGroupChatManager,
90+
)
8791

8892
def _create_group_chat_manager_factory(
8993
self,

python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_selector_group_chat.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,8 @@ def _mentioned_agents(self, message_content: str, agent_names: List[str]) -> Dic
140140
+ re.escape(name.replace("_", r"\_"))
141141
+ r")(?=\W)"
142142
)
143-
count = len(re.findall(regex, f" {message_content} ")) # Pad the message to help with matching
143+
# Pad the message to help with matching
144+
count = len(re.findall(regex, f" {message_content} "))
144145
if count > 0:
145146
mentions[name] = count
146147
return mentions
@@ -184,6 +185,7 @@ def __init__(
184185
participants: List[ChatAgent],
185186
model_client: ChatCompletionClient,
186187
*,
188+
termination_condition: TerminationCondition | None = None,
187189
selector_prompt: str = """You are in a role play game. The following roles are available:
188190
{roles}.
189191
Read the following conversation. Then select the next role from {participants} to play. Only return the role.
@@ -194,7 +196,9 @@ def __init__(
194196
""",
195197
allow_repeated_speaker: bool = False,
196198
):
197-
super().__init__(participants, group_chat_manager_class=SelectorGroupChatManager)
199+
super().__init__(
200+
participants, termination_condition=termination_condition, group_chat_manager_class=SelectorGroupChatManager
201+
)
198202
# Validate the participants.
199203
if len(participants) < 2:
200204
raise ValueError("At least two participants are required for SelectorGroupChat.")

python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_swarm_group_chat.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,10 @@ class Swarm(BaseGroupChat):
8282
await team.run("What is bob's birthday?", termination_condition=MaxMessageTermination(3))
8383
"""
8484

85-
def __init__(self, participants: List[ChatAgent]):
86-
super().__init__(participants, group_chat_manager_class=SwarmGroupChatManager)
85+
def __init__(self, participants: List[ChatAgent], termination_condition: TerminationCondition | None = None):
86+
super().__init__(
87+
participants, termination_condition=termination_condition, group_chat_manager_class=SwarmGroupChatManager
88+
)
8789

8890
def _create_group_chat_manager_factory(
8991
self,

python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/quickstart.ipynb

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -37,32 +37,32 @@
3737
"text": [
3838
"\n",
3939
"--------------------------------------------------------------------------- \n",
40-
"\u001b[91m[2024-10-23T12:15:51.582079]:\u001b[0m\n",
40+
"\u001b[91m[2024-10-29T15:48:06.329810]:\u001b[0m\n",
4141
"\n",
4242
"What is the weather in New York?\n",
4343
"--------------------------------------------------------------------------- \n",
44-
"\u001b[91m[2024-10-23T12:15:52.745820], writing_agent:\u001b[0m\n",
44+
"\u001b[91m[2024-10-29T15:48:08.085839], weather_agent:\u001b[0m\n",
4545
"\n",
46-
"The weather in New York is currently 73 degrees and sunny. TERMINATE\n",
46+
"The weather in New York is 73 degrees and sunny.\n",
4747
"--------------------------------------------------------------------------- \n",
48-
"\u001b[91m[2024-10-23T12:15:52.746210], Termination:\u001b[0m\n",
48+
"\u001b[91m[2024-10-29T15:48:08.086180], Termination:\u001b[0m\n",
4949
"\n",
50-
"Maximal number of messages 1 reached, current message count: 1\n",
51-
" TaskResult(messages=[TextMessage(source='user', content='What is the weather in New York?'), StopMessage(source='writing_agent', content='The weather in New York is currently 73 degrees and sunny. TERMINATE')])\n"
50+
"Maximum number of messages 2 reached, current message count: 2\n",
51+
" TaskResult(messages=[TextMessage(source='user', content='What is the weather in New York?'), TextMessage(source='weather_agent', content='The weather in New York is 73 degrees and sunny.')])\n"
5252
]
5353
}
5454
],
5555
"source": [
5656
"import logging\n",
5757
"\n",
5858
"from autogen_agentchat import EVENT_LOGGER_NAME\n",
59-
"from autogen_agentchat.agents import ToolUseAssistantAgent\n",
59+
"from autogen_agentchat.agents import AssistantAgent\n",
6060
"from autogen_agentchat.logging import ConsoleLogHandler\n",
6161
"from autogen_agentchat.task import MaxMessageTermination\n",
6262
"from autogen_agentchat.teams import RoundRobinGroupChat\n",
63-
"from autogen_core.components.tools import FunctionTool\n",
6463
"from autogen_ext.models import OpenAIChatCompletionClient\n",
6564
"\n",
65+
"# set up logging. You can define your own logger\n",
6666
"logger = logging.getLogger(EVENT_LOGGER_NAME)\n",
6767
"logger.addHandler(ConsoleLogHandler())\n",
6868
"logger.setLevel(logging.INFO)\n",
@@ -73,22 +73,18 @@
7373
" return f\"The weather in {city} is 73 degrees and Sunny.\"\n",
7474
"\n",
7575
"\n",
76-
"# wrap the tool for use with the agent\n",
77-
"get_weather_tool = FunctionTool(get_weather, description=\"Get the weather for a city\")\n",
78-
"\n",
7976
"# define an agent\n",
80-
"weather_agent = ToolUseAssistantAgent(\n",
81-
" name=\"writing_agent\",\n",
77+
"weather_agent = AssistantAgent(\n",
78+
" name=\"weather_agent\",\n",
8279
" model_client=OpenAIChatCompletionClient(model=\"gpt-4o-2024-08-06\"),\n",
83-
" registered_tools=[get_weather_tool],\n",
80+
" tools=[get_weather],\n",
8481
")\n",
8582
"\n",
8683
"# add the agent to a team\n",
87-
"agent_team = RoundRobinGroupChat([weather_agent])\n",
84+
"agent_team = RoundRobinGroupChat([weather_agent], termination_condition=MaxMessageTermination(max_messages=2))\n",
8885
"# Note: if running in a Python file directly you'll need to use asyncio.run(agent_team.run(...)) instead of await agent_team.run(...)\n",
8986
"result = await agent_team.run(\n",
9087
" task=\"What is the weather in New York?\",\n",
91-
" termination_condition=MaxMessageTermination(max_messages=1),\n",
9288
")\n",
9389
"print(\"\\n\", result)"
9490
]
@@ -97,7 +93,7 @@
9793
"cell_type": "markdown",
9894
"metadata": {},
9995
"source": [
100-
"The code snippet above introduces two high level concepts in AgentChat: `Agent` and `Team`. An Agent helps us define what actions are taken when a message is received. Specifically, we use the `ToolUseAssistantAgent` preset - an agent that can be given a function that it can then use to address tasks. A Team helps us define the rules for how agents interact with each other. In the `RoundRobinGroupChat` team, agents receive messages in a sequential round-robin fashion. "
96+
"The code snippet above introduces two high level concepts in AgentChat: `Agent` and `Team`. An Agent helps us define what actions are taken when a message is received. Specifically, we use the `AssistantAgent` preset - an agent that can be given tools (functions) that it can then use to address tasks. A Team helps us define the rules for how agents interact with each other. In the `RoundRobinGroupChat` team, agents receive messages in a sequential round-robin fashion. "
10197
]
10298
},
10399
{
@@ -113,7 +109,7 @@
113109
],
114110
"metadata": {
115111
"kernelspec": {
116-
"display_name": ".venv",
112+
"display_name": "agnext",
117113
"language": "python",
118114
"name": "python3"
119115
},
@@ -127,7 +123,7 @@
127123
"name": "python",
128124
"nbconvert_exporter": "python",
129125
"pygments_lexer": "ipython3",
130-
"version": "3.12.6"
126+
"version": "3.11.9"
131127
}
132128
},
133129
"nbformat": 4,

0 commit comments

Comments
 (0)