A programming framework for agentic AI
AgentChat pause, resume, and reset (#4088)
Eric Zhu2e3155be2af3
diff --git a/README.md b/README.mdindex 9084b6938..5875a89a1 100644--- a/README.md+++ b/README.md@@ -124,7 +124,7 @@ async def main() -> None:termination = TextMentionTermination("TERMINATE")group_chat = RoundRobinGroupChat([coding_assistant_agent, code_executor_agent], termination_condition=termination)stream = group_chat.run_stream(- "Create a plot of NVDIA and TSLA stock returns YTD from 2024-01-01 and save it to 'nvidia_tesla_2024_ytd.png'."+ task="Create a plot of NVDIA and TSLA stock returns YTD from 2024-01-01 and save it to 'nvidia_tesla_2024_ytd.png'.")async for message in stream:print(message)diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.pyindex 811430564..a11f4a2d6 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_base_chat_agent.py@@ -53,41 +53,49 @@ class BaseChatAgent(ChatAgent, ABC):async def run(self,- task: str,*,+ task: str | None = None,cancellation_token: CancellationToken | None = None,) -> TaskResult:"""Run the agent with the given task and return the result."""if cancellation_token is None:cancellation_token = CancellationToken()- first_message = TextMessage(content=task, source="user")- response = await self.on_messages([first_message], cancellation_token)- messages: List[AgentMessage] = [first_message]+ input_messages: List[ChatMessage] = []+ output_messages: List[AgentMessage] = []+ if task is not None:+ msg = TextMessage(content=task, source="user")+ input_messages.append(msg)+ output_messages.append(msg)+ response = await self.on_messages(input_messages, cancellation_token)if response.inner_messages is not None:- messages += response.inner_messages- messages.append(response.chat_message)- return TaskResult(messages=messages)+ output_messages += response.inner_messages+ output_messages.append(response.chat_message)+ return TaskResult(messages=output_messages)async def run_stream(self,- task: str,*,+ task: str | None = None,cancellation_token: CancellationToken | None = None,) -> AsyncGenerator[AgentMessage | TaskResult, None]:"""Run the agent with the given task and return a stream of messagesand the final task result as the last item in the stream."""if cancellation_token is None:cancellation_token = CancellationToken()- first_message = TextMessage(content=task, source="user")- yield first_message- messages: List[AgentMessage] = [first_message]- async for message in self.on_messages_stream([first_message], cancellation_token):+ input_messages: List[ChatMessage] = []+ output_messages: List[AgentMessage] = []+ if task is not None:+ msg = TextMessage(content=task, source="user")+ input_messages.append(msg)+ output_messages.append(msg)+ yield msg+ async for message in self.on_messages_stream(input_messages, cancellation_token):if isinstance(message, Response):yield message.chat_message- messages.append(message.chat_message)- yield TaskResult(messages=messages)+ output_messages.append(message.chat_message)+ yield TaskResult(messages=output_messages)else:- messages.append(message)+ output_messages.append(message)yield message@abstractmethoddiff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_task.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_task.pyindex 1c33f7ecc..7bb6d1e08 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_task.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_task.py@@ -22,19 +22,27 @@ class TaskRunner(Protocol):async def run(self,- task: str,*,+ task: str | None = None,cancellation_token: CancellationToken | None = None,) -> TaskResult:- """Run the task."""+ """Run the task and return the result.++ The runner is stateful and a subsequent call to this method will continue+ from where the previous call left off. If the task is not specified,+ the runner will continue with the current task."""...def run_stream(self,- task: str,*,+ task: str | None = None,cancellation_token: CancellationToken | None = None,) -> AsyncGenerator[AgentMessage | TaskResult, None]:"""Run the task and produces a stream of messages and the final result- :class:`TaskResult` as the last item in the stream."""+ :class:`TaskResult` as the last item in the stream.++ The runner is stateful and a subsequent call to this method will continue+ from where the previous call left off. If the task is not specified,+ the runner will continue with the current task."""...diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.py b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.pyindex e112a3b51..198d50179 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/base/_team.py@@ -4,4 +4,6 @@ from ._task import TaskRunnerclass Team(TaskRunner, Protocol):- pass+ async def reset(self) -> None:+ """Reset the team and all its participants to its initial state."""+ ...diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.pyindex a2dd74d61..a0ac13604 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py@@ -1,8 +1,10 @@+from ._group_chat._base_group_chat import BaseGroupChatfrom ._group_chat._round_robin_group_chat import RoundRobinGroupChatfrom ._group_chat._selector_group_chat import SelectorGroupChatfrom ._group_chat._swarm_group_chat import Swarm__all__ = [+ "BaseGroupChat","RoundRobinGroupChat","SelectorGroupChat","Swarm",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 cc5c0e581..409080439 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@@ -21,7 +21,7 @@ from ...base import ChatAgent, TaskResult, Team, TerminationConditionfrom ...messages import AgentMessage, TextMessagefrom ._base_group_chat_manager import BaseGroupChatManagerfrom ._chat_agent_container import ChatAgentContainer-from ._events import GroupChatMessage, GroupChatStart, GroupChatTermination+from ._events import GroupChatMessage, GroupChatReset, GroupChatStart, GroupChatTerminationevent_logger = logging.getLogger(EVENT_LOGGER_NAME)@@ -44,10 +44,31 @@ class BaseGroupChat(Team, ABC):if len(participants) != len(set(participant.name for participant in participants)):raise ValueError("The participant names must be unique.")self._participants = participants- self._team_id = str(uuid.uuid4())self._base_group_chat_manager_class = group_chat_manager_classself._termination_condition = termination_condition- self._message_thread: List[AgentMessage] = []++ # Constants for the group chat.+ self._team_id = str(uuid.uuid4())+ self._group_topic_type = "group_topic"+ self._output_topic_type = "output_topic"+ self._group_chat_manager_topic_type = "group_chat_manager"+ self._participant_topic_types: List[str] = [participant.name for participant in participants]+ self._participant_descriptions: List[str] = [participant.description for participant in participants]+ self._collector_agent_type = "collect_output_messages"++ # Constants for the closure agent to collect the output messages.+ self._stop_reason: str | None = None+ self._output_message_queue: asyncio.Queue[AgentMessage | None] = asyncio.Queue()++ # Create a runtime for the team.+ # TODO: The runtime should be created by a managed context.+ self._runtime = SingleThreadedAgentRuntime()++ # Flag to track if the group chat has been initialized.+ self._initialized = False++ # Flag to track if the group chat is running.+ self._is_running = False@abstractmethoddef _create_group_chat_manager_factory(@@ -56,7 +77,6 @@ class BaseGroupChat(Team, ABC):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,) -> Callable[[], BaseGroupChatManager]: ...@@ -75,89 +95,46 @@ class BaseGroupChat(Team, ABC):return _factory- async def run(- self,- task: str,- *,- cancellation_token: CancellationToken | None = None,- ) -> TaskResult:- """Run the team and return the result. The base implementation uses- :meth:`run_stream` to run the team and then returns the final result."""- async for message in self.run_stream(- task,- cancellation_token=cancellation_token,- ):- if isinstance(message, TaskResult):- return message- raise AssertionError("The stream should have returned the final result.")-- async def run_stream(- self,- task: str,- *,- cancellation_token: CancellationToken | None = None,- ) -> AsyncGenerator[AgentMessage | TaskResult, None]:- """Run the team and produces a stream of messages and the final result- of the type :class:`TaskResult` as the last item in the stream."""-- # TODO: runtime is currently a local variable, but it should be stored in- # a managed context so it can be accessed by all nested teams. Also, the runtime- # should be not be started or stopped by the team, but by the context.-- # Create the runtime.- runtime = SingleThreadedAgentRuntime()-+ async def _init(self, runtime: AgentRuntime) -> None:# Constants for the group chat manager.- group_chat_manager_agent_type = AgentType("group_chat_manager")- group_chat_manager_topic_type = group_chat_manager_agent_type.type- group_topic_type = "round_robin_group_topic"- output_topic_type = "output_topic"+ group_chat_manager_agent_type = AgentType(self._group_chat_manager_topic_type)# Register participants.- participant_topic_types: List[str] = []- participant_descriptions: List[str] = []- for participant in self._participants:- # Use the participant name as the agent type and topic type.- agent_type = participant.name- topic_type = participant.name+ for participant, participant_topic_type in zip(self._participants, self._participant_topic_types, strict=False):+ # Use the participant topic type as the agent type.+ agent_type = participant_topic_type# Register the participant factory.await ChatAgentContainer.register(runtime,type=agent_type,- factory=self._create_participant_factory(group_topic_type, output_topic_type, participant),+ factory=self._create_participant_factory(self._group_topic_type, self._output_topic_type, participant),)# Add subscriptions for the participant.- await runtime.add_subscription(TypeSubscription(topic_type=topic_type, agent_type=agent_type))- await runtime.add_subscription(TypeSubscription(topic_type=group_topic_type, agent_type=agent_type))- # Add the participant to the lists.- participant_descriptions.append(participant.description)- participant_topic_types.append(topic_type)+ await runtime.add_subscription(TypeSubscription(topic_type=participant_topic_type, agent_type=agent_type))+ await runtime.add_subscription(TypeSubscription(topic_type=self._group_topic_type, agent_type=agent_type))# Register the group chat manager.await self._base_group_chat_manager_class.register(runtime,type=group_chat_manager_agent_type.type,factory=self._create_group_chat_manager_factory(- group_topic_type=group_topic_type,- output_topic_type=output_topic_type,- participant_topic_types=participant_topic_types,- participant_descriptions=participant_descriptions,- message_thread=self._message_thread,+ group_topic_type=self._group_topic_type,+ output_topic_type=self._output_topic_type,+ participant_topic_types=self._participant_topic_types,+ participant_descriptions=self._participant_descriptions,termination_condition=self._termination_condition,),)# Add subscriptions for the group chat manager.await runtime.add_subscription(- TypeSubscription(topic_type=group_chat_manager_topic_type, agent_type=group_chat_manager_agent_type.type)+ TypeSubscription(+ topic_type=self._group_chat_manager_topic_type, agent_type=group_chat_manager_agent_type.type+ ))await runtime.add_subscription(- TypeSubscription(topic_type=group_topic_type, agent_type=group_chat_manager_agent_type.type)+ TypeSubscription(topic_type=self._group_topic_type, agent_type=group_chat_manager_agent_type.type))- # Create a closure agent to collect the output messages.- stop_reason: str | None = None- output_message_queue: asyncio.Queue[AgentMessage | None] = asyncio.Queue()-async def collect_output_messages(_runtime: AgentRuntime,id: AgentId,@@ -166,34 +143,142 @@ class BaseGroupChat(Team, ABC):) -> None:event_logger.info(message.message)if isinstance(message, GroupChatTermination):- nonlocal stop_reason- stop_reason = message.message.content+ self._stop_reason = message.message.contentreturn- await output_message_queue.put(message.message)+ await self._output_message_queue.put(message.message)await ClosureAgent.register(runtime,- type="collect_output_messages",+ type=self._collector_agent_type,closure=collect_output_messages,subscriptions=lambda: [- TypeSubscription(topic_type=output_topic_type, agent_type="collect_output_messages"),+ TypeSubscription(topic_type=self._output_topic_type, agent_type=self._collector_agent_type),],)+ self._initialized = True++ async def run(+ self,+ *,+ task: str | None = None,+ cancellation_token: CancellationToken | None = None,+ ) -> TaskResult:+ """Run the team and return the result. The base implementation uses+ :meth:`run_stream` to run the team and then returns the final result.++ Example using the :class:`~autogen_agentchat.teams.RoundRobinGroupChat` team:+++ .. code-block:: python++ import asyncio+ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.task import MaxMessageTermination+ from autogen_agentchat.teams import RoundRobinGroupChat+ from autogen_ext.models import OpenAIChatCompletionClient+++ async def main() -> None:+ model_client = OpenAIChatCompletionClient(model="gpt-4o")++ agent1 = AssistantAgent("Assistant1", model_client=model_client)+ agent2 = AssistantAgent("Assistant2", model_client=model_client)+ termination = MaxMessageTermination(3)+ team = RoundRobinGroupChat([agent1, agent2], termination_condition=termination)++ result = await team.run(task="Count from 1 to 10, respond one at a time.")+ print(result)++ # Reset the termination condition.+ await termination.reset()++ # Run the team again without a task.+ result = await team.run()+ print(result)+++ asyncio.run(main())+ """+ result: TaskResult | None = None+ async for message in self.run_stream(+ task=task,+ cancellation_token=cancellation_token,+ ):+ if isinstance(message, TaskResult):+ result = message+ if result is not None:+ return result+ raise AssertionError("The stream should have returned the final result.")++ async def run_stream(+ self,+ *,+ task: str | None = None,+ cancellation_token: CancellationToken | None = None,+ ) -> AsyncGenerator[AgentMessage | TaskResult, None]:+ """Run the team and produces a stream of messages and the final result+ of the type :class:`TaskResult` as the last item in the stream.++ Example using the :class:`~autogen_agentchat.teams.RoundRobinGroupChat` team:++ .. code-block:: python++ import asyncio+ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.task import MaxMessageTermination+ from autogen_agentchat.teams import RoundRobinGroupChat+ from autogen_ext.models import OpenAIChatCompletionClient+++ async def main() -> None:+ model_client = OpenAIChatCompletionClient(model="gpt-4o")++ agent1 = AssistantAgent("Assistant1", model_client=model_client)+ agent2 = AssistantAgent("Assistant2", model_client=model_client)+ termination = MaxMessageTermination(3)+ team = RoundRobinGroupChat([agent1, agent2], termination_condition=termination)++ stream = team.run_stream(task="Count from 1 to 10, respond one at a time.")+ async for message in stream:+ print(message)++ # Reset the termination condition.+ await termination.reset()++ # Run the team again without a task.+ stream = team.run_stream()+ async for message in stream:+ print(message)+++ asyncio.run(main())+ """++ if self._is_running:+ raise ValueError("The team is already running, it cannot run again until it is stopped.")+ self._is_running = True# Start the runtime.- runtime.start()+ # TODO: The runtime should be started by a managed context.+ self._runtime.start()++ if not self._initialized:+ await self._init(self._runtime)- # Run the team by publishing the task to the group chat manager.- first_chat_message = TextMessage(content=task, source="user")- await runtime.publish_message(+ # Run the team by publishing the start message.+ if task is None:+ first_chat_message = None+ else:+ first_chat_message = TextMessage(content=task, source="user")+ await self._runtime.publish_message(GroupChatStart(message=first_chat_message),- topic_id=TopicId(type=group_topic_type, source=self._team_id),+ topic_id=TopicId(type=self._group_topic_type, source=self._team_id),)# Start a coroutine to stop the runtime and signal the output message queue is complete.async def stop_runtime() -> None:- await runtime.stop_when_idle()- await output_message_queue.put(None)+ await self._runtime.stop_when_idle()+ await self._output_message_queue.put(None)shutdown_task = asyncio.create_task(stop_runtime())@@ -201,7 +286,7 @@ class BaseGroupChat(Team, ABC):output_messages: List[AgentMessage] = []# Yield the messsages until the queue is empty.while True:- message = await output_message_queue.get()+ message = await self._output_message_queue.get()if message is None:breakyield message@@ -211,4 +296,74 @@ class BaseGroupChat(Team, ABC):await shutdown_task# Yield the final result.- yield TaskResult(messages=output_messages, stop_reason=stop_reason)+ yield TaskResult(messages=output_messages, stop_reason=self._stop_reason)++ # Indicate that the team is no longer running.+ self._is_running = False++ async def reset(self) -> None:+ """Reset the team and its participants to their initial state.++ This includes the termination condition. The team must be stopped before it can be reset.++ Raises:+ RuntimeError: If the team has not been initialized or is currently running.++ Example using the :class:`~autogen_agentchat.teams.RoundRobinGroupChat` team:++ .. code-block:: python++ import asyncio+ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.task import MaxMessageTermination+ from autogen_agentchat.teams import RoundRobinGroupChat+ from autogen_ext.models import OpenAIChatCompletionClient+++ async def main() -> None:+ model_client = OpenAIChatCompletionClient(model="gpt-4o")++ agent1 = AssistantAgent("Assistant1", model_client=model_client)+ agent2 = AssistantAgent("Assistant2", model_client=model_client)+ termination = MaxMessageTermination(3)+ team = RoundRobinGroupChat([agent1, agent2], termination_condition=termination)+ stream = team.run_stream(task="Count from 1 to 10, respond one at a time.")+ async for message in stream:+ print(message)++ # Reset the team.+ await team.reset()+ stream = team.run_stream(task="Count from 1 to 10, respond one at a time.")+ async for message in stream:+ print(message)+++ asyncio.run(main())+ """++ if not self._initialized:+ raise RuntimeError("The group chat has not been initialized. It must be run before it can be reset.")++ if self._is_running:+ raise RuntimeError("The group chat is currently running. It must be stopped before it can be reset.")+ self._is_running = True++ # Start the runtime.+ self._runtime.start()++ # Send a reset message to the group chat.+ await self._runtime.publish_message(+ GroupChatReset(),+ topic_id=TopicId(type=self._group_topic_type, source=self._team_id),+ )++ # Stop the runtime.+ await self._runtime.stop_when_idle()++ # Reset the output message queue.+ self._stop_reason = None+ while not self._output_message_queue.empty():+ self._output_message_queue.get_nowait()++ # Indicate that the team is no longer running.+ self._is_running = Falsediff --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 ab10c2b86..ebbd9d5c8 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@@ -6,7 +6,13 @@ from autogen_core.components import DefaultTopicId, eventfrom ...base import TerminationConditionfrom ...messages import AgentMessage, StopMessage-from ._events import GroupChatAgentResponse, GroupChatRequestPublish, GroupChatStart, GroupChatTermination+from ._events import (+ GroupChatAgentResponse,+ GroupChatRequestPublish,+ GroupChatReset,+ GroupChatStart,+ GroupChatTermination,+)from ._sequential_routed_agent import SequentialRoutedAgent@@ -28,7 +34,6 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None = None,):super().__init__(description="Group chat manager")@@ -42,16 +47,13 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):raise ValueError("The group topic type must not be in the participant topic types.")self._participant_topic_types = participant_topic_typesself._participant_descriptions = participant_descriptions- self._message_thread = message_thread+ self._message_thread: List[AgentMessage] = []self._termination_condition = termination_condition@eventasync def handle_start(self, message: GroupChatStart, ctx: MessageContext) -> None:"""Handle the start of a group chat by selecting a speaker to start the conversation."""- # Log the start message.- await self.publish_message(message, topic_id=DefaultTopicId(type=self._output_topic_type))-# Check if the conversation has already terminated.if self._termination_condition is not None and self._termination_condition.terminated:early_stop_message = StopMessage(@@ -63,18 +65,23 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):# Stop the group chat.return- # Append the user message to the message thread.- self._message_thread.append(message.message)+ if message.message is not None:+ # Log the start message.+ await self.publish_message(message, topic_id=DefaultTopicId(type=self._output_topic_type))- # Check if the conversation should be terminated.- if self._termination_condition is not None:- stop_message = await self._termination_condition([message.message])- if stop_message is not None:- await self.publish_message(- GroupChatTermination(message=stop_message), topic_id=DefaultTopicId(type=self._output_topic_type)- )- # Stop the group chat.- return+ # Append the user message to the message thread.+ self._message_thread.append(message.message)++ # Check if the conversation should be terminated.+ if self._termination_condition is not None:+ stop_message = await self._termination_condition([message.message])+ if stop_message is not None:+ await self.publish_message(+ GroupChatTermination(message=stop_message),+ topic_id=DefaultTopicId(type=self._output_topic_type),+ )+ # Stop the group chat.+ returnspeaker_topic_type = await self.select_speaker(self._message_thread)await self.publish_message(GroupChatRequestPublish(), topic_id=DefaultTopicId(type=speaker_topic_type))@@ -104,11 +111,21 @@ class BaseGroupChatManager(SequentialRoutedAgent, ABC):speaker_topic_type = await self.select_speaker(self._message_thread)await self.publish_message(GroupChatRequestPublish(), topic_id=DefaultTopicId(type=speaker_topic_type))+ @event+ async def handle_reset(self, message: GroupChatReset, ctx: MessageContext) -> None:+ # Reset the group chat manager.+ await self.reset()+@abstractmethodasync def select_speaker(self, thread: List[AgentMessage]) -> str:"""Select a speaker from the participants and return thetopic type of the selected speaker."""...+ @abstractmethod+ async def reset(self) -> None:+ """Reset the group chat manager."""+ ...+async def on_unhandled_message(self, message: Any, ctx: MessageContext) -> None:raise ValueError(f"Unhandled message in group chat manager: {type(message)}")diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.pyindex 689748338..19739dfdf 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_chat_agent_container.py@@ -30,7 +30,8 @@ class ChatAgentContainer(SequentialRoutedAgent):@eventasync def handle_start(self, message: GroupChatStart, ctx: MessageContext) -> None:"""Handle a start event by appending the content to the buffer."""- self._message_buffer.append(message.message)+ if message.message is not None:+ self._message_buffer.append(message.message)@eventasync def handle_agent_response(self, message: GroupChatAgentResponse, ctx: MessageContext) -> None:diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_events.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_events.pyindex 5e1635bb8..4ae4d892c 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_events.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_events.py@@ -7,8 +7,8 @@ from ...messages import AgentMessage, ChatMessage, StopMessageclass GroupChatStart(BaseModel):"""A request to start a group chat."""- message: ChatMessage- """The user message that started the group chat."""+ message: ChatMessage | None = None+ """An optional user message to start the group chat."""class GroupChatAgentResponse(BaseModel):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 4f355b58e..9638051e7 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@@ -15,7 +15,6 @@ class RoundRobinGroupChatManager(BaseGroupChatManager):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,) -> None:super().__init__(@@ -23,11 +22,16 @@ class RoundRobinGroupChatManager(BaseGroupChatManager):output_topic_type,participant_topic_types,participant_descriptions,- message_thread,termination_condition,)self._next_speaker_index = 0+ async def reset(self) -> None:+ self._message_thread.clear()+ if self._termination_condition is not None:+ await self._termination_condition.reset()+ self._next_speaker_index = 0+async def select_speaker(self, thread: List[AgentMessage]) -> str:"""Select a speaker from the participants in a round-robin fashion."""current_speaker_index = self._next_speaker_index@@ -124,7 +128,6 @@ class RoundRobinGroupChat(BaseGroupChat):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,) -> Callable[[], RoundRobinGroupChatManager]:def _factory() -> RoundRobinGroupChatManager:@@ -133,7 +136,6 @@ class RoundRobinGroupChat(BaseGroupChat):output_topic_type,participant_topic_types,participant_descriptions,- message_thread,termination_condition,)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 39c763c48..7e8f35832 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@@ -32,7 +32,6 @@ class SelectorGroupChatManager(BaseGroupChatManager):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,model_client: ChatCompletionClient,selector_prompt: str,@@ -44,7 +43,6 @@ class SelectorGroupChatManager(BaseGroupChatManager):output_topic_type,participant_topic_types,participant_descriptions,- message_thread,termination_condition,)self._model_client = model_client@@ -53,6 +51,12 @@ class SelectorGroupChatManager(BaseGroupChatManager):self._allow_repeated_speaker = allow_repeated_speakerself._selector_func = selector_func+ async def reset(self) -> None:+ self._message_thread.clear()+ if self._termination_condition is not None:+ await self._termination_condition.reset()+ self._previous_speaker = None+async def select_speaker(self, thread: List[AgentMessage]) -> str:"""Selects the next speaker in a group chat using a ChatCompletion client,with the selector function as override if it returns a speaker name.@@ -340,7 +344,6 @@ Read the above conversation. Then select the next role from {participants} to ploutput_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,) -> Callable[[], BaseGroupChatManager]:return lambda: SelectorGroupChatManager(@@ -348,7 +351,6 @@ Read the above conversation. Then select the next role from {participants} to ploutput_topic_type,participant_topic_types,participant_descriptions,- message_thread,termination_condition,self._model_client,self._selector_prompt,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 bf464b526..f3116d75f 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@@ -19,7 +19,6 @@ class SwarmGroupChatManager(BaseGroupChatManager):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,) -> None:super().__init__(@@ -27,11 +26,16 @@ class SwarmGroupChatManager(BaseGroupChatManager):output_topic_type,participant_topic_types,participant_descriptions,- message_thread,termination_condition,)self._current_speaker = participant_topic_types[0]+ async def reset(self) -> None:+ self._message_thread.clear()+ if self._termination_condition is not None:+ await self._termination_condition.reset()+ self._current_speaker = self._participant_topic_types[0]+async def select_speaker(self, thread: List[AgentMessage]) -> str:"""Select a speaker from the participants based on handoff message."""if len(thread) > 0 and isinstance(thread[-1], HandoffMessage):@@ -108,7 +112,6 @@ class Swarm(BaseGroupChat):output_topic_type: str,participant_topic_types: List[str],participant_descriptions: List[str],- message_thread: List[AgentMessage],termination_condition: TerminationCondition | None,) -> Callable[[], SwarmGroupChatManager]:def _factory() -> SwarmGroupChatManager:@@ -117,7 +120,6 @@ class Swarm(BaseGroupChat):output_topic_type,participant_topic_types,participant_descriptions,- message_thread,termination_condition,)diff --git a/python/packages/autogen-agentchat/tests/test_assistant_agent.py b/python/packages/autogen-agentchat/tests/test_assistant_agent.pyindex 5e133b91a..d847744ba 100644--- a/python/packages/autogen-agentchat/tests/test_assistant_agent.py+++ b/python/packages/autogen-agentchat/tests/test_assistant_agent.py@@ -110,7 +110,7 @@ async def test_run_with_tools(monkeypatch: pytest.MonkeyPatch) -> None:model_client=OpenAIChatCompletionClient(model=model, api_key=""),tools=[_pass_function, _fail_function, FunctionTool(_echo_function, description="Echo")],)- result = await tool_use_agent.run("task")+ result = await tool_use_agent.run(task="task")assert len(result.messages) == 4assert isinstance(result.messages[0], TextMessage)assert result.messages[0].models_usage is None@@ -128,7 +128,7 @@ async def test_run_with_tools(monkeypatch: pytest.MonkeyPatch) -> None:# Test streaming.mock._curr_index = 0 # pyright: ignoreindex = 0- async for message in tool_use_agent.run_stream("task"):+ async for message in tool_use_agent.run_stream(task="task"):if isinstance(message, TaskResult):assert message == resultelse:@@ -178,7 +178,7 @@ async def test_handoffs(monkeypatch: pytest.MonkeyPatch) -> None:handoffs=[handoff],)assert HandoffMessage in tool_use_agent.produced_message_types- result = await tool_use_agent.run("task")+ result = await tool_use_agent.run(task="task")assert len(result.messages) == 4assert isinstance(result.messages[0], TextMessage)assert result.messages[0].models_usage is None@@ -196,7 +196,7 @@ async def test_handoffs(monkeypatch: pytest.MonkeyPatch) -> None:# Test streaming.mock._curr_index = 0 # pyright: ignoreindex = 0- async for message in tool_use_agent.run_stream("task"):+ async for message in tool_use_agent.run_stream(task="task"):if isinstance(message, TaskResult):assert message == resultelse:diff --git a/python/packages/autogen-agentchat/tests/test_group_chat.py b/python/packages/autogen-agentchat/tests/test_group_chat.pyindex 5b37d166b..f51d86eec 100644--- a/python/packages/autogen-agentchat/tests/test_group_chat.py+++ b/python/packages/autogen-agentchat/tests/test_group_chat.py@@ -157,7 +157,7 @@ async def test_round_robin_group_chat(monkeypatch: pytest.MonkeyPatch) -> None:participants=[coding_assistant_agent, code_executor_agent], termination_condition=termination)result = await team.run(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",)expected_messages = ["Write a program that prints 'Hello, world!'",@@ -179,9 +179,9 @@ async def test_round_robin_group_chat(monkeypatch: pytest.MonkeyPatch) -> None:# Test streaming.mock.reset()index = 0- await termination.reset()+ await team.reset()async for message in team.run_stream(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",):if isinstance(message, TaskResult):assert message == result@@ -256,7 +256,7 @@ async def test_round_robin_group_chat_with_tools(monkeypatch: pytest.MonkeyPatchtermination = TextMentionTermination("TERMINATE")team = RoundRobinGroupChat(participants=[tool_use_agent, echo_agent], termination_condition=termination)result = await team.run(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",)assert len(result.messages) == 6@@ -284,9 +284,9 @@ async def test_round_robin_group_chat_with_tools(monkeypatch: pytest.MonkeyPatchtool_use_agent._model_context.clear() # pyright: ignoremock.reset()index = 0- await termination.reset()+ await team.reset()async for message in team.run_stream(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",):if isinstance(message, TaskResult):assert message == result@@ -295,6 +295,40 @@ async def test_round_robin_group_chat_with_tools(monkeypatch: pytest.MonkeyPatchindex += 1+async def test_round_robin_group_chat_with_resume_and_reset() -> 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")+ termination = MaxMessageTermination(3)+ team = RoundRobinGroupChat(participants=[agent_1, agent_2, agent_3, agent_4], termination_condition=termination)+ result = await team.run(+ task="Write a program that prints 'Hello, world!'",+ )+ assert len(result.messages) == 3+ assert result.messages[1].source == "agent_1"+ assert result.messages[2].source == "agent_2"+ assert result.stop_reason is not None++ # Resume.+ await termination.reset()+ result = await team.run()+ assert len(result.messages) == 3+ assert result.messages[0].source == "agent_3"+ assert result.messages[1].source == "agent_4"+ assert result.messages[2].source == "agent_1"+ 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) == 3+ assert result.messages[1].source == "agent_1"+ assert result.messages[2].source == "agent_2"+ assert result.stop_reason is not None++@pytest.mark.asyncioasync def test_selector_group_chat(monkeypatch: pytest.MonkeyPatch) -> None:model = "gpt-4o-2024-05-13"@@ -363,7 +397,7 @@ async def test_selector_group_chat(monkeypatch: pytest.MonkeyPatch) -> None:termination_condition=termination,)result = await team.run(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",)assert len(result.messages) == 6assert result.messages[0].content == "Write a program that prints 'Hello, world!'"@@ -378,9 +412,9 @@ async def test_selector_group_chat(monkeypatch: pytest.MonkeyPatch) -> None:mock.reset()agent1._count = 0 # pyright: ignoreindex = 0- await termination.reset()+ await team.reset()async for message in team.run_stream(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",):if isinstance(message, TaskResult):assert message == result@@ -416,7 +450,7 @@ async def test_selector_group_chat_two_speakers(monkeypatch: pytest.MonkeyPatch)model_client=OpenAIChatCompletionClient(model=model, api_key=""),)result = await team.run(- "Write a program that prints 'Hello, world!'",+ task="Write a program that prints 'Hello, world!'",)assert len(result.messages) == 5assert result.messages[0].content == "Write a program that prints 'Hello, world!'"@@ -432,8 +466,8 @@ async def test_selector_group_chat_two_speakers(monkeypatch: pytest.MonkeyPatch)mock.reset()agent1._count = 0 # pyright: ignoreindex = 0- await termination.reset()- async for message in team.run_stream("Write a program that prints 'Hello, world!'"):+ await team.reset()+ async for message in team.run_stream(task="Write a program that prints 'Hello, world!'"):if isinstance(message, TaskResult):assert message == resultelse:@@ -488,7 +522,7 @@ async def test_selector_group_chat_two_speakers_allow_repeated(monkeypatch: pytetermination_condition=termination,allow_repeated_speaker=True,)- result = await team.run("Write a program that prints 'Hello, world!'")+ result = await team.run(task="Write a program that prints 'Hello, world!'")assert len(result.messages) == 4assert result.messages[0].content == "Write a program that prints 'Hello, world!'"assert result.messages[1].source == "agent2"@@ -499,8 +533,8 @@ async def test_selector_group_chat_two_speakers_allow_repeated(monkeypatch: pyte# Test streaming.mock.reset()index = 0- await termination.reset()- async for message in team.run_stream("Write a program that prints 'Hello, world!'"):+ await team.reset()+ async for message in team.run_stream(task="Write a program that prints 'Hello, world!'"):if isinstance(message, TaskResult):assert message == resultelse:@@ -549,7 +583,7 @@ async def test_selector_group_chat_custom_selector(monkeypatch: pytest.MonkeyPatselector_func=_select_agent,termination_condition=termination,)- result = await team.run("task")+ result = await team.run(task="task")assert len(result.messages) == 6assert result.messages[1].source == "agent1"assert result.messages[2].source == "agent2"@@ -590,7 +624,7 @@ async def test_swarm_handoff() -> None:termination = MaxMessageTermination(6)team = Swarm([second_agent, first_agent, third_agent], termination_condition=termination)- result = await team.run("task")+ result = await team.run(task="task")assert len(result.messages) == 6assert result.messages[0].content == "task"assert result.messages[1].content == "Transferred to third_agent."@@ -605,8 +639,8 @@ async def test_swarm_handoff() -> None:# Test streaming.index = 0- await termination.reset()- stream = team.run_stream("task")+ await team.reset()+ stream = team.run_stream(task="task")async for message in stream:if isinstance(message, TaskResult):assert message == result@@ -680,7 +714,7 @@ async def test_swarm_handoff_using_tool_calls(monkeypatch: pytest.MonkeyPatch) -agent2 = _HandOffAgent("agent2", description="agent 2", next_agent="agent1")termination = TextMentionTermination("TERMINATE")team = Swarm([agent1, agent2], termination_condition=termination)- result = await team.run("task")+ result = await team.run(task="task")assert len(result.messages) == 7assert result.messages[0].content == "task"assert isinstance(result.messages[1], ToolCallMessage)@@ -695,8 +729,8 @@ async def test_swarm_handoff_using_tool_calls(monkeypatch: pytest.MonkeyPatch) -agent1._model_context.clear() # pyright: ignoremock.reset()index = 0- await termination.reset()- stream = team.run_stream("task")+ await team.reset()+ stream = team.run_stream(task="task")async for message in stream:if isinstance(message, TaskResult):assert message == resultdiff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/company-research.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/company-research.ipynbindex ce5844f4d..21d10aadc 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/company-research.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/company-research.ipynb@@ -401,7 +401,7 @@}],"source": [- "result = await team.run(\"Write a financial report on American airlines\")\n",+ "result = await team.run(task=\"Write a financial report on American airlines\")\n","print(result)"]}@@ -422,7 +422,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.11.5"+ "version": "3.12.6"}},"nbformat": 4,diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/literature-review.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/literature-review.ipynbindex cefb6e6f4..94f08abdb 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/literature-review.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/examples/literature-review.ipynb@@ -355,7 +355,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.11.5"+ "version": "3.12.6"}},"nbformat": 4,diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/quickstart.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/quickstart.ipynbindex 1a5875325..833c57624 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/quickstart.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/quickstart.ipynb@@ -71,7 +71,7 @@" agent_team = RoundRobinGroupChat([weather_agent], termination_condition=termination)\n","\n"," # Run the team and stream messages\n",- " stream = agent_team.run_stream(\"What is the weather in New York?\")\n",+ " stream = agent_team.run_stream(task=\"What is the weather in New York?\")\n"," async for response in stream:\n"," print(response)\n","\n",@@ -114,7 +114,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.11.5"+ "version": "3.12.6"}},"nbformat": 4,diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynbindex 5ca7a0dc0..6be1e1334 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/selector-group-chat.ipynb@@ -261,7 +261,7 @@" model_client=OpenAIChatCompletionClient(model=\"gpt-4o-mini\"),\n"," termination_condition=termination,\n",")\n",- "await team.run(\"Help user plan a trip and book a flight.\")"+ "await team.run(task=\"Help user plan a trip and book a flight.\")"]}],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.ipynbindex b85f1223c..c52e66439 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@@ -77,7 +77,7 @@},{"cell_type": "code",- "execution_count": 2,+ "execution_count": null,"metadata": {},"outputs": [{@@ -105,7 +105,7 @@"source": ["termination = MaxMessageTermination(max_messages=1)\n","round_robin_team = RoundRobinGroupChat([tool_use_agent, writing_assistant_agent], termination_condition=termination)\n",- "round_robin_team_result = await round_robin_team.run(\"Write a Haiku about the weather in Paris\")"+ "round_robin_team_result = await round_robin_team.run(task=\"Write a Haiku about the weather in Paris\")"]},{@@ -134,7 +134,7 @@},{"cell_type": "code",- "execution_count": 3,+ "execution_count": null,"metadata": {},"outputs": [{@@ -177,7 +177,7 @@" [tool_use_agent, writing_assistant_agent], model_client=model_client, termination_condition=termination\n",")\n","\n",- "llm_team_result = await llm_team.run(\"What is the weather in paris right now? Also write a haiku about it.\")"+ "llm_team_result = await llm_team.run(task=\"What is the weather in paris right now? Also write a haiku about it.\")"]},{@@ -208,7 +208,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.11.5"+ "version": "3.12.6"}},"nbformat": 4,diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynbindex 301ce6663..e10942491 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/tutorial/termination.ipynb@@ -70,7 +70,7 @@},{"cell_type": "code",- "execution_count": 2,+ "execution_count": null,"metadata": {},"outputs": [{@@ -110,7 +110,7 @@"source": ["max_msg_termination = MaxMessageTermination(max_messages=3)\n","round_robin_team = RoundRobinGroupChat([writing_assistant_agent], termination_condition=max_msg_termination)\n",- "round_robin_team_result = await round_robin_team.run(\"Write a unique, Haiku about the weather in Paris\")"+ "round_robin_team_result = await round_robin_team.run(task=\"Write a unique, Haiku about the weather in Paris\")"]},{@@ -174,7 +174,7 @@"text_termination = TextMentionTermination(\"TERMINATE\")\n","round_robin_team = RoundRobinGroupChat([writing_assistant_agent], termination_condition=text_termination)\n","\n",- "round_robin_team_result = await round_robin_team.run(\"Write a unique, Haiku about the weather in Paris\")"+ "round_robin_team_result = await round_robin_team.run(task=\"Write a unique, Haiku about the weather in Paris\")"]}],@@ -194,7 +194,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.11.5"+ "version": "3.12.6"}},"nbformat": 4,