-
Notifications
You must be signed in to change notification settings - Fork 817
Expand file tree
/
Copy pathtest_event_loop.py
More file actions
1134 lines (967 loc) · 33.1 KB
/
test_event_loop.py
File metadata and controls
1134 lines (967 loc) · 33.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 concurrent
import threading
import unittest.mock
from unittest.mock import ANY, AsyncMock, MagicMock, call, patch
import pytest
import strands
import strands.telemetry
from strands import Agent
from strands.event_loop._retry import ModelRetryStrategy
from strands.hooks import (
AfterModelCallEvent,
BeforeModelCallEvent,
BeforeToolCallEvent,
HookRegistry,
MessageAddedEvent,
)
from strands.interrupt import Interrupt, _InterruptState
from strands.telemetry.metrics import EventLoopMetrics
from strands.tools.executors import SequentialToolExecutor
from strands.tools.registry import ToolRegistry
from strands.types._events import EventLoopStopEvent
from strands.types.exceptions import (
ContextWindowOverflowException,
EventLoopException,
MaxTokensReachedException,
ModelThrottledException,
)
from tests.fixtures.mock_hook_provider import MockHookProvider
from tests.fixtures.mocked_model_provider import MockedModelProvider
@pytest.fixture
def mock_sleep():
with patch.object(strands.event_loop._retry.asyncio, "sleep", new_callable=AsyncMock) as mock:
yield mock
@pytest.fixture
def model():
return unittest.mock.Mock()
@pytest.fixture
def system_prompt():
return "p1"
@pytest.fixture
def messages():
return [{"role": "user", "content": [{"text": "Hello"}]}]
@pytest.fixture
def tool_registry():
return ToolRegistry()
@pytest.fixture
def thread_pool():
return concurrent.futures.ThreadPoolExecutor(max_workers=1)
@pytest.fixture
def tool(tool_registry):
@strands.tool
def tool_for_testing(random_string: str):
return random_string
tool_registry.register_tool(tool_for_testing)
return tool_for_testing
@pytest.fixture
def tool_times_2(tool_registry):
@strands.tools.tool
def multiply_by_2(x: int) -> int:
return x * 2
tool_registry.register_tool(multiply_by_2)
return multiply_by_2
@pytest.fixture
def tool_times_5(tool_registry):
@strands.tools.tool
def multiply_by_5(x: int) -> int:
return x * 5
tool_registry.register_tool(multiply_by_5)
return multiply_by_5
@pytest.fixture
def tool_stream(tool):
return [
{
"contentBlockStart": {
"start": {
"toolUse": {
"toolUseId": "t1",
"name": tool.tool_spec["name"],
},
},
},
},
{"contentBlockDelta": {"delta": {"toolUse": {"input": '{"random_string": "abcdEfghI123"}'}}}},
{"contentBlockStop": {}},
{"messageStop": {"stopReason": "tool_use"}},
]
@pytest.fixture
def hook_registry():
registry = HookRegistry()
# Register default retry strategy
retry_strategy = ModelRetryStrategy()
retry_strategy.register_hooks(registry)
return registry
@pytest.fixture
def hook_provider(hook_registry):
provider = MockHookProvider(event_types="all")
hook_registry.add_hook(provider)
return provider
@pytest.fixture
def tool_executor():
return SequentialToolExecutor()
@pytest.fixture
def agent(model, system_prompt, messages, tool_registry, thread_pool, hook_registry, tool_executor):
mock = unittest.mock.Mock(name="agent")
mock.__class__ = Agent
mock.config.cache_points = []
mock.model = model
mock.system_prompt = system_prompt
mock.messages = messages
mock.tool_registry = tool_registry
mock.thread_pool = thread_pool
mock.event_loop_metrics = EventLoopMetrics()
mock.event_loop_metrics.reset_usage_metrics()
mock.hooks = hook_registry
mock.tool_executor = tool_executor
mock._interrupt_state = _InterruptState()
mock._cancel_signal = threading.Event()
mock.trace_attributes = {}
mock.retry_strategy = ModelRetryStrategy()
return mock
@pytest.fixture
def mock_tracer():
tracer = MagicMock()
tracer.start_event_loop_cycle_span.return_value = MagicMock()
tracer.start_model_invoke_span.return_value = MagicMock()
return tracer
@pytest.mark.asyncio
async def test_event_loop_cycle_text_response(
agent,
model,
agenerator,
alist,
):
model.stream.return_value = agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
)
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
events = await alist(stream)
tru_stop_reason, tru_message, _, tru_request_state, _, _ = events[-1]["stop"]
exp_stop_reason = "end_turn"
exp_message = {"role": "assistant", "content": [{"text": "test text"}]}
exp_request_state = {}
assert tru_stop_reason == exp_stop_reason and tru_message == exp_message and tru_request_state == exp_request_state
@pytest.mark.asyncio
async def test_event_loop_cycle_text_response_throttling(
mock_sleep,
agent,
model,
agenerator,
alist,
):
model.stream.side_effect = [
ModelThrottledException("ThrottlingException | ConverseStream"),
agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
),
]
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
events = await alist(stream)
tru_stop_reason, tru_message, _, tru_request_state, _, _ = events[-1]["stop"]
exp_stop_reason = "end_turn"
exp_message = {"role": "assistant", "content": [{"text": "test text"}]}
exp_request_state = {}
assert tru_stop_reason == exp_stop_reason and tru_message == exp_message and tru_request_state == exp_request_state
# Verify that sleep was called once with the initial delay
mock_sleep.assert_called_once()
@pytest.mark.asyncio
async def test_event_loop_cycle_exponential_backoff(
mock_sleep,
agent,
model,
agenerator,
alist,
):
"""Test that the exponential backoff works correctly with multiple retries."""
# Set up the model to raise throttling exceptions multiple times before succeeding
model.stream.side_effect = [
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
),
]
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
events = await alist(stream)
tru_stop_reason, tru_message, _, tru_request_state, _, _ = events[-1]["stop"]
# Verify the final response
assert tru_stop_reason == "end_turn"
assert tru_message == {"role": "assistant", "content": [{"text": "test text"}]}
assert tru_request_state == {}
# Verify that sleep was called with increasing delays
# Initial delay is 4, then 8, then 16
assert mock_sleep.call_count == 3
assert mock_sleep.call_args_list == [call(4), call(8), call(16)]
@pytest.mark.asyncio
async def test_event_loop_cycle_text_response_throttling_exceeded(
mock_sleep,
agent,
model,
alist,
):
model.stream.side_effect = [
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
ModelThrottledException("ThrottlingException | ConverseStream"),
]
with pytest.raises(ModelThrottledException):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
mock_sleep.assert_has_calls(
[
call(4),
call(8),
call(16),
call(32),
call(64),
]
)
@pytest.mark.asyncio
async def test_event_loop_cycle_text_response_error(
agent,
model,
alist,
):
model.stream.side_effect = RuntimeError("Unhandled error")
with pytest.raises(RuntimeError):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
@patch("strands.event_loop.event_loop.recover_message_on_max_tokens_reached")
@pytest.mark.asyncio
async def test_event_loop_cycle_tool_result(
mock_recover_message,
agent,
model,
system_prompt,
messages,
tool_stream,
tool_registry,
agenerator,
alist,
):
model.stream.side_effect = [
agenerator(tool_stream),
agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
),
]
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
events = await alist(stream)
tru_stop_reason, tru_message, _, tru_request_state, _, _ = events[-1]["stop"]
exp_stop_reason = "end_turn"
exp_message = {"role": "assistant", "content": [{"text": "test text"}]}
exp_request_state = {}
assert tru_stop_reason == exp_stop_reason and tru_message == exp_message and tru_request_state == exp_request_state
# Verify that recover_message_on_max_tokens_reached was NOT called for tool_use stop reason
mock_recover_message.assert_not_called()
model.stream.assert_called_with(
[
{"role": "user", "content": [{"text": "Hello"}]},
{
"role": "assistant",
"content": [
{
"toolUse": {
"toolUseId": "t1",
"name": "tool_for_testing",
"input": {"random_string": "abcdEfghI123"},
}
}
],
},
{
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": "t1",
"status": "success",
"content": [{"text": "abcdEfghI123"}],
},
},
],
},
{"role": "assistant", "content": [{"text": "test text"}]},
],
tool_registry.get_all_tool_specs(),
"p1",
tool_choice=None,
system_prompt_content=unittest.mock.ANY,
invocation_state=unittest.mock.ANY,
)
@pytest.mark.asyncio
async def test_event_loop_cycle_tool_result_error(
agent,
model,
tool_stream,
agenerator,
alist,
):
model.stream.side_effect = [agenerator(tool_stream)]
with pytest.raises(EventLoopException):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
@pytest.mark.asyncio
async def test_event_loop_cycle_tool_result_no_tool_handler(
agent,
model,
tool_stream,
agenerator,
alist,
):
model.stream.side_effect = [agenerator(tool_stream)]
# Set tool_handler to None for this test
agent.tool_handler = None
with pytest.raises(EventLoopException):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
@pytest.mark.asyncio
async def test_event_loop_cycle_stop(
agent,
model,
tool,
agenerator,
alist,
):
model.stream.side_effect = [
agenerator(
[
{
"contentBlockStart": {
"start": {
"toolUse": {
"toolUseId": "t1",
"name": tool.tool_spec["name"],
},
},
},
},
{"contentBlockStop": {}},
{"messageStop": {"stopReason": "tool_use"}},
]
),
]
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={"request_state": {"stop_event_loop": True}},
)
events = await alist(stream)
tru_stop_reason, tru_message, _, tru_request_state, _, _ = events[-1]["stop"]
exp_stop_reason = "tool_use"
exp_message = {
"role": "assistant",
"content": [
{
"toolUse": {
"input": {},
"name": "tool_for_testing",
"toolUseId": "t1",
}
}
],
}
exp_request_state = {"stop_event_loop": True}
assert tru_stop_reason == exp_stop_reason and tru_message == exp_message and tru_request_state == exp_request_state
@pytest.mark.asyncio
async def test_cycle_exception(
agent,
model,
tool_stream,
agenerator,
):
model.stream.side_effect = [
agenerator(tool_stream),
agenerator(tool_stream),
agenerator(tool_stream),
ValueError("Invalid error presented"),
]
tru_stop_event = None
exp_stop_event = {"force_stop": True, "force_stop_reason": "Invalid error presented"}
with pytest.raises(EventLoopException):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
async for event in stream:
tru_stop_event = event
assert tru_stop_event == exp_stop_event
@patch("strands.event_loop.event_loop.get_tracer")
@pytest.mark.asyncio
async def test_event_loop_cycle_creates_spans(
mock_get_tracer,
agent,
model,
mock_tracer,
agenerator,
alist,
):
# Setup
mock_get_tracer.return_value = mock_tracer
cycle_span = MagicMock()
mock_tracer.start_event_loop_cycle_span.return_value = cycle_span
model_span = MagicMock()
mock_tracer.start_model_invoke_span.return_value = model_span
model.stream.return_value = agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
)
# Call event_loop_cycle
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
# Verify tracer methods were called correctly
mock_get_tracer.assert_called_once()
mock_tracer.start_event_loop_cycle_span.assert_called_once()
mock_tracer.start_model_invoke_span.assert_called_once()
mock_tracer.end_model_invoke_span.assert_called_once()
mock_tracer.end_event_loop_cycle_span.assert_called_once()
@patch("strands.event_loop.event_loop.get_tracer")
@pytest.mark.asyncio
async def test_event_loop_tracing_with_model_error(
mock_get_tracer,
agent,
model,
mock_tracer,
alist,
):
# Setup
mock_get_tracer.return_value = mock_tracer
cycle_span = MagicMock()
mock_tracer.start_event_loop_cycle_span.return_value = cycle_span
model_span = MagicMock()
mock_tracer.start_model_invoke_span.return_value = model_span
# Set up model to raise an exception
model.stream.side_effect = ContextWindowOverflowException("Input too long")
# Call event_loop_cycle, expecting it to handle the exception
with pytest.raises(ContextWindowOverflowException):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
@pytest.mark.asyncio
async def test_event_loop_cycle_max_tokens_exception(
agent,
model,
agenerator,
alist,
):
"""Test that max_tokens stop reason calls _recover_message_on_max_tokens_reached then MaxTokensReachedException."""
model.stream.side_effect = [
agenerator(
[
{
"contentBlockStart": {
"start": {
"toolUse": {
"toolUseId": "t1",
"name": "asdf",
"input": {}, # empty
},
},
},
},
{"contentBlockStop": {}},
{"messageStop": {"stopReason": "max_tokens"}},
]
),
]
# Call event_loop_cycle, expecting it to raise MaxTokensReachedException
expected_message = (
"Agent has reached an unrecoverable state due to max_tokens limit. "
"For more information see: "
"https://strandsagents.com/latest/user-guide/concepts/agents/agent-loop/#maxtokensreachedexception"
)
with pytest.raises(MaxTokensReachedException, match=expected_message):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
# Verify the exception message contains the expected content
assert len(agent.messages) == 2
assert "tool use was incomplete due" in agent.messages[1]["content"][0]["text"]
@patch("strands.event_loop.event_loop.get_tracer")
@pytest.mark.asyncio
async def test_event_loop_tracing_with_tool_execution(
mock_get_tracer,
agent,
model,
tool_stream,
mock_tracer,
agenerator,
alist,
):
# Setup
mock_get_tracer.return_value = mock_tracer
cycle_span = MagicMock()
mock_tracer.start_event_loop_cycle_span.return_value = cycle_span
model_span = MagicMock()
mock_tracer.start_model_invoke_span.return_value = model_span
# Set up model to return tool use and then text response
model.stream.side_effect = [
agenerator(tool_stream),
agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
),
]
# Call event_loop_cycle which should execute a tool
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
# Verify the parent_span parameter is passed to run_tools
# At a minimum, verify both model spans were created (one for each model invocation)
assert mock_tracer.start_model_invoke_span.call_count == 2
assert mock_tracer.end_model_invoke_span.call_count == 2
@patch("strands.event_loop.event_loop.get_tracer")
@pytest.mark.asyncio
async def test_event_loop_tracing_with_throttling_exception(
mock_get_tracer,
agent,
model,
mock_tracer,
agenerator,
alist,
):
# Setup
mock_get_tracer.return_value = mock_tracer
cycle_span = MagicMock()
mock_tracer.start_event_loop_cycle_span.return_value = cycle_span
model_span = MagicMock()
mock_tracer.start_model_invoke_span.return_value = model_span
# Set up model to raise a throttling exception and then succeed
model.stream.side_effect = [
ModelThrottledException("Throttling Error"),
agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
),
]
# Mock the time.sleep function to speed up the test
with patch.object(asyncio, "sleep", new_callable=unittest.mock.AsyncMock):
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
# Verify span was created for the successful retry
assert mock_tracer.start_model_invoke_span.call_count == 2
assert mock_tracer.end_model_invoke_span.call_count == 1
@patch("strands.event_loop.event_loop.get_tracer")
@pytest.mark.asyncio
async def test_event_loop_cycle_with_parent_span(
mock_get_tracer,
agent,
model,
messages,
mock_tracer,
agenerator,
alist,
):
# Setup
mock_get_tracer.return_value = mock_tracer
parent_span = MagicMock()
cycle_span = MagicMock()
mock_tracer.start_event_loop_cycle_span.return_value = cycle_span
model.stream.return_value = agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
)
# Set the parent span for this test
agent.trace_span = parent_span
# Call event_loop_cycle with a parent span
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
# Verify parent_span was used when creating cycle span
mock_tracer.start_event_loop_cycle_span.assert_called_once_with(
invocation_state=unittest.mock.ANY,
parent_span=parent_span,
messages=messages,
custom_trace_attributes=unittest.mock.ANY,
)
@pytest.mark.asyncio
async def test_request_state_initialization(alist):
# Create a mock agent
mock_agent = MagicMock()
# not setting this to False results in endless recursion
mock_agent._interrupt_state.activated = False
mock_agent._cancel_signal = threading.Event()
mock_agent.event_loop_metrics.start_cycle.return_value = (0, MagicMock())
mock_agent.hooks.invoke_callbacks_async = AsyncMock()
# Call without providing request_state
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=mock_agent,
invocation_state={},
)
events = await alist(stream)
_, _, _, tru_request_state, _, _ = events[-1]["stop"]
# Verify request_state was initialized to empty dict
assert tru_request_state == {}
# Call with pre-existing request_state
initial_request_state = {"key": "value"}
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=mock_agent,
invocation_state={"request_state": initial_request_state},
)
events = await alist(stream)
_, _, _, tru_request_state, _, _ = events[-1]["stop"]
# Verify existing request_state was preserved
assert tru_request_state == initial_request_state
@pytest.mark.asyncio
async def test_prepare_next_cycle_in_tool_execution(agent, model, tool_stream, agenerator, alist):
"""Test that cycle ID and metrics are properly updated during tool execution."""
model.stream.side_effect = [
agenerator(tool_stream),
agenerator(
[
{"contentBlockStop": {}},
]
),
]
# Create a mock for recurse_event_loop to capture the invocation_state passed to it
with unittest.mock.patch.object(strands.event_loop.event_loop, "recurse_event_loop") as mock_recurse:
# Set up mock to return a valid response
mock_recurse.return_value = agenerator(
[
(
"end_turn",
{"role": "assistant", "content": [{"text": "test text"}]},
strands.telemetry.metrics.EventLoopMetrics(),
{},
),
]
)
# Call event_loop_cycle which should execute a tool and then call recurse_event_loop
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
assert mock_recurse.called
# Verify required properties are present
recursive_args = mock_recurse.call_args[1]
assert "event_loop_parent_cycle_id" in recursive_args["invocation_state"]
assert (
recursive_args["invocation_state"]["event_loop_parent_cycle_id"]
== recursive_args["invocation_state"]["event_loop_cycle_id"]
)
@pytest.mark.asyncio
async def test_event_loop_cycle_exception_model_hooks(mock_sleep, agent, model, agenerator, alist, hook_provider):
"""Test that model hooks are correctly emitted even when throttled."""
# Set up the model to raise throttling exceptions multiple times before succeeding
exception = ModelThrottledException("ThrottlingException | ConverseStream")
model.stream.side_effect = [
exception,
exception,
exception,
agenerator(
[
{"contentBlockDelta": {"delta": {"text": "test text"}}},
{"contentBlockStop": {}},
]
),
]
stream = strands.event_loop.event_loop.event_loop_cycle(
agent=agent,
invocation_state={},
)
await alist(stream)
count, events = hook_provider.get_events()
assert count == 9
# 1st call - throttled
assert next(events) == BeforeModelCallEvent(agent=agent, invocation_state=ANY)
expected_after = AfterModelCallEvent(agent=agent, invocation_state=ANY, stop_response=None, exception=exception)
expected_after.retry = True
assert next(events) == expected_after
# 2nd call - throttled
assert next(events) == BeforeModelCallEvent(agent=agent, invocation_state=ANY)
expected_after = AfterModelCallEvent(agent=agent, invocation_state=ANY, stop_response=None, exception=exception)
expected_after.retry = True
assert next(events) == expected_after
# 3rd call - throttled
assert next(events) == BeforeModelCallEvent(agent=agent, invocation_state=ANY)
expected_after = AfterModelCallEvent(agent=agent, invocation_state=ANY, stop_response=None, exception=exception)
expected_after.retry = True
assert next(events) == expected_after
# 4th call - successful
assert next(events) == BeforeModelCallEvent(agent=agent, invocation_state=ANY)
assert next(events) == AfterModelCallEvent(
agent=agent,
invocation_state=ANY,
stop_response=AfterModelCallEvent.ModelStopResponse(
message={"content": [{"text": "test text"}], "role": "assistant"}, stop_reason="end_turn"
),
exception=None,
)
# Final message
assert next(events) == MessageAddedEvent(
agent=agent, message={"content": [{"text": "test text"}], "role": "assistant"}
)
@pytest.mark.asyncio
async def test_event_loop_cycle_interrupt(agent, model, tool_stream, agenerator, alist):
def interrupt_callback(event):
event.interrupt("test_name", "test reason")
agent.hooks.add_callback(BeforeToolCallEvent, interrupt_callback)
model.stream.side_effect = [agenerator(tool_stream)]
stream = strands.event_loop.event_loop.event_loop_cycle(agent, invocation_state={})
events = await alist(stream)
tru_stop_reason, _, _, _, tru_interrupts, _ = events[-1]["stop"]
exp_stop_reason = "interrupt"
exp_interrupts = [
Interrupt(
id="v1:before_tool_call:t1:78714d6c-613c-5cf4-bf25-7037569941f9",
name="test_name",
reason="test reason",
),
]
assert tru_stop_reason == exp_stop_reason and tru_interrupts == exp_interrupts
tru_state = agent._interrupt_state.to_dict()
exp_state = {
"activated": True,
"context": {
"tool_results": [],
"tool_use_message": {
"content": [
{
"toolUse": {
"input": {"random_string": "abcdEfghI123"},
"name": "tool_for_testing",
"toolUseId": "t1",
},
},
],
"role": "assistant",
},
},
"interrupts": {
"v1:before_tool_call:t1:78714d6c-613c-5cf4-bf25-7037569941f9": {
"id": "v1:before_tool_call:t1:78714d6c-613c-5cf4-bf25-7037569941f9",
"name": "test_name",
"reason": "test reason",
"response": None,
},
},
}
assert tru_state == exp_state
@pytest.mark.asyncio
async def test_event_loop_cycle_interrupt_resume(agent, model, tool, tool_times_2, agenerator, alist):
interrupt = Interrupt(
id="v1:before_tool_call:t1:78714d6c-613c-5cf4-bf25-7037569941f9",
name="test_name",
reason="test reason",
response="test response",
)
tool_use_message = {
"role": "assistant",
"content": [
{
"toolUse": {
"toolUseId": "t1",
"name": "tool_for_testing",
"input": {"random_string": "test input"},
}
},
{
"toolUse": {
"toolUseId": "t2",
"name": "tool_times_2",
"input": {},
}
},
],
}
tool_results = [
{
"toolUseId": "t2",
"status": "success",
"content": [{"text": "t2 result"}],
},
]
agent._interrupt_state.context = {"tool_use_message": tool_use_message, "tool_results": tool_results}
agent._interrupt_state.interrupts[interrupt.id] = interrupt
agent._interrupt_state.activate()
interrupt_response = {}
def interrupt_callback(event):
interrupt_response["response"] = event.interrupt("test_name", "test reason")
agent.hooks.add_callback(BeforeToolCallEvent, interrupt_callback)
model.stream.side_effect = [agenerator([{"contentBlockStop": {}}])]
stream = strands.event_loop.event_loop.event_loop_cycle(agent, invocation_state={})
events = await alist(stream)