forked from microsoft/autogen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_group_chat_graph.py
More file actions
1449 lines (1192 loc) · 52.7 KB
/
test_group_chat_graph.py
File metadata and controls
1449 lines (1192 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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, StopMessage, 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]
@pytest.mark.asyncio
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,
)
@pytest.fixture
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 --------------------
@pytest.mark.asyncio
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 --------------------
@pytest.mark.asyncio
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 --------------------
@pytest.mark.asyncio
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]
@pytest.mark.asyncio
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"}
@pytest.mark.asyncio
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]
@pytest.mark.asyncio
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]
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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: