A programming framework for agentic AI
[FEATURE] Option to emit group chat manager messages in AgentChat (#6303)
EeS844de21c00de
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py b/python/packages/autogen-agentchat/src/autogen_agentchat/messages.pyindex da67e07fd..206bcc6e4 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/messages.py@@ -519,6 +519,18 @@ class ThoughtEvent(BaseAgentEvent):return self.content+class SelectSpeakerEvent(BaseAgentEvent):+ """An event signaling the selection of speakers for a conversation."""++ content: List[str]+ """The names of the selected speakers."""++ type: Literal["SelectSpeakerEvent"] = "SelectSpeakerEvent"++ def to_text(self) -> str:+ return str(self.content)++class MessageFactory:""":meta private:@@ -541,6 +553,7 @@ class MessageFactory:self._message_types[UserInputRequestedEvent.__name__] = UserInputRequestedEventself._message_types[ModelClientStreamingChunkEvent.__name__] = ModelClientStreamingChunkEventself._message_types[ThoughtEvent.__name__] = ThoughtEvent+ self._message_types[SelectSpeakerEvent.__name__] = SelectSpeakerEventself._message_types[CodeGenerationEvent.__name__] = CodeGenerationEventself._message_types[CodeExecutionEvent.__name__] = CodeExecutionEvent@@ -596,6 +609,7 @@ AgentEvent = Annotated[| UserInputRequestedEvent| ModelClientStreamingChunkEvent| ThoughtEvent+ | SelectSpeakerEvent| CodeGenerationEvent| CodeExecutionEvent,Field(discriminator="type"),@@ -623,6 +637,7 @@ __all__ = ["UserInputRequestedEvent","ModelClientStreamingChunkEvent","ThoughtEvent",+ "SelectSpeakerEvent","MessageFactory","CodeGenerationEvent","CodeExecutionEvent",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.pyindex 23efbf459..efc4dc3f0 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@@ -55,6 +55,7 @@ class BaseGroupChat(Team, ABC, ComponentBase[BaseModel]):max_turns: int | None = None,runtime: AgentRuntime | None = None,custom_message_types: List[type[BaseAgentEvent | BaseChatMessage]] | None = None,+ emit_team_events: bool = False,):if len(participants) == 0:raise ValueError("At least one participant is required.")@@ -123,6 +124,9 @@ class BaseGroupChat(Team, ABC, ComponentBase[BaseModel]):# Flag to track if the group chat is running.self._is_running = False+ # Flag to track if the team events should be emitted.+ self._emit_team_events = emit_team_events+@abstractmethoddef _create_group_chat_manager_factory(self,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.pyindex 7122894df..afd340762 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@@ -1,11 +1,11 @@import asynciofrom abc import ABC, abstractmethod-from typing import Any, List+from typing import Any, List, Sequencefrom autogen_core import DefaultTopicId, MessageContext, event, rpcfrom ...base import TerminationCondition-from ...messages import BaseAgentEvent, BaseChatMessage, MessageFactory, StopMessage+from ...messages import BaseAgentEvent, BaseChatMessage, MessageFactory, SelectSpeakerEvent, StopMessagefrom ._events import (GroupChatAgentResponse,GroupChatError,@@ -45,6 +45,7 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):termination_condition: TerminationCondition | None,max_turns: int | None,message_factory: MessageFactory,+ emit_team_events: bool = False,):super().__init__(description="Group chat manager",@@ -77,6 +78,7 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):self._max_turns = max_turnsself._current_turn = 0self._message_factory = message_factory+ self._emit_team_events = emit_team_events@rpcasync def handle_start(self, message: GroupChatStart, ctx: MessageContext) -> None:@@ -116,15 +118,9 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):self._message_thread.extend(message.messages)# Check termination condition after processing all messages- if self._termination_condition is not None:- stop_message = await self._termination_condition(message.messages)- if stop_message is not None:- # Reset the termination condition.- await self._termination_condition.reset()- # Signal termination to the caller of the team.- await self._signal_termination(stop_message)- # Stop the group chat.- return+ if await self._apply_termination_condition(message.messages):+ # Stop the group chat.+ return# Select a speaker to start/continue the conversationspeaker_name_future = asyncio.ensure_future(self.select_speaker(self._message_thread))@@ -133,6 +129,9 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):speaker_name = await speaker_name_futureif speaker_name not in self._participant_name_to_topic_type:raise RuntimeError(f"Speaker {speaker_name} not found in participant names.")+ await self._log_speaker_selection(speaker_name)++ # Send the message to the next speakerspeaker_topic_type = self._participant_name_to_topic_type[speaker_name]await self.publish_message(GroupChatRequestPublish(),@@ -153,34 +152,9 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):delta.append(message.agent_response.chat_message)# Check if the conversation should be terminated.- if self._termination_condition is not None:- stop_message = await self._termination_condition(delta)- if stop_message is not None:- # Reset the termination conditions and turn count.- await self._termination_condition.reset()- self._current_turn = 0- # Signal termination to the caller of the team.- await self._signal_termination(stop_message)- # Stop the group chat.- 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=self._name,- )- # Reset the termination conditions and turn count.- if self._termination_condition is not None:- await self._termination_condition.reset()- self._current_turn = 0- # Signal termination to the caller of the team.- await self._signal_termination(stop_message)- # Stop the group chat.- return+ if await self._apply_termination_condition(delta, increment_turn_count=True):+ # Stop the group chat.+ return# Select a speaker to continue the conversation.speaker_name_future = asyncio.ensure_future(self.select_speaker(self._message_thread))@@ -189,6 +163,9 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):speaker_name = await speaker_name_futureif speaker_name not in self._participant_name_to_topic_type:raise RuntimeError(f"Speaker {speaker_name} not found in participant names.")+ await self._log_speaker_selection(speaker_name)++ # Send the message to the next speakersspeaker_topic_type = self._participant_name_to_topic_type[speaker_name]await self.publish_message(GroupChatRequestPublish(),@@ -202,6 +179,51 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):# Raise the exception to the runtime.raise+ async def _apply_termination_condition(+ self, delta: Sequence[BaseAgentEvent | BaseChatMessage], increment_turn_count: bool = False+ ) -> bool:+ """Apply the termination condition to the delta and return True if the conversation should be terminated.+ It also resets the termination condition and turn count, and signals termination to the caller of the team."""+ if self._termination_condition is not None:+ stop_message = await self._termination_condition(delta)+ if stop_message is not None:+ # Reset the termination conditions and turn count.+ await self._termination_condition.reset()+ self._current_turn = 0+ # Signal termination to the caller of the team.+ await self._signal_termination(stop_message)+ # Stop the group chat.+ return True+ if increment_turn_count:+ # 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=self._name,+ )+ # Reset the termination conditions and turn count.+ if self._termination_condition is not None:+ await self._termination_condition.reset()+ self._current_turn = 0+ # Signal termination to the caller of the team.+ await self._signal_termination(stop_message)+ # Stop the group chat.+ return True+ return False++ async def _log_speaker_selection(self, speaker_name: str) -> None:+ """Log the selected speaker to the output message queue."""+ select_msg = SelectSpeakerEvent(content=[speaker_name], source=self._name)+ if self._emit_team_events:+ await self.publish_message(+ GroupChatMessage(message=select_msg),+ topic_id=DefaultTopicId(type=self._output_topic_type),+ )+ await self._output_message_queue.put(select_msg)+async def _signal_termination(self, message: StopMessage) -> None:termination_event = GroupChatTermination(message=message)# Log the early stop message.diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_group_chat.pyindex 6cc32701e..60b18df9f 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_group_chat.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_group_chat.py@@ -28,6 +28,7 @@ class MagenticOneGroupChatConfig(BaseModel):max_turns: int | None = Nonemax_stalls: intfinal_answer_prompt: str+ emit_team_events: bool = Falseclass MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig]):@@ -46,6 +47,7 @@ class MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig])max_turns (int, optional): The maximum number of turns in the group chat before stopping. Defaults to 20.max_stalls (int, optional): The maximum number of stalls allowed before re-planning. Defaults to 3.final_answer_prompt (str, optional): The LLM prompt used to generate the final answer or response from the team's transcript. A default (sensible for GPT-4o class models) is provided.+ emit_team_events (bool, optional): Whether to emit team events through :meth:`BaseGroupChat.run_stream`. Defaults to False.Raises:ValueError: In orchestration logic if progress ledger does not have required keys or if next speaker is not valid.@@ -103,6 +105,7 @@ class MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig])runtime: AgentRuntime | None = None,max_stalls: int = 3,final_answer_prompt: str = ORCHESTRATOR_FINAL_ANSWER_PROMPT,+ emit_team_events: bool = False,):super().__init__(participants,@@ -111,6 +114,7 @@ class MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig])termination_condition=termination_condition,max_turns=max_turns,runtime=runtime,+ emit_team_events=emit_team_events,)# Validate the participants.@@ -147,6 +151,7 @@ class MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig])self._final_answer_prompt,output_message_queue,termination_condition,+ self._emit_team_events,)def _to_config(self) -> MagenticOneGroupChatConfig:@@ -159,6 +164,7 @@ class MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig])max_turns=self._max_turns,max_stalls=self._max_stalls,final_answer_prompt=self._final_answer_prompt,+ emit_team_events=self._emit_team_events,)@classmethod@@ -175,4 +181,5 @@ class MagenticOneGroupChat(BaseGroupChat, Component[MagenticOneGroupChatConfig])max_turns=config.max_turns,max_stalls=config.max_stalls,final_answer_prompt=config.final_answer_prompt,+ emit_team_events=config.emit_team_events,)diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_orchestrator.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_orchestrator.pyindex 4e6681315..78bf3929a 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_orchestrator.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_magentic_one/_magentic_one_orchestrator.py@@ -20,6 +20,7 @@ from ....messages import (HandoffMessage,MessageFactory,MultiModalMessage,+ SelectSpeakerEvent,StopMessage,TextMessage,ToolCallExecutionEvent,@@ -68,6 +69,7 @@ class MagenticOneOrchestrator(BaseGroupChatManager):final_answer_prompt: str,output_message_queue: asyncio.Queue[BaseAgentEvent | BaseChatMessage | GroupChatTermination],termination_condition: TerminationCondition | None,+ emit_team_events: bool,):super().__init__(name,@@ -80,6 +82,7 @@ class MagenticOneOrchestrator(BaseGroupChatManager):termination_condition,max_turns,message_factory,+ emit_team_events=emit_team_events,)self._model_client = model_clientself._max_stalls = max_stalls@@ -405,6 +408,15 @@ class MagenticOneOrchestrator(BaseGroupChatManager):cancellation_token=cancellation_token,)+ # Send the message to the next speaker+ if self._emit_team_events:+ select_msg = SelectSpeakerEvent(content=[next_speaker], source=self._name)+ await self.publish_message(+ GroupChatMessage(message=select_msg),+ topic_id=DefaultTopicId(type=self._output_topic_type),+ )+ await self._output_message_queue.put(select_msg)+async def _update_task_ledger(self, cancellation_token: CancellationToken) -> None:"""Update the task ledger (outer loop) with the latest facts and plan."""context = self._thread_to_context()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.pyindex 8d9218619..915490c20 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@@ -28,6 +28,7 @@ class RoundRobinGroupChatManager(BaseGroupChatManager):termination_condition: TerminationCondition | None,max_turns: int | None,message_factory: MessageFactory,+ emit_team_events: bool,) -> None:super().__init__(name,@@ -40,6 +41,7 @@ class RoundRobinGroupChatManager(BaseGroupChatManager):termination_condition,max_turns,message_factory,+ emit_team_events,)self._next_speaker_index = 0@@ -81,6 +83,7 @@ class RoundRobinGroupChatConfig(BaseModel):participants: List[ComponentModel]termination_condition: ComponentModel | None = Nonemax_turns: int | None = None+ emit_team_events: bool = Falseclass RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):@@ -94,6 +97,7 @@ class RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):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.+ emit_team_events (bool, optional): Whether to emit team events through :meth:`BaseGroupChat.run_stream`. Defaults to False.Raises:ValueError: If no participants are provided or if participant names are not unique.@@ -167,6 +171,7 @@ class RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):max_turns: int | None = None,runtime: AgentRuntime | None = None,custom_message_types: List[type[BaseAgentEvent | BaseChatMessage]] | None = None,+ emit_team_events: bool = False,) -> None:super().__init__(participants,@@ -176,6 +181,7 @@ class RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):max_turns=max_turns,runtime=runtime,custom_message_types=custom_message_types,+ emit_team_events=emit_team_events,)def _create_group_chat_manager_factory(@@ -203,6 +209,7 @@ class RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):termination_condition,max_turns,message_factory,+ self._emit_team_events,)return _factory@@ -214,6 +221,7 @@ class RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):participants=participants,termination_condition=termination_condition,max_turns=self._max_turns,+ emit_team_events=self._emit_team_events,)@classmethod@@ -222,4 +230,9 @@ class RoundRobinGroupChat(BaseGroupChat, Component[RoundRobinGroupChatConfig]):termination_condition = (TerminationCondition.load_component(config.termination_condition) if config.termination_condition else None)- return cls(participants, termination_condition=termination_condition, max_turns=config.max_turns)+ return cls(+ participants,+ termination_condition=termination_condition,+ max_turns=config.max_turns,+ emit_team_events=config.emit_team_events,+ )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.pyindex 1aa5aa337..2a7b15889 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@@ -55,6 +55,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):selector_func: Optional[SelectorFuncType],max_selector_attempts: int,candidate_func: Optional[CandidateFuncType],+ emit_team_events: bool,) -> None:super().__init__(name,@@ -67,6 +68,7 @@ class SelectorGroupChatManager(BaseGroupChatManager):termination_condition,max_turns,message_factory,+ emit_team_events,)self._model_client = model_clientself._selector_prompt = selector_prompt@@ -278,6 +280,7 @@ class SelectorGroupChatConfig(BaseModel):allow_repeated_speaker: bool# selector_func: ComponentModel | Nonemax_selector_attempts: int = 3+ emit_team_events: bool = Falseclass SelectorGroupChat(BaseGroupChat, Component[SelectorGroupChatConfig]):@@ -307,7 +310,7 @@ class SelectorGroupChat(BaseGroupChat, Component[SelectorGroupChatConfig]):A custom function that takes the conversation history and returns a filtered list of candidates for the next speakerselection using model. If the function returns an empty list or `None`, `SelectorGroupChat` will raise a `ValueError`.This function is only used if `selector_func` is not set. The `allow_repeated_speaker` will be ignored if set.-+ emit_team_events (bool, optional): Whether to emit team events through :meth:`BaseGroupChat.run_stream`. Defaults to False.Raises:ValueError: If the number of participants is less than two or if the selector prompt is invalid.@@ -449,6 +452,7 @@ Read the above conversation. Then select the next role from {participants} to plselector_func: Optional[SelectorFuncType] = None,candidate_func: Optional[CandidateFuncType] = None,custom_message_types: List[type[BaseAgentEvent | BaseChatMessage]] | None = None,+ emit_team_events: bool = False,):super().__init__(participants,@@ -458,6 +462,7 @@ Read the above conversation. Then select the next role from {participants} to plmax_turns=max_turns,runtime=runtime,custom_message_types=custom_message_types,+ emit_team_events=emit_team_events,)# Validate the participants.if len(participants) < 2:@@ -499,6 +504,7 @@ Read the above conversation. Then select the next role from {participants} to plself._selector_func,self._max_selector_attempts,self._candidate_func,+ self._emit_team_events,)def _to_config(self) -> SelectorGroupChatConfig:@@ -511,6 +517,7 @@ Read the above conversation. Then select the next role from {participants} to plallow_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,+ emit_team_events=self._emit_team_events,)@classmethod@@ -528,4 +535,5 @@ Read the above conversation. Then select the next role from {participants} to pl# selector_func=ComponentLoader.load_component(config.selector_func, Callable[[Sequence[BaseAgentEvent | BaseChatMessage]], str | None])# if config.selector_func# else None,+ emit_team_events=config.emit_team_events,)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.pyindex 8a810896f..1c0637cd1 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@@ -27,6 +27,7 @@ class SwarmGroupChatManager(BaseGroupChatManager):termination_condition: TerminationCondition | None,max_turns: int | None,message_factory: MessageFactory,+ emit_team_events: bool,) -> None:super().__init__(name,@@ -39,6 +40,7 @@ class SwarmGroupChatManager(BaseGroupChatManager):termination_condition,max_turns,message_factory,+ emit_team_events,)self._current_speaker = self._participant_names[0]@@ -111,6 +113,7 @@ class SwarmConfig(BaseModel):participants: List[ComponentModel]termination_condition: ComponentModel | None = Nonemax_turns: int | None = None+ emit_team_events: bool = Falseclass Swarm(BaseGroupChat, Component[SwarmConfig]):@@ -126,6 +129,7 @@ class Swarm(BaseGroupChat, Component[SwarmConfig]):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.+ emit_team_events (bool, optional): Whether to emit team events through :meth:`BaseGroupChat.run_stream`. Defaults to False.Basic example:@@ -213,6 +217,7 @@ class Swarm(BaseGroupChat, Component[SwarmConfig]):max_turns: int | None = None,runtime: AgentRuntime | None = None,custom_message_types: List[type[BaseAgentEvent | BaseChatMessage]] | None = None,+ emit_team_events: bool = False,) -> None:super().__init__(participants,@@ -222,6 +227,7 @@ class Swarm(BaseGroupChat, Component[SwarmConfig]):max_turns=max_turns,runtime=runtime,custom_message_types=custom_message_types,+ emit_team_events=emit_team_events,)# The first participant must be able to produce handoff messages.first_participant = self._participants[0]@@ -253,6 +259,7 @@ class Swarm(BaseGroupChat, Component[SwarmConfig]):termination_condition,max_turns,message_factory,+ self._emit_team_events,)return _factory@@ -264,6 +271,7 @@ class Swarm(BaseGroupChat, Component[SwarmConfig]):participants=participants,termination_condition=termination_condition,max_turns=self._max_turns,+ emit_team_events=self._emit_team_events,)@classmethod@@ -272,4 +280,9 @@ class Swarm(BaseGroupChat, Component[SwarmConfig]):termination_condition = (TerminationCondition.load_component(config.termination_condition) if config.termination_condition else None)- return cls(participants, termination_condition=termination_condition, max_turns=config.max_turns)+ return cls(+ participants,+ termination_condition=termination_condition,+ max_turns=config.max_turns,+ emit_team_events=config.emit_team_events,+ )diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.pyindex e9aee1ba7..9cf9a1b58 100644--- a/python/packages/autogen-agentchat/tests/test_group_chat.py+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py@@ -19,6 +19,7 @@ from autogen_agentchat.messages import (BaseChatMessage,HandoffMessage,MultiModalMessage,+ SelectSpeakerEvent,StopMessage,StructuredMessage,TextMessage,@@ -277,6 +278,55 @@ async def test_round_robin_group_chat(runtime: AgentRuntime | None) -> None:assert result.messages[1:] == result_2.messages[1:]+async def test_round_robin_group_chat_with_team_event(runtime: AgentRuntime | None) -> None:+ model_client = ReplayChatCompletionClient(+ [+ 'Here is the program\n ```python\nprint("Hello, world!")\n```',+ "TERMINATE",+ ],+ )+ with tempfile.TemporaryDirectory() as temp_dir:+ code_executor_agent = CodeExecutorAgent(+ "code_executor", code_executor=LocalCommandLineCodeExecutor(work_dir=temp_dir)+ )+ coding_assistant_agent = AssistantAgent(+ "coding_assistant",+ model_client=model_client,+ )+ termination = TextMentionTermination("TERMINATE")+ team = RoundRobinGroupChat(+ participants=[coding_assistant_agent, code_executor_agent],+ termination_condition=termination,+ runtime=runtime,+ emit_team_events=True,+ )+ result = await team.run(+ task="Write a program that prints 'Hello, world!'",+ )+ assert len(result.messages) == 7+ assert isinstance(result.messages[0], TextMessage)+ assert isinstance(result.messages[1], SelectSpeakerEvent)+ assert isinstance(result.messages[2], TextMessage)+ assert isinstance(result.messages[3], SelectSpeakerEvent)+ assert isinstance(result.messages[4], TextMessage)+ assert isinstance(result.messages[5], SelectSpeakerEvent)+ assert isinstance(result.messages[6], TextMessage)++ # Test streaming.+ model_client.reset()+ index = 0+ await team.reset()+ async for message in team.run_stream(+ task="Write a program that prints 'Hello, world!'",+ ):+ if isinstance(message, TaskResult):+ assert message == result+ else:+ assert message == result.messages[index]+ index += 1++@pytest.mark.asyncioasync def test_round_robin_group_chat_unknown_task_message_type(runtime: AgentRuntime | None) -> None:model_client = ReplayChatCompletionClient([])@@ -631,6 +681,65 @@ async def test_selector_group_chat(runtime: AgentRuntime | None) -> None:assert result2 == result+async def test_selector_group_chat_with_team_event(runtime: AgentRuntime | None) -> None:+ model_client = ReplayChatCompletionClient(+ ["agent3", "agent2", "agent1", "agent2", "agent1"],+ )+ agent1 = _StopAgent("agent1", description="echo agent 1", stop_at=2)+ agent2 = _EchoAgent("agent2", description="echo agent 2")+ agent3 = _EchoAgent("agent3", description="echo agent 3")+ termination = TextMentionTermination("TERMINATE")+ team = SelectorGroupChat(+ participants=[agent1, agent2, agent3],+ model_client=model_client,+ termination_condition=termination,+ runtime=runtime,+ emit_team_events=True,+ )+ result = await team.run(+ task="Write a program that prints 'Hello, world!'",+ )+ assert len(result.messages) == 11+ assert isinstance(result.messages[0], TextMessage)+ assert isinstance(result.messages[1], SelectSpeakerEvent)+ assert isinstance(result.messages[2], TextMessage)+ assert isinstance(result.messages[3], SelectSpeakerEvent)+ assert isinstance(result.messages[4], TextMessage)+ assert isinstance(result.messages[5], SelectSpeakerEvent)+ assert isinstance(result.messages[6], TextMessage)+ assert isinstance(result.messages[7], SelectSpeakerEvent)+ assert isinstance(result.messages[8], TextMessage)+ assert isinstance(result.messages[9], SelectSpeakerEvent)+ assert isinstance(result.messages[10], StopMessage)+ assert result.messages[0].content == "Write a program that prints 'Hello, world!'"+ assert result.messages[1].content == ["agent3"]+ assert result.messages[2].source == "agent3"+ assert result.messages[3].content == ["agent2"]+ assert result.messages[4].source == "agent2"+ assert result.messages[5].content == ["agent1"]+ assert result.messages[6].source == "agent1"+ assert result.messages[7].content == ["agent2"]+ assert result.messages[8].source == "agent2"+ assert result.messages[9].content == ["agent1"]+ assert result.messages[10].source == "agent1"+ assert result.stop_reason is not None and result.stop_reason == "Text 'TERMINATE' mentioned"++ # Test streaming.+ model_client.reset()+ agent1._count = 0 # pyright: ignore+ index = 0+ await team.reset()+ async for message in team.run_stream(+ task="Write a program that prints 'Hello, world!'",+ ):+ if isinstance(message, TaskResult):+ assert message == result+ else:+ assert message == result.messages[index]+ index += 1++@pytest.mark.asyncio@pytest.mark.parametrize("task",@@ -1019,6 +1128,60 @@ async def test_swarm_handoff(runtime: AgentRuntime | None) -> None:assert manager_1._current_speaker == manager_2._current_speaker # pyright: ignore+async def test_swarm_handoff_with_team_events(runtime: AgentRuntime | None) -> None:+ first_agent = _HandOffAgent("first_agent", description="first agent", next_agent="second_agent")+ second_agent = _HandOffAgent("second_agent", description="second agent", next_agent="third_agent")+ third_agent = _HandOffAgent("third_agent", description="third agent", next_agent="first_agent")++ termination = MaxMessageTermination(6)+ team = Swarm(+ [second_agent, first_agent, third_agent],+ termination_condition=termination,+ runtime=runtime,+ emit_team_events=True,+ )+ result = await team.run(task="task")+ assert len(result.messages) == 11+ assert isinstance(result.messages[0], TextMessage)+ assert isinstance(result.messages[1], SelectSpeakerEvent)+ assert isinstance(result.messages[2], HandoffMessage)+ assert isinstance(result.messages[3], SelectSpeakerEvent)+ assert isinstance(result.messages[4], HandoffMessage)+ assert isinstance(result.messages[5], SelectSpeakerEvent)+ assert isinstance(result.messages[6], HandoffMessage)+ assert isinstance(result.messages[7], SelectSpeakerEvent)+ assert isinstance(result.messages[8], HandoffMessage)+ assert isinstance(result.messages[9], SelectSpeakerEvent)+ assert isinstance(result.messages[10], HandoffMessage)+ assert result.messages[0].content == "task"+ assert result.messages[1].content == ["second_agent"]+ assert result.messages[2].content == "Transferred to third_agent."+ assert result.messages[3].content == ["third_agent"]+ assert result.messages[4].content == "Transferred to first_agent."+ assert result.messages[5].content == ["first_agent"]+ assert result.messages[6].content == "Transferred to second_agent."+ assert result.messages[7].content == ["second_agent"]+ assert result.messages[8].content == "Transferred to third_agent."+ assert result.messages[9].content == ["third_agent"]+ assert result.messages[10].content == "Transferred to first_agent."+ assert (+ result.stop_reason is not None+ and result.stop_reason == "Maximum number of messages 6 reached, current message count: 6"+ )++ # Test streaming.+ index = 0+ await team.reset()+ stream = team.run_stream(task="task")+ async for message in stream:+ if isinstance(message, TaskResult):+ assert message == result+ else:+ assert message == result.messages[index]+ index += 1++@pytest.mark.asyncio@pytest.mark.parametrize("task",