A programming framework for agentic AI
Added Graph Based Execution functionality to Autogen (#6333)
abhinav-aegis9f8e892d276d
diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.pyindex a6732d12e..90faeaac4 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py@@ -6,6 +6,7 @@ BaseChatAgent is the base class for all agents in AgentChat.from ._assistant_agent import AssistantAgentfrom ._base_chat_agent import BaseChatAgentfrom ._code_executor_agent import CodeExecutorAgent+from ._message_filter_agent import MessageFilterAgent, MessageFilterConfig, PerSourceFilterfrom ._society_of_mind_agent import SocietyOfMindAgentfrom ._user_proxy_agent import UserProxyAgent@@ -15,4 +16,7 @@ __all__ = ["CodeExecutorAgent","SocietyOfMindAgent","UserProxyAgent",+ "MessageFilterAgent",+ "MessageFilterConfig",+ "PerSourceFilter",]diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_message_filter_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_message_filter_agent.pynew file mode 100644index 000000000..0905e694d--- /dev/null+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_message_filter_agent.py@@ -0,0 +1,203 @@+from typing import AsyncGenerator, List, Literal, Optional, Sequence, Union++from autogen_core import CancellationToken, Component, ComponentModel+from pydantic import BaseModel++from autogen_agentchat.agents import BaseChatAgent+from autogen_agentchat.base import Response+from autogen_agentchat.messages import BaseAgentEvent, BaseChatMessage++# ------------------------------+# Message Filter Config+# ------------------------------+++class PerSourceFilter(BaseModel):+ source: str+ position: Optional[Literal["first", "last"]] = None+ count: Optional[int] = None+++class MessageFilterConfig(BaseModel):+ per_source: List[PerSourceFilter]+++# ------------------------------+# Component Config+# ------------------------------+++class MessageFilterAgentConfig(BaseModel):+ name: str+ wrapped_agent: ComponentModel+ filter: MessageFilterConfig+++# ------------------------------+# Message Filter Agent+# ------------------------------+++class MessageFilterAgent(BaseChatAgent, Component[MessageFilterAgentConfig]):+ """+ A wrapper agent that filters incoming messages before passing them to the inner agent.++ .. warning::++ This is an experimental feature, and the API will change in the future releases.++ This is useful in scenarios like multi-agent workflows where an agent should only+ process a subset of the full message history—for example, only the last message+ from each upstream agent, or only the first message from a specific source.++ Filtering is configured using :class:`MessageFilterConfig`, which supports:+ - Filtering by message source (e.g., only messages from "user" or another agent)+ - Selecting the first N or last N messages from each source+ - If position is `None`, all messages from that source are included++ This agent is compatible with both direct message passing and team-based execution+ such as :class:`~autogen_agentchat.teams.GraphFlow`.++ Example:+ >>> agent_a = MessageFilterAgent(+ ... name="A",+ ... wrapped_agent=some_other_agent,+ ... filter=MessageFilterConfig(+ ... per_source=[+ ... PerSourceFilter(source="user", position="first", count=1),+ ... PerSourceFilter(source="B", position="last", count=2),+ ... ]+ ... ),+ ... )++ Example use case with Graph:+ Suppose you have a looping multi-agent graph: A → B → A → B → C.++ You want:+ - A to only see the user message and the last message from B+ - B to see the user message, last message from A, and its own prior responses (for reflection)+ - C to see the user message and the last message from B++ Wrap the agents like so:++ >>> agent_a = MessageFilterAgent(+ ... name="A",+ ... wrapped_agent=agent_a_inner,+ ... filter=MessageFilterConfig(+ ... per_source=[+ ... PerSourceFilter(source="user", position="first", count=1),+ ... PerSourceFilter(source="B", position="last", count=1),+ ... ]+ ... ),+ ... )++ >>> agent_b = MessageFilterAgent(+ ... name="B",+ ... wrapped_agent=agent_b_inner,+ ... filter=MessageFilterConfig(+ ... per_source=[+ ... PerSourceFilter(source="user", position="first", count=1),+ ... PerSourceFilter(source="A", position="last", count=1),+ ... PerSourceFilter(source="B", position="last", count=10),+ ... ]+ ... ),+ ... )++ >>> agent_c = MessageFilterAgent(+ ... name="C",+ ... wrapped_agent=agent_c_inner,+ ... filter=MessageFilterConfig(+ ... per_source=[+ ... PerSourceFilter(source="user", position="first", count=1),+ ... PerSourceFilter(source="B", position="last", count=1),+ ... ]+ ... ),+ ... )++ Then define the graph:++ >>> graph = DiGraph(+ ... nodes={+ ... "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ ... "B": DiGraphNode(+ ... name="B",+ ... edges=[+ ... DiGraphEdge(target="C", condition="exit"),+ ... DiGraphEdge(target="A", condition="loop"),+ ... ],+ ... ),+ ... "C": DiGraphNode(name="C", edges=[]),+ ... },+ ... default_start_node="A",+ ... )++ This will ensure each agent sees only what is needed for its decision or action logic.+ """++ component_config_schema = MessageFilterAgentConfig+ component_provider_override = "autogen_agentchat.agents.MessageFilterAgent"++ def __init__(+ self,+ name: str,+ wrapped_agent: BaseChatAgent,+ filter: MessageFilterConfig,+ ):+ super().__init__(name=name, description=f"{wrapped_agent.description} (with message filtering)")+ self._wrapped_agent = wrapped_agent+ self._filter = filter++ @property+ def produced_message_types(self) -> Sequence[type[BaseChatMessage]]:+ return self._wrapped_agent.produced_message_types++ def _apply_filter(self, messages: Sequence[BaseChatMessage]) -> Sequence[BaseChatMessage]:+ result: List[BaseChatMessage] = []++ for source_filter in self._filter.per_source:+ msgs = [m for m in messages if m.source == source_filter.source]++ if source_filter.position == "first" and source_filter.count:+ msgs = msgs[: source_filter.count]+ elif source_filter.position == "last" and source_filter.count:+ msgs = msgs[-source_filter.count :]++ result.extend(msgs)++ return result++ async def on_messages(+ self,+ messages: Sequence[BaseChatMessage],+ cancellation_token: CancellationToken,+ ) -> Response:+ filtered = self._apply_filter(messages)+ return await self._wrapped_agent.on_messages(filtered, cancellation_token)++ async def on_messages_stream(+ self,+ messages: Sequence[BaseChatMessage],+ cancellation_token: CancellationToken,+ ) -> AsyncGenerator[Union[BaseAgentEvent, BaseChatMessage, Response], None]:+ filtered = self._apply_filter(messages)+ async for item in self._wrapped_agent.on_messages_stream(filtered, cancellation_token):+ yield item++ async def on_reset(self, cancellation_token: CancellationToken) -> None:+ await self._wrapped_agent.on_reset(cancellation_token)++ def _to_config(self) -> MessageFilterAgentConfig:+ return MessageFilterAgentConfig(+ name=self.name,+ wrapped_agent=self._wrapped_agent.dump_component(),+ filter=self._filter,+ )++ @classmethod+ def _from_config(cls, config: MessageFilterAgentConfig) -> "MessageFilterAgent":+ wrapped = BaseChatAgent.load_component(config.wrapped_agent)+ return cls(+ name=config.name,+ wrapped_agent=wrapped,+ filter=config.filter,+ )diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.pyindex e44628edc..712976980 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/__init__.py@@ -4,6 +4,13 @@ Each team inherits from the BaseGroupChat class."""from ._group_chat._base_group_chat import BaseGroupChat+from ._group_chat._graph import (+ DiGraph,+ DiGraphBuilder,+ DiGraphEdge,+ DiGraphNode,+ GraphFlow,+)from ._group_chat._magentic_one import MagenticOneGroupChatfrom ._group_chat._round_robin_group_chat import RoundRobinGroupChatfrom ._group_chat._selector_group_chat import SelectorGroupChat@@ -15,4 +22,9 @@ __all__ = ["SelectorGroupChat","Swarm","MagenticOneGroupChat",+ "DiGraphBuilder",+ "DiGraph",+ "DiGraphNode",+ "DiGraphEdge",+ "GraphFlow",]diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/__init__.pynew file mode 100644index 000000000..f38d6d653--- /dev/null+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/__init__.py@@ -0,0 +1,17 @@+from ._digraph_group_chat import (+ DiGraph,+ DiGraphEdge,+ DiGraphNode,+ GraphFlow,+ GraphFlowManager,+)+from ._graph_builder import DiGraphBuilder++__all__ = [+ "GraphFlow",+ "DiGraph",+ "GraphFlowManager",+ "DiGraphNode",+ "DiGraphEdge",+ "DiGraphBuilder",+]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.pynew file mode 100644index 000000000..9917a2a8b--- /dev/null+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_digraph_group_chat.py@@ -0,0 +1,721 @@+import asyncio+from typing import Any, Callable, Dict, List, Literal, Mapping, Sequence, Set++from autogen_core import AgentRuntime, CancellationToken, Component, ComponentModel+from pydantic import BaseModel+from typing_extensions import Self++from autogen_agentchat.agents import BaseChatAgent+from autogen_agentchat.base import ChatAgent, OrTerminationCondition, Response, TerminationCondition+from autogen_agentchat.conditions import StopMessageTermination+from autogen_agentchat.messages import (+ BaseAgentEvent,+ BaseChatMessage,+ ChatMessage,+ MessageFactory,+ StopMessage,+ TextMessage,+)+from autogen_agentchat.state import BaseGroupChatManagerState+from autogen_agentchat.teams import BaseGroupChat++from ..._group_chat._base_group_chat_manager import BaseGroupChatManager+from ..._group_chat._events import GroupChatTermination++_DIGRAPH_STOP_AGENT_NAME = "DiGraphStopAgent"+_DIGRAPH_STOP_AGENT_MESSAGE = "Digraph execution is complete"+++class DiGraphEdge(BaseModel):+ """Represents a directed edge in a :class:`DiGraph`, with an optional execution condition.++ .. warning::++ This is an experimental feature, and the API will change in the future releases.++ """++ target: str # Target node name+ condition: str | None = None # Optional execution condition (trigger-based)+ """(Experimental) Condition to execute this edge.+ If None, the edge is unconditional. If a string, the edge is conditional on the presence of that string in the last agent chat message.+ NOTE: This is an experimental feature WILL change in the future releases to allow for better spcification of branching conditions+ similar to the `TerminationCondition` class.+ """+++class DiGraphNode(BaseModel):+ """Represents a node (agent) in a :class:`DiGraph`, with its outgoing edges and activation type.++ .. warning::++ This is an experimental feature, and the API will change in the future releases.++ """++ name: str # Agent's name+ edges: List[DiGraphEdge] = [] # Outgoing edges+ activation: Literal["all", "any"] = "all"+++class DiGraph(BaseModel):+ """Defines a directed graph structure with nodes and edges.+ :class:`GraphFlow` uses this to determine execution order and conditions.++ .. warning::++ This is an experimental feature, and the API will change in the future releases.++ """++ nodes: Dict[str, DiGraphNode] # Node name → DiGraphNode mapping+ default_start_node: str | None = None # Default start node name+ _has_cycles: bool | None = None # Cyclic graph flag++ def get_parents(self) -> Dict[str, List[str]]:+ """Compute a mapping of each node to its parent nodes."""+ parents: Dict[str, List[str]] = {node: [] for node in self.nodes}+ for node in self.nodes.values():+ for edge in node.edges:+ parents[edge.target].append(node.name)+ return parents++ def get_start_nodes(self) -> Set[str]:+ """Return the nodes that have no incoming edges (entry points)."""+ if self.default_start_node:+ return {self.default_start_node}++ parents = self.get_parents()+ return set([node_name for node_name, parent_list in parents.items() if not parent_list])++ def get_leaf_nodes(self) -> Set[str]:+ """Return nodes that have no outgoing edges (final output nodes)."""+ return set([name for name, node in self.nodes.items() if not node.edges])++ def has_cycles_with_exit(self) -> bool:+ """+ Check if the graph has any cycles and validate that each cycle has at least one conditional edge.++ Returns:+ bool: True if there is at least one cycle and all cycles have an exit condition.+ False if there are no cycles.++ Raises:+ ValueError: If there is a cycle without any conditional edge.+ """+ visited: Set[str] = set()+ rec_stack: Set[str] = set()+ path: List[str] = []++ def dfs(node_name: str) -> bool:+ visited.add(node_name)+ rec_stack.add(node_name)+ path.append(node_name)++ for edge in self.nodes[node_name].edges:+ target = edge.target+ if target not in visited:+ if dfs(target):+ return True+ elif target in rec_stack:+ # Found a cycle → extract the cycle+ cycle_start_index = path.index(target)+ cycle_nodes = path[cycle_start_index:]+ cycle_edges: List[DiGraphEdge] = []+ for n in cycle_nodes:+ cycle_edges.extend(self.nodes[n].edges)+ if not any(edge.condition for edge in cycle_edges):+ raise ValueError(+ f"Cycle detected without exit condition: {' -> '.join(cycle_nodes + cycle_nodes[:1])}"+ )+ return True # Found cycle, but it has an exit condition++ rec_stack.remove(node_name)+ path.pop()+ return False++ has_cycle = False+ for node in self.nodes:+ if node not in visited:+ if dfs(node):+ has_cycle = True++ return has_cycle++ def get_has_cycles(self) -> bool:+ """Indicates if the graph has at least one cycle (with valid exit conditions)."""+ if self._has_cycles is None:+ self._has_cycles = self.has_cycles_with_exit()++ return self._has_cycles++ def graph_validate(self) -> None:+ """Validate graph structure and execution rules."""+ if not self.nodes:+ raise ValueError("Graph has no nodes.")++ if not self.get_start_nodes():+ raise ValueError("Graph must have at least one start node")++ if not self.get_leaf_nodes():+ raise ValueError("Graph must have at least one leaf node")++ # Outgoing edge condition validation (per node)+ for node in self.nodes.values():+ # Check that if a node has an outgoing conditional edge, then all outgoing edges are conditional+ has_condition = any(edge.condition for edge in node.edges)+ has_unconditioned = any(edge.condition is None for edge in node.edges)+ if has_condition and has_unconditioned:+ raise ValueError(f"Node '{node.name}' has a mix of conditional and unconditional edges.")++ self._has_cycles = self.has_cycles_with_exit()+++class GraphFlowManagerState(BaseGroupChatManagerState):+ """Tracks active execution state for DAG-based execution."""++ active_nodes: List[str] = [] # Currently executing nodes+ type: str = "GraphManagerState"+++class GraphFlowManager(BaseGroupChatManager):+ """Manages execution of agents using a Directed Graph execution model."""++ def __init__(+ self,+ name: str,+ group_topic_type: str,+ output_topic_type: str,+ participant_topic_types: List[str],+ participant_names: List[str],+ participant_descriptions: List[str],+ output_message_queue: asyncio.Queue[BaseAgentEvent | BaseChatMessage | GroupChatTermination],+ termination_condition: TerminationCondition | None,+ max_turns: int | None,+ message_factory: MessageFactory,+ graph: DiGraph,+ ) -> None:+ """Initialize the graph-based execution manager."""+ super().__init__(+ name=name,+ group_topic_type=group_topic_type,+ output_topic_type=output_topic_type,+ participant_topic_types=participant_topic_types,+ participant_names=participant_names,+ participant_descriptions=participant_descriptions,+ output_message_queue=output_message_queue,+ termination_condition=termination_condition,+ max_turns=max_turns,+ message_factory=message_factory,+ )+ self._graph = graph+ self._graph.graph_validate()+ self._graph_has_cycles = self._graph.get_has_cycles()+ if self._graph_has_cycles and self._termination_condition is None and self._max_turns is None:+ raise ValueError("A termination condition is required for cyclic graphs without a maximum turn limit.")++ self._use_default_start = self._graph.default_start_node is not None+ self._default_start_executed = False+ self._start_nodes = graph.get_start_nodes()+ self._leaf_nodes = graph.get_leaf_nodes()+ self._parents = graph.get_parents() # Parent node dependencies - helper dict to get all incoming edges+ self._active_nodes: Set[str] = set() # Currently executing nodes+ self._active_node_count: Dict[str, int] = {+ node: 0 for node in graph.nodes+ } # Number of times a node has been active++ # These are nodes next in line for execution as one or more of their parent nodes have started execution.+ # They execute when all their parent nodes have executed.+ # Nodes are added to this dict when at least one of their parent nodes becomes active.+ # Start nodes (no parents) are added to this dict at initialization as they are always ready to run.+ self._pending_execution: Dict[str, List[str]] = {node: [] for node in graph.get_start_nodes()}++ def _get_valid_target(self, node: DiGraphNode, content: str) -> str:+ """Check if a condition is met in the chat history."""+ for edge in node.edges:+ if edge.condition and edge.condition in content:+ return edge.target++ raise RuntimeError(f"Condition not met for node {node.name}. Content: {content}")++ def _is_node_ready(self, node_name: str) -> bool:+ """Check if a node is ready to execute based on its parent nodes.+ If activation is any then execute as soon as any parent has finished+ If activation is all then execute only when all parents have finished+ """+ node = self._graph.nodes[node_name]+ if node.activation == "any":+ return bool(self._pending_execution[node_name])+ return all(parent in self._pending_execution[node_name] for parent in self._parents[node_name])++ async def _select_speakers(self, thread: List[BaseAgentEvent | BaseChatMessage], many: bool = True) -> List[str]:+ """Select the next set of agents to execute based on DAG constraints."""+ next_speakers: Set[str] = set()+ source_node: DiGraphNode | None = None+ source: str | None = None++ if thread and isinstance(thread[-1], BaseChatMessage):+ source = thread[-1].source # name of the agent that just finished+ content = thread[-1].to_model_text()++ # Safety check: only an active node can send a response+ if source != "user":+ if source not in self._active_nodes:+ raise RuntimeError(f"Agent '{source}' is not currently active.")++ # Mark the node as no longer active (it just finished)+ self._active_node_count[source] -= 1++ if self._active_node_count[source] <= 0:+ self._active_nodes.remove(source)++ source_node = self._graph.nodes[source]++ if source_node.edges:+ # Case: conditional edges — only execute if condition is met+ target_nodes_names: List[str] = []+ if source_node.edges[0].condition is not None:+ target_nodes_names = [self._get_valid_target(source_node, content)]+ other_nodes = [+ edge.target for edge in source_node.edges if edge.target != target_nodes_names[0]+ ]+ for other_node in other_nodes:+ other_active_parents = [+ parent+ for parent in self._parents[other_node]+ if (parent != source and parent in self._active_nodes)+ ]+ if not other_active_parents:+ self._pending_execution.pop(other_node)+ else:+ self._pending_execution[other_node] = other_active_parents++ else:+ # Case: unconditional edges — mark this source as completed for all its children+ target_nodes_names = [edge.target for edge in source_node.edges]++ for target in target_nodes_names:+ self._pending_execution[target].append(source)+ else:+ # TODO: Check if there are any usecase where the User can decide on the next speaker+ pass++ # After updating _pending_execution, check which nodes are now unblocked+ for node_name in list(self._pending_execution):+ if self._use_default_start and not self._default_start_executed:+ if node_name == self._graph.default_start_node:+ next_speakers.add(node_name)+ self._default_start_executed = True+ break++ if self._is_node_ready(node_name):+ next_speakers.add(node_name)+ node = self._graph.nodes[node_name]+ if node.activation == "all":+ self._pending_execution.pop(node_name)+ else:+ # If activation is any, remove the parent that just finished+ if source is not None:+ self._pending_execution[node_name] = [+ parent for parent in self._pending_execution[node_name] if parent != source+ ]++ # If none of the other parents of this node are active, remove this node from pending execution+ node_parents = self._parents[node_name]+ if not any(parent in self._active_nodes for parent in node_parents):+ self._pending_execution.pop(node_name)++ if not many:+ break++ # Prepopulate children of next_speakers into _pending_execution+ for node_name in next_speakers:+ for edge in self._graph.nodes[node_name].edges:+ if edge.target not in self._pending_execution:+ self._pending_execution[edge.target] = []++ # Mark newly selected speakers as active+ for speaker in next_speakers:+ if speaker not in self._active_nodes:+ self._active_nodes.add(speaker)++ self._active_node_count[speaker] += 1++ if not self._pending_execution and not next_speakers and not self._active_nodes:+ next_speakers = set([_DIGRAPH_STOP_AGENT_NAME]) # Call the termination agent++ return list(next_speakers)++ async def select_speakers(self, thread: List[BaseAgentEvent | BaseChatMessage]) -> List[str]:+ return await self._select_speakers(thread)++ async def select_speaker(self, thread: List[BaseAgentEvent | BaseChatMessage]) -> str:+ """Select a speaker from the participants and return the+ topic type of the selected speaker."""+ speakers = await self._select_speakers(thread, many=False)+ if not speakers:+ raise RuntimeError("No available speakers found.")+ return speakers[0]++ async def validate_group_state(self, messages: List[BaseChatMessage] | None) -> None:+ pass++ async def save_state(self) -> Mapping[str, Any]:+ """Save the execution state."""+ state = {+ "message_thread": [message.dump() for message in self._message_thread],+ "current_turn": self._current_turn,+ "active_nodes": list(self._active_nodes),+ "pending_execution": self._pending_execution,+ "active_node_count": self._active_node_count,+ "default_start_executed": self._default_start_executed,+ }+ return state++ async def load_state(self, state: Mapping[str, Any]) -> None:+ """Restore execution state from saved data."""+ self._message_thread = [self._message_factory.create(msg) for msg in state["message_thread"]]+ self._current_turn = state["current_turn"]+ self._active_nodes = set(state["active_nodes"])+ self._pending_execution = state["pending_execution"]+ self._active_node_count = state["active_node_count"]+ self._default_start_executed = state.get("default_start_executed", False)++ async def reset(self) -> None:+ """Reset execution state to the start of the graph."""+ self._current_turn = 0+ self._message_thread.clear()+ if self._termination_condition:+ await self._termination_condition.reset()++ self._active_nodes = set()+ self._active_node_count = {node: 0 for node in self._graph.nodes}+ self._pending_execution = {node: [] for node in self._start_nodes}+ self._default_start_executed = False+++class _StopAgent(BaseChatAgent):+ def __init__(self) -> None:+ super().__init__(_DIGRAPH_STOP_AGENT_NAME, "Agent that terminates the GraphFlow.")++ @property+ def produced_message_types(self) -> Sequence[type[ChatMessage]]:+ return (TextMessage, StopMessage)++ async def on_messages(self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken) -> Response:+ return Response(chat_message=StopMessage(content=_DIGRAPH_STOP_AGENT_MESSAGE, source=self.name))++ async def on_reset(self, cancellation_token: CancellationToken) -> None:+ pass+++class GraphFlowConfig(BaseModel):+ """The declarative configuration for GraphFlow."""++ participants: List[ComponentModel]+ termination_condition: ComponentModel | None = None+ max_turns: int | None = None+ graph: DiGraph # The execution graph for agents+++class GraphFlow(BaseGroupChat, Component[GraphFlowConfig]):+ """A team that runs a group chat following a Directed Graph execution pattern.++ .. warning::++ This is an experimental feature, and the API will change in the future releases.++ This group chat executes agents based on a directed graph (:class:`DiGraph`) structure,+ allowing complex workflows such as sequential execution, parallel fan-out,+ conditional branching, join patterns, and loops with explicit exit conditions.++ The execution order is determined by the edges defined in the `DiGraph`. Each node+ in the graph corresponds to an agent, and edges define the flow of messages between agents.+ Nodes can be configured to activate when:++ - **All** parent nodes have completed (activation="all") → default+ - **Any** parent node completes (activation="any")++ Conditional branching is supported using edge conditions, where the next agent(s) are selected+ based on content in the chat history. Loops are permitted as long as there is a condition+ that eventually exits the loop.++ .. note::++ Use the :class:`DiGraphBuilder` class to create a :class:`DiGraph` easily. It provides a fluent API+ for adding nodes and edges, setting entry points, and validating the graph structure.+ See the :class:`DiGraphBuilder` documentation for more details.+ The :class:`GraphFlow` class is designed to be used with the :class:`DiGraphBuilder` for creating complex workflows.+++ Args:+ participants (List[ChatAgent]): The participants in the group chat.+ termination_condition (TerminationCondition, optional): Termination condition for the chat.+ max_turns (int, optional): Maximum number of turns before forcing termination.+ graph (DiGraph): Directed execution graph defining node flow and conditions.++ Raises:+ ValueError: If participant names are not unique, or if graph validation fails (e.g., cycles without exit).++ Examples:++ **Sequential Flow: A → B → C**++ .. code-block:: python++ import asyncio++ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.conditions import MaxMessageTermination+ from autogen_agentchat.teams import DiGraphBuilder, GraphFlow+ from autogen_ext.models.openai import OpenAIChatCompletionClient+++ async def main():+ # Initialize agents with OpenAI model clients.+ model_client = OpenAIChatCompletionClient(model="gpt-4.1-nano")+ agent_a = AssistantAgent("A", model_client=model_client, system_message="You are a helpful assistant.")+ agent_b = AssistantAgent("B", model_client=model_client, system_message="Translate input to Chinese.")+ agent_c = AssistantAgent("C", model_client=model_client, system_message="Translate input to English.")++ # Create a directed graph with sequential flow A -> B -> C.+ builder = DiGraphBuilder()+ builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ builder.add_edge(agent_a, agent_b).add_edge(agent_b, agent_c)+ graph = builder.build()++ # Create a GraphFlow team with the directed graph.+ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ termination_condition=MaxMessageTermination(5),+ )++ # Run the team and print the events.+ async for event in team.run_stream(task="Write a short story about a cat."):+ print(event)+++ asyncio.run(main())++ **Parallel Fan-out: A → (B, C)**++ .. code-block:: python++ import asyncio++ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.conditions import MaxMessageTermination+ from autogen_agentchat.teams import DiGraphBuilder, GraphFlow+ from autogen_ext.models.openai import OpenAIChatCompletionClient+++ async def main():+ # Initialize agents with OpenAI model clients.+ model_client = OpenAIChatCompletionClient(model="gpt-4.1-nano")+ agent_a = AssistantAgent("A", model_client=model_client, system_message="You are a helpful assistant.")+ agent_b = AssistantAgent("B", model_client=model_client, system_message="Translate input to Chinese.")+ agent_c = AssistantAgent("C", model_client=model_client, system_message="Translate input to Japanese.")++ # Create a directed graph with fan-out flow A -> (B, C).+ builder = DiGraphBuilder()+ builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ builder.add_edge(agent_a, agent_b).add_edge(agent_a, agent_c)+ graph = builder.build()++ # Create a GraphFlow team with the directed graph.+ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ termination_condition=MaxMessageTermination(5),+ )++ # Run the team and print the events.+ async for event in team.run_stream(task="Write a short story about a cat."):+ print(event)+++ asyncio.run(main())++ **Conditional Branching: A → B (if 'yes') or C (if 'no')**++ .. code-block:: python++ import asyncio++ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.conditions import MaxMessageTermination+ from autogen_agentchat.teams import DiGraphBuilder, GraphFlow+ from autogen_ext.models.openai import OpenAIChatCompletionClient+++ async def main():+ # Initialize agents with OpenAI model clients.+ model_client = OpenAIChatCompletionClient(model="gpt-4.1-nano")+ agent_a = AssistantAgent(+ "A",+ model_client=model_client,+ system_message="Detect if the input is in Chinese. If it is, say 'yes', else say 'no', and nothing else.",+ )+ agent_b = AssistantAgent("B", model_client=model_client, system_message="Translate input to English.")+ agent_c = AssistantAgent("C", model_client=model_client, system_message="Translate input to Chinese.")++ # Create a directed graph with conditional branching flow A -> B ("yes"), A -> C ("no").+ builder = DiGraphBuilder()+ builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ builder.add_edge(agent_a, agent_b, condition="yes")+ builder.add_edge(agent_a, agent_c, condition="no")+ graph = builder.build()++ # Create a GraphFlow team with the directed graph.+ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ termination_condition=MaxMessageTermination(5),+ )++ # Run the team and print the events.+ async for event in team.run_stream(task="AutoGen is a framework for building AI agents."):+ print(event)+++ asyncio.run(main())++ **Loop with exit condition: A → B → C (if 'APPROVE') or A (if 'REJECT')**++ .. code-block:: python++ import asyncio++ from autogen_agentchat.agents import AssistantAgent+ from autogen_agentchat.conditions import MaxMessageTermination+ from autogen_agentchat.teams import DiGraphBuilder, GraphFlow+ from autogen_ext.models.openai import OpenAIChatCompletionClient+++ async def main():+ # Initialize agents with OpenAI model clients.+ model_client = OpenAIChatCompletionClient(model="gpt-4.1")+ agent_a = AssistantAgent(+ "A",+ model_client=model_client,+ system_message="You are a helpful assistant.",+ )+ agent_b = AssistantAgent(+ "B",+ model_client=model_client,+ system_message="Provide feedback on the input, if your feedback has been addressed, "+ "say 'APPROVE', else say 'REJECT' and provide a reason.",+ )+ agent_c = AssistantAgent(+ "C", model_client=model_client, system_message="Translate the final product to Korean."+ )++ # Create a loop graph with conditional exit: A -> B -> C ("APPROVE"), B -> A ("REJECT").+ builder = DiGraphBuilder()+ builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ builder.add_edge(agent_a, agent_b)+ builder.add_conditional_edges(agent_b, {"APPROVE": agent_c, "REJECT": agent_a})+ builder.set_entry_point(agent_a)+ graph = builder.build()++ # Create a GraphFlow team with the directed graph.+ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ termination_condition=MaxMessageTermination(20), # Max 20 messages to avoid infinite loop.+ )++ # Run the team and print the events.+ async for event in team.run_stream(task="Write a short poem about AI Agents."):+ print(event)+++ asyncio.run(main())+ """++ component_config_schema = GraphFlowConfig+ component_provider_override = "autogen_agentchat.teams.GraphFlow"++ def __init__(+ self,+ participants: List[ChatAgent],+ graph: DiGraph,+ termination_condition: TerminationCondition | None = None,+ max_turns: int | None = None,+ runtime: AgentRuntime | None = None,+ custom_message_types: List[type[BaseAgentEvent | BaseChatMessage]] | None = None,+ ) -> None:+ stop_agent = _StopAgent()+ stop_agent_termination = StopMessageTermination()+ termination_condition = (+ stop_agent_termination+ if not termination_condition+ else OrTerminationCondition(stop_agent_termination, termination_condition)+ )++ participants = [stop_agent] + participants+ super().__init__(+ participants,+ group_chat_manager_name="GraphManager",+ group_chat_manager_class=GraphFlowManager,+ termination_condition=termination_condition,+ max_turns=max_turns,+ runtime=runtime,+ custom_message_types=custom_message_types,+ )+ self._graph = graph++ def _create_group_chat_manager_factory(+ self,+ name: str,+ group_topic_type: str,+ output_topic_type: str,+ participant_topic_types: List[str],+ participant_names: List[str],+ participant_descriptions: List[str],+ output_message_queue: asyncio.Queue[BaseAgentEvent | BaseChatMessage | GroupChatTermination],+ termination_condition: TerminationCondition | None,+ max_turns: int | None,+ message_factory: MessageFactory,+ ) -> Callable[[], GraphFlowManager]:+ """Creates the factory method for initializing the DiGraph-based chat manager."""++ def _factory() -> GraphFlowManager:+ return GraphFlowManager(+ name=name,+ group_topic_type=group_topic_type,+ output_topic_type=output_topic_type,+ participant_topic_types=participant_topic_types,+ participant_names=participant_names,+ participant_descriptions=participant_descriptions,+ output_message_queue=output_message_queue,+ termination_condition=termination_condition,+ max_turns=max_turns,+ message_factory=message_factory,+ graph=self._graph,+ )++ return _factory++ def _to_config(self) -> GraphFlowConfig:+ """Converts the instance into a configuration object."""+ participants = [participant.dump_component() for participant in self._participants]+ termination_condition = self._termination_condition.dump_component() if self._termination_condition else None+ return GraphFlowConfig(+ participants=participants,+ termination_condition=termination_condition,+ max_turns=self._max_turns,+ graph=self._graph,+ )++ @classmethod+ def _from_config(cls, config: GraphFlowConfig) -> Self:+ """Reconstructs an instance from a configuration object."""+ participants = [ChatAgent.load_component(participant) for participant in config.participants]+ termination_condition = (+ TerminationCondition.load_component(config.termination_condition) if config.termination_condition else None+ )+ return cls(+ participants, graph=config.graph, termination_condition=termination_condition, max_turns=config.max_turns+ )diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_graph_builder.py b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_graph_builder.pynew file mode 100644index 000000000..ec1e1b611--- /dev/null+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_graph/_graph_builder.py@@ -0,0 +1,122 @@+from typing import Dict, Literal, Optional, Union++from autogen_agentchat.base import ChatAgent++from ._digraph_group_chat import DiGraph, DiGraphEdge, DiGraphNode+++class DiGraphBuilder:+ """+ A fluent builder for constructing :class:`DiGraph` execution graphs used in :class:`GraphFlow`.++ .. warning::++ This is an experimental feature, and the API will change in the future releases.++ This utility provides a convenient way to programmatically build a graph of agent interactions,+ including complex execution flows such as:++ - Sequential chains+ - Parallel fan-outs+ - Conditional branching+ - Cyclic loops with safe exits++ Each node in the graph represents an agent. Edges define execution paths between agents,+ and can optionally be conditioned on message content.++ The builder is compatible with the `Graph` runner and supports both standard and filtered agents.++ Methods:+ - add_node(agent, activation): Add an agent node to the graph.+ - add_edge(source, target, condition): Connect two nodes optionally with a condition.+ - add_conditional_edges(source, condition_to_target): Add multiple conditional edges from a source.+ - set_entry_point(agent): Define the default start node (optional).+ - build(): Generate a validated `DiGraph`.+ - get_participants(): Return the list of added agents.++ Example — Sequential Flow A → B → C:+ >>> builder = GraphBuilder()+ >>> builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ >>> builder.add_edge(agent_a, agent_b).add_edge(agent_b, agent_c)+ >>> team = Graph(+ ... participants=builder.get_participants(),+ ... graph=builder.build(),+ ... termination_condition=MaxMessageTermination(5),+ ... )++ Example — Parallel Fan-out A → (B, C):+ >>> builder = GraphBuilder()+ >>> builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ >>> builder.add_edge(agent_a, agent_b).add_edge(agent_a, agent_c)++ Example — Conditional Branching A → B ("yes"), A → C ("no"):+ >>> builder = GraphBuilder()+ >>> builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ >>> builder.add_conditional_edges(agent_a, {"yes": agent_b, "no": agent_c})++ Example — Loop: A → B → A ("loop"), B → C ("exit"):+ >>> builder = GraphBuilder()+ >>> builder.add_node(agent_a).add_node(agent_b).add_node(agent_c)+ >>> builder.add_edge(agent_a, agent_b)+ >>> builder.add_conditional_edges(agent_b, {"loop": agent_a, "exit": agent_c})+ """++ def __init__(self) -> None:+ self.nodes: Dict[str, DiGraphNode] = {}+ self.agents: Dict[str, ChatAgent] = {}+ self._default_start_node: Optional[str] = None++ def _get_name(self, obj: Union[str, ChatAgent]) -> str:+ return obj if isinstance(obj, str) else obj.name++ def add_node(self, agent: ChatAgent, activation: Literal["all", "any"] = "all") -> "DiGraphBuilder":+ """Add a node to the graph and register its agent."""+ name = agent.name+ if name not in self.nodes:+ self.nodes[name] = DiGraphNode(name=name, edges=[], activation=activation)+ self.agents[name] = agent+ return self++ def add_edge(+ self, source: Union[str, ChatAgent], target: Union[str, ChatAgent], condition: Optional[str] = None+ ) -> "DiGraphBuilder":+ """Add a directed edge from source to target, optionally with a condition."""+ source_name = self._get_name(source)+ target_name = self._get_name(target)++ if source_name not in self.nodes:+ raise ValueError(f"Source node '{source_name}' must be added before adding an edge.")+ if target_name not in self.nodes:+ raise ValueError(f"Target node '{target_name}' must be added before adding an edge.")++ self.nodes[source_name].edges.append(DiGraphEdge(target=target_name, condition=condition))+ return self++ def add_conditional_edges(+ self, source: Union[str, ChatAgent], condition_to_target: Dict[str, Union[str, ChatAgent]]+ ) -> "DiGraphBuilder":+ """Add multiple conditional edges from a source node based on condition strings."""+ for condition, target in condition_to_target.items():+ self.add_edge(source, target, condition)+ return self++ def set_entry_point(self, name: Union[str, ChatAgent]) -> "DiGraphBuilder":+ """Set the default start node of the graph."""+ node_name = self._get_name(name)+ if node_name not in self.nodes:+ raise ValueError(f"Start node '{node_name}' must be added before setting as entry point.")+ self._default_start_node = node_name+ return self++ def build(self) -> DiGraph:+ """Build and validate the DiGraph."""+ graph = DiGraph(+ nodes=self.nodes,+ default_start_node=self._default_start_node,+ )+ graph.graph_validate()+ return graph++ def get_participants(self) -> list[ChatAgent]:+ """Return the list of agents in the builder, in insertion order."""+ return list(self.agents.values())diff --git a/python/packages/autogen-agentchat/tests/test_group_chat_graph.py b/python/packages/autogen-agentchat/tests/test_group_chat_graph.pynew file mode 100644index 000000000..c6aa5362d--- /dev/null+++ b/python/packages/autogen-agentchat/tests/test_group_chat_graph.py@@ -0,0 +1,1401 @@+import asyncio+from typing import Any, AsyncGenerator, Callable, Dict, List, Sequence, Set+from unittest.mock import AsyncMock, patch++import pytest+import pytest_asyncio+from autogen_agentchat.agents import (+ AssistantAgent,+ BaseChatAgent,+ MessageFilterAgent,+ MessageFilterConfig,+ PerSourceFilter,+)+from autogen_agentchat.base import Response, TaskResult+from autogen_agentchat.conditions import MaxMessageTermination+from autogen_agentchat.messages import BaseChatMessage, ChatMessage, MessageFactory, TextMessage+from autogen_agentchat.messages import BaseTextChatMessage as TextChatMessage+from autogen_agentchat.teams import (+ DiGraphBuilder,+ GraphFlow,+)+from autogen_agentchat.teams._group_chat._events import ( # type: ignore[attr-defined]+ BaseAgentEvent,+ GroupChatTermination,+)+from autogen_agentchat.teams._group_chat._graph._digraph_group_chat import (+ _DIGRAPH_STOP_AGENT_NAME, # pyright: ignore[reportPrivateUsage]+ DiGraph,+ DiGraphEdge,+ DiGraphNode,+ GraphFlowManager,+)+from autogen_core import AgentRuntime, CancellationToken, Component, SingleThreadedAgentRuntime+from autogen_ext.models.replay import ReplayChatCompletionClient+from pydantic import BaseModel+++def test_create_digraph() -> None:+ """Test creating a simple directed graph."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ assert "A" in graph.nodes+ assert "B" in graph.nodes+ assert "C" in graph.nodes+ assert len(graph.nodes["A"].edges) == 1+ assert len(graph.nodes["B"].edges) == 1+ assert len(graph.nodes["C"].edges) == 0+++def test_get_parents() -> None:+ """Test computing parent relationships."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ parents = graph.get_parents()+ assert parents["A"] == []+ assert parents["B"] == ["A"]+ assert parents["C"] == ["B"]+++def test_get_start_nodes() -> None:+ """Test retrieving start nodes (nodes with no incoming edges)."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ start_nodes = graph.get_start_nodes()+ assert start_nodes == set(["A"])+++def test_get_leaf_nodes() -> None:+ """Test retrieving leaf nodes (nodes with no outgoing edges)."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ leaf_nodes = graph.get_leaf_nodes()+ assert leaf_nodes == set(["C"])+++def test_serialization() -> None:+ """Test serializing and deserializing the graph."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B", condition="trigger1")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ serialized = graph.model_dump_json()+ deserialized_graph = DiGraph.model_validate_json(serialized)++ assert deserialized_graph.nodes["A"].edges[0].target == "B"+ assert deserialized_graph.nodes["A"].edges[0].condition == "trigger1"+ assert deserialized_graph.nodes["B"].edges[0].target == "C"+++def test_invalid_graph_no_start_node() -> None:+ """Test validation failure when there is no start node."""+ graph = DiGraph(+ nodes={+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="B")]), # Forms a cycle+ }+ )++ start_nodes = graph.get_start_nodes()+ assert len(start_nodes) == 0 # Now it correctly fails when no start nodes exist+++def test_invalid_graph_no_leaf_node() -> None:+ """Test validation failure when there is no leaf node."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="A")]), # Circular reference+ }+ )++ leaf_nodes = graph.get_leaf_nodes()+ assert len(leaf_nodes) == 0 # No true endpoint because of cycle+++def test_condition_edge_execution() -> None:+ """Test conditional edge execution support."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B", condition="TRIGGER")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ assert graph.nodes["A"].edges[0].condition == "TRIGGER"+ assert graph.nodes["B"].edges[0].condition is None+++def test_graph_with_multiple_paths() -> None:+ """Test a graph with multiple execution paths."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B"), DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="D")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="D")]),+ "D": DiGraphNode(name="D", edges=[]),+ }+ )++ parents = graph.get_parents()+ assert parents["B"] == ["A"]+ assert parents["C"] == ["A"]+ assert parents["D"] == ["B", "C"]++ start_nodes = graph.get_start_nodes()+ assert start_nodes == set(["A"])++ leaf_nodes = graph.get_leaf_nodes()+ assert leaf_nodes == set(["D"])+++def test_cycle_detection_no_cycle() -> None:+ """Test that a valid acyclic graph returns False for cycle check."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )+ assert not graph.has_cycles_with_exit()+++def test_cycle_detection_with_exit_condition() -> None:+ """Test a graph with cycle and conditional exit passes validation."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="A", condition="exit")]), # Cycle with condition+ }+ )+ assert graph.has_cycles_with_exit()+++def test_cycle_detection_without_exit_condition() -> None:+ """Test that cycle without exit condition raises an error."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="A")]), # Cycle without condition+ "D": DiGraphNode(name="D", edges=[DiGraphEdge(target="E")]),+ "E": DiGraphNode(name="E", edges=[]),+ }+ )+ with pytest.raises(ValueError, match="Cycle detected without exit condition: A -> B -> C -> A"):+ graph.has_cycles_with_exit()+++def test_validate_graph_success() -> None:+ """Test successful validation of a valid graph."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[]),+ }+ )+ # No error should be raised+ graph.graph_validate()+ assert not graph.get_has_cycles()+++def test_validate_graph_missing_start_node() -> None:+ """Test validation failure when no start node exists."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="A")]), # Cycle+ }+ )+ with pytest.raises(ValueError, match="Graph must have at least one start node"):+ graph.graph_validate()+++def test_validate_graph_missing_leaf_node() -> None:+ """Test validation failure when no leaf node exists."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="B")]), # Cycle+ }+ )+ with pytest.raises(ValueError, match="Graph must have at least one leaf node"):+ graph.graph_validate()+++def test_validate_graph_mixed_conditions() -> None:+ """Test validation failure when node has mixed conditional and unconditional edges."""+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B", condition="cond"), DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )+ with pytest.raises(ValueError, match="Node 'A' has a mix of conditional and unconditional edges"):+ graph.graph_validate()+++def test_get_valid_target() -> None:+ node = DiGraphNode(+ name="A",+ edges=[DiGraphEdge(target="B", condition="approve"), DiGraphEdge(target="C", condition="reject")],+ )+ manager = GraphFlowManager.__new__(GraphFlowManager)++ assert manager._get_valid_target(node, "please approve this") == "B" # pyright: ignore[reportPrivateUsage]+ assert manager._get_valid_target(node, "i reject this") == "C" # pyright: ignore[reportPrivateUsage]+ with pytest.raises(RuntimeError):+ manager._get_valid_target(node, "unknown path") # pyright: ignore[reportPrivateUsage]+++def test_is_node_ready_all_and_any() -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[], activation="all"),+ }+ )++ manager = GraphFlowManager.__new__(GraphFlowManager)+ manager._graph = graph # pyright: ignore[reportPrivateUsage]+ manager._parents = graph.get_parents() # pyright: ignore[reportPrivateUsage]++ # === Test "all" activation ===+ # Case 1: No parent finished+ manager._pending_execution = {"C": []} # pyright: ignore[reportPrivateUsage]+ assert not manager._is_node_ready("C") # pyright: ignore[reportPrivateUsage]++ # Case 2: One parent finished+ manager._pending_execution = {"C": ["A"]} # pyright: ignore[reportPrivateUsage]+ assert not manager._is_node_ready("C") # pyright: ignore[reportPrivateUsage]++ # Case 3: All parents finished+ manager._pending_execution = {"C": ["A", "B"]} # pyright: ignore[reportPrivateUsage]+ assert manager._is_node_ready("C") # pyright: ignore[reportPrivateUsage]++ # === Test "any" activation ===+ graph.nodes["C"].activation = "any"++ # Case 1: No parent finished+ manager._pending_execution = {"C": []} # pyright: ignore[reportPrivateUsage]+ assert not manager._is_node_ready("C") # pyright: ignore[reportPrivateUsage]++ # Case 2: One parent finished+ manager._pending_execution = {"C": ["B"]} # pyright: ignore[reportPrivateUsage]+ assert manager._is_node_ready("C") # pyright: ignore[reportPrivateUsage]++ # Case 3: All parents finished+ manager._pending_execution = {"C": ["A", "B"]} # pyright: ignore[reportPrivateUsage]+ assert manager._is_node_ready("C") # pyright: ignore[reportPrivateUsage]+++async def test_invalid_digraph_manager_cycle_without_termination() -> None:+ """Test GraphManager raises error for cyclic graph without termination condition."""+ # Create a cyclic graph A → B → A+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="A")]),+ }+ )++ output_queue: asyncio.Queue[BaseAgentEvent | BaseChatMessage | GroupChatTermination] = asyncio.Queue()++ with patch(+ "autogen_agentchat.teams._group_chat._base_group_chat_manager.BaseGroupChatManager.__init__",+ return_value=None,+ ):+ manager = GraphFlowManager.__new__(GraphFlowManager)++ with pytest.raises(ValueError, match="Graph must have at least one start node"):+ manager.__init__( # type: ignore[misc]+ name="test_manager",+ group_topic_type="topic",+ output_topic_type="topic",+ participant_topic_types=["topic1", "topic2"],+ participant_names=["A", "B"],+ participant_descriptions=["Agent A", "Agent B"],+ output_message_queue=output_queue,+ termination_condition=None,+ max_turns=None,+ message_factory=MessageFactory(),+ graph=graph,+ )+++def digraph_manager() -> Callable[..., GraphFlowManager]:+ @patch(+ "autogen_agentchat.teams._group_chat._base_group_chat_manager.BaseGroupChatManager.__init__", return_value=None+ )+ def _create(+ _: Any,+ graph: DiGraph,+ active_nodes: Set[str] | None = None,+ thread: List[BaseAgentEvent | BaseChatMessage] | None = None,+ pending: Dict[str, List[str]] | None = None,+ ) -> GraphFlowManager:+ manager = GraphFlowManager.__new__(GraphFlowManager)+ manager._graph = graph # pyright: ignore[reportPrivateUsage]+ manager._parents = graph.get_parents() # pyright: ignore[reportPrivateUsage]+ manager._start_nodes = graph.get_start_nodes() # pyright: ignore[reportPrivateUsage]+ manager._leaf_nodes = graph.get_leaf_nodes() # pyright: ignore[reportPrivateUsage]+ manager._active_nodes = set(active_nodes or []) # pyright: ignore[reportPrivateUsage]+ manager._active_node_count = {node: 0 for node in graph.nodes} # pyright: ignore[reportPrivateUsage]+ manager._message_factory = MessageFactory() # pyright: ignore[reportPrivateUsage]+ manager._message_thread = thread if thread is not None else [] # pyright: ignore[reportPrivateUsage]+ manager._pending_execution = pending if pending is not None else {node: [] for node in graph.get_start_nodes()} # pyright: ignore[reportPrivateUsage]+ manager._name = "test_manager" # pyright: ignore[reportPrivateUsage]+ manager._use_default_start = False # pyright: ignore[reportPrivateUsage]+ return manager++ return _create+++# -------------------- Test: Sequential Flow --------------------+async def test_select_speakers_linear(digraph_manager: Callable[..., GraphFlowManager]) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )+ message_thread = [TextChatMessage(source="A", content="done", metadata={})]+ manager = digraph_manager(graph=graph, active_nodes={"A"}, thread=message_thread, pending={"B": [], "C": []})++ result = await manager.select_speakers(manager._message_thread) # pyright: ignore[reportPrivateUsage]+ assert result == ["B"]+ assert "B" in manager._active_nodes # pyright: ignore[reportPrivateUsage]+++# -------------------- Test: Parallel Fan-out --------------------+++async def test_select_speakers_parallel(digraph_manager: Callable[..., GraphFlowManager]) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B"), DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )+ message_thread = [TextChatMessage(source="A", content="done", metadata={})]+ manager = digraph_manager(graph=graph, active_nodes={"A"}, thread=message_thread, pending={"B": [], "C": []})++ result = await manager.select_speakers(manager._message_thread) # pyright: ignore[reportPrivateUsage]+ assert set(result) == {"B", "C"}+ assert "B" in manager._active_nodes # pyright: ignore[reportPrivateUsage]+ assert "C" in manager._active_nodes # pyright: ignore[reportPrivateUsage]+++# -------------------- Test: Conditional Path --------------------+async def test_select_speakers_conditional(digraph_manager: Callable[..., GraphFlowManager]) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(+ name="A", edges=[DiGraphEdge(target="B", condition="yes"), DiGraphEdge(target="C", condition="no")]+ ),+ "B": DiGraphNode(name="B", edges=[]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )+ message_thread = [TextChatMessage(source="A", content="no", metadata={})]+ manager = digraph_manager(graph=graph, active_nodes={"A"}, thread=message_thread, pending={"B": [], "C": []})++ result = await manager.select_speakers(manager._message_thread) # pyright: ignore[reportPrivateUsage]+ assert result == ["C"]+ assert "C" in manager._active_nodes # pyright: ignore[reportPrivateUsage]+++async def test_select_speakers_from_start_nodes(digraph_manager: Callable[..., GraphFlowManager]) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[]),+ "B": DiGraphNode(name="B", edges=[]),+ }+ )+ # No prior message — both are start nodes+ manager = digraph_manager(graph=graph, active_nodes=set(), thread=[], pending={"A": [], "B": []})+ result = await manager.select_speakers([])+ assert set(result) == {"A", "B"}+++async def test_select_speakers_termination(digraph_manager: Callable[..., GraphFlowManager]) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[]),+ }+ )++ # Create the manager and manually patch _signal_termination to track calls+ manager = digraph_manager(+ graph=graph, active_nodes={"A"}, thread=[TextChatMessage(source="A", content="done", metadata={})], pending={}+ )+ manager._signal_termination = AsyncMock() # type: ignore[assignment]++ result = await manager.select_speakers(manager._message_thread) # pyright: ignore[reportPrivateUsage]++ # No speakers left to run, so result should be empty+ assert result == [_DIGRAPH_STOP_AGENT_NAME]+++async def test_select_speakers_conditional_all_activation(+ digraph_manager: Callable[..., GraphFlowManager],+) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(+ name="A", edges=[DiGraphEdge(target="B", condition="yes"), DiGraphEdge(target="C", condition="no")]+ ),+ "B": DiGraphNode(name="B", edges=[], activation="all"),+ "C": DiGraphNode(name="C", edges=[], activation="all"),+ }+ )+ message_thread = [TextChatMessage(source="A", content="no", metadata={})]+ manager = digraph_manager(graph=graph, active_nodes={"A"}, thread=message_thread, pending={"B": [], "C": []})++ result = await manager.select_speakers(manager._message_thread) # pyright: ignore[reportPrivateUsage]+ assert result == ["C"]+ assert "C" in manager._active_nodes # pyright: ignore[reportPrivateUsage]+++async def test_select_speakers_conditional_any_activation(+ digraph_manager: Callable[..., GraphFlowManager],+) -> None:+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(+ name="A", edges=[DiGraphEdge(target="B", condition="yes"), DiGraphEdge(target="C", condition="no")]+ ),+ "B": DiGraphNode(name="B", edges=[], activation="any"),+ "C": DiGraphNode(name="C", edges=[], activation="any"),+ }+ )+ message_thread = [TextChatMessage(source="A", content="yes", metadata={})]+ manager = digraph_manager(graph=graph, active_nodes={"A"}, thread=message_thread, pending={"B": [], "C": []})++ result = await manager.select_speakers(manager._message_thread) # pyright: ignore[reportPrivateUsage]+ assert result == ["B"]+ assert "B" in manager._active_nodes # pyright: ignore[reportPrivateUsage]+++class _EchoAgent(BaseChatAgent):+ def __init__(self, name: str, description: str) -> None:+ super().__init__(name, description)+ self._last_message: str | None = None+ self._total_messages = 0++ @property+ def produced_message_types(self) -> Sequence[type[BaseChatMessage]]:+ return (TextMessage,)++ @property+ def total_messages(self) -> int:+ return self._total_messages++ async def on_messages(self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken) -> Response:+ if len(messages) > 0:+ assert isinstance(messages[0], TextMessage)+ self._last_message = messages[0].content+ self._total_messages += 1+ return Response(chat_message=TextMessage(content=messages[0].content, source=self.name))+ else:+ assert self._last_message is not None+ self._total_messages += 1+ return Response(chat_message=TextMessage(content=self._last_message, source=self.name))++ async def on_reset(self, cancellation_token: CancellationToken) -> None:+ self._last_message = None+++@pytest_asyncio.fixture(params=["single_threaded", "embedded"]) # type: ignore+async def runtime(request: pytest.FixtureRequest) -> AsyncGenerator[AgentRuntime | None, None]:+ if request.param == "single_threaded":+ runtime = SingleThreadedAgentRuntime()+ runtime.start()+ yield runtime+ await runtime.stop()+ elif request.param == "embedded":+ yield None+++TaskType = str | List[ChatMessage] | ChatMessage+++async def test_digraph_group_chat_sequential_execution(runtime: AgentRuntime | None) -> None:+ # 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 chat+ result: TaskResult = await team.run(task="Hello from User")++ assert len(result.messages) == 5+ assert isinstance(result.messages[0], TextMessage)+ assert result.messages[0].source == "user"+ assert result.messages[1].source == "A"+ assert result.messages[2].source == "B"+ assert result.messages[3].source == "C"+ assert result.messages[4].source == _DIGRAPH_STOP_AGENT_NAME+ assert all(isinstance(m, TextMessage) for m in result.messages[:-1])+ assert result.stop_reason is not None+++async def test_digraph_group_chat_parallel_fanout(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B"), DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[]),+ "C": DiGraphNode(name="C", edges=[]),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result: TaskResult = await team.run(task="Start")+ assert len(result.messages) == 5+ assert result.messages[0].source == "user"+ assert result.messages[1].source == "A"+ assert set(m.source for m in result.messages[2:-1]) == {"B", "C"}+ assert result.messages[-1].source == _DIGRAPH_STOP_AGENT_NAME+ assert result.stop_reason is not None+++async def test_digraph_group_chat_parallel_join_all(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[], activation="all"),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result: TaskResult = await team.run(task="Go")+ assert len(result.messages) == 5+ assert result.messages[0].source == "user"+ assert set([result.messages[1].source, result.messages[2].source]) == {"A", "B"}+ assert result.messages[3].source == "C"+ assert result.messages[-1].source == _DIGRAPH_STOP_AGENT_NAME+ assert result.stop_reason is not None+++async def test_digraph_group_chat_parallel_join_any(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="C")]),+ "C": DiGraphNode(name="C", edges=[], activation="any"),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result: TaskResult = await team.run(task="Start")++ assert len(result.messages) == 5+ assert result.messages[0].source == "user"+ sources = [m.source for m in result.messages[1:]]++ # C must be last+ assert sources[-2] == "C"++ # A and B must both execute+ assert {"A", "B"}.issubset(set(sources))++ # One of A or B must execute before C+ index_a = sources.index("A")+ index_b = sources.index("B")+ index_c = sources.index("C")+ assert index_c > min(index_a, index_b)+ assert result.messages[-1].source == _DIGRAPH_STOP_AGENT_NAME+ assert result.stop_reason is not None+++async def test_digraph_group_chat_multiple_start_nodes(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[]),+ "B": DiGraphNode(name="B", edges=[]),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result: TaskResult = await team.run(task="Start")+ assert len(result.messages) == 4+ assert result.messages[0].source == "user"+ assert set(m.source for m in result.messages[1:-1]) == {"A", "B"}+ assert result.messages[-1].source == _DIGRAPH_STOP_AGENT_NAME+ assert result.stop_reason is not None+++async def test_digraph_group_chat_disconnected_graph(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")+ agent_d = _EchoAgent("D", description="Echo agent D")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(name="B", edges=[]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="D")]),+ "D": DiGraphNode(name="D", edges=[]),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c, agent_d],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(10),+ )++ result: TaskResult = await team.run(task="Go")+ assert len(result.messages) == 6+ assert result.messages[0].source == "user"+ assert {"A", "C"} == set([result.messages[1].source, result.messages[2].source])+ assert {"B", "D"} == set([result.messages[3].source, result.messages[4].source])+ assert result.messages[-1].source == _DIGRAPH_STOP_AGENT_NAME+ assert result.stop_reason is not None+++async def test_digraph_group_chat_conditional_branch(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(+ name="A", edges=[DiGraphEdge(target="B", condition="yes"), DiGraphEdge(target="C", condition="no")]+ ),+ "B": DiGraphNode(name="B", edges=[], activation="any"),+ "C": DiGraphNode(name="C", edges=[], activation="any"),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result = await team.run(task="Trigger yes")+ assert result.messages[2].source == "B"+++async def test_digraph_group_chat_loop_with_exit_condition(runtime: AgentRuntime | None) -> None:+ # Agents A and C: Echo Agents+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_c = _EchoAgent("C", description="Echo agent C")++ # Replay model client for agent B+ model_client = ReplayChatCompletionClient(+ chat_completions=[+ "loop", # First time B will ask to loop+ "loop", # Second time B will ask to loop+ "exit", # Third time B will say exit+ ]+ )+ # Agent B: Assistant Agent using Replay Client+ agent_b = AssistantAgent("B", description="Decision agent B", model_client=model_client)++ # DiGraph: A → B → C (conditional back to A or terminate)+ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(+ name="B", edges=[DiGraphEdge(target="C", condition="exit"), DiGraphEdge(target="A", condition="loop")]+ ),+ "C": DiGraphNode(name="C", edges=[]),+ },+ default_start_node="A",+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(20),+ )++ # Run+ result = await team.run(task="Start")++ # Assert message order+ expected_sources = [+ "user",+ "A",+ "B", # 1st loop+ "A",+ "B", # 2nd loop+ "A",+ "B",+ "C",+ _DIGRAPH_STOP_AGENT_NAME,+ ]++ actual_sources = [m.source for m in result.messages]++ assert actual_sources == expected_sources+ assert result.stop_reason is not None+ assert result.messages[-2].source == "C"+ assert any(m.content == "exit" for m in result.messages[:-1]) # type: ignore[attr-defined,union-attr]+ assert result.messages[-1].source == _DIGRAPH_STOP_AGENT_NAME+++async def test_digraph_group_chat_parallel_join_any_1(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")+ agent_d = _EchoAgent("D", description="Echo agent D")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B"), DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="D")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="D")]),+ "D": DiGraphNode(name="D", edges=[], activation="any"),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c, agent_d],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(10),+ )++ result = await team.run(task="Run parallel join")+ sequence = [msg.source for msg in result.messages if isinstance(msg, TextMessage)]+ assert sequence[0] == "user"+ # B and C should both run+ assert "B" in sequence+ assert "C" in sequence+ # D should trigger twice → once after B and once after C (order depends on runtime)+ d_indices = [i for i, s in enumerate(sequence) if s == "D"]+ assert len(d_indices) == 1+ # Each D trigger must be after corresponding B or C+ b_index = sequence.index("B")+ c_index = sequence.index("C")+ assert any(d > b_index for d in d_indices)+ assert any(d > c_index for d in d_indices)+ assert result.stop_reason is not None+++async def test_digraph_group_chat_chained_parallel_join_any(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")+ agent_d = _EchoAgent("D", description="Echo agent D")+ agent_e = _EchoAgent("E", description="Echo agent E")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B"), DiGraphEdge(target="C")]),+ "B": DiGraphNode(name="B", edges=[DiGraphEdge(target="D")]),+ "C": DiGraphNode(name="C", edges=[DiGraphEdge(target="D")]),+ "D": DiGraphNode(name="D", edges=[DiGraphEdge(target="E")], activation="any"),+ "E": DiGraphNode(name="E", edges=[], activation="any"),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c, agent_d, agent_e],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(20),+ )++ result = await team.run(task="Run chained parallel join-any")++ sequence = [msg.source for msg in result.messages if isinstance(msg, TextMessage)]++ # D should trigger twice+ d_indices = [i for i, s in enumerate(sequence) if s == "D"]+ assert len(d_indices) == 1+ # Each D trigger must be after corresponding B or C+ b_index = sequence.index("B")+ c_index = sequence.index("C")+ assert any(d > b_index for d in d_indices)+ assert any(d > c_index for d in d_indices)++ # E should also trigger twice → once after each D+ e_indices = [i for i, s in enumerate(sequence) if s == "E"]+ assert len(e_indices) == 1+ assert e_indices[0] > d_indices[0]+ assert result.stop_reason is not None+++async def test_digraph_group_chat_multiple_conditional(runtime: AgentRuntime | None) -> None:+ agent_a = _EchoAgent("A", description="Echo agent A")+ agent_b = _EchoAgent("B", description="Echo agent B")+ agent_c = _EchoAgent("C", description="Echo agent C")+ agent_d = _EchoAgent("D", description="Echo agent D")++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(+ name="A",+ edges=[+ DiGraphEdge(target="B", condition="apple"),+ DiGraphEdge(target="C", condition="banana"),+ DiGraphEdge(target="D", condition="cherry"),+ ],+ ),+ "B": DiGraphNode(name="B", edges=[]),+ "C": DiGraphNode(name="C", edges=[]),+ "D": DiGraphNode(name="D", edges=[]),+ }+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c, agent_d],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ # Test banana branch+ result = await team.run(task="banana")+ assert result.messages[2].source == "C"+++class _TestMessageFilterAgentConfig(BaseModel):+ name: str+ description: str = "Echo test agent"+++class _TestMessageFilterAgent(BaseChatAgent, Component[_TestMessageFilterAgentConfig]):+ component_config_schema = _TestMessageFilterAgentConfig+ component_provider_override = "test_group_chat_graph._TestMessageFilterAgent"++ def __init__(self, name: str, description: str = "Echo test agent") -> None:+ super().__init__(name=name, description=description)+ self.received_messages: list[BaseChatMessage] = []++ @property+ def produced_message_types(self) -> Sequence[type[BaseChatMessage]]:+ return (TextMessage,)++ async def on_messages(self, messages: Sequence[BaseChatMessage], cancellation_token: CancellationToken) -> Response:+ self.received_messages.extend(messages)+ return Response(chat_message=TextMessage(content="ACK", source=self.name))++ async def on_reset(self, cancellation_token: CancellationToken) -> None:+ self.received_messages.clear()++ def _to_config(self) -> _TestMessageFilterAgentConfig:+ return _TestMessageFilterAgentConfig(name=self.name, description=self.description)++ @classmethod+ def _from_config(cls, config: _TestMessageFilterAgentConfig) -> "_TestMessageFilterAgent":+ return cls(name=config.name, description=config.description)+++async def test_message_filter_agent_empty_filter_blocks_all() -> None:+ inner_agent = _TestMessageFilterAgent("inner")+ wrapper = MessageFilterAgent(+ name="wrapper",+ wrapped_agent=inner_agent,+ filter=MessageFilterConfig(per_source=[]),+ )+ messages = [+ TextMessage(source="user", content="Hello"),+ TextMessage(source="system", content="System msg"),+ ]+ await wrapper.on_messages(messages, CancellationToken())+ assert len(inner_agent.received_messages) == 0+++async def test_message_filter_agent_with_position_none_gets_all() -> None:+ inner_agent = _TestMessageFilterAgent("inner")+ wrapper = MessageFilterAgent(+ name="wrapper",+ wrapped_agent=inner_agent,+ filter=MessageFilterConfig(per_source=[PerSourceFilter(source="user", position=None, count=None)]),+ )+ messages = [+ TextMessage(source="user", content="A"),+ TextMessage(source="user", content="B"),+ TextMessage(source="system", content="Ignore this"),+ ]+ await wrapper.on_messages(messages, CancellationToken())+ assert len(inner_agent.received_messages) == 2+ assert {m.content for m in inner_agent.received_messages} == {"A", "B"} # type: ignore[attr-defined]+++async def test_digraph_group_chat() -> None:+ inner_agent = _TestMessageFilterAgent("agent")+ wrapper = MessageFilterAgent(+ name="agent",+ wrapped_agent=inner_agent,+ filter=MessageFilterConfig(+ per_source=[+ PerSourceFilter(source="user", position="last", count=2),+ PerSourceFilter(source="system", position="first", count=1),+ ]+ ),+ )+ config = wrapper.dump_component()+ loaded = MessageFilterAgent.load_component(config)+ assert loaded.name == "agent"+ assert loaded._filter == wrapper._filter # pyright: ignore[reportPrivateUsage]+ assert loaded._wrapped_agent.name == wrapper._wrapped_agent.name # pyright: ignore[reportPrivateUsage]++ # Run on_messages and validate filtering still works+ messages = [+ TextMessage(source="user", content="u1"),+ TextMessage(source="user", content="u2"),+ TextMessage(source="user", content="u3"),+ TextMessage(source="system", content="s1"),+ TextMessage(source="system", content="s2"),+ ]+ await loaded.on_messages(messages, CancellationToken())+ received = loaded._wrapped_agent.received_messages # type: ignore[attr-defined]+ assert {m.content for m in received} == {"u2", "u3", "s1"} # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]+++async def test_message_filter_agent_in_digraph_group_chat(runtime: AgentRuntime | None) -> None:+ inner_agent = _TestMessageFilterAgent("filtered")+ filtered = MessageFilterAgent(+ name="filtered",+ wrapped_agent=inner_agent,+ filter=MessageFilterConfig(+ per_source=[+ PerSourceFilter(source="user", position="last", count=1),+ ]+ ),+ )++ graph = DiGraph(+ nodes={+ "filtered": DiGraphNode(name="filtered", edges=[]),+ }+ )++ team = GraphFlow(+ participants=[filtered],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(3),+ )++ result = await team.run(task="only last user message matters")+ assert result.stop_reason is not None+ assert any(msg.source == "filtered" for msg in result.messages)+ assert any(msg.content == "ACK" for msg in result.messages if msg.source == "filtered") # type: ignore[attr-defined,union-attr]+++async def test_message_filter_agent_loop_graph_visibility(runtime: AgentRuntime | None) -> None:+ agent_a_inner = _TestMessageFilterAgent("A")+ agent_a = MessageFilterAgent(+ name="A",+ wrapped_agent=agent_a_inner,+ filter=MessageFilterConfig(+ per_source=[+ PerSourceFilter(source="user", position="first", count=1),+ PerSourceFilter(source="B", position="last", count=1),+ ]+ ),+ )++ from autogen_agentchat.agents import AssistantAgent+ from autogen_ext.models.replay import ReplayChatCompletionClient++ model_client = ReplayChatCompletionClient(["loop", "loop", "exit"])+ agent_b_inner = AssistantAgent("B", model_client=model_client)+ agent_b = MessageFilterAgent(+ name="B",+ wrapped_agent=agent_b_inner,+ filter=MessageFilterConfig(+ per_source=[+ PerSourceFilter(source="user", position="first", count=1),+ PerSourceFilter(source="A", position="last", count=1),+ PerSourceFilter(source="B", position="last", count=10),+ ]+ ),+ )++ agent_c_inner = _TestMessageFilterAgent("C")+ agent_c = MessageFilterAgent(+ name="C",+ wrapped_agent=agent_c_inner,+ filter=MessageFilterConfig(+ per_source=[+ PerSourceFilter(source="user", position="first", count=1),+ PerSourceFilter(source="B", position="last", count=1),+ ]+ ),+ )++ graph = DiGraph(+ nodes={+ "A": DiGraphNode(name="A", edges=[DiGraphEdge(target="B")]),+ "B": DiGraphNode(+ name="B",+ edges=[+ DiGraphEdge(target="C", condition="exit"),+ DiGraphEdge(target="A", condition="loop"),+ ],+ ),+ "C": DiGraphNode(name="C", edges=[]),+ },+ default_start_node="A",+ )++ team = GraphFlow(+ participants=[agent_a, agent_b, agent_c],+ graph=graph,+ runtime=runtime,+ termination_condition=MaxMessageTermination(20),+ )++ result = await team.run(task="Start")+ assert result.stop_reason is not None++ # Check A received: 1 user + 2 from B+ assert [m.source for m in agent_a_inner.received_messages].count("user") == 1+ assert [m.source for m in agent_a_inner.received_messages].count("B") == 2++ # Check C received: 1 user + 1 from B+ assert [m.source for m in agent_c_inner.received_messages].count("user") == 1+ assert [m.source for m in agent_c_inner.received_messages].count("B") == 1++ # Check B received: 1 user + multiple from A + own messages+ model_msgs = await agent_b_inner.model_context.get_messages()+ sources = [m.source for m in model_msgs] # type: ignore[union-attr]+ assert sources.count("user") == 1 # pyright: ignore[reportUnknownMemberType]+ assert sources.count("A") >= 3 # pyright: ignore[reportUnknownMemberType]+ assert sources.count("B") >= 2 # pyright: ignore[reportUnknownMemberType]+++# Test Graph Builder+def test_add_node() -> None:+ client = ReplayChatCompletionClient(["response"])+ agent = AssistantAgent("A", model_client=client)+ builder = DiGraphBuilder()+ builder.add_node(agent)++ assert "A" in builder.nodes+ assert "A" in builder.agents+ assert builder.nodes["A"].activation == "all"+++def test_add_edge() -> None:+ client = ReplayChatCompletionClient(["1", "2"])+ a = AssistantAgent("A", model_client=client)+ b = AssistantAgent("B", model_client=client)++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b)+ builder.add_edge(a, b)++ assert builder.nodes["A"].edges[0].target == "B"+ assert builder.nodes["A"].edges[0].condition is None+++def test_add_conditional_edges() -> None:+ client = ReplayChatCompletionClient(["1", "2"])+ a = AssistantAgent("A", model_client=client)+ b = AssistantAgent("B", model_client=client)+ c = AssistantAgent("C", model_client=client)++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_conditional_edges(a, {"yes": b, "no": c})++ edges = builder.nodes["A"].edges+ assert len(edges) == 2+ conditions = {e.condition for e in edges}+ targets = {e.target for e in edges}+ assert conditions == {"yes", "no"}+ assert targets == {"B", "C"}+++def test_set_entry_point() -> None:+ client = ReplayChatCompletionClient(["ok"])+ a = AssistantAgent("A", model_client=client)+ builder = DiGraphBuilder().add_node(a).set_entry_point(a)+ graph = builder.build()++ assert graph.default_start_node == "A"+++def test_build_graph_validation() -> None:+ client = ReplayChatCompletionClient(["1", "2", "3"])+ a = AssistantAgent("A", model_client=client)+ b = AssistantAgent("B", model_client=client)+ c = AssistantAgent("C", model_client=client)++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_edge("A", "B").add_edge("B", "C")+ builder.set_entry_point("A")+ graph = builder.build()++ assert isinstance(graph, DiGraph)+ assert set(graph.nodes.keys()) == {"A", "B", "C"}+ assert graph.get_start_nodes() == {"A"}+ assert graph.get_leaf_nodes() == {"C"}+++def test_build_fan_out() -> None:+ client = ReplayChatCompletionClient(["hi"] * 3)+ a = AssistantAgent("A", model_client=client)+ b = AssistantAgent("B", model_client=client)+ c = AssistantAgent("C", model_client=client)++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_edge(a, b).add_edge(a, c)+ builder.set_entry_point(a)+ graph = builder.build()++ assert graph.get_start_nodes() == {"A"}+ assert graph.get_leaf_nodes() == {"B", "C"}+++def test_build_parallel_join() -> None:+ client = ReplayChatCompletionClient(["go"] * 3)+ a = AssistantAgent("A", model_client=client)+ b = AssistantAgent("B", model_client=client)+ c = AssistantAgent("C", model_client=client)++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c, activation="all")+ builder.add_edge(a, c).add_edge(b, c)+ builder.set_entry_point(a)+ builder.add_edge(b, c)+ builder.nodes["B"] = DiGraphNode(name="B", edges=[DiGraphEdge(target="C")])+ graph = builder.build()++ assert graph.nodes["C"].activation == "all"+ assert graph.get_leaf_nodes() == {"C"}+++def test_build_conditional_loop() -> None:+ client = ReplayChatCompletionClient(["loop", "loop", "exit"])+ a = AssistantAgent("A", model_client=client)+ b = AssistantAgent("B", model_client=client)+ c = AssistantAgent("C", model_client=client)++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_edge(a, b)+ builder.add_conditional_edges(b, {"loop": a, "exit": c})+ builder.set_entry_point(a)+ graph = builder.build()++ assert graph.nodes["B"].edges[0].condition == "loop"+ assert graph.nodes["B"].edges[1].condition == "exit"+ assert graph.has_cycles_with_exit()+++async def test_graph_builder_sequential_execution(runtime: AgentRuntime | None) -> None:+ a = _EchoAgent("A", description="Echo A")+ b = _EchoAgent("B", description="Echo B")+ c = _EchoAgent("C", description="Echo C")++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_edge(a, b).add_edge(b, c)++ team = GraphFlow(+ participants=builder.get_participants(),+ graph=builder.build(),+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result = await team.run(task="Start")+ assert [m.source for m in result.messages[1:-1]] == ["A", "B", "C"]+ assert result.stop_reason is not None+++async def test_graph_builder_fan_out(runtime: AgentRuntime | None) -> None:+ a = _EchoAgent("A", description="Echo A")+ b = _EchoAgent("B", description="Echo B")+ c = _EchoAgent("C", description="Echo C")++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_edge(a, b).add_edge(a, c)++ team = GraphFlow(+ participants=builder.get_participants(),+ graph=builder.build(),+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result = await team.run(task="Start")+ sources = [m.source for m in result.messages if isinstance(m, TextMessage)]+ assert set(sources[1:]) == {"A", "B", "C"}+ assert result.stop_reason is not None+++async def test_graph_builder_conditional_execution(runtime: AgentRuntime | None) -> None:+ a = _EchoAgent("A", description="Echo A")+ b = _EchoAgent("B", description="Echo B")+ c = _EchoAgent("C", description="Echo C")++ builder = DiGraphBuilder()+ builder.add_node(a).add_node(b).add_node(c)+ builder.add_conditional_edges(a, {"yes": b, "no": c})++ team = GraphFlow(+ participants=builder.get_participants(),+ graph=builder.build(),+ runtime=runtime,+ termination_condition=MaxMessageTermination(5),+ )++ result = await team.run(task="no")+ sources = [m.source for m in result.messages]+ assert "C" in sources+ assert result.stop_reason is not None+++async def test_graph_builder_with_filter_agent(runtime: AgentRuntime | None) -> None:+ inner = _EchoAgent("X", description="Echo X")+ filter_agent = MessageFilterAgent(+ name="X",+ wrapped_agent=inner,+ filter=MessageFilterConfig(per_source=[PerSourceFilter(source="user", position="last", count=1)]),+ )++ builder = DiGraphBuilder()+ builder.add_node(filter_agent)++ team = GraphFlow(+ participants=builder.get_participants(),+ graph=builder.build(),+ runtime=runtime,+ termination_condition=MaxMessageTermination(3),+ )++ result = await team.run(task="Hello")+ assert any(m.source == "X" and m.content == "Hello" for m in result.messages) # type: ignore[union-attr]+ assert result.stop_reason is not None