-
Notifications
You must be signed in to change notification settings - Fork 806
Expand file tree
/
Copy pathtest_bedrock.py
More file actions
2887 lines (2336 loc) · 104 KB
/
test_bedrock.py
File metadata and controls
2887 lines (2336 loc) · 104 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 copy
import logging
import os
import sys
import traceback
import unittest.mock
from unittest.mock import ANY
import boto3
import pydantic
import pytest
from botocore.config import Config as BotocoreConfig
from botocore.exceptions import ClientError, EventStreamError
import strands
from strands import _exception_notes
from strands.models import BedrockModel, CacheConfig
from strands.models.bedrock import (
_DEFAULT_BEDROCK_MODEL_ID,
DEFAULT_BEDROCK_MODEL_ID,
DEFAULT_BEDROCK_REGION,
DEFAULT_READ_TIMEOUT,
)
from strands.types.exceptions import ContextWindowOverflowException, ModelThrottledException
from strands.types.tools import ToolSpec
FORMATTED_DEFAULT_MODEL_ID = DEFAULT_BEDROCK_MODEL_ID.format("us")
@pytest.fixture
def session_cls():
# Mock the creation of a Session so that we don't depend on environment variables or profiles
with unittest.mock.patch.object(strands.models.bedrock.boto3, "Session") as mock_session_cls:
mock_session = unittest.mock.Mock()
mock_session.region_name = None
mock_session_cls.return_value = mock_session
yield mock_session_cls
@pytest.fixture
def mock_client_method(session_cls):
# the boto3.Session().client(...) method
return session_cls.return_value.client
@pytest.fixture
def bedrock_client(session_cls):
mock_client = session_cls.return_value.client.return_value
mock_client.meta = unittest.mock.MagicMock()
mock_client.meta.region_name = "us-west-2"
yield mock_client
@pytest.fixture
def model_id():
return "m1"
@pytest.fixture
def model(bedrock_client, model_id):
_ = bedrock_client
return BedrockModel(model_id=model_id)
@pytest.fixture
def messages():
return [{"role": "user", "content": [{"text": "test"}]}]
@pytest.fixture
def system_prompt():
return "s1"
@pytest.fixture
def additional_request_fields():
return {"a": 1}
@pytest.fixture
def additional_response_field_paths():
return ["p1"]
@pytest.fixture
def guardrail_config():
return {
"guardrail_id": "g1",
"guardrail_version": "v1",
"guardrail_stream_processing_mode": "async",
"guardrail_trace": "enabled",
}
@pytest.fixture
def inference_config():
return {
"max_tokens": 1,
"stop_sequences": ["stop"],
"temperature": 1,
"top_p": 1,
}
@pytest.fixture
def tool_spec() -> ToolSpec:
return {
"description": "description",
"name": "name",
"inputSchema": {"key": "val"},
}
@pytest.fixture
def cache_type():
return "default"
@pytest.fixture
def test_output_model_cls():
class TestOutputModel(pydantic.BaseModel):
name: str
age: int
return TestOutputModel
def test__init__default_model_id(bedrock_client):
"""Test that BedrockModel uses DEFAULT_MODEL_ID when no model_id is provided."""
_ = bedrock_client
model = BedrockModel()
tru_model_id = model.get_config().get("model_id")
exp_model_id = FORMATTED_DEFAULT_MODEL_ID
assert tru_model_id == exp_model_id
def test__init__with_default_region(session_cls, mock_client_method):
"""Test that BedrockModel uses the provided region."""
with unittest.mock.patch.object(os, "environ", {}):
BedrockModel()
session_cls.return_value.client.assert_called_with(
region_name=DEFAULT_BEDROCK_REGION, config=ANY, service_name=ANY, endpoint_url=None
)
def test__init__with_session_region(session_cls, mock_client_method):
"""Test that BedrockModel uses the provided region."""
session_cls.return_value.region_name = "eu-blah-1"
BedrockModel()
mock_client_method.assert_called_with(region_name="eu-blah-1", config=ANY, service_name=ANY, endpoint_url=None)
def test__init__with_custom_region(mock_client_method):
"""Test that BedrockModel uses the provided region."""
custom_region = "us-east-1"
BedrockModel(region_name=custom_region)
mock_client_method.assert_called_with(region_name=custom_region, config=ANY, service_name=ANY, endpoint_url=None)
def test__init__with_default_environment_variable_region(mock_client_method):
"""Test that BedrockModel uses the AWS_REGION since we code that in."""
with unittest.mock.patch.object(os, "environ", {"AWS_REGION": "eu-west-2"}):
BedrockModel()
mock_client_method.assert_called_with(region_name="eu-west-2", config=ANY, service_name=ANY, endpoint_url=None)
def test__init__region_precedence(mock_client_method, session_cls):
"""Test that BedrockModel uses the correct ordering of precedence when determining region."""
with unittest.mock.patch.object(os, "environ", {"AWS_REGION": "us-environment-1"}) as mock_os_environ:
session_cls.return_value.region_name = "us-session-1"
# specifying a region always wins out
BedrockModel(region_name="us-specified-1")
mock_client_method.assert_called_with(
region_name="us-specified-1", config=ANY, service_name=ANY, endpoint_url=None
)
# other-wise uses the session's
BedrockModel()
mock_client_method.assert_called_with(
region_name="us-session-1", config=ANY, service_name=ANY, endpoint_url=None
)
# environment variable next
session_cls.return_value.region_name = None
BedrockModel()
mock_client_method.assert_called_with(
region_name="us-environment-1", config=ANY, service_name=ANY, endpoint_url=None
)
mock_os_environ.pop("AWS_REGION")
session_cls.return_value.region_name = None # No session region
BedrockModel()
mock_client_method.assert_called_with(
region_name=DEFAULT_BEDROCK_REGION, config=ANY, service_name=ANY, endpoint_url=None
)
def test__init__with_endpoint_url(mock_client_method):
"""Test that BedrockModel uses the provided endpoint_url for VPC endpoints."""
custom_endpoint = "https://vpce-12345-abcde.bedrock-runtime.us-west-2.vpce.amazonaws.com"
with unittest.mock.patch.object(os, "environ", {}):
BedrockModel(endpoint_url=custom_endpoint)
mock_client_method.assert_called_with(
region_name=DEFAULT_BEDROCK_REGION, config=ANY, service_name=ANY, endpoint_url=custom_endpoint
)
def test__init__with_region_and_session_raises_value_error():
"""Test that BedrockModel raises ValueError when both region and session are provided."""
with pytest.raises(ValueError):
_ = BedrockModel(region_name="us-east-1", boto_session=boto3.Session(region_name="us-east-1"))
def test__init__default_user_agent(session_cls, bedrock_client):
"""Set user agent when no boto_client_config is provided."""
_ = BedrockModel()
# Verify the client was created with the correct config
client = session_cls.return_value.client
client.assert_called_once()
args, kwargs = client.call_args
assert kwargs["service_name"] == "bedrock-runtime"
assert isinstance(kwargs["config"], BotocoreConfig)
assert kwargs["config"].user_agent_extra == "strands-agents"
assert kwargs["config"].read_timeout == DEFAULT_READ_TIMEOUT
def test__init__default_read_timeout(session_cls, bedrock_client):
"""Set default read timeout when no boto_client_config is provided."""
_ = BedrockModel()
# Verify the client was created with the correct read timeout
client = session_cls.return_value.client
client.assert_called_once()
args, kwargs = client.call_args
assert isinstance(kwargs["config"], BotocoreConfig)
assert kwargs["config"].read_timeout == DEFAULT_READ_TIMEOUT
def test__init__with_custom_boto_client_config_no_user_agent(session_cls, bedrock_client):
"""Set user agent when boto_client_config is provided without user_agent_extra."""
custom_config = BotocoreConfig(read_timeout=900)
_ = BedrockModel(boto_client_config=custom_config)
# Verify the client was created with the correct config
client = session_cls.return_value.client
client.assert_called_once()
args, kwargs = client.call_args
assert kwargs["service_name"] == "bedrock-runtime"
assert isinstance(kwargs["config"], BotocoreConfig)
assert kwargs["config"].user_agent_extra == "strands-agents"
assert kwargs["config"].read_timeout == 900
def test__init__with_custom_boto_client_config_with_user_agent(session_cls, bedrock_client):
"""Append to existing user agent when boto_client_config is provided with user_agent_extra."""
custom_config = BotocoreConfig(user_agent_extra="existing-agent", read_timeout=900)
_ = BedrockModel(boto_client_config=custom_config)
# Verify the client was created with the correct config
client = session_cls.return_value.client
client.assert_called_once()
args, kwargs = client.call_args
assert kwargs["service_name"] == "bedrock-runtime"
assert isinstance(kwargs["config"], BotocoreConfig)
assert kwargs["config"].user_agent_extra == "existing-agent strands-agents"
assert kwargs["config"].read_timeout == 900
def test__init__model_config(bedrock_client):
_ = bedrock_client
model = BedrockModel(max_tokens=1)
tru_max_tokens = model.get_config().get("max_tokens")
exp_max_tokens = 1
assert tru_max_tokens == exp_max_tokens
def test_update_config(model, model_id):
model.update_config(model_id=model_id)
tru_model_id = model.get_config().get("model_id")
exp_model_id = model_id
assert tru_model_id == exp_model_id
def test_format_request_default(model, messages, model_id):
tru_request = model._format_request(messages)
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_additional_request_fields(model, messages, model_id, additional_request_fields):
model.update_config(additional_request_fields=additional_request_fields)
tru_request = model._format_request(messages)
exp_request = {
"additionalModelRequestFields": additional_request_fields,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_additional_response_field_paths(model, messages, model_id, additional_response_field_paths):
model.update_config(additional_response_field_paths=additional_response_field_paths)
tru_request = model._format_request(messages)
exp_request = {
"additionalModelResponseFieldPaths": additional_response_field_paths,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_guardrail_config(model, messages, model_id, guardrail_config):
model.update_config(**guardrail_config)
tru_request = model._format_request(messages)
exp_request = {
"guardrailConfig": {
"guardrailIdentifier": guardrail_config["guardrail_id"],
"guardrailVersion": guardrail_config["guardrail_version"],
"trace": guardrail_config["guardrail_trace"],
"streamProcessingMode": guardrail_config["guardrail_stream_processing_mode"],
},
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_guardrail_config_without_trace_or_stream_processing_mode(model, messages, model_id):
model.update_config(
**{
"guardrail_id": "g1",
"guardrail_version": "v1",
}
)
tru_request = model._format_request(messages)
exp_request = {
"guardrailConfig": {
"guardrailIdentifier": "g1",
"guardrailVersion": "v1",
"trace": "enabled",
},
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_inference_config(model, messages, model_id, inference_config):
model.update_config(**inference_config)
tru_request = model._format_request(messages)
exp_request = {
"inferenceConfig": {
"maxTokens": inference_config["max_tokens"],
"stopSequences": inference_config["stop_sequences"],
"temperature": inference_config["temperature"],
"topP": inference_config["top_p"],
},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_system_prompt(model, messages, model_id, system_prompt):
tru_request = model._format_request(messages, system_prompt_content=[{"text": system_prompt}])
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [{"text": system_prompt}],
}
assert tru_request == exp_request
def test_format_request_system_prompt_content(model, messages, model_id):
"""Test _format_request with SystemContentBlock input."""
system_prompt_content = [{"text": "You are a helpful assistant."}, {"cachePoint": {"type": "default"}}]
tru_request = model._format_request(messages, system_prompt_content=system_prompt_content)
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": system_prompt_content,
}
assert tru_request == exp_request
def test_format_request_system_prompt_content_with_cache_prompt_config(model, messages, model_id):
"""Test _format_request with SystemContentBlock and cache_prompt config (backwards compatibility)."""
system_prompt_content = [{"text": "You are a helpful assistant."}]
model.update_config(cache_prompt="default")
with pytest.warns(UserWarning, match="cache_prompt is deprecated"):
tru_request = model._format_request(messages, system_prompt_content=system_prompt_content)
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [{"text": "You are a helpful assistant."}, {"cachePoint": {"type": "default"}}],
}
assert tru_request == exp_request
def test_format_request_empty_system_prompt_content(model, messages, model_id):
"""Test _format_request with empty SystemContentBlock list."""
tru_request = model._format_request(messages, system_prompt_content=[])
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
}
assert tru_request == exp_request
def test_format_request_tool_specs(model, messages, model_id, tool_spec):
tru_request = model._format_request(messages, tool_specs=[tool_spec])
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": {"auto": {}},
},
}
assert tru_request == exp_request
def test_format_request_tool_choice_auto(model, messages, model_id, tool_spec):
tool_choice = {"auto": {}}
tru_request = model._format_request(messages, [tool_spec], tool_choice=tool_choice)
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": tool_choice,
},
}
assert tru_request == exp_request
def test_format_request_tool_choice_any(model, messages, model_id, tool_spec):
tool_choice = {"any": {}}
tru_request = model._format_request(messages, [tool_spec], tool_choice=tool_choice)
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": tool_choice,
},
}
assert tru_request == exp_request
def test_format_request_tool_choice_tool(model, messages, model_id, tool_spec):
tool_choice = {"tool": {"name": "test_tool"}}
tru_request = model._format_request(messages, [tool_spec], tool_choice=tool_choice)
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": tool_choice,
},
}
assert tru_request == exp_request
def test_format_request_cache(model, messages, model_id, tool_spec, cache_type):
model.update_config(cache_prompt=cache_type, cache_tools=cache_type)
with pytest.warns(UserWarning, match="cache_prompt is deprecated"):
tru_request = model._format_request(messages, tool_specs=[tool_spec])
exp_request = {
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [{"cachePoint": {"type": cache_type}}],
"toolConfig": {
"tools": [
{"toolSpec": tool_spec},
{"cachePoint": {"type": cache_type}},
],
"toolChoice": {"auto": {}},
},
}
assert tru_request == exp_request
@pytest.mark.asyncio
async def test_stream_throttling_exception_from_event_stream_error(bedrock_client, model, messages, alist):
error_message = "Rate exceeded"
bedrock_client.converse_stream.side_effect = EventStreamError(
{"Error": {"Message": error_message, "Code": "ThrottlingException"}}, "ConverseStream"
)
with pytest.raises(ModelThrottledException) as excinfo:
await alist(model.stream(messages))
assert error_message in str(excinfo.value)
bedrock_client.converse_stream.assert_called_once_with(
modelId="m1", messages=messages, system=[], inferenceConfig={}
)
@pytest.mark.asyncio
async def test_stream_with_invalid_content_throws(bedrock_client, model, alist):
# We used to hang on None, so ensure we don't regress: https://github.com/strands-agents/sdk-python/issues/642
messages = [{"role": "user", "content": None}]
with pytest.raises(TypeError):
await alist(model.stream(messages))
@pytest.mark.asyncio
async def test_stream_throttling_exception_from_general_exception(bedrock_client, model, messages, alist):
error_message = "ThrottlingException: Rate exceeded for ConverseStream"
bedrock_client.converse_stream.side_effect = ClientError(
{"Error": {"Message": error_message, "Code": "ThrottlingException"}}, "Any"
)
with pytest.raises(ModelThrottledException) as excinfo:
await alist(model.stream(messages))
assert error_message in str(excinfo.value)
bedrock_client.converse_stream.assert_called_once_with(
modelId="m1", messages=messages, system=[], inferenceConfig={}
)
@pytest.mark.asyncio
async def test_stream_throttling_exception_lowercase(bedrock_client, model, messages, alist):
"""Test that lowercase throttlingException is converted to ModelThrottledException."""
error_message = "throttlingException: Rate exceeded for ConverseStream"
bedrock_client.converse_stream.side_effect = ClientError(
{"Error": {"Message": error_message, "Code": "throttlingException"}}, "Any"
)
with pytest.raises(ModelThrottledException) as excinfo:
await alist(model.stream(messages))
assert error_message in str(excinfo.value)
bedrock_client.converse_stream.assert_called_once_with(
modelId="m1", messages=messages, system=[], inferenceConfig={}
)
@pytest.mark.asyncio
async def test_stream_throttling_exception_lowercase_non_streaming(bedrock_client, messages, alist):
"""Test that lowercase throttlingException is converted to ModelThrottledException in non-streaming mode."""
error_message = "throttlingException: Rate exceeded for Converse"
bedrock_client.converse.side_effect = ClientError(
{"Error": {"Message": error_message, "Code": "throttlingException"}}, "Any"
)
model = BedrockModel(model_id="test-model", streaming=False)
with pytest.raises(ModelThrottledException) as excinfo:
await alist(model.stream(messages))
assert error_message in str(excinfo.value)
bedrock_client.converse.assert_called_once()
bedrock_client.converse_stream.assert_not_called()
@pytest.mark.asyncio
async def test_general_exception_is_raised(bedrock_client, model, messages, alist):
error_message = "Should be raised up"
bedrock_client.converse_stream.side_effect = ValueError(error_message)
with pytest.raises(ValueError) as excinfo:
await alist(model.stream(messages))
assert error_message in str(excinfo.value)
bedrock_client.converse_stream.assert_called_once_with(
modelId="m1", messages=messages, system=[], inferenceConfig={}
)
@pytest.mark.asyncio
async def test_stream(bedrock_client, model, messages, tool_spec, model_id, additional_request_fields, alist):
bedrock_client.converse_stream.return_value = {"stream": ["e1", "e2"]}
request = {
"additionalModelRequestFields": additional_request_fields,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": {"auto": {}},
},
}
model.update_config(additional_request_fields=additional_request_fields)
response = model.stream(messages, [tool_spec])
tru_chunks = await alist(response)
exp_chunks = ["e1", "e2"]
assert tru_chunks == exp_chunks
bedrock_client.converse_stream.assert_called_once_with(**request)
@pytest.mark.asyncio
async def test_stream_with_system_prompt_content(bedrock_client, model, messages, alist):
"""Test stream method with system_prompt_content parameter."""
bedrock_client.converse_stream.return_value = {"stream": ["e1", "e2"]}
system_prompt_content = [{"text": "You are a helpful assistant."}, {"cachePoint": {"type": "default"}}]
response = model.stream(messages, system_prompt_content=system_prompt_content)
tru_chunks = await alist(response)
exp_chunks = ["e1", "e2"]
assert tru_chunks == exp_chunks
# Verify the request was formatted with system_prompt_content
expected_request = {
"inferenceConfig": {},
"modelId": "m1",
"messages": messages,
"system": system_prompt_content,
}
bedrock_client.converse_stream.assert_called_once_with(**expected_request)
@pytest.mark.asyncio
async def test_stream_backwards_compatibility_single_text_block(bedrock_client, model, messages, alist):
"""Test that single text block in system_prompt_content works with legacy system_prompt."""
bedrock_client.converse_stream.return_value = {"stream": ["e1", "e2"]}
system_prompt_content = [{"text": "You are a helpful assistant."}]
response = model.stream(
messages, system_prompt="You are a helpful assistant.", system_prompt_content=system_prompt_content
)
await alist(response)
# Verify the request was formatted with system_prompt_content
expected_request = {
"inferenceConfig": {},
"modelId": "m1",
"messages": messages,
"system": system_prompt_content,
}
bedrock_client.converse_stream.assert_called_once_with(**expected_request)
@pytest.mark.asyncio
async def test_stream_stream_input_guardrails(
bedrock_client, model, messages, tool_spec, model_id, additional_request_fields, alist
):
metadata_event = {
"metadata": {
"usage": {"inputTokens": 0, "outputTokens": 0, "totalTokens": 0},
"metrics": {"latencyMs": 245},
"trace": {
"guardrail": {
"inputAssessment": {
"3e59qlue4hag": {
"wordPolicy": {
"customWords": [
{
"match": "CACTUS",
"action": "BLOCKED",
"detected": True,
}
]
}
}
}
}
},
}
}
bedrock_client.converse_stream.return_value = {"stream": [metadata_event]}
request = {
"additionalModelRequestFields": additional_request_fields,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": {"auto": {}},
},
}
model.update_config(additional_request_fields=additional_request_fields)
response = model.stream(messages, [tool_spec])
tru_chunks = await alist(response)
exp_chunks = [
{"redactContent": {"redactUserContentMessage": "[User input redacted.]"}},
metadata_event,
]
assert tru_chunks == exp_chunks
bedrock_client.converse_stream.assert_called_once_with(**request)
@pytest.mark.asyncio
async def test_stream_stream_input_guardrails_full_trace(
bedrock_client, model, messages, tool_spec, model_id, additional_request_fields, alist
):
"""Test guardrails are correctly detected also with guardrail_trace="enabled_full".
In that case bedrock returns all filters, including those not detected/blocked."""
metadata_event = {
"metadata": {
"usage": {"inputTokens": 0, "outputTokens": 0, "totalTokens": 0},
"metrics": {"latencyMs": 245},
"trace": {
"guardrail": {
"inputAssessment": {
"jrv9qlue4hag": {
"contentPolicy": {
"filters": [
{
"action": "NONE",
"confidence": "NONE",
"detected": False,
"filterStrength": "HIGH",
"type": "SEXUAL",
},
{
"action": "BLOCKED",
"confidence": "LOW",
"detected": True,
"filterStrength": "HIGH",
"type": "VIOLENCE",
},
{
"action": "NONE",
"confidence": "NONE",
"detected": False,
"filterStrength": "HIGH",
"type": "HATE",
},
{
"action": "NONE",
"confidence": "NONE",
"detected": False,
"filterStrength": "HIGH",
"type": "INSULTS",
},
{
"action": "NONE",
"confidence": "NONE",
"detected": False,
"filterStrength": "HIGH",
"type": "PROMPT_ATTACK",
},
{
"action": "NONE",
"confidence": "NONE",
"detected": False,
"filterStrength": "HIGH",
"type": "MISCONDUCT",
},
]
}
}
}
}
},
}
}
bedrock_client.converse_stream.return_value = {"stream": [metadata_event]}
request = {
"additionalModelRequestFields": additional_request_fields,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": {"auto": {}},
},
}
model.update_config(additional_request_fields=additional_request_fields)
response = model.stream(messages, [tool_spec])
tru_chunks = await alist(response)
exp_chunks = [
{"redactContent": {"redactUserContentMessage": "[User input redacted.]"}},
metadata_event,
]
assert tru_chunks == exp_chunks
bedrock_client.converse_stream.assert_called_once_with(**request)
@pytest.mark.asyncio
async def test_stream_stream_output_guardrails(
bedrock_client, model, messages, tool_spec, model_id, additional_request_fields, alist
):
model.update_config(guardrail_redact_input=False, guardrail_redact_output=True)
metadata_event = {
"metadata": {
"usage": {"inputTokens": 0, "outputTokens": 0, "totalTokens": 0},
"metrics": {"latencyMs": 245},
"trace": {
"guardrail": {
"outputAssessments": {
"3e59qlue4hag": [
{
"wordPolicy": {
"customWords": [
{
"match": "CACTUS",
"action": "BLOCKED",
"detected": True,
}
]
},
}
]
},
}
},
}
}
bedrock_client.converse_stream.return_value = {"stream": [metadata_event]}
request = {
"additionalModelRequestFields": additional_request_fields,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": {"auto": {}},
},
}
model.update_config(additional_request_fields=additional_request_fields)
response = model.stream(messages, [tool_spec])
tru_chunks = await alist(response)
exp_chunks = [
{"redactContent": {"redactAssistantContentMessage": "[Assistant output redacted.]"}},
metadata_event,
]
assert tru_chunks == exp_chunks
bedrock_client.converse_stream.assert_called_once_with(**request)
@pytest.mark.asyncio
async def test_stream_output_guardrails_redacts_input_and_output(
bedrock_client, model, messages, tool_spec, model_id, additional_request_fields, alist
):
model.update_config(guardrail_redact_output=True)
metadata_event = {
"metadata": {
"usage": {"inputTokens": 0, "outputTokens": 0, "totalTokens": 0},
"metrics": {"latencyMs": 245},
"trace": {
"guardrail": {
"outputAssessments": {
"3e59qlue4hag": [
{
"wordPolicy": {
"customWords": [
{
"match": "CACTUS",
"action": "BLOCKED",
"detected": True,
}
]
},
}
]
},
}
},
}
}
bedrock_client.converse_stream.return_value = {"stream": [metadata_event]}
request = {
"additionalModelRequestFields": additional_request_fields,
"inferenceConfig": {},
"modelId": model_id,
"messages": messages,
"system": [],
"toolConfig": {
"tools": [{"toolSpec": tool_spec}],
"toolChoice": {"auto": {}},
},
}
model.update_config(additional_request_fields=additional_request_fields)
response = model.stream(messages, [tool_spec])
tru_chunks = await alist(response)
exp_chunks = [
{"redactContent": {"redactUserContentMessage": "[User input redacted.]"}},
{"redactContent": {"redactAssistantContentMessage": "[Assistant output redacted.]"}},
metadata_event,
]
assert tru_chunks == exp_chunks
bedrock_client.converse_stream.assert_called_once_with(**request)
@pytest.mark.asyncio
async def test_stream_output_no_blocked_guardrails_doesnt_redact(
bedrock_client, model, messages, tool_spec, model_id, additional_request_fields, alist
):
metadata_event = {
"metadata": {
"usage": {"inputTokens": 0, "outputTokens": 0, "totalTokens": 0},
"metrics": {"latencyMs": 245},
"trace": {
"guardrail": {
"outputAssessments": {
"3e59qlue4hag": [
{
"wordPolicy": {
"customWords": [
{
"match": "CACTUS",
"action": "NONE",
"detected": True,
}
]
},
}
]
},
}
},
}
}
bedrock_client.converse_stream.return_value = {"stream": [metadata_event]}