-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathtest_workflow_hitl.py
More file actions
2102 lines (1850 loc) · 64.1 KB
/
test_workflow_hitl.py
File metadata and controls
2102 lines (1850 loc) · 64.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
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Testings for the Workflow HITL scenarios."""
import asyncio
import copy
from typing import Any
from typing import AsyncGenerator
from unittest import mock
from google.adk.agents.context import Context
from google.adk.agents.llm_agent import LlmAgent
from google.adk.apps.app import App
from google.adk.apps.app import ResumabilityConfig
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.adk.events.event import Event
from google.adk.events.request_input import RequestInput
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.tools.long_running_tool import LongRunningFunctionTool
from google.adk.workflow import BaseNode
from google.adk.workflow import Edge
from google.adk.workflow import node
from google.adk.workflow import START
from google.adk.workflow._node_status import NodeStatus
from google.adk.workflow._workflow import Workflow
from google.adk.workflow.utils._rehydration_utils import _wrap_response
from google.adk.workflow.utils._workflow_hitl_utils import create_request_input_response
from google.adk.workflow.utils._workflow_hitl_utils import get_request_input_interrupt_ids
from google.adk.workflow.utils._workflow_hitl_utils import REQUEST_CREDENTIAL_FUNCTION_CALL_NAME
from google.adk.workflow.utils._workflow_hitl_utils import REQUEST_INPUT_FUNCTION_CALL_NAME
from google.genai import types
from pydantic import BaseModel
from pydantic import ConfigDict
from pydantic import Field
import pytest
from typing_extensions import override
from . import workflow_testing_utils
from .. import testing_utils
from .workflow_testing_utils import InputCapturingNode
from .workflow_testing_utils import RequestInputNode
ANY = mock.ANY
class _TestingNode(BaseNode):
"""A node that produces a simple message."""
model_config = ConfigDict(arbitrary_types_allowed=True)
name: str = Field(default='')
message: str = Field(default='')
delay: float = Field(default=0)
@override
def get_name(self) -> str:
return self.name
@override
async def _run_impl(
self,
*,
ctx: Context,
node_input: Any,
) -> AsyncGenerator[Any, None]:
if self.delay > 0:
await asyncio.sleep(self.delay)
yield Event(output=self.message)
def long_running_tool_func():
"""A test tool that simulates a long-running operation."""
return None
@pytest.mark.parametrize(
'resumable',
[
pytest.param(
False, marks=pytest.mark.xfail(reason='Fails in non-resumable mode')
),
pytest.param(
True, marks=pytest.mark.xfail(reason='Resumability broken in V2')
),
],
)
@pytest.mark.asyncio
async def test_workflow_pause_and_resume(
request: pytest.FixtureRequest,
resumable: bool,
):
"""Tests that a workflow can pause and resume.
This test uses LlmAgent with LongRunningFunctionTool.
"""
node_a = _TestingNode(name='NodeA', message='Executing A')
node_b = LlmAgent(
name='NodeB_agent',
model=testing_utils.MockModel.create(
responses=[
types.Part.from_function_call(
name='long_running_tool_func',
args={},
),
types.Part.from_text(text='LLM response after tool'),
]
),
tools=[LongRunningFunctionTool(func=long_running_tool_func)],
)
node_c = _TestingNode(name='NodeC', message='Executing C')
agent = Workflow(
name='test_workflow_agent_hitl',
edges=[
(START, node_a),
(node_a, node_b),
(node_b, node_c),
],
)
app = App(
name=request.function.__name__,
root_agent=agent,
resumability_config=(
ResumabilityConfig(is_resumable=True) if resumable else None
),
)
runner = testing_utils.InMemoryRunner(app=app)
# First run: should pause on the long-running function call.
user_event = testing_utils.get_user_content('start workflow')
events1 = await runner.run_async(user_event)
invocation_id = events1[0].invocation_id
fc_event = workflow_testing_utils.find_function_call_event(
events1, 'long_running_tool_func'
)
function_call_id = fc_event.content.parts[0].function_call.id
simplified_events1 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events1),
)
)
# Filter to outer workflow state checkpoint events only (LlmAgent as Mesh
# emits internal state events that are implementation details).
outer_state_events1 = [
e
for e in simplified_events1
if e[0] == 'test_workflow_agent_hitl'
and isinstance(e[1], dict)
and 'nodes' in e[1]
]
# Verify the outer workflow saw: NodeB_agent (interrupted).
if resumable:
assert outer_state_events1[-1] == (
'test_workflow_agent_hitl',
{
'nodes': {
'NodeA': {'status': NodeStatus.COMPLETED.value},
'NodeB_agent': {
'status': NodeStatus.WAITING.value,
'interrupts': [function_call_id],
},
},
},
)
tool_response = testing_utils.UserContent(
types.Part(
function_response=types.FunctionResponse(
id=function_call_id,
name='long_running_tool_func',
response={'result': 'Final tool output'},
)
)
)
# Resume with tool output.
# In resumable mode, reuse the invocation_id so agent state is loaded.
# In non-resumable mode, use a new invocation so state is reconstructed
# from session events.
events2 = await runner.run_async(
new_message=tool_response,
invocation_id=invocation_id,
)
simplified_events2 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events2),
include_resume_inputs=True,
)
)
# Filter to outer workflow state checkpoint events only.
outer_state_events2 = [
e
for e in simplified_events2
if e[0] == 'test_workflow_agent_hitl'
and isinstance(e[1], dict)
and 'nodes' in e[1]
]
# Verify NodeB_agent resumed, completed, and NodeC ran.
if resumable:
assert outer_state_events2[-1] == (
'test_workflow_agent_hitl',
{
'nodes': {
'NodeA': {'status': NodeStatus.COMPLETED.value},
'NodeB_agent': {'status': NodeStatus.COMPLETED.value},
'NodeC': {'status': NodeStatus.COMPLETED.value},
}
},
)
# Verify end_of_agent was emitted.
end_events = [
e
for e in simplified_events2
if e[0] == 'test_workflow_agent_hitl'
and e[1] == testing_utils.END_OF_AGENT
]
assert len(end_events) == 1
@pytest.mark.xfail(reason='Resumability broken in V2')
@pytest.mark.asyncio
async def test_workflow_interrupt_allows_parallel_execution(
request: pytest.FixtureRequest,
):
"""Tests that if one node is interrupted, parallel nodes can execute.
This test uses LlmAgent with LongRunningFunctionTool, which requires
resumability to preserve the LLM's conversation state across interrupts.
"""
node_a = LlmAgent(
name='NodeA',
model=testing_utils.MockModel.create(
responses=[
types.Part.from_function_call(
name='long_running_tool_func',
args={},
),
]
),
tools=[LongRunningFunctionTool(func=long_running_tool_func)],
)
node_b = _TestingNode(name='NodeB', message='Executing B', delay=0.5)
agent = Workflow(
name='test_workflow_agent_parallel_interrupt',
edges=[
(START, node_a),
(START, node_b),
],
)
app = App(
name=request.function.__name__,
root_agent=agent,
resumability_config=ResumabilityConfig(is_resumable=True),
)
runner = testing_utils.InMemoryRunner(app=app)
user_event = testing_utils.get_user_content('start workflow')
events = await runner.run_async(user_event)
fc_event = workflow_testing_utils.find_function_call_event(
events, 'long_running_tool_func'
)
function_call_id = fc_event.content.parts[0].function_call.id
simplified = workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events)
)
# Filter to outer workflow state checkpoint events only (LlmAgent as Mesh
# emits internal state events that are implementation details).
outer_state = [
e
for e in simplified
if e[0] == 'test_workflow_agent_parallel_interrupt'
and isinstance(e[1], dict)
and 'nodes' in e[1]
]
# Verify final state: NodeA interrupted, NodeB completed.
assert outer_state[-1] == (
'test_workflow_agent_parallel_interrupt',
{
'nodes': {
'NodeA': {
'status': NodeStatus.WAITING.value,
'interrupts': [function_call_id],
},
'NodeB': {'status': NodeStatus.COMPLETED.value},
},
},
)
@pytest.mark.parametrize(
'resumable',
[
False,
pytest.param(
True, marks=pytest.mark.xfail(reason='Resumability broken in V2')
),
],
)
@pytest.mark.asyncio
async def test_workflow_request_input_resume(
request: pytest.FixtureRequest, resumable: bool
):
"""Tests resume with RequestInputEvent."""
class UserDetails(BaseModel):
name: str
age: int
node_a = RequestInputNode(
name='NodeA_input',
message='Please provide user details.',
response_schema=UserDetails.model_json_schema(),
)
node_b = _TestingNode(name='NodeB', message='Received user details')
agent = Workflow(
name='test_workflow_agent_input_schema',
edges=[
Edge(from_node=START, to_node=node_a),
Edge(from_node=node_a, to_node=node_b),
],
)
app = App(
name=request.function.__name__,
root_agent=agent,
resumability_config=(
ResumabilityConfig(is_resumable=True) if resumable else None
),
)
runner = testing_utils.InMemoryRunner(app=app)
# Run and expect RequestInputEvent
user_event = testing_utils.get_user_content('start workflow')
events1 = await runner.run_async(user_event)
request_input_event = workflow_testing_utils.find_function_call_event(
events1, REQUEST_INPUT_FUNCTION_CALL_NAME
)
assert request_input_event is not None
args = request_input_event.content.parts[0].function_call.args
assert args['message'] == 'Please provide user details.'
assert args['response_schema'] == {
'properties': {
'name': {'title': 'Name', 'type': 'string'},
'age': {'title': 'Age', 'type': 'integer'},
},
'required': ['name', 'age'],
'title': 'UserDetails',
'type': 'object',
}
interrupt_id = get_request_input_interrupt_ids(request_input_event)[0]
invocation_id = request_input_event.invocation_id
simplified_events1 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events1)
)
)
expected_events1 = [
(
'test_workflow_agent_input_schema',
{
'nodes': {
'NodeA_input': {'status': NodeStatus.RUNNING.value},
}
},
),
(
'test_workflow_agent_input_schema@1/NodeA_input@1',
types.Part(
function_call=types.FunctionCall(
name=REQUEST_INPUT_FUNCTION_CALL_NAME,
args={
'interruptId': interrupt_id,
'message': 'Please provide user details.',
'payload': None,
'response_schema': {
'properties': {
'name': {'title': 'Name', 'type': 'string'},
'age': {'title': 'Age', 'type': 'integer'},
},
'required': ['name', 'age'],
'title': 'UserDetails',
'type': 'object',
},
},
)
),
),
(
'test_workflow_agent_input_schema',
{
'nodes': {
'NodeA_input': {
'status': NodeStatus.WAITING.value,
'interrupts': [interrupt_id],
},
},
},
),
]
if resumable:
assert simplified_events1 == expected_events1
else:
assert simplified_events1 == (
workflow_testing_utils.strip_checkpoint_events(expected_events1)
)
# Resume with user input
user_input = create_request_input_response(
interrupt_id, {'name': 'John', 'age': 30}
)
events2 = await runner.run_async(
new_message=testing_utils.UserContent(user_input),
invocation_id=invocation_id,
)
simplified_events2 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events2)
)
)
expected_events2 = [
(
'test_workflow_agent_input_schema@1/NodeA_input@1',
{'output': {'age': 30, 'name': 'John'}},
),
(
'test_workflow_agent_input_schema',
{
'nodes': {
'NodeA_input': {'status': NodeStatus.COMPLETED.value},
'NodeB': {
'status': NodeStatus.RUNNING.value,
},
}
},
),
(
'test_workflow_agent_input_schema@1/NodeB@1',
{
'output': 'Received user details',
},
),
(
'test_workflow_agent_input_schema',
{
'nodes': {
'NodeA_input': {'status': NodeStatus.COMPLETED.value},
'NodeB': {'status': NodeStatus.COMPLETED.value},
}
},
),
('test_workflow_agent_input_schema', testing_utils.END_OF_AGENT),
]
if resumable:
assert simplified_events2 == expected_events2
else:
# In V2 non-resumable mode, NodeA_input is skipped and does not yield output again.
# So we filter out its output event.
expected_non_resumable = [
e
for e in expected_events2
if not (e[0].split('/')[-1].split('@')[0] == 'NodeA_input')
]
expected_non_resumable = workflow_testing_utils.strip_checkpoint_events(
expected_non_resumable
)
assert simplified_events2 == expected_non_resumable
@pytest.mark.asyncio
async def test_workflow_allows_mixing_output_and_request_input(
request: pytest.FixtureRequest,
):
"""Tests that yielding both output and RequestInput is allowed in V2."""
class _YieldOutputAndRequestInputNode(BaseNode):
"""A node that yields output and requests input."""
model_config = ConfigDict(arbitrary_types_allowed=True)
name: str = Field(default='')
def __init__(self, *, name: str):
super().__init__()
object.__setattr__(self, 'name', name)
@override
def get_name(self) -> str:
return self.name
@override
async def _run_impl(
self,
*,
ctx: Context,
node_input: Any,
) -> AsyncGenerator[Any, None]:
yield Event(output='output 1')
yield RequestInput(interrupt_id='req1')
node_a = _YieldOutputAndRequestInputNode(name='NodeA')
node_b = InputCapturingNode(name='NodeB')
agent = Workflow(
name='test_agent',
edges=[
(START, node_a),
(node_a, node_b),
],
)
app = App(
name=request.function.__name__,
root_agent=agent,
)
runner = testing_utils.InMemoryRunner(app=app)
events = await runner.run_async(testing_utils.get_user_content('start'))
simplified = workflow_testing_utils.simplify_events_with_node_and_agent_state(
events
)
# In V2, mixing output and interrupts is ALLOWED.
# The node yields the output event and then the RequestInput event.
assert len(simplified) == 2
assert simplified[0] == (
'test_agent@1/NodeA@1',
{'output': 'output 1'},
)
assert simplified[1][0] == 'test_agent@1/NodeA@1'
assert simplified[1][1].function_call.name == 'adk_request_input'
assert simplified[1][1].function_call.args['interruptId'] == 'req1'
@pytest.mark.parametrize(
'resumable', [False, pytest.param(True, marks=pytest.mark.xfail)]
)
@pytest.mark.asyncio
async def test_workflow_rerun_on_resume(
request: pytest.FixtureRequest, resumable: bool
):
"""Tests node requests input and reruns itself upon resume."""
class _RerunNode(BaseNode):
model_config = ConfigDict(arbitrary_types_allowed=True)
rerun_on_resume: bool = Field(default=True)
name: str = Field(default='')
def __init__(self, *, name: str):
super().__init__()
object.__setattr__(self, 'name', name)
@override
def get_name(self) -> str:
return self.name
@override
async def _run_impl(
self, *, ctx: Context, node_input: Any
) -> AsyncGenerator[Any, None]:
if 'count' not in ctx.session.state:
ctx.session.state['count'] = 0
approval = None
if ctx.session.state['count'] == 0:
if resume_input := ctx.resume_inputs.get('ask_approval'):
ctx.session.state['count'] = 1
approval = resume_input['approved']
else:
yield RequestInput(
message='Needs approval', interrupt_id='ask_approval'
)
return
yield Event(output={'approval': approval})
node_a = _RerunNode(name='NodeA')
agent = Workflow(
name='test_agent',
edges=[Edge(from_node=START, to_node=node_a)],
)
app = App(
name=request.function.__name__,
root_agent=agent,
resumability_config=(
ResumabilityConfig(is_resumable=True) if resumable else None
),
)
runner = testing_utils.InMemoryRunner(app=app)
# Run 1: node requests input
events1 = await runner.run_async(testing_utils.get_user_content('start'))
simplified_events1 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events1),
)
)
req_events = workflow_testing_utils.get_request_input_events(events1)
assert len(req_events) == 1
interrupt_id1 = get_request_input_interrupt_ids(req_events[0])[0]
invocation_id = events1[0].invocation_id
if resumable:
assert simplified_events1[-1] == (
'test_agent',
{
'nodes': {
'NodeA': {
'status': NodeStatus.WAITING.value,
'interrupts': [interrupt_id1],
},
},
},
)
# Run 2: provide input, node reruns and completes
events2 = await runner.run_async(
new_message=testing_utils.UserContent(
create_request_input_response(interrupt_id1, {'approved': True})
),
invocation_id=invocation_id,
)
simplified_events2 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events2),
include_resume_inputs=True,
)
)
expected_events2 = [
(
'test_agent',
{
'nodes': {
'NodeA': {
'status': NodeStatus.RUNNING.value,
'resume_inputs': {interrupt_id1: {'approved': True}},
},
}
},
),
(
'test_agent@1/NodeA@1',
{
'output': {'approval': True},
},
),
(
'test_agent',
{
'nodes': {
'NodeA': {'status': NodeStatus.COMPLETED.value},
}
},
),
('test_agent', testing_utils.END_OF_AGENT),
]
if resumable:
assert simplified_events2 == expected_events2
else:
assert simplified_events2 == (
workflow_testing_utils.strip_checkpoint_events(expected_events2)
)
@pytest.mark.parametrize(
'resumable', [False, pytest.param(True, marks=pytest.mark.xfail)]
)
@pytest.mark.asyncio
async def test_workflow_rerun_with_multiple_inputs(
request: pytest.FixtureRequest,
resumable: bool,
):
"""Tests node with rerun_on_resume=True requests multiple inputs and resumed one by one."""
class _RerunNodeWithTwoInputs(BaseNode):
model_config = ConfigDict(arbitrary_types_allowed=True)
rerun_on_resume: bool = Field(default=True)
name: str = Field(default='')
def __init__(self, *, name: str):
super().__init__()
object.__setattr__(self, 'name', name)
@override
def get_name(self) -> str:
return self.name
@override
async def _run_impl(
self, *, ctx: Context, node_input: Any
) -> AsyncGenerator[Any, None]:
if resume_input := ctx.resume_inputs.get('req1'):
yield Event(state={'input1': resume_input['text']})
if resume_input := ctx.resume_inputs.get('req2'):
yield Event(state={'input2': resume_input['text']})
if 'input1' not in ctx.state and 'req1' not in ctx.resume_inputs:
yield RequestInput(message='input 1', interrupt_id='req1')
return
if 'input2' not in ctx.state and 'req2' not in ctx.resume_inputs:
yield RequestInput(message='input 2', interrupt_id='req2')
return
input1 = ctx.resume_inputs['req1']['text']
input2 = ctx.resume_inputs['req2']['text']
yield Event(
output={
'input1': input1,
'input2': input2,
},
)
node_a = _RerunNodeWithTwoInputs(name='NodeA')
agent = Workflow(
name='test_agent',
edges=[Edge(from_node=START, to_node=node_a)],
)
app = App(
name=request.function.__name__,
root_agent=agent,
resumability_config=(
ResumabilityConfig(is_resumable=True) if resumable else None
),
)
runner = testing_utils.InMemoryRunner(app=app)
# Run 1: node requests 1st input
events1 = await runner.run_async(testing_utils.get_user_content('start'))
simplified_events1 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events1),
)
)
req_events1 = workflow_testing_utils.get_request_input_events(events1)
assert len(req_events1) == 1
interrupt_id1 = get_request_input_interrupt_ids(req_events1[0])[0]
assert interrupt_id1 == 'req1'
invocation_id = events1[0].invocation_id
if resumable:
assert simplified_events1[-1] == (
'test_agent',
{
'nodes': {
'NodeA': {
'status': NodeStatus.WAITING.value,
'interrupts': [interrupt_id1],
},
},
},
)
# Run 2: provide 1st input, node reruns and requests 2nd input
events2 = await runner.run_async(
new_message=testing_utils.UserContent(
create_request_input_response(interrupt_id1, {'text': 'response 1'})
),
invocation_id=invocation_id,
)
assert all(
e.invocation_id == invocation_id for e in events2 if e.invocation_id
)
simplified_events2 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events2),
include_resume_inputs=True,
)
)
req_events2 = workflow_testing_utils.get_request_input_events(events2)
assert len(req_events2) == 1
interrupt_id2 = get_request_input_interrupt_ids(req_events2[0])[0]
assert interrupt_id2 == 'req2'
expected_events2 = [
(
'test_agent',
{
'nodes': {
'NodeA': {
'status': NodeStatus.RUNNING.value,
'resume_inputs': {interrupt_id1: {'text': 'response 1'}},
},
}
},
),
(
'test_agent@1/NodeA@1',
types.Part(
function_call=types.FunctionCall(
name=REQUEST_INPUT_FUNCTION_CALL_NAME,
args={
'interruptId': 'req2',
'message': 'input 2',
'payload': None,
'response_schema': None,
},
)
),
),
(
'test_agent',
{
'nodes': {
'NodeA': {
'status': NodeStatus.WAITING.value,
'interrupts': [interrupt_id2],
'resume_inputs': {interrupt_id1: {'text': 'response 1'}},
},
},
},
),
]
if resumable:
assert simplified_events2 == expected_events2
else:
assert simplified_events2 == (
workflow_testing_utils.strip_checkpoint_events(expected_events2)
)
# Run 3: provide 2nd input, node reruns and completes
events3 = await runner.run_async(
new_message=testing_utils.UserContent(
create_request_input_response(interrupt_id2, {'text': 'response 2'})
),
invocation_id=invocation_id,
)
assert all(
e.invocation_id == invocation_id for e in events3 if e.invocation_id
)
simplified_events3 = (
workflow_testing_utils.simplify_events_with_node_and_agent_state(
copy.deepcopy(events3),
include_resume_inputs=True,
)
)
expected_events3 = [
(
'test_agent',
{
'nodes': {
'NodeA': {
'status': NodeStatus.RUNNING.value,
'resume_inputs': {
interrupt_id1: {'text': 'response 1'},
interrupt_id2: {'text': 'response 2'},
},
},
}
},
),
(
'test_agent@1/NodeA@1',
{
'output': {'input1': 'response 1', 'input2': 'response 2'},
},
),
(
'test_agent',
{
'nodes': {
'NodeA': {'status': NodeStatus.COMPLETED.value},
}
},
),
('test_agent', testing_utils.END_OF_AGENT),
]
if resumable:
assert simplified_events3 == expected_events3
else:
assert simplified_events3 == (
workflow_testing_utils.strip_checkpoint_events(expected_events3)
)
class _MultiHitlRerunNode(BaseNode):
model_config = ConfigDict(arbitrary_types_allowed=True)
rerun_on_resume: bool = Field(default=True)
name: str = Field(default='')
def __init__(self, *, name: str):
super().__init__()
object.__setattr__(self, 'name', name)
@override
def get_name(self) -> str:
return self.name
@override
async def _run_impl(
self, *, ctx: Context, node_input: Any
) -> AsyncGenerator[Any, None]:
if not ctx.resume_inputs.get('req1'):
yield RequestInput(interrupt_id='req1', message='request 1')
return
if not ctx.resume_inputs.get('req2'):
yield RequestInput(interrupt_id='req2', message='request 2')
return
yield Event(output='final_output')
@pytest.mark.parametrize(
'resumable', [False, pytest.param(True, marks=pytest.mark.xfail)]
)
@pytest.mark.asyncio
async def test_rerun_with_multiple_hitl_and_outputs(
request: pytest.FixtureRequest,
resumable: bool,
):
"""Tests that a re-runnable node with multiple HITL accumulates outputs."""
node_a = _MultiHitlRerunNode(name='NodeA')
node_b = InputCapturingNode(name='NodeB')
agent = Workflow(
name='test_agent_multi_hitl',
edges=[
(START, node_a),
(node_a, node_b),
],
)
app = App(
name=request.function.__name__,
root_agent=agent,
resumability_config=(
ResumabilityConfig(is_resumable=True) if resumable else None
),
)
session_service = InMemorySessionService()
artifact_service = InMemoryArtifactService()
memory_service = InMemoryMemoryService()
runner1 = Runner(
app=app,
session_service=session_service,
artifact_service=artifact_service,
memory_service=memory_service,
)
runner2 = Runner(
app=app,
session_service=session_service,
artifact_service=artifact_service,
memory_service=memory_service,
)
runner3 = Runner(
app=app,
session_service=session_service,
artifact_service=artifact_service,
memory_service=memory_service,
)
session = await session_service.create_session(
app_name=app.name, user_id='test_user'
)
async def collect_events(agen):
events = []
async for e in agen:
events.append(e)
return events
# Run 1: node requests input1
events1 = await collect_events(
runner1.run_async(
user_id=session.user_id,
session_id=session.id,
new_message=testing_utils.get_user_content('start'),
)
)
req_events1 = workflow_testing_utils.get_request_input_events(events1)
assert len(req_events1) == 1
assert get_request_input_interrupt_ids(req_events1[0])[0] == 'req1'
invocation_id = events1[0].invocation_id
# Run 2: provide input1, node requests input2.
events2 = await collect_events(
runner2.run_async(
user_id=session.user_id,
session_id=session.id,
new_message=testing_utils.UserContent(
create_request_input_response('req1', {'text': 'response 1'})
),
invocation_id=invocation_id if resumable else None,