-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathtest_bedrock.py
More file actions
3612 lines (3196 loc) · 156 KB
/
test_bedrock.py
File metadata and controls
3612 lines (3196 loc) · 156 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
from __future__ import annotations as _annotations
from datetime import date, datetime, timezone
from types import SimpleNamespace
from typing import Any
import pytest
from typing_extensions import TypedDict
from pydantic_ai import (
BinaryContent,
BuiltinToolCallPart,
BuiltinToolReturnPart,
CachePoint,
DocumentUrl,
FinalResultEvent,
FunctionToolCallEvent,
FunctionToolResultEvent,
ImageUrl,
ModelMessage,
ModelRequest,
ModelResponse,
PartDeltaEvent,
PartEndEvent,
PartStartEvent,
RetryPromptPart,
SystemPromptPart,
TextPart,
TextPartDelta,
ThinkingPart,
ThinkingPartDelta,
ToolCallPart,
ToolCallPartDelta,
ToolReturnPart,
UserPromptPart,
VideoUrl,
)
from pydantic_ai.agent import Agent
from pydantic_ai.builtin_tools import CodeExecutionTool
from pydantic_ai.exceptions import ModelAPIError, ModelHTTPError, ModelRetry, UsageLimitExceeded, UserError
from pydantic_ai.messages import (
AgentStreamEvent,
BuiltinToolCallEvent, # pyright: ignore[reportDeprecated]
BuiltinToolResultEvent, # pyright: ignore[reportDeprecated]
UploadedFile,
)
from pydantic_ai.models import ModelRequestParameters
from pydantic_ai.profiles import DEFAULT_PROFILE
from pydantic_ai.providers import Provider
from pydantic_ai.run import AgentRunResult, AgentRunResultEvent
from pydantic_ai.tools import ToolDefinition
from pydantic_ai.usage import RequestUsage, RunUsage, UsageLimits
from .._inline_snapshot import snapshot
from ..conftest import IsDatetime, IsInstance, IsNow, IsStr, try_import
with try_import() as imports_successful:
from botocore.exceptions import ClientError
from mypy_boto3_bedrock_runtime.type_defs import MessageUnionTypeDef, SystemContentBlockTypeDef, ToolTypeDef
from pydantic_ai.models.bedrock import BedrockConverseModel, BedrockModelName, BedrockModelSettings
from pydantic_ai.models.openai import OpenAIResponsesModel, OpenAIResponsesModelSettings
from pydantic_ai.providers.bedrock import BedrockProvider
from pydantic_ai.providers.openai import OpenAIProvider
pytestmark = [
pytest.mark.skipif(not imports_successful(), reason='bedrock not installed'),
pytest.mark.anyio,
pytest.mark.vcr,
pytest.mark.filterwarnings(
'ignore:`BuiltinToolCallEvent` is deprecated, look for `PartStartEvent` and `PartDeltaEvent` with `BuiltinToolCallPart` instead.:DeprecationWarning'
),
pytest.mark.filterwarnings(
'ignore:`BuiltinToolResultEvent` is deprecated, look for `PartStartEvent` and `PartDeltaEvent` with `BuiltinToolReturnPart` instead.:DeprecationWarning'
),
]
class _StubBedrockClient:
"""Minimal Bedrock client that always raises the provided error."""
def __init__(self, error: ClientError):
self._error = error
self.meta = SimpleNamespace(endpoint_url='https://bedrock.stub')
def converse(self, **_: Any) -> None:
raise self._error
def converse_stream(self, **_: Any) -> None:
raise self._error
def count_tokens(self, **_: Any) -> None:
raise self._error
class _StubBedrockProvider(Provider[Any]):
"""Provider implementation backed by the stub client."""
def __init__(self, client: _StubBedrockClient):
self._client = client
@property
def name(self) -> str:
return 'bedrock-stub'
@property
def base_url(self) -> str:
return 'https://bedrock.stub'
@property
def client(self) -> _StubBedrockClient:
return self._client
@staticmethod
def model_profile(model_name: str):
return DEFAULT_PROFILE
def _bedrock_model_with_client_error(error: ClientError) -> BedrockConverseModel:
"""Instantiate a BedrockConverseModel wired to always raise the given error."""
return BedrockConverseModel(
'us.amazon.nova-micro-v1:0',
provider=_StubBedrockProvider(_StubBedrockClient(error)),
)
async def test_bedrock_model(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
assert model.base_url == 'https://bedrock-runtime.us-east-1.amazonaws.com'
agent = Agent(model=model, system_prompt='You are a chatbot.')
result = await agent.run('Hello!')
assert result.output == snapshot(
"Hello! How can I assist you today? Whether you have questions, need information, or just want to chat, I'm here to help."
)
assert result.usage() == snapshot(RunUsage(requests=1, input_tokens=7, output_tokens=30))
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[
SystemPromptPart(
content='You are a chatbot.',
timestamp=IsDatetime(),
),
UserPromptPart(
content='Hello!',
timestamp=IsDatetime(),
),
],
timestamp=IsDatetime(),
run_id=IsStr(),
),
ModelResponse(
parts=[
TextPart(
content="Hello! How can I assist you today? Whether you have questions, need information, or just want to chat, I'm here to help."
)
],
usage=RequestUsage(input_tokens=7, output_tokens=30),
model_name='us.amazon.nova-micro-v1:0',
timestamp=IsDatetime(),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'end_turn'},
finish_reason='stop',
run_id=IsStr(),
),
]
)
@pytest.mark.vcr()
async def test_bedrock_model_usage_limit_exceeded(
allow_model_requests: None,
bedrock_provider: BedrockProvider,
):
model = BedrockConverseModel('us.anthropic.claude-sonnet-4-20250514-v1:0', provider=bedrock_provider)
agent = Agent(model=model)
with pytest.raises(
UsageLimitExceeded,
match='The next request would exceed the input_tokens_limit of 18 \\(input_tokens=23\\)',
):
await agent.run(
['The quick brown fox jumps over the lazydog.', CachePoint(), 'What was next?'],
usage_limits=UsageLimits(input_tokens_limit=18, count_tokens_before_request=True),
)
@pytest.mark.vcr()
async def test_bedrock_model_usage_limit_not_exceeded(
allow_model_requests: None,
bedrock_provider: BedrockProvider,
):
model = BedrockConverseModel('us.anthropic.claude-sonnet-4-20250514-v1:0', provider=bedrock_provider)
agent = Agent(model=model)
result = await agent.run(
'The quick brown fox jumps over the lazydog.',
usage_limits=UsageLimits(input_tokens_limit=25, count_tokens_before_request=True),
)
assert result.output == snapshot(
'I notice there\'s a small typo in your message - it should be "lazy dog" (two words) rather than '
'"lazydog."\n\nThe corrected version is: "The quick brown fox jumps over the lazy dog."\n\n'
'This is a famous pangram - a sentence that contains every letter of the English alphabet at least once. '
"It's commonly used for testing typewriters, keyboards, fonts, and other applications where you want to "
"display all the letters.\n\nIs there something specific you'd like to know about this phrase, or were you "
'perhaps testing something?'
)
@pytest.mark.vcr()
async def test_bedrock_count_tokens_error(allow_model_requests: None, bedrock_provider: BedrockProvider):
"""Test that errors convert to ModelHTTPError."""
model_id = 'us.does-not-exist-model-v1:0'
model = BedrockConverseModel(model_id, provider=bedrock_provider)
agent = Agent(model)
with pytest.raises(ModelHTTPError) as exc_info:
await agent.run('hello', usage_limits=UsageLimits(input_tokens_limit=20, count_tokens_before_request=True))
assert exc_info.value.status_code == 400
assert exc_info.value.model_name == model_id
assert exc_info.value.body.get('Error', {}).get('Message') == 'The provided model identifier is invalid.' # type: ignore[union-attr]
async def test_bedrock_request_non_http_error():
error = ClientError({'Error': {'Code': 'TestException', 'Message': 'broken connection'}}, 'converse')
model = _bedrock_model_with_client_error(error)
params = ModelRequestParameters()
with pytest.raises(ModelAPIError) as exc_info:
await model.request([ModelRequest.user_text_prompt('hi')], None, params)
assert exc_info.value.message == snapshot(
'An error occurred (TestException) when calling the converse operation: broken connection'
)
async def test_bedrock_count_tokens_non_http_error():
error = ClientError({'Error': {'Code': 'TestException', 'Message': 'broken connection'}}, 'count_tokens')
model = _bedrock_model_with_client_error(error)
params = ModelRequestParameters()
with pytest.raises(ModelAPIError) as exc_info:
await model.count_tokens([ModelRequest.user_text_prompt('hi')], None, params)
assert exc_info.value.message == snapshot(
'An error occurred (TestException) when calling the count_tokens operation: broken connection'
)
async def test_bedrock_stream_non_http_error():
error = ClientError({'Error': {'Code': 'TestException', 'Message': 'broken connection'}}, 'converse_stream')
model = _bedrock_model_with_client_error(error)
params = ModelRequestParameters()
with pytest.raises(ModelAPIError) as exc_info:
async with model.request_stream([ModelRequest.user_text_prompt('hi')], None, params) as stream:
async for _ in stream:
pass
assert 'broken connection' in exc_info.value.message
async def test_stub_provider_properties():
# tests the test utility itself...
error = ClientError({'Error': {'Code': 'TestException', 'Message': 'test'}}, 'converse')
model = _bedrock_model_with_client_error(error)
provider = model._provider # pyright: ignore[reportPrivateUsage]
assert provider.name == 'bedrock-stub'
assert provider.base_url == 'https://bedrock.stub'
async def test_bedrock_model_structured_output(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', retries=5)
class Response(TypedDict):
temperature: str
date: date
city: str
@agent.tool_plain
async def temperature(city: str, date: date) -> str:
"""Get the temperature in a city on a specific date.
Args:
city: The city name.
date: The date.
Returns:
The temperature in degrees Celsius.
"""
return '30°C'
result = await agent.run('What was the temperature in London 1st January 2022?', output_type=Response)
assert result.output == snapshot({'temperature': '30°C', 'date': date(2022, 1, 1), 'city': 'London'})
assert result.usage() == snapshot(RunUsage(requests=3, input_tokens=2019, output_tokens=120, tool_calls=1))
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[
UserPromptPart(
content='What was the temperature in London 1st January 2022?',
timestamp=IsNow(tz=timezone.utc),
)
],
timestamp=IsNow(tz=timezone.utc),
instructions='You are a helpful chatbot.',
run_id=IsStr(),
),
ModelResponse(
parts=[
ToolCallPart(
tool_name='temperature',
args={'date': '2022-01-01', 'city': 'London'},
tool_call_id=IsStr(),
)
],
usage=RequestUsage(input_tokens=571, output_tokens=22),
model_name='us.amazon.nova-micro-v1:0',
timestamp=IsNow(tz=timezone.utc),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'tool_use'},
finish_reason='tool_call',
run_id=IsStr(),
),
ModelRequest(
parts=[
ToolReturnPart(
tool_name='temperature',
content='30°C',
tool_call_id=IsStr(),
timestamp=IsNow(tz=timezone.utc),
)
],
timestamp=IsNow(tz=timezone.utc),
instructions='You are a helpful chatbot.',
run_id=IsStr(),
),
ModelResponse(
parts=[
TextPart(
content="""\
<thinking> The tool has provided the temperature for London on 1st January 2022, which was 30°C. I will now provide this information to the user.</thinking>
The temperature in London on 1st January 2022 was 30°C.\
"""
)
],
usage=RequestUsage(input_tokens=627, output_tokens=67),
model_name='us.amazon.nova-micro-v1:0',
timestamp=IsDatetime(),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'end_turn'},
finish_reason='stop',
run_id=IsStr(),
),
ModelRequest(
parts=[
RetryPromptPart(
content=[
{
'type': 'json_invalid',
'loc': (),
'msg': 'Invalid JSON: expected value at line 2 column 1',
'input': """\
<thinking> The tool has provided the temperature for London on 1st January 2022, which was 30°C. I will now provide this information to the user.</thinking>
The temperature in London on 1st January 2022 was 30°C.\
""",
'ctx': {'error': 'expected value at line 2 column 1'},
}
],
tool_call_id=IsStr(),
timestamp=IsDatetime(),
)
],
timestamp=IsDatetime(),
instructions='You are a helpful chatbot.',
run_id=IsStr(),
),
ModelResponse(
parts=[
ToolCallPart(
tool_name='final_result',
args={'date': '2022-01-01', 'city': 'London', 'temperature': '30°C'},
tool_call_id='tooluse_qVHAm8Q9QMGoJRkk06_TVA',
)
],
usage=RequestUsage(input_tokens=821, output_tokens=31),
model_name='us.amazon.nova-micro-v1:0',
timestamp=IsDatetime(),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'tool_use'},
finish_reason='tool_call',
run_id=IsStr(),
),
ModelRequest(
parts=[
ToolReturnPart(
tool_name='final_result',
content='Final result processed.',
tool_call_id=IsStr(),
timestamp=IsNow(tz=timezone.utc),
)
],
timestamp=IsNow(tz=timezone.utc),
run_id=IsStr(),
),
]
)
async def test_bedrock_model_stream(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings={'temperature': 0.0})
async with agent.run_stream('What is the capital of France?') as result:
data = await result.get_output()
assert data == snapshot(
'The capital of France is Paris. Paris is not only the capital city but also the most populous city in France, and it is a major center for culture, commerce, fashion, and international diplomacy. Known for its historical landmarks, such as the Eiffel Tower, the Louvre Museum, and Notre-Dame Cathedral, Paris is often referred to as "The City of Light" or "The City of Love."'
)
assert result.usage() == snapshot(RunUsage(requests=1, input_tokens=13, output_tokens=82))
async def test_bedrock_model_anthropic_model_with_tools(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('anthropic.claude-v2', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings={'temperature': 0.0})
@agent.tool_plain
async def get_current_temperature(city: str) -> str:
"""Get the current temperature in a city.
Args:
city: The city name.
Returns:
The current temperature in degrees Celsius.
"""
return '30°C' # pragma: no cover
# dated March 2025, update when no longer the case
# TODO(Marcelo): Anthropic models don't support tools on the Bedrock Converse Interface.
# I'm unsure what to do, so for the time being I'm just documenting the test. Let's see if someone complains.
with pytest.raises(Exception):
await agent.run('What is the current temperature in London?')
async def test_bedrock_model_anthropic_model_without_tools(
allow_model_requests: None, bedrock_provider: BedrockProvider
):
model = BedrockConverseModel('us.anthropic.claude-sonnet-4-5-20250929-v1:0', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings={'temperature': 0.0})
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
"The capital of France is **Paris**. It's the largest city in France and has been the country's capital since the 12th century. Paris is known for its iconic landmarks like the Eiffel Tower, the Louvre Museum, Notre-Dame Cathedral, and its rich history, culture, and cuisine."
)
async def test_bedrock_model_retry(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(
model=model, instructions='You are a helpful chatbot.', model_settings={'temperature': 0.0}, retries=2
)
@agent.tool_plain
async def get_capital(country: str) -> str:
"""Get the capital of a country.
Args:
country: The country name.
"""
raise ModelRetry('The country is not supported.')
result = await agent.run('What is the capital of France?')
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[
UserPromptPart(
content='What is the capital of France?',
timestamp=IsDatetime(),
),
],
instructions='You are a helpful chatbot.',
timestamp=IsDatetime(),
run_id=IsStr(),
),
ModelResponse(
parts=[
TextPart(
content='<thinking> To determine the capital of France, I can use the provided tool that returns the capital of a given country. Since the country in question is France, I will use the tool with the country parameter set to "France". </thinking>\n'
),
ToolCallPart(
tool_name='get_capital',
args={'country': 'France'},
tool_call_id=IsStr(),
),
],
usage=RequestUsage(input_tokens=426, output_tokens=66),
model_name='us.amazon.nova-micro-v1:0',
timestamp=IsDatetime(),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'tool_use'},
finish_reason='tool_call',
run_id=IsStr(),
),
ModelRequest(
parts=[
RetryPromptPart(
content='The country is not supported.',
tool_name='get_capital',
tool_call_id=IsStr(),
timestamp=IsDatetime(),
)
],
instructions='You are a helpful chatbot.',
timestamp=IsDatetime(),
run_id=IsStr(),
),
ModelResponse(
parts=[
TextPart(
content="""\
<thinking> It appears that there was an error in retrieving the capital of France as the tool indicated that the country is not supported. Since the tool is not able to provide the requested information, I will respond to the User with the information I have access to. </thinking> \n\
The capital of France is Paris. If you need any further information, feel free to ask!\
"""
)
],
usage=RequestUsage(input_tokens=531, output_tokens=76),
model_name='us.amazon.nova-micro-v1:0',
timestamp=IsDatetime(),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'end_turn'},
finish_reason='stop',
run_id=IsStr(),
),
]
)
async def test_bedrock_model_max_tokens(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings={'max_tokens': 5})
result = await agent.run('What is the capital of France?')
assert result.output == snapshot('The capital of France is')
async def test_bedrock_model_top_p(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings={'top_p': 0.5})
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
'The capital of France is Paris. Paris is not only the capital city but also the most populous city in France, and it is a major center for culture, fashion, gastronomy, and international diplomacy.'
)
async def test_bedrock_model_performance_config(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
model_settings = BedrockModelSettings(bedrock_performance_configuration={'latency': 'optimized'})
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings=model_settings)
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
'The capital of France is Paris. It is one of the most visited cities in the world and is known for its rich history, culture, and iconic landmarks such as the Eiffel Tower, the Louvre Museum, and Notre-Dame Cathedral. Paris is also a major center for finance, diplomacy, commerce, fashion, science, and arts.'
)
async def test_bedrock_model_guardrail_config(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
model_settings = BedrockModelSettings(
bedrock_guardrail_config={
'guardrailIdentifier': 'xbgw7g293v7o',
'guardrailVersion': 'DRAFT',
'trace': 'enabled',
}
)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings=model_settings)
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
"The capital of France is Paris. Paris is not only the capital city but also the most populous city in France, serving as the center of French government, culture, and commerce. It's known for its historical and cultural landmarks such as the Eiffel Tower, the Louvre Museum, Notre-Dame Cathedral, and many charming neighborhoods like Montmartre."
)
async def test_bedrock_model_other_parameters(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
model_settings = BedrockModelSettings(
bedrock_prompt_variables={'leo': {'text': 'aaaa'}},
bedrock_additional_model_requests_fields={'test': 'test'},
bedrock_request_metadata={'test': 'test'},
bedrock_additional_model_response_fields_paths=['test'],
)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings=model_settings)
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
'The capital of France is Paris. Paris is not only the capital city but also the most populous city in France, known for its significant cultural, political, and economic influence both within the country and globally. It is famous for landmarks such as the Eiffel Tower, the Louvre Museum, and the Notre-Dame Cathedral, among many other historical and architectural treasures.'
)
async def test_bedrock_model_service_tier(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
model_settings = BedrockModelSettings(bedrock_service_tier={'type': 'flex'})
agent = Agent(model=model, system_prompt='You are a helpful chatbot.', model_settings=model_settings)
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
'The capital of France is Paris. Paris is not only the capital city but also the most populous city in France, known for its significant cultural, political, and economic influence both within the country and globally. It is famous for landmarks such as the Eiffel Tower, the Louvre Museum, and the Notre-Dame Cathedral, among many other historical and architectural treasures.'
)
async def test_bedrock_model_iter_stream(allow_model_requests: None, bedrock_provider: BedrockProvider):
model = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(model=model, instructions='You are a helpful chatbot.', model_settings={'top_p': 0.5})
@agent.tool_plain
async def get_capital(country: str) -> str:
"""Get the capital of a country.
Args:
country: The country name.
"""
return 'Paris' # pragma: no cover
@agent.tool_plain
async def get_temperature(city: str) -> str:
"""Get the temperature in a city.
Args:
city: The city name.
"""
return '30°C'
event_parts: list[Any] = []
async with agent.iter(user_prompt='What is the temperature of the capital of France?') as agent_run:
async for node in agent_run:
if Agent.is_model_request_node(node) or Agent.is_call_tools_node(node):
async with node.stream(agent_run.ctx) as request_stream:
async for event in request_stream:
event_parts.append(event)
assert event_parts == snapshot(
[
PartStartEvent(index=0, part=TextPart(content='<thinking')),
FinalResultEvent(tool_name=None, tool_call_id=None),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='> To find')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' the temperature')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' of the capital of France,')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' I need to first')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' determine the capital')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' of France and')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' then get')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' the current')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' temperature in')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' that city. The')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' capital of France is Paris')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='. I')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' will use')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' the "get_temperature"')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' tool to find the current temperature')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' in Paris.</')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='thinking')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='>\n')),
PartEndEvent(
index=0,
part=TextPart(
content='<thinking> To find the temperature of the capital of France, I need to first determine the capital of France and then get the current temperature in that city. The capital of France is Paris. I will use the "get_temperature" tool to find the current temperature in Paris.</thinking>\n'
),
next_part_kind='tool-call',
),
PartStartEvent(
index=1,
part=ToolCallPart(tool_name='get_temperature', tool_call_id=IsStr()),
previous_part_kind='text',
),
PartDeltaEvent(
index=1,
delta=ToolCallPartDelta(args_delta='{"city":"Paris"}', tool_call_id=IsStr()),
),
PartEndEvent(
index=1,
part=ToolCallPart(tool_name='get_temperature', args='{"city":"Paris"}', tool_call_id=IsStr()),
),
IsInstance(FunctionToolCallEvent),
FunctionToolResultEvent(
result=ToolReturnPart(
tool_name='get_temperature',
content='30°C',
tool_call_id=IsStr(),
timestamp=IsDatetime(),
)
),
PartStartEvent(index=0, part=TextPart(content='The')),
FinalResultEvent(tool_name=None, tool_call_id=None),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' current temperature in Paris, the')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' capital of France,')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta=' is 30°C')),
PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='.')),
PartEndEvent(
index=0, part=TextPart(content='The current temperature in Paris, the capital of France, is 30°C.')
),
]
)
@pytest.mark.vcr()
async def test_image_as_binary_content_input(
allow_model_requests: None, image_content: BinaryContent, bedrock_provider: BedrockProvider
):
m = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
result = await agent.run(['What fruit is in the image?', image_content])
assert result.output == snapshot(
'The image features a fruit that is round and has a green skin with brown dots. The fruit is cut in half, revealing its interior, which is also green. Based on the appearance and characteristics, the fruit in the image is a kiwi.'
)
@pytest.mark.vcr()
async def test_video_as_binary_content_input(
allow_model_requests: None, video_content: BinaryContent, bedrock_provider: BedrockProvider
):
m = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
result = await agent.run(['Explain me this video', video_content])
assert result.output == snapshot(
'The video shows a camera set up on a tripod, pointed at a scenic view of a rocky landscape under a clear sky. The camera remains stationary throughout the video, capturing the same view without any changes.'
)
@pytest.mark.vcr()
async def test_image_url_input(
allow_model_requests: None, bedrock_provider: BedrockProvider, disable_ssrf_protection_for_vcr: None
):
m = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
result = await agent.run(
[
'What is this vegetable?',
ImageUrl(url='https://t3.ftcdn.net/jpg/00/85/79/92/360_F_85799278_0BBGV9OAdQDTLnKwAPBCcg1J7QtiieJY.jpg'),
]
)
assert result.output == snapshot(
'The image shows a potato. It is oval in shape and has a yellow skin with numerous dark brown patches. These patches are known as lenticels, which are pores that allow the potato to breathe. The potato is a root vegetable that is widely cultivated and consumed around the world. It is a versatile ingredient that can be used in a variety of dishes, including mashed potatoes, fries, and potato salad.'
)
@pytest.mark.vcr()
async def test_video_url_input(
allow_model_requests: None, bedrock_provider: BedrockProvider, disable_ssrf_protection_for_vcr: None
):
m = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
result = await agent.run(
[
'Explain me this video',
VideoUrl(url='https://t3.ftcdn.net/jpg/00/85/79/92/small_video.mp4'),
]
)
assert result.output == snapshot(
'The video shows a camera set up on a tripod, pointed at a scenic view of a rocky landscape under a clear sky. The camera remains stationary throughout the video, capturing the same view without any changes.'
)
@pytest.mark.vcr()
async def test_document_url_input(
allow_model_requests: None, bedrock_provider: BedrockProvider, disable_ssrf_protection_for_vcr: None
):
m = BedrockConverseModel('anthropic.claude-v2', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
document_url = DocumentUrl(url='https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf')
result = await agent.run(['What is the main content on this document?', document_url])
assert result.output == snapshot(
'Based on the provided XML data, the main content of the document is "Dummy PDF file". This is contained in the <document_content> tag for the document with index="1".'
)
@pytest.mark.vcr()
async def test_text_document_url_input(
allow_model_requests: None, bedrock_provider: BedrockProvider, disable_ssrf_protection_for_vcr: None
):
m = BedrockConverseModel('anthropic.claude-v2', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
text_document_url = DocumentUrl(url='https://example-files.online-convert.com/document/txt/example.txt')
result = await agent.run(['What is the main content on this document?', text_document_url])
assert result.output == snapshot(
"""\
Based on the text in the <document_content> tag, the main content of this document appears to be:
An example text describing the use of "John Doe" as a placeholder name in legal cases, hospitals, and other contexts where a party's real identity is unknown or needs to be withheld. It provides background on how "John Doe" and "Jane Doe" are commonly used in the United States and Canada for this purpose, in contrast to other English speaking countries that use names like "Joe Bloggs". The text gives examples of using John/Jane Doe for legal cases, unidentified corpses, and as generic names on forms. It also mentions how "Baby Doe" and "Precious Doe" are used for unidentified children.\
"""
)
async def test_s3_image_url_input(bedrock_provider: BedrockProvider):
"""Test that s3:// image URLs are passed directly to Bedrock API without downloading."""
model = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
image_url = ImageUrl(url='s3://my-bucket/images/test-image.jpg', media_type='image/jpeg')
req = [
ModelRequest(parts=[UserPromptPart(content=['What is in this image?', image_url])]),
]
_, bedrock_messages = await model._map_messages(req, ModelRequestParameters(), None) # type: ignore[reportPrivateUsage]
assert bedrock_messages == snapshot(
[
{
'role': 'user',
'content': [
{'text': 'What is in this image?'},
{
'image': {
'format': 'jpeg',
'source': {'s3Location': {'uri': 's3://my-bucket/images/test-image.jpg'}},
}
},
],
}
]
)
async def test_s3_video_url_input(bedrock_provider: BedrockProvider):
"""Test that s3:// video URLs are passed directly to Bedrock API."""
model = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
video_url = VideoUrl(url='s3://my-bucket/videos/test-video.mp4', media_type='video/mp4')
req = [
ModelRequest(parts=[UserPromptPart(content=['Describe this video', video_url])]),
]
_, bedrock_messages = await model._map_messages(req, ModelRequestParameters(), None) # type: ignore[reportPrivateUsage]
assert bedrock_messages == snapshot(
[
{
'role': 'user',
'content': [
{'text': 'Describe this video'},
{
'video': {
'format': 'mp4',
'source': {'s3Location': {'uri': 's3://my-bucket/videos/test-video.mp4'}},
}
},
],
}
]
)
async def test_s3_document_url_input(bedrock_provider: BedrockProvider):
"""Test that s3:// document URLs are passed directly to Bedrock API."""
model = BedrockConverseModel('anthropic.claude-v2', provider=bedrock_provider)
document_url = DocumentUrl(url='s3://my-bucket/documents/test-doc.pdf', media_type='application/pdf')
req = [
ModelRequest(parts=[UserPromptPart(content=['What is the main content on this document?', document_url])]),
]
_, bedrock_messages = await model._map_messages(req, ModelRequestParameters(), None) # type: ignore[reportPrivateUsage]
assert bedrock_messages == snapshot(
[
{
'role': 'user',
'content': [
{'text': 'What is the main content on this document?'},
{
'document': {
'format': 'pdf',
'name': 'Document 1',
'source': {'s3Location': {'uri': 's3://my-bucket/documents/test-doc.pdf'}},
}
},
],
}
]
)
async def test_s3_url_with_bucket_owner(bedrock_provider: BedrockProvider):
"""Test that s3:// URLs with bucketOwner parameter are parsed correctly."""
model = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
image_url = ImageUrl(url='s3://my-bucket/images/test-image.jpg?bucketOwner=123456789012', media_type='image/jpeg')
req = [
ModelRequest(parts=[UserPromptPart(content=['What is in this image?', image_url])]),
]
_, bedrock_messages = await model._map_messages(req, ModelRequestParameters(), None) # type: ignore[reportPrivateUsage]
assert bedrock_messages == snapshot(
[
{
'role': 'user',
'content': [
{'text': 'What is in this image?'},
{
'image': {
'format': 'jpeg',
'source': {
's3Location': {
'uri': 's3://my-bucket/images/test-image.jpg',
'bucketOwner': '123456789012',
}
},
}
},
],
}
]
)
@pytest.mark.vcr()
async def test_text_as_binary_content_input(allow_model_requests: None, bedrock_provider: BedrockProvider):
m = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
agent = Agent(m, instructions='You are a helpful chatbot.')
text_content = BinaryContent(data=b'This is a test document.', media_type='text/plain')
result = await agent.run(['What is the main content on this document?', text_content])
assert result.output == snapshot(
"""\
The document you're referring to appears to be a test document, which means its primary purpose is likely to serve as an example or a placeholder rather than containing substantive content. Test documents are commonly used for various purposes such as:
1. **Software Testing**: To verify that a system can correctly handle, display, or process documents.
2. **Design Mockups**: To illustrate how a document might look in a particular format or style.
3. **Training Materials**: To provide examples for instructional purposes.
4. **Placeholders**: To fill space in a system or application where real content will eventually be placed.
Since this is a test document, it probably doesn't contain any meaningful or specific information beyond what is necessary to serve its testing purpose. If you have specific questions about the format, structure, or any particular element within the document, feel free to ask!\
"""
)
@pytest.mark.vcr()
async def test_bedrock_model_instructions(allow_model_requests: None, bedrock_provider: BedrockProvider):
m = BedrockConverseModel('us.amazon.nova-pro-v1:0', provider=bedrock_provider)
def instructions() -> str:
return 'You are a helpful assistant.'
agent = Agent(m, instructions=instructions)
result = await agent.run('What is the capital of France?')
assert result.all_messages() == snapshot(
[
ModelRequest(
parts=[UserPromptPart(content='What is the capital of France?', timestamp=IsDatetime())],
timestamp=IsDatetime(),
instructions='You are a helpful assistant.',
run_id=IsStr(),
),
ModelResponse(
parts=[
TextPart(
content='The capital of France is Paris. Paris is not only the political and economic hub of the country but also a major center for culture, fashion, art, and tourism. It is renowned for its rich history, iconic landmarks such as the Eiffel Tower, Notre-Dame Cathedral, and the Louvre Museum, as well as its influence on global culture and cuisine.'
)
],
usage=RequestUsage(input_tokens=13, output_tokens=71),
model_name='us.amazon.nova-pro-v1:0',
timestamp=IsDatetime(),
provider_name='bedrock',
provider_url='https://bedrock-runtime.us-east-1.amazonaws.com',
provider_details={'finish_reason': 'end_turn'},
finish_reason='stop',
run_id=IsStr(),
),
]
)
@pytest.mark.vcr()
async def test_bedrock_empty_system_prompt(allow_model_requests: None, bedrock_provider: BedrockProvider):
m = BedrockConverseModel('us.amazon.nova-micro-v1:0', provider=bedrock_provider)
agent = Agent(m)
result = await agent.run('What is the capital of France?')
assert result.output == snapshot(
'The capital of France is Paris. Paris, officially known as "Ville de Paris," is not only the capital city but also the most populous city in France. It is located in the northern central part of the country along the Seine River. Paris is a major global city, renowned for its cultural, political, economic, and social influence. It is famous for its landmarks such as the Eiffel Tower, the Louvre Museum, Notre-Dame Cathedral, and the Champs-Élysées, among many other historic and modern attractions. The city has played a significant role in the history of art, fashion, gastronomy, and science.'
)
@pytest.mark.vcr()
async def test_bedrock_multiple_documents_in_history(