Repository navigation
Expand file tree
/
Copy pathstate_graph_api_smoke.py
More file actions
1616 lines (1395 loc) · 55.1 KB
/
Copy pathstate_graph_api_smoke.py
File metadata and controls
1616 lines (1395 loc) · 55.1 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
import operator
from typing import Annotated, TypedDict
from agentcore import ChatPromptTemplate, PromptTemplate
from agentcore.graph import (
Command,
END,
START,
IntelligenceRouter,
IntelligenceRule,
IntelligenceSubscription,
MessagesState,
RuntimeContext,
StateGraph,
add_messages,
)
try:
from langgraph.graph import END as COMPAT_END
from langgraph.graph import MessagesState as CompatMessagesState
from langgraph.graph import START as COMPAT_START
from langgraph.graph import StateGraph as CompatStateGraph
from langgraph.graph import add_messages as compat_add_messages
except ModuleNotFoundError:
from agentcore_langgraph_native.langgraph_compat import END as COMPAT_END
from agentcore_langgraph_native.langgraph_compat import MessagesState as CompatMessagesState
from agentcore_langgraph_native.langgraph_compat import START as COMPAT_START
from agentcore_langgraph_native.langgraph_compat import StateGraph as CompatStateGraph
from agentcore_langgraph_native.langgraph_compat import add_messages as compat_add_messages
summary_prompt = PromptTemplate(
"Agent: {agent}\nQuestion: {question}\nContext:\n{context}"
).partial(agent="planner")
rendered_summary_prompt = summary_prompt.render(
question="How should we test prompt infrastructure?",
context={"focus": ["rendering", "model invocation"]},
)
assert "Agent: planner" in rendered_summary_prompt.text
assert '"focus": [' in rendered_summary_prompt.text
assert summary_prompt.variables == ("agent", "question", "context")
chat_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a careful {role}."),
("user", "Question: {question}\nConstraints:\n{constraints}"),
],
name="planning_chat",
).partial(role="planner")
rendered_chat_prompt = chat_prompt.render(
question="How should we wire prompt templates?",
constraints=["keep the API small", "make it reusable"],
)
assert rendered_chat_prompt.as_messages()[0]["role"] == "system"
assert rendered_chat_prompt.as_messages()[1]["role"] == "user"
assert "SYSTEM:\nYou are a careful planner." in rendered_chat_prompt.to_text()
assert rendered_chat_prompt.to_model_input(mode="messages")[1]["role"] == "user"
assert chat_prompt.variables == ("role", "question", "constraints")
def draft_step(state, config):
steps = list(state.get("steps", []))
steps.append("draft")
return {"steps": steps}
def review_step(state, config):
steps = list(state.get("steps", []))
steps.append("review")
return {"steps": steps, "done": True}
sequence_graph = StateGraph(dict, name="python_sequence_migration_smoke", worker_count=2)
sequence_graph.add_sequence([("draft", draft_step), review_step])
sequence_graph.set_finish_point("review_step")
sequence_compiled = sequence_graph.compile(name="python_sequence_override", debug=True)
assert sequence_compiled.name == "python_sequence_override"
sequence_result = sequence_compiled.invoke({"steps": []})
assert sequence_result["steps"] == ["draft", "review"]
assert sequence_result["done"] is True
try:
sequence_graph.compile(checkpointer=object())
raise AssertionError("compile(checkpointer=...) should have raised")
except NotImplementedError:
pass
def route_entry(state, config):
configurable = dict(config.get("configurable", {}))
return configurable.get("entry", "left")
def left_branch(state, config):
return {"entry_branch": "left"}
def right_branch(state, config):
return {"entry_branch": "right"}
conditional_entry_graph = StateGraph(
dict,
name="python_conditional_entry_smoke",
worker_count=2,
)
conditional_entry_graph.add_node("left", left_branch)
conditional_entry_graph.add_node("right", right_branch)
conditional_entry_graph.add_conditional_edges(
START,
route_entry,
{"left": "left", "right": "right"},
)
conditional_entry_graph.set_finish_point("left")
conditional_entry_graph.set_finish_point("right")
conditional_entry_compiled = conditional_entry_graph.compile()
assert conditional_entry_compiled.invoke({}, config={"configurable": {"entry": "left"}})["entry_branch"] == "left"
assert conditional_entry_compiled.invoke({}, config={"configurable": {"entry": "right"}})["entry_branch"] == "right"
def join_left(state, config):
return {"left_done": True}
def join_right(state, config):
return {"right_done": True}
def join_node(state, config):
return {"joined": bool(state["left_done"] and state["right_done"])}
join_graph = StateGraph(dict, name="python_join_sequence_smoke", worker_count=4)
join_graph.add_fanout("fanout")
join_graph.add_node("left", join_left)
join_graph.add_node("right", join_right)
join_graph.add_node("join", join_node)
join_graph.add_edge(START, "fanout")
join_graph.add_edge("fanout", "left")
join_graph.add_edge("fanout", "right")
join_graph.add_edge(["left", "right"], "join")
join_graph.set_finish_point("join")
join_result = join_graph.compile().invoke({})
assert join_result["joined"] is True
def compat_route_entry(state, config):
configurable = dict((config or {}).get("configurable", {}))
return configurable.get("entry", "draft")
def compat_draft(state, config):
steps = list(state.get("steps", []))
steps.append("draft")
return {"steps": steps}
def compat_review(state, config):
steps = list(state.get("steps", []))
steps.append("review")
return {"steps": steps, "compat_done": True}
compat_graph = CompatStateGraph(dict, name="python_langgraph_compat_smoke", worker_count=2)
compat_graph.add_sequence([("draft", compat_draft), ("review", compat_review)])
compat_graph.add_node("fallback", lambda state, config: {"steps": ["fallback"], "compat_done": False})
compat_graph.set_conditional_entry_point(
compat_route_entry,
{"draft": "draft", "fallback": "fallback"},
)
compat_graph.set_finish_point("review")
compat_graph.set_finish_point("fallback")
compat_compiled = compat_graph.compile(name="python_langgraph_compat_override", debug=False)
assert compat_compiled.invoke({"steps": []}, config={"configurable": {"entry": "draft"}}) == {
"steps": ["draft", "review"],
"compat_done": True,
}
assert compat_compiled.invoke({"steps": []}, config={"configurable": {"entry": "fallback"}}) == {
"steps": ["fallback"],
"compat_done": False,
}
try:
compat_graph.compile(checkpointer=object())
raise AssertionError("compat compile(checkpointer=...) should have raised")
except NotImplementedError:
pass
class ReducerState(TypedDict, total=False):
count: Annotated[int, operator.add]
notes: Annotated[list[str], operator.add]
seen: Annotated[bool, operator.or_]
floor: Annotated[int, min]
ceiling: Annotated[int, max]
summary: str
def reduce_left(state, config):
return {"count": 1, "notes": ["left"], "seen": False, "floor": 10, "ceiling": 10}
def reduce_right(state, config):
return {"count": 2, "notes": ["right"], "seen": True, "floor": 3, "ceiling": 12}
def reduce_join(state, config):
return {
"summary": f"{state['count']}|{','.join(state['notes'])}|{int(state['seen'])}|{state['floor']}|{state['ceiling']}"
}
reducer_graph = StateGraph(ReducerState, name="python_reducer_schema_smoke", worker_count=4)
reducer_graph.add_fanout("fanout")
reducer_graph.add_node("left", reduce_left)
reducer_graph.add_node("right", reduce_right)
reducer_graph.add_node("join", reduce_join)
reducer_graph.add_edge(START, "fanout")
reducer_graph.add_edge("fanout", "left")
reducer_graph.add_edge("fanout", "right")
reducer_graph.add_edge(["left", "right"], "join")
reducer_graph.set_finish_point("join")
reducer_result = reducer_graph.compile().invoke(
{"count": 5, "notes": ["base"], "seen": False, "floor": 7, "ceiling": 11}
)
assert reducer_result["count"] == 8
assert reducer_result["notes"] == ["base", "left", "right"]
assert reducer_result["seen"] is True
assert reducer_result["floor"] == 3
assert reducer_result["ceiling"] == 12
assert reducer_result["summary"] == "8|base,left,right|1|3|12"
def reduce_step_one(state, config):
return {"count": 1, "notes": ["one"], "seen": False, "floor": 10, "ceiling": 10}
def reduce_step_two(state, config):
return {"count": 2, "notes": ["two"], "seen": True, "floor": 3, "ceiling": 12}
sequential_reducer_graph = StateGraph(
ReducerState,
name="python_sequential_reducer_schema_smoke",
worker_count=2,
)
sequential_reducer_graph.add_sequence(
[
("one", reduce_step_one),
("two", reduce_step_two),
("summary", reduce_join),
]
)
sequential_reducer_graph.set_finish_point("summary")
sequential_reducer_result = sequential_reducer_graph.compile().invoke(
{"count": 5, "notes": ["base"], "seen": False, "floor": 7, "ceiling": 11}
)
assert sequential_reducer_result["count"] == 8
assert sequential_reducer_result["notes"] == ["base", "one", "two"]
assert sequential_reducer_result["seen"] is True
assert sequential_reducer_result["floor"] == 3
assert sequential_reducer_result["ceiling"] == 12
assert sequential_reducer_result["summary"] == "8|base,one,two|1|3|12"
def reducer_loop_step(state, config):
return {"count": 1}
def reducer_loop_route(state, config):
return END if int(state["count"]) >= 3 else "step"
reducer_route_graph = StateGraph(
ReducerState,
name="python_reducer_route_overlay_smoke",
worker_count=2,
)
reducer_route_graph.add_node("step", reducer_loop_step)
reducer_route_graph.add_edge(START, "step")
reducer_route_graph.add_conditional_edges("step", reducer_loop_route, {END: END, "step": "step"})
reducer_route_result = reducer_route_graph.compile().invoke(
{"count": 0, "notes": [], "seen": False, "floor": 100, "ceiling": 0}
)
assert reducer_route_result["count"] == 3
class NativeMessageState(MessagesState, total=False):
summary: str
def message_left(state, config):
return {
"messages": [
{"id": "replace", "role": "assistant", "content": "left-replace"},
{"role": "tool", "content": "left-anon"},
]
}
def message_right(state, config):
return {
"messages": [
{"id": "new", "role": "assistant", "content": "right-new"},
{"id": "replace", "role": "assistant", "content": "right-replace"},
]
}
def summarize_messages(state, config):
return {"summary": ",".join(message["content"] for message in state["messages"])}
message_graph = StateGraph(NativeMessageState, name="python_message_schema_smoke", worker_count=4)
message_graph.add_fanout("fanout")
message_graph.add_node("left", message_left)
message_graph.add_node("right", message_right)
message_graph.add_join("join", summarize_messages)
message_graph.add_edge(START, "fanout")
message_graph.add_edge("fanout", "left")
message_graph.add_edge("fanout", "right")
message_graph.add_edge(["left", "right"], "join")
message_graph.set_finish_point("join")
message_result = message_graph.compile().invoke(
{
"messages": [
{"id": "keep", "role": "user", "content": "base-keep"},
{"id": "replace", "role": "assistant", "content": "base-old"},
{"role": "user", "content": "base-anon"},
]
}
)
assert [message["content"] for message in message_result["messages"]] == [
"base-keep",
"right-replace",
"base-anon",
"left-anon",
"right-new",
]
assert message_result["summary"] == "base-keep,right-replace,base-anon,left-anon,right-new"
assert add_messages(
[{"id": "x", "content": "old"}, {"content": "anon"}],
[{"id": "x", "content": "new"}],
) == [{"id": "x", "content": "new"}, {"content": "anon"}]
sequential_message_graph = StateGraph(
NativeMessageState,
name="python_sequential_message_schema_smoke",
worker_count=2,
)
sequential_message_graph.add_sequence(
[
("left", message_left),
("right", message_right),
("summary", summarize_messages),
]
)
sequential_message_graph.set_finish_point("summary")
sequential_message_result = sequential_message_graph.compile().invoke(
{
"messages": [
{"id": "keep", "role": "user", "content": "base-keep"},
{"id": "replace", "role": "assistant", "content": "base-old"},
{"role": "user", "content": "base-anon"},
]
}
)
assert [message["content"] for message in sequential_message_result["messages"]] == [
"base-keep",
"right-replace",
"base-anon",
"left-anon",
"right-new",
]
assert sequential_message_result["summary"] == "base-keep,right-replace,base-anon,left-anon,right-new"
class SharedSubgraphState(TypedDict, total=False):
topic: str
steps: int
answer: str
def prepare_shared(state, config):
return {
"topic": "agentcore-runtime",
"steps": int(state.get("steps", 0)) + 1,
}
def child_shared_step(state, config):
return {
"steps": int(state.get("steps", 0)) + 1,
"answer": f"{state['topic']}::shared-child",
}
shared_child = StateGraph(SharedSubgraphState, name="python_shared_child", worker_count=2)
shared_child.add_node("child_step", child_shared_step)
shared_child.add_edge(START, "child_step")
shared_child.set_finish_point("child_step")
shared_parent = StateGraph(SharedSubgraphState, name="python_shared_parent", worker_count=2)
shared_parent.add_sequence([("prepare", prepare_shared), ("shared_child", shared_child)])
shared_result = shared_parent.compile().invoke({})
assert shared_result["topic"] == "agentcore-runtime"
assert shared_result["steps"] == 2
assert shared_result["answer"] == "agentcore-runtime::shared-child"
compat_reducer_graph = CompatStateGraph(ReducerState, name="python_compat_reducer_smoke", worker_count=4)
compat_reducer_graph.add_fanout("fanout")
compat_reducer_graph.add_node("left", lambda state, config: {"count": 1, "notes": ["left"], "seen": False, "floor": 10, "ceiling": 10})
compat_reducer_graph.add_node("right", lambda state, config: {"count": 2, "notes": ["right"], "seen": True, "floor": 3, "ceiling": 12})
compat_reducer_graph.add_join(
"join",
lambda state, config: {
"summary": f"{state['count']}|{','.join(state['notes'])}|{int(state['seen'])}|{state['floor']}|{state['ceiling']}"
},
)
compat_reducer_graph.add_edge(COMPAT_START, "fanout")
compat_reducer_graph.add_edge("fanout", "left")
compat_reducer_graph.add_edge("fanout", "right")
compat_reducer_graph.add_edge(["left", "right"], "join")
compat_reducer_graph.set_finish_point("join")
compat_reducer_result = compat_reducer_graph.compile().invoke(
{"count": 5, "notes": ["base"], "seen": False, "floor": 7, "ceiling": 11}
)
assert compat_reducer_result["count"] == 8
assert compat_reducer_result["notes"] == ["base", "left", "right"]
assert compat_reducer_result["seen"] is True
assert compat_reducer_result["floor"] == 3
assert compat_reducer_result["ceiling"] == 12
assert compat_reducer_result["summary"] == "8|base,left,right|1|3|12"
compat_sequential_reducer_graph = CompatStateGraph(
ReducerState,
name="python_compat_sequential_reducer_smoke",
worker_count=2,
)
compat_sequential_reducer_graph.add_sequence(
[
("one", reduce_step_one),
("two", reduce_step_two),
("summary", reduce_join),
]
)
compat_sequential_reducer_graph.set_finish_point("summary")
compat_sequential_reducer_result = compat_sequential_reducer_graph.compile().invoke(
{"count": 5, "notes": ["base"], "seen": False, "floor": 7, "ceiling": 11}
)
assert compat_sequential_reducer_result["count"] == 8
assert compat_sequential_reducer_result["notes"] == ["base", "one", "two"]
assert compat_sequential_reducer_result["seen"] is True
assert compat_sequential_reducer_result["floor"] == 3
assert compat_sequential_reducer_result["ceiling"] == 12
assert compat_sequential_reducer_result["summary"] == "8|base,one,two|1|3|12"
compat_reducer_route_graph = CompatStateGraph(
ReducerState,
name="python_compat_reducer_route_overlay_smoke",
worker_count=2,
)
compat_reducer_route_graph.add_node("step", reducer_loop_step)
compat_reducer_route_graph.add_edge(COMPAT_START, "step")
compat_reducer_route_graph.add_conditional_edges(
"step",
lambda state, config: COMPAT_END if int(state["count"]) >= 3 else "step",
{COMPAT_END: COMPAT_END, "step": "step"},
)
compat_reducer_route_result = compat_reducer_route_graph.compile().invoke(
{"count": 0, "notes": [], "seen": False, "floor": 100, "ceiling": 0}
)
assert compat_reducer_route_result["count"] == 3
class CompatMessageState(CompatMessagesState, total=False):
summary: str
compat_message_graph = CompatStateGraph(CompatMessageState, name="python_compat_message_schema_smoke", worker_count=4)
compat_message_graph.add_fanout("fanout")
compat_message_graph.add_node("left", message_left)
compat_message_graph.add_node("right", message_right)
compat_message_graph.add_join("join", summarize_messages)
compat_message_graph.add_edge(COMPAT_START, "fanout")
compat_message_graph.add_edge("fanout", "left")
compat_message_graph.add_edge("fanout", "right")
compat_message_graph.add_edge(["left", "right"], "join")
compat_message_graph.set_finish_point("join")
compat_message_result = compat_message_graph.compile().invoke(
{
"messages": [
{"id": "keep", "role": "user", "content": "base-keep"},
{"id": "replace", "role": "assistant", "content": "base-old"},
{"role": "user", "content": "base-anon"},
]
}
)
assert [message["content"] for message in compat_message_result["messages"]] == [
"base-keep",
"right-replace",
"base-anon",
"left-anon",
"right-new",
]
assert compat_message_result["summary"] == "base-keep,right-replace,base-anon,left-anon,right-new"
assert compat_add_messages(
[{"id": "x", "content": "old"}, {"content": "anon"}],
[{"id": "x", "content": "new"}],
) == [{"id": "x", "content": "new"}, {"content": "anon"}]
compat_shared_child = CompatStateGraph(SharedSubgraphState, name="python_compat_shared_child", worker_count=2)
compat_shared_child.add_node(
"child_step",
lambda state, config: {
"steps": int(state.get("steps", 0)) + 1,
"answer": f"{state['topic']}::compat-shared-child",
},
)
compat_shared_child.add_edge(COMPAT_START, "child_step")
compat_shared_child.set_finish_point("child_step")
compat_shared_parent = CompatStateGraph(SharedSubgraphState, name="python_compat_shared_parent", worker_count=2)
compat_shared_parent.add_sequence(
[
("prepare", lambda state, config: {"topic": "compat-runtime", "steps": int(state.get("steps", 0)) + 1}),
("compat_shared_child", compat_shared_child),
]
)
compat_shared_result = compat_shared_parent.compile().invoke({})
assert compat_shared_result["topic"] == "compat-runtime"
assert compat_shared_result["steps"] == 2
assert compat_shared_result["answer"] == "compat-runtime::compat-shared-child"
async def planner(state, config):
history = list(state.get("history", []))
next_count = int(state.get("count", 0)) + 1
history.append(f"step-{next_count}")
payload = dict(state.get("payload", {}))
payload["last"] = history[-1]
configurable = dict(config.get("configurable", {}))
await asyncio.sleep(0)
return {
"count": next_count,
"history": history,
"payload": payload,
"run_label": configurable.get("run_label", "unset"),
"tag_count": len(config.get("tags", [])),
}
async def route(state, config):
await asyncio.sleep(0)
target_count = int(dict(config.get("configurable", {})).get("target_count", 2))
return END if state["count"] >= target_count else "planner"
graph = StateGraph(dict, name="python_state_graph_api_smoke", worker_count=2)
graph.add_node("planner", planner)
graph.add_edge(START, "planner")
graph.add_conditional_edges("planner", route, {END: END, "planner": "planner"})
compiled = graph.compile()
final_state = compiled.invoke(
{
"count": 0,
"history": [],
"payload": {"seed": True},
"binary": b"agentcore",
},
config={
"configurable": {"run_label": "sync", "target_count": 2},
"tags": ["smoke", "sync"],
},
)
print(f"DEBUG: final_state['count'] = {final_state.get('count')}")
assert final_state["count"] == 2
assert final_state["history"] == ["step-1", "step-2"]
assert final_state["payload"] == {"seed": True, "last": "step-2"}
assert final_state["binary"] == b"agentcore"
assert final_state["run_label"] == "sync"
assert final_state["tag_count"] == 2
details = compiled.invoke_with_metadata(
{"count": 0, "history": [], "payload": {}},
config={"configurable": {"run_label": "details", "target_count": 2}, "tags": ["meta"]},
)
assert details["summary"]["status"] == "completed"
assert details["summary"]["steps_executed"] >= 2
assert details["proof"]["combined_digest"] != 0
assert [event["node_name"] for event in details["trace"]] == ["planner", "planner"]
events = list(
compiled.stream(
{"count": 0, "history": [], "payload": {}},
config={"configurable": {"run_label": "stream", "target_count": 2}, "tags": ["stream"]},
)
)
assert [event["node_name"] for event in events] == ["planner", "planner"]
for event in events:
print(f"DEBUG: event['node_name']={event.get('node_name')}, event['graph_name']='{event.get('graph_name')}'")
assert all(event["graph_name"] == "python_state_graph_api_smoke" for event in events)
batch_results = compiled.batch(
[{"count": 0, "history": [], "payload": {}}, {"count": 0, "history": [], "payload": {}}],
config=[
{"configurable": {"run_label": "batch-a", "target_count": 2}, "tags": ["batch"]},
{"configurable": {"run_label": "batch-b", "target_count": 3}, "tags": ["batch"]},
],
)
assert [result["count"] for result in batch_results] == [2, 3]
assert [result["run_label"] for result in batch_results] == ["batch-a", "batch-b"]
def write_intelligence(state, config, runtime: RuntimeContext):
intelligence = runtime.intelligence
snapshot_before = intelligence.snapshot()
assert snapshot_before["counts"] == {
"tasks": 0,
"claims": 0,
"evidence": 0,
"decisions": 0,
"memories": 0,
}
assert intelligence.summary()["counts"]["tasks"] == 0
intelligence.upsert_task(
"task:draft-answer",
title="Draft answer",
owner="planner",
details={"question": state.get("question", "unknown")},
status="in_progress",
priority=3,
confidence=0.6,
)
intelligence.upsert_task(
"task:urgent-followup",
title="Urgent follow-up",
owner="planner",
details={"question": state.get("question", "unknown"), "priority": "urgent"},
status="open",
priority=1,
confidence=0.95,
)
intelligence.upsert_task(
"task:review-summary",
title="Review summary",
owner="reviewer",
details={"question": state.get("question", "unknown")},
status="completed",
priority=5,
confidence=0.7,
)
intelligence.upsert_claim(
"claim:agentcore-native",
subject="agentcore",
relation="is",
object="native_runtime",
statement={"text": "AgentCore is a native runtime"},
status="supported",
confidence=0.95,
)
intelligence.add_evidence(
"evidence:runtime-benchmark",
kind="benchmark",
source="state_graph_api_smoke",
content={"speedup_x": 2.0},
task_key="task:draft-answer",
claim_key="claim:agentcore-native",
confidence=0.8,
)
intelligence.record_decision(
"decision:publish-summary",
task_key="task:draft-answer",
claim_key="claim:agentcore-native",
summary={"action": "document"},
status="selected",
confidence=0.7,
)
intelligence.remember(
"memory:semantic:agentcore-native",
layer="semantic",
scope="runtime",
content={"fact": "AgentCore is native"},
task_key="task:draft-answer",
claim_key="claim:agentcore-native",
importance=0.75,
)
intelligence.remember(
"memory:semantic:low-priority",
layer="semantic",
scope="runtime",
content={"fact": "Low priority memory"},
task_key="task:review-summary",
claim_key="claim:agentcore-native",
importance=0.2,
)
intelligence.remember(
"memory:semantic:high-priority",
layer="semantic",
scope="runtime",
content={"fact": "High priority memory"},
task_key="task:urgent-followup",
claim_key="claim:agentcore-native",
importance=0.95,
)
snapshot_after = intelligence.snapshot()
assert snapshot_after["counts"]["tasks"] == 3
assert snapshot_after["counts"]["claims"] == 1
assert snapshot_after["counts"]["evidence"] == 1
assert snapshot_after["counts"]["decisions"] == 1
assert snapshot_after["counts"]["memories"] == 3
in_progress_tasks = intelligence.query(kind="tasks", status="in_progress")
assert in_progress_tasks["counts"]["tasks"] == 1
assert in_progress_tasks["tasks"][0]["key"] == "task:draft-answer"
semantic_claims = intelligence.query(
kind="claims",
subject="agentcore",
relation="is",
object="native_runtime",
)
assert semantic_claims["counts"]["claims"] == 1
assert semantic_claims["claims"][0]["key"] == "claim:agentcore-native"
assert intelligence.count(
kind="claims",
subject="agentcore",
relation="is",
object="native_runtime",
) == 1
semantic_memories = intelligence.query(kind="memories", layer="semantic", scope="runtime")
assert semantic_memories["counts"]["memories"] == 3
assert [memory["key"] for memory in semantic_memories["memories"]] == [
"memory:semantic:agentcore-native",
"memory:semantic:low-priority",
"memory:semantic:high-priority",
]
related_to_task = intelligence.related(task_key="task:draft-answer")
assert related_to_task["counts"] == {
"tasks": 1,
"claims": 1,
"evidence": 1,
"decisions": 1,
"memories": 1,
}
planner_agenda = intelligence.agenda(owner="planner")
assert planner_agenda["counts"]["tasks"] == 2
assert planner_agenda["tasks"][0]["key"] == "task:draft-answer"
assert planner_agenda["tasks"][1]["key"] == "task:urgent-followup"
next_planner_task = intelligence.next_task(owner="planner")
assert next_planner_task is not None
assert next_planner_task["key"] == "task:draft-answer"
open_planner_agenda = intelligence.agenda(owner="planner", status="open")
assert open_planner_agenda["counts"]["tasks"] == 1
assert open_planner_agenda["tasks"][0]["key"] == "task:urgent-followup"
recalled_memories = intelligence.recall(scope="runtime", layer="semantic")
assert recalled_memories["counts"]["memories"] == 3
assert [memory["key"] for memory in recalled_memories["memories"]] == [
"memory:semantic:high-priority",
"memory:semantic:agentcore-native",
"memory:semantic:low-priority",
]
focus = intelligence.focus(owner="planner", scope="runtime", limit=3)
assert focus["counts"] == {
"tasks": 3,
"claims": 1,
"evidence": 1,
"decisions": 1,
"memories": 3,
}
assert [task["key"] for task in focus["tasks"]] == [
"task:draft-answer",
"task:urgent-followup",
"task:review-summary",
]
assert focus["claims"][0]["key"] == "claim:agentcore-native"
assert focus["memories"][0]["key"] == "memory:semantic:high-priority"
semantic_focus = intelligence.focus(
subject="agentcore",
relation="is",
object="native_runtime",
limit=3,
)
assert semantic_focus["counts"] == {
"tasks": 3,
"claims": 1,
"evidence": 1,
"decisions": 1,
"memories": 3,
}
assert semantic_focus["claims"][0]["key"] == "claim:agentcore-native"
return {"intelligence_written": True}
def read_intelligence(state, config, runtime: RuntimeContext):
assert state.get("intelligence_written") is True
snapshot = runtime.intelligence.snapshot()
assert snapshot["counts"]["tasks"] == 3
assert snapshot["tasks"][0]["title"] == "Draft answer"
assert snapshot["claims"][0]["subject"] == "agentcore"
assert snapshot["evidence"][0]["content"]["speedup_x"] == 2.0
assert snapshot["decisions"][0]["status"] == "selected"
assert snapshot["memories"][0]["layer"] == "semantic"
assert runtime.intelligence.summary()["decision_status"]["selected"] == 1
assert runtime.intelligence.next_task(owner="planner")["key"] == "task:draft-answer"
assert runtime.intelligence.recall(scope="runtime", limit=1)["memories"][0]["key"] == "memory:semantic:high-priority"
assert runtime.intelligence.focus(owner="planner", scope="runtime", limit=2)["tasks"][0]["key"] == "task:draft-answer"
return {
"intelligence_written": True,
"intelligence_task_status": snapshot["tasks"][0]["status"],
"intelligence_memory_count": snapshot["counts"]["memories"],
"intelligence_task_count": snapshot["counts"]["tasks"],
"intelligence_decision_status": snapshot["decisions"][0]["status"],
}
intelligence_graph = StateGraph(dict, name="python_intelligence_runtime_smoke", worker_count=2)
intelligence_graph.add_node("write", write_intelligence)
intelligence_graph.add_node("read", read_intelligence)
intelligence_graph.add_edge(START, "write")
intelligence_graph.add_edge("write", "read")
intelligence_graph.add_edge("read", END)
intelligence_compiled = intelligence_graph.compile()
intelligence_details = intelligence_compiled.invoke_with_metadata({"question": "what is AgentCore?"})
assert intelligence_details["state"].get("intelligence_written") is True
assert intelligence_details["state"].get("intelligence_task_status") == "in_progress"
assert intelligence_details["state"].get("intelligence_memory_count") == 3
assert intelligence_details["state"].get("intelligence_task_count") == 3
assert intelligence_details["state"].get("intelligence_decision_status") == "selected"
assert intelligence_details["intelligence"]["counts"] == {
"tasks": 3,
"claims": 1,
"evidence": 1,
"decisions": 1,
"memories": 3,
}
assert intelligence_details["intelligence"]["tasks"][0]["title"] == "Draft answer"
assert intelligence_details["intelligence"]["evidence"][0]["content"]["speedup_x"] == 2.0
def validate_supporting_claims(state, config, runtime: RuntimeContext):
intelligence = runtime.intelligence
intelligence.upsert_task(
"task:supporting-claims",
title="Supporting claims task",
owner="support-owner",
status="in_progress",
priority=4,
confidence=0.8,
)
intelligence.upsert_claim(
"claim:supporting:strong",
subject="agentcore",
relation="supports",
object="supporting-claim-ranking",
status="supported",
confidence=0.9,
)
intelligence.upsert_claim(
"claim:supporting:weak",
subject="agentcore",
relation="supports",
object="supporting-claim-ranking",
status="supported",
confidence=0.7,
)
intelligence.add_evidence(
"evidence:supporting:strong",
kind="benchmark",
source="supporting-claims",
task_key="task:supporting-claims",
claim_key="claim:supporting:strong",
content={"strength": "strong"},
confidence=0.96,
)
intelligence.record_decision(
"decision:supporting:strong",
task_key="task:supporting-claims",
claim_key="claim:supporting:strong",
summary={"selected": True},
status="selected",
confidence=0.94,
)
intelligence.remember(
"memory:supporting:strong",
layer="semantic",
scope="supporting-claims",
task_key="task:supporting-claims",
claim_key="claim:supporting:strong",
content={"memory": "strong"},
importance=0.9,
)
intelligence.add_evidence(
"evidence:supporting:weak",
kind="observation",
source="supporting-claims",
task_key="task:supporting-claims",
claim_key="claim:supporting:weak",
content={"strength": "weak"},
confidence=0.45,
)
ranked_task_claims = intelligence.supporting_claims(
task_key="task:supporting-claims",
limit=2,
)
assert ranked_task_claims["counts"]["claims"] == 2
assert [claim["key"] for claim in ranked_task_claims["claims"]] == [
"claim:supporting:strong",
"claim:supporting:weak",
]
ranked_semantic_claims = intelligence.supporting_claims(
subject="agentcore",
relation="supports",
object="supporting-claim-ranking",
limit=2,
)
assert ranked_semantic_claims["counts"]["claims"] == 2
assert ranked_semantic_claims["claims"][0]["key"] == "claim:supporting:strong"
assert ranked_semantic_claims["claims"][1]["key"] == "claim:supporting:weak"
return {"best_supporting_claim": ranked_semantic_claims["claims"][0]["key"]}
supporting_claims_graph = StateGraph(dict, name="python_supporting_claims_smoke", worker_count=2)
supporting_claims_graph.add_node("rank", validate_supporting_claims)
supporting_claims_graph.add_edge(START, "rank")
supporting_claims_graph.add_edge("rank", END)
supporting_claims_details = supporting_claims_graph.compile().invoke_with_metadata({})
assert supporting_claims_details["state"]["best_supporting_claim"] == "claim:supporting:strong"
assert supporting_claims_details["intelligence"]["claims"][0]["key"] == "claim:supporting:strong"
def validate_action_candidates(state, config, runtime: RuntimeContext):
intelligence = runtime.intelligence
intelligence.upsert_task(
"task:action:strong",
title="Strong action",
owner="action-owner",
status="open",
priority=4,
confidence=0.8,
)
intelligence.upsert_task(
"task:action:weak",
title="Weak action",
owner="action-owner",
status="open",
priority=4,
confidence=0.8,
)
intelligence.upsert_claim(
"claim:action:strong",
subject="agentcore",
relation="supports",
object="action-ranking",
status="supported",
confidence=0.9,
)
intelligence.upsert_claim(
"claim:action:weak",
subject="agentcore",
relation="supports",
object="action-ranking",
status="supported",
confidence=0.7,
)
intelligence.add_evidence(
"evidence:action:strong",
kind="benchmark",
source="action-candidates",
task_key="task:action:strong",
claim_key="claim:action:strong",
content={"strength": "strong"},
confidence=0.95,
)
intelligence.record_decision(
"decision:action:strong",
task_key="task:action:strong",
claim_key="claim:action:strong",
summary={"selected": True},