Skip to content

A programming framework for agentic AI

Fix GraphFlow to support multiple task execution without explicit reset (#6747)

Copilotc23b9454a87d
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_digraph_group_chat.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_digraph_group_chat.py
index aaca418df..544afb222 100644
--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_digraph_group_chat.py
+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_digraph_group_chat.py
@@ -472,12 +472,20 @@ class GraphFlowManager(BaseGroupChatManager):
# If there are no speakers, trigger the stop agent.
if not speakers:
speakers = [_DIGRAPH_STOP_AGENT_NAME]
+ # Reset the execution state when the stop agent is selected, as this means the graph has naturally completed
+ self._reset_execution_state()
return speakers
async def validate_group_state(self, messages: List[BaseChatMessage] | None) -> None:
pass
+ def _reset_execution_state(self) -> None:
+ """Reset the graph execution state to the initial state."""
+ self._remaining = {target: Counter(groups) for target, groups in self._graph.get_remaining_map().items()}
+ self._enqueued_any = {n: {g: False for g in self._enqueued_any[n]} for n in self._enqueued_any}
+ self._ready = deque([n for n in self._graph.get_start_nodes()])
+
async def save_state(self) -> Mapping[str, Any]:
"""Save the execution state."""
state = {
@@ -503,9 +511,7 @@ class GraphFlowManager(BaseGroupChatManager):
self._message_thread.clear()
if self._termination_condition:
await self._termination_condition.reset()
- self._remaining = {target: Counter(groups) for target, groups in self._graph.get_remaining_map().items()}
- self._enqueued_any = {n: {g: False for g in self._enqueued_any[n]} for n in self._enqueued_any}
- self._ready = deque([n for n in self._graph.get_start_nodes()])
+ self._reset_execution_state()
class _StopAgent(BaseChatAgent):
diff --git a/python/packages/autogen-agentchat/tests/test_group_chat_graph.py b/python/packages/autogen-agentchat/tests/test_group_chat_graph.py
index 33f57e697..adcc42958 100644
--- a/python/packages/autogen-agentchat/tests/test_group_chat_graph.py
+++ b/python/packages/autogen-agentchat/tests/test_group_chat_graph.py
@@ -407,7 +407,7 @@ class _EchoAgent(BaseChatAgent):
async def on_messages(self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken) -> Response:
if len(messages) > 0:
- assert isinstance(messages[0], TextMessage)
+ assert isinstance(messages[0], TextMessage) or isinstance(messages[0], StopMessage)
self._last_message = messages[0].content
self._total_messages += 1
return Response(chat_message=TextMessage(content=messages[0].content, source=self.name))
@@ -1626,3 +1626,115 @@ async def test_builder_with_lambda_condition(runtime: AgentRuntime | None) -> No
# Test with "odd" in message - should go to C
result = await team.run(task="odd message")
assert result.messages[2].source == "C"
+
+
+async def test_digraph_group_chat_multiple_task_execution(runtime: AgentRuntime | None) -> None:
+ """Test that GraphFlow can run multiple tasks sequentially after resetting execution state."""
+ # Create agents A → B → C
+ agent_a = _EchoAgent("A", description="Echo agent A")
+ agent_b = _EchoAgent("B", description="Echo agent B")
+ agent_c = _EchoAgent("C", description="Echo agent C")
+
+ # Define graph A → B → C
+ graph = DiGraph(
+ nodes={
+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),
+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),
+ "C": DiGraphNode(name="C", edges=[]),
+ }
+ )
+
+ # Create team using Graph
+ team = GraphFlow(
+ participants=[agent_a, agent_b, agent_c],
+ graph=graph,
+ runtime=runtime,
+ termination_condition=MaxMessageTermination(5),
+ )
+
+ # Run the first task
+ result1: TaskResult = await team.run(task="First task")
+
+ assert len(result1.messages) == 5
+ assert isinstance(result1.messages[0], TextMessage)
+ assert result1.messages[0].source == "user"
+ assert result1.messages[0].content == "First task"
+ assert result1.messages[1].source == "A"
+ assert result1.messages[2].source == "B"
+ assert result1.messages[3].source == "C"
+ assert result1.messages[4].source == _DIGRAPH_STOP_AGENT_NAME
+ assert result1.stop_reason is not None
+
+ # Run the second task - should work without explicit reset
+ result2: TaskResult = await team.run(task="Second task")
+
+ assert len(result2.messages) == 5
+ assert isinstance(result2.messages[0], TextMessage)
+ assert result2.messages[0].source == "user"
+ assert result2.messages[0].content == "Second task"
+ assert result2.messages[1].source == "A"
+ assert result2.messages[2].source == "B"
+ assert result2.messages[3].source == "C"
+ assert result2.messages[4].source == _DIGRAPH_STOP_AGENT_NAME
+ assert result2.stop_reason is not None
+
+ # Verify agents were properly reset and executed again
+ assert agent_a.total_messages == 2 # Once for each task
+ assert agent_b.total_messages == 2 # Once for each task
+ assert agent_c.total_messages == 2 # Once for each task
+
+
+async def test_digraph_group_chat_resume_with_termination_condition(runtime: AgentRuntime | None) -> None:
+ """Test that GraphFlow can be resumed with the same execution state when a termination condition is reached."""
+ # Create agents A → B → C
+ agent_a = _EchoAgent("A", description="Echo agent A")
+ agent_b = _EchoAgent("B", description="Echo agent B")
+ agent_c = _EchoAgent("C", description="Echo agent C")
+
+ # Define graph A → B → C
+ graph = DiGraph(
+ nodes={
+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),
+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),
+ "C": DiGraphNode(name="C", edges=[]),
+ }
+ )
+
+ # Create team with MaxMessageTermination that will stop before completion
+ team = GraphFlow(
+ participants=[agent_a, agent_b, agent_c],
+ graph=graph,
+ runtime=runtime,
+ termination_condition=MaxMessageTermination(3), # Stop after user + A + B
+ )
+
+ # Run the graph flow until termination condition is reached
+ result1: TaskResult = await team.run(task="Start execution")
+
+ # Should have stopped at termination condition (user + A + B messages)
+ assert len(result1.messages) == 3
+ assert result1.messages[0].source == "user"
+ assert result1.messages[1].source == "A"
+ assert result1.messages[2].source == "B"
+ assert result1.stop_reason is not None
+
+ # Verify A and B ran, but C did not
+ assert agent_a.total_messages == 1
+ assert agent_b.total_messages == 1
+ assert agent_c.total_messages == 0
+
+ # Resume the graph flow with no task to continue where it left off
+ result2: TaskResult = await team.run()
+
+ # Should continue and execute C, then complete with stop agent
+ assert len(result2.messages) == 2
+ assert result2.messages[0].source == "C"
+ assert result2.messages[1].source == _DIGRAPH_STOP_AGENT_NAME
+ assert result2.stop_reason is not None
+
+ # Verify C now ran and the execution state was preserved
+ assert agent_a.total_messages == 1 # Still only ran once
+ assert agent_b.total_messages == 1 # Still only ran once
+ assert agent_c.total_messages == 1 # Now ran once