forked from strands-agents/sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_anthropic.py
More file actions
981 lines (800 loc) · 28.1 KB
/
test_anthropic.py
File metadata and controls
981 lines (800 loc) · 28.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
import logging
import unittest.mock
import anthropic
import pydantic
import pytest
import strands
from strands.models.anthropic import AnthropicModel
from strands.types.exceptions import ContextWindowOverflowException, ModelThrottledException
@pytest.fixture
def anthropic_client():
with unittest.mock.patch.object(strands.models.anthropic.anthropic, "AsyncAnthropic") as mock_client_cls:
yield mock_client_cls.return_value
@pytest.fixture
def model_id():
return "m1"
@pytest.fixture
def max_tokens():
return 1
@pytest.fixture
def model(anthropic_client, model_id, max_tokens):
_ = anthropic_client
return AnthropicModel(model_id=model_id, max_tokens=max_tokens)
@pytest.fixture
def messages():
return [{"role": "user", "content": [{"text": "test"}]}]
@pytest.fixture
def system_prompt():
return "s1"
@pytest.fixture
def test_output_model_cls():
class TestOutputModel(pydantic.BaseModel):
name: str
age: int
return TestOutputModel
def test__init__model_configs(anthropic_client, model_id, max_tokens):
_ = anthropic_client
model = AnthropicModel(model_id=model_id, max_tokens=max_tokens, params={"temperature": 1})
tru_temperature = model.get_config().get("params")
exp_temperature = {"temperature": 1}
assert tru_temperature == exp_temperature
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, max_tokens):
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [{"role": "user", "content": [{"type": "text", "text": "test"}]}],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_params(model, messages, model_id, max_tokens):
model.update_config(params={"temperature": 1})
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [{"role": "user", "content": [{"type": "text", "text": "test"}]}],
"model": model_id,
"tools": [],
"temperature": 1,
}
assert tru_request == exp_request
def test_format_request_with_system_prompt(model, messages, model_id, max_tokens, system_prompt):
tru_request = model.format_request(messages, system_prompt=system_prompt)
exp_request = {
"max_tokens": max_tokens,
"messages": [{"role": "user", "content": [{"type": "text", "text": "test"}]}],
"model": model_id,
"system": system_prompt,
"tools": [],
}
assert tru_request == exp_request
@pytest.mark.parametrize(
("content", "formatted_content"),
[
# PDF
(
{
"document": {"format": "pdf", "name": "test doc", "source": {"bytes": b"pdf"}},
},
{
"source": {
"data": "cGRm",
"media_type": "application/pdf",
"type": "base64",
},
"title": "test doc",
"type": "document",
},
),
# Plain text
(
{
"document": {"format": "txt", "name": "test doc", "source": {"bytes": b"txt"}},
},
{
"source": {
"data": "txt",
"media_type": "text/plain",
"type": "text",
},
"title": "test doc",
"type": "document",
},
),
],
)
def test_format_request_with_document(content, formatted_content, model, model_id, max_tokens):
messages = [
{
"role": "user",
"content": [content],
},
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [
{
"role": "user",
"content": [formatted_content],
},
],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_image(model, model_id, max_tokens):
messages = [
{
"role": "user",
"content": [
{
"image": {
"format": "jpg",
"source": {"bytes": b"base64encodedimage"},
},
},
],
},
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [
{
"role": "user",
"content": [
{
"source": {
"data": "YmFzZTY0ZW5jb2RlZGltYWdl",
"media_type": "image/jpeg",
"type": "base64",
},
"type": "image",
},
],
},
],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_reasoning(model, model_id, max_tokens):
messages = [
{
"role": "user",
"content": [
{
"reasoningContent": {
"reasoningText": {
"signature": "reasoning_signature",
"text": "reasoning_text",
},
},
},
],
},
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [
{
"role": "user",
"content": [
{
"signature": "reasoning_signature",
"thinking": "reasoning_text",
"type": "thinking",
},
],
},
],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_tool_use(model, model_id, max_tokens):
messages = [
{
"role": "assistant",
"content": [
{
"toolUse": {
"toolUseId": "c1",
"name": "calculator",
"input": {"expression": "2+2"},
},
},
],
},
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [
{
"role": "assistant",
"content": [
{
"id": "c1",
"input": {"expression": "2+2"},
"name": "calculator",
"type": "tool_use",
},
],
},
],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_tool_results(model, model_id, max_tokens):
messages = [
{
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": "c1",
"status": "success",
"content": [
{"text": "see image"},
{"json": ["see image"]},
{
"image": {
"format": "jpg",
"source": {"bytes": b"base64encodedimage"},
},
},
],
}
}
],
}
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [
{
"role": "user",
"content": [
{
"content": [
{
"text": "see image",
"type": "text",
},
{
"text": '["see image"]',
"type": "text",
},
{
"source": {
"data": "YmFzZTY0ZW5jb2RlZGltYWdl",
"media_type": "image/jpeg",
"type": "base64",
},
"type": "image",
},
],
"is_error": False,
"tool_use_id": "c1",
"type": "tool_result",
},
],
},
],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_unsupported_type(model):
messages = [
{
"role": "user",
"content": [{"unsupported": {}}],
},
]
with pytest.raises(TypeError, match="content_type=<unsupported> | unsupported type"):
model.format_request(messages)
def test_format_request_with_cache_point(model, model_id, max_tokens):
messages = [
{
"role": "user",
"content": [
{"text": "cache me"},
{"cachePoint": {"type": "default"}},
],
},
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [
{
"role": "user",
"content": [
{
"cache_control": {"type": "ephemeral"},
"text": "cache me",
"type": "text",
},
],
},
],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_with_empty_content(model, model_id, max_tokens):
messages = [
{
"role": "user",
"content": [],
},
]
tru_request = model.format_request(messages)
exp_request = {
"max_tokens": max_tokens,
"messages": [],
"model": model_id,
"tools": [],
}
assert tru_request == exp_request
def test_format_request_tool_choice_auto(model, messages, model_id, max_tokens):
tool_specs = [{"description": "test tool", "name": "test_tool", "inputSchema": {"json": {"key": "value"}}}]
tool_choice = {"auto": {}}
tru_request = model.format_request(messages, tool_specs, tool_choice=tool_choice)
exp_request = {
"max_tokens": max_tokens,
"messages": [{"role": "user", "content": [{"type": "text", "text": "test"}]}],
"model": model_id,
"tools": [
{
"name": "test_tool",
"description": "test tool",
"input_schema": {"key": "value"},
}
],
"tool_choice": {"type": "auto"},
}
assert tru_request == exp_request
def test_format_request_tool_choice_any(model, messages, model_id, max_tokens):
tool_specs = [{"description": "test tool", "name": "test_tool", "inputSchema": {"json": {"key": "value"}}}]
tool_choice = {"any": {}}
tru_request = model.format_request(messages, tool_specs, tool_choice=tool_choice)
exp_request = {
"max_tokens": max_tokens,
"messages": [{"role": "user", "content": [{"type": "text", "text": "test"}]}],
"model": model_id,
"tools": [
{
"name": "test_tool",
"description": "test tool",
"input_schema": {"key": "value"},
}
],
"tool_choice": {"type": "any"},
}
assert tru_request == exp_request
def test_format_request_tool_choice_tool(model, messages, model_id, max_tokens):
tool_specs = [{"description": "test tool", "name": "test_tool", "inputSchema": {"json": {"key": "value"}}}]
tool_choice = {"tool": {"name": "test_tool"}}
tru_request = model.format_request(messages, tool_specs, tool_choice=tool_choice)
exp_request = {
"max_tokens": max_tokens,
"messages": [{"role": "user", "content": [{"type": "text", "text": "test"}]}],
"model": model_id,
"tools": [
{
"name": "test_tool",
"description": "test tool",
"input_schema": {"key": "value"},
}
],
"tool_choice": {"name": "test_tool", "type": "tool"},
}
assert tru_request == exp_request
def test_format_chunk_message_start(model):
event = {"type": "message_start"}
tru_chunk = model.format_chunk(event)
exp_chunk = {"messageStart": {"role": "assistant"}}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_start_tool_use(model):
event = {
"content_block": {
"id": "c1",
"name": "calculator",
"type": "tool_use",
},
"index": 0,
"type": "content_block_start",
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"contentBlockStart": {
"contentBlockIndex": 0,
"start": {"toolUse": {"name": "calculator", "toolUseId": "c1"}},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_start_other(model):
event = {
"content_block": {
"type": "text",
},
"index": 0,
"type": "content_block_start",
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"contentBlockStart": {
"contentBlockIndex": 0,
"start": {},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_delta_signature_delta(model):
event = {
"delta": {
"type": "signature_delta",
"signature": "s1",
},
"index": 0,
"type": "content_block_delta",
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"contentBlockDelta": {
"contentBlockIndex": 0,
"delta": {
"reasoningContent": {
"signature": "s1",
},
},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_delta_thinking_delta(model):
event = {
"delta": {
"type": "thinking_delta",
"thinking": "t1",
},
"index": 0,
"type": "content_block_delta",
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"contentBlockDelta": {
"contentBlockIndex": 0,
"delta": {
"reasoningContent": {
"text": "t1",
},
},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_delta_input_json_delta_delta(model):
event = {
"delta": {
"type": "input_json_delta",
"partial_json": "{",
},
"index": 0,
"type": "content_block_delta",
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"contentBlockDelta": {
"contentBlockIndex": 0,
"delta": {
"toolUse": {
"input": "{",
},
},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_delta_text_delta(model):
event = {
"delta": {
"type": "text_delta",
"text": "hello",
},
"index": 0,
"type": "content_block_delta",
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"contentBlockDelta": {
"contentBlockIndex": 0,
"delta": {"text": "hello"},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_content_block_delta_unknown(model):
event = {
"delta": {
"type": "unknown",
},
"type": "content_block_delta",
}
with pytest.raises(RuntimeError, match="chunk_type=<content_block_delta>, delta=<unknown> | unknown type"):
model.format_chunk(event)
def test_format_chunk_content_block_stop(model):
event = {"type": "content_block_stop", "index": 0}
tru_chunk = model.format_chunk(event)
exp_chunk = {"contentBlockStop": {"contentBlockIndex": 0}}
assert tru_chunk == exp_chunk
def test_format_chunk_message_stop(model):
event = {"type": "message_stop", "message": {"stop_reason": "end_turn"}}
tru_chunk = model.format_chunk(event)
exp_chunk = {"messageStop": {"stopReason": "end_turn"}}
assert tru_chunk == exp_chunk
def test_format_chunk_metadata(model):
event = {
"type": "metadata",
"usage": {"input_tokens": 1, "output_tokens": 2},
}
tru_chunk = model.format_chunk(event)
exp_chunk = {
"metadata": {
"usage": {
"inputTokens": 1,
"outputTokens": 2,
"totalTokens": 3,
},
"metrics": {
"latencyMs": 0,
},
},
}
assert tru_chunk == exp_chunk
def test_format_chunk_unknown(model):
event = {"type": "unknown"}
with pytest.raises(RuntimeError, match="chunk_type=<unknown> | unknown type"):
model.format_chunk(event)
@pytest.mark.asyncio
async def test_stream(anthropic_client, model, agenerator, alist):
mock_event_1 = unittest.mock.Mock(
type="message_start",
dict=lambda: {"type": "message_start"},
model_dump=lambda: {"type": "message_start"},
)
mock_event_2 = unittest.mock.Mock(
type="unknown",
dict=lambda: {"type": "unknown"},
model_dump=lambda: {"type": "unknown"},
)
mock_event_3 = unittest.mock.Mock(
type="metadata",
message=unittest.mock.Mock(
usage=unittest.mock.Mock(
dict=lambda: {"input_tokens": 1, "output_tokens": 2},
model_dump=lambda: {"input_tokens": 1, "output_tokens": 2},
)
),
)
mock_context = unittest.mock.AsyncMock()
mock_context.__aenter__.return_value = agenerator([mock_event_1, mock_event_2, mock_event_3])
anthropic_client.messages.stream.return_value = mock_context
messages = [{"role": "user", "content": [{"text": "hello"}]}]
response = model.stream(messages, None, None)
tru_events = await alist(response)
exp_events = [
{"messageStart": {"role": "assistant"}},
{"metadata": {"usage": {"inputTokens": 1, "outputTokens": 2, "totalTokens": 3}, "metrics": {"latencyMs": 0}}},
]
assert tru_events == exp_events
# Check that the formatted request was passed to the client
expected_request = {
"max_tokens": 1,
"messages": [{"role": "user", "content": [{"type": "text", "text": "hello"}]}],
"model": "m1",
"tools": [],
}
anthropic_client.messages.stream.assert_called_once_with(**expected_request)
@pytest.mark.asyncio
async def test_stream_premature_termination(anthropic_client, model, agenerator, alist):
"""Test that stream fails clearly on premature termination.
When the Anthropic API stream ends before message_stop (e.g. network
timeout), the request should fail with a clear error instead of crashing
with AttributeError.
Regression test for #1868.
"""
mock_event_1 = unittest.mock.Mock(
type="message_start",
model_dump=lambda: {"type": "message_start"},
)
# Last event has no .message attribute (simulating premature termination)
mock_event_2 = unittest.mock.Mock(
type="content_block_stop",
model_dump=lambda: {"type": "content_block_stop", "index": 0},
spec=["type", "model_dump"],
)
mock_context = unittest.mock.AsyncMock()
mock_context.__aenter__.return_value = agenerator([mock_event_1, mock_event_2])
anthropic_client.messages.stream.return_value = mock_context
messages = [{"role": "user", "content": [{"text": "hello"}]}]
response = model.stream(messages, None, None)
with pytest.raises(RuntimeError, match="without usage metadata"):
await alist(response)
@pytest.mark.asyncio
async def test_stream_empty_no_events(anthropic_client, model, agenerator, alist):
"""Test that an empty stream fails clearly."""
mock_context = unittest.mock.AsyncMock()
mock_context.__aenter__.return_value = agenerator([])
anthropic_client.messages.stream.return_value = mock_context
messages = [{"role": "user", "content": [{"text": "hello"}]}]
response = model.stream(messages, None, None)
with pytest.raises(RuntimeError, match="before receiving any events"):
await alist(response)
@pytest.mark.asyncio
async def test_stream_rate_limit_error(anthropic_client, model, alist):
anthropic_client.messages.stream.side_effect = anthropic.RateLimitError(
"rate limit", response=unittest.mock.Mock(), body=None
)
messages = [{"role": "user", "content": [{"text": "hello"}]}]
with pytest.raises(ModelThrottledException, match="rate limit"):
await alist(model.stream(messages))
@pytest.mark.parametrize(
"overflow_message",
[
"...input is too long...",
"...input length exceeds context window...",
"...input and output tokens exceed your context limit...",
],
)
@pytest.mark.asyncio
async def test_stream_bad_request_overflow_error(overflow_message, anthropic_client, model):
anthropic_client.messages.stream.side_effect = anthropic.BadRequestError(
overflow_message, response=unittest.mock.Mock(), body=None
)
messages = [{"role": "user", "content": [{"text": "hello"}]}]
with pytest.raises(ContextWindowOverflowException):
await anext(model.stream(messages))
@pytest.mark.asyncio
async def test_stream_bad_request_error(anthropic_client, model):
anthropic_client.messages.stream.side_effect = anthropic.BadRequestError(
"bad", response=unittest.mock.Mock(), body=None
)
messages = [{"role": "user", "content": [{"text": "hello"}]}]
with pytest.raises(anthropic.BadRequestError, match="bad"):
await anext(model.stream(messages))
@pytest.mark.asyncio
async def test_structured_output(anthropic_client, model, test_output_model_cls, agenerator, alist):
messages = [{"role": "user", "content": [{"text": "Generate a person"}]}]
events = [
unittest.mock.Mock(type="message_start", model_dump=unittest.mock.Mock(return_value={"type": "message_start"})),
unittest.mock.Mock(
type="content_block_start",
model_dump=unittest.mock.Mock(
return_value={
"type": "content_block_start",
"index": 0,
"content_block": {"type": "tool_use", "id": "123", "name": "TestOutputModel"},
}
),
),
unittest.mock.Mock(
type="content_block_delta",
model_dump=unittest.mock.Mock(
return_value={
"type": "content_block_delta",
"index": 0,
"delta": {"type": "input_json_delta", "partial_json": '{"name": "John", "age": 30}'},
},
),
),
unittest.mock.Mock(
type="content_block_stop",
model_dump=unittest.mock.Mock(return_value={"type": "content_block_stop", "index": 0}),
),
unittest.mock.Mock(
type="message_stop",
model_dump=unittest.mock.Mock(
return_value={"type": "message_stop", "message": {"stop_reason": "tool_use"}}
),
),
unittest.mock.Mock(
message=unittest.mock.Mock(
usage=unittest.mock.Mock(
model_dump=unittest.mock.Mock(return_value={"input_tokens": 0, "output_tokens": 0})
),
),
),
]
mock_context = unittest.mock.AsyncMock()
mock_context.__aenter__.return_value = agenerator(events)
anthropic_client.messages.stream.return_value = mock_context
stream = model.structured_output(test_output_model_cls, messages)
events = await alist(stream)
tru_result = events[-1]
exp_result = {"output": test_output_model_cls(name="John", age=30)}
assert tru_result == exp_result
def test_config_validation_warns_on_unknown_keys(anthropic_client, captured_warnings):
"""Test that unknown config keys emit a warning."""
AnthropicModel(model_id="test-model", max_tokens=100, invalid_param="test")
assert len(captured_warnings) == 1
assert "Invalid configuration parameters" in str(captured_warnings[0].message)
assert "invalid_param" in str(captured_warnings[0].message)
def test_update_config_validation_warns_on_unknown_keys(model, captured_warnings):
"""Test that update_config warns on unknown keys."""
model.update_config(wrong_param="test")
assert len(captured_warnings) == 1
assert "Invalid configuration parameters" in str(captured_warnings[0].message)
assert "wrong_param" in str(captured_warnings[0].message)
def test_tool_choice_supported_no_warning(model, messages, captured_warnings):
"""Test that toolChoice doesn't emit warning for supported providers."""
tool_choice = {"auto": {}}
model.format_request(messages, tool_choice=tool_choice)
assert len(captured_warnings) == 0
def test_tool_choice_none_no_warning(model, messages, captured_warnings):
"""Test that None toolChoice doesn't emit warning."""
model.format_request(messages, tool_choice=None)
assert len(captured_warnings) == 0
def test_format_request_filters_s3_source_image(model, model_id, max_tokens, caplog):
"""Test that images with Location sources are filtered out with warning."""
caplog.set_level(logging.WARNING, logger="strands.models.anthropic")
messages = [
{
"role": "user",
"content": [
{"text": "look at this image"},
{
"image": {
"format": "png",
"source": {"location": {"type": "s3", "uri": "s3://my-bucket/image.png"}},
},
},
],
},
]
tru_request = model.format_request(messages)
# Image with S3 source should be filtered, text should remain
exp_messages = [
{"role": "user", "content": [{"type": "text", "text": "look at this image"}]},
]
assert tru_request["messages"] == exp_messages
assert "Location sources are not supported by Anthropic" in caplog.text
def test_format_request_filters_location_source_document(model, model_id, max_tokens, caplog):
"""Test that documents with Location sources are filtered out with warning."""
caplog.set_level(logging.WARNING, logger="strands.models.anthropic")
messages = [
{
"role": "user",
"content": [
{"text": "analyze this document"},
{
"document": {
"format": "pdf",
"name": "report.pdf",
"source": {"location": {"type": "s3", "uri": "s3://my-bucket/report.pdf"}},
},
},
{
"document": {
"format": "pdf",
"name": "report.pdf",
"source": {"location": {"type": "s3", "uri": "s3://my-bucket/report.pdf"}},
},
},
],
},
]
tru_request = model.format_request(messages)
# Document with S3 source should be filtered, text should remain
exp_messages = [
{"role": "user", "content": [{"type": "text", "text": "analyze this document"}]},
]
assert tru_request["messages"] == exp_messages
assert "Location sources are not supported by Anthropic" in caplog.text