-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathtest_anthropic_llm.py
More file actions
1930 lines (1686 loc) · 62.5 KB
/
test_anthropic_llm.py
File metadata and controls
1930 lines (1686 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import json
import os
import sys
from unittest import mock
from unittest.mock import AsyncMock
from unittest.mock import MagicMock
from anthropic import types as anthropic_types
from google.adk import version as adk_version
from google.adk.models import anthropic_llm
from google.adk.models.anthropic_llm import AnthropicLlm
from google.adk.models.anthropic_llm import Claude
from google.adk.models.anthropic_llm import content_to_message_param
from google.adk.models.anthropic_llm import function_declaration_to_tool_param
from google.adk.models.anthropic_llm import part_to_message_block
from google.adk.models.llm_request import LlmRequest
from google.adk.models.llm_response import LlmResponse
from google.genai import types
from google.genai import version as genai_version
from google.genai.types import Content
from google.genai.types import Part
import pytest
@pytest.fixture
def generate_content_response():
return anthropic_types.Message(
id="msg_vrtx_testid",
content=[
anthropic_types.TextBlock(
citations=None, text="Hi! How can I help you today?", type="text"
)
],
model="claude-3-5-sonnet-v2-20241022",
role="assistant",
stop_reason="end_turn",
stop_sequence=None,
type="message",
usage=anthropic_types.Usage(
cache_creation_input_tokens=0,
cache_read_input_tokens=0,
input_tokens=13,
output_tokens=12,
server_tool_use=None,
service_tier=None,
),
)
@pytest.fixture
def generate_llm_response():
return LlmResponse.create(
types.GenerateContentResponse(
candidates=[
types.Candidate(
content=Content(
role="model",
parts=[Part.from_text(text="Hello, how can I help you?")],
),
finish_reason=types.FinishReason.STOP,
)
]
)
)
@pytest.fixture
def claude_llm():
return Claude(model="claude-3-5-sonnet-v2@20241022")
@pytest.fixture
def llm_request():
return LlmRequest(
model="claude-3-5-sonnet-v2@20241022",
contents=[Content(role="user", parts=[Part.from_text(text="Hello")])],
config=types.GenerateContentConfig(
temperature=0.1,
response_modalities=[types.Modality.TEXT],
system_instruction="You are a helpful assistant",
),
)
def test_claude_anthropic_client_creation():
# Test with environment variables
with mock.patch.dict(
os.environ,
{
"GOOGLE_CLOUD_PROJECT": "env-project",
"GOOGLE_CLOUD_LOCATION": "env-location",
},
):
model = Claude(model="claude-3-5-sonnet-v2@20241022")
with mock.patch(
"google.adk.models.anthropic_llm.AsyncAnthropicVertex", autospec=True
) as mock_client_class:
_ = model._anthropic_client
mock_client_class.assert_called_once()
_, kwargs = mock_client_class.call_args
assert kwargs["project_id"] == "env-project"
assert kwargs["region"] == "env-location"
def test_claude_anthropic_client_creation_with_full_resource_name():
# Test with full resource name in model string
model = Claude(
model="projects/test-project/locations/test-location/publishers/anthropic/models/claude-3-5-sonnet-v2@20241022"
)
with mock.patch(
"google.adk.models.anthropic_llm.AsyncAnthropicVertex", autospec=True
) as mock_client_class:
_ = model._anthropic_client
mock_client_class.assert_called_once()
_, kwargs = mock_client_class.call_args
assert kwargs["project_id"] == "test-project"
assert kwargs["region"] == "test-location"
def test_supported_models():
models = Claude.supported_models()
assert len(models) == 2
assert models[0] == r"claude-3-.*"
assert models[1] == r"claude-.*-4.*"
function_declaration_test_cases = [
(
"function_with_no_parameters",
types.FunctionDeclaration(
name="get_current_time",
description="Gets the current time.",
),
anthropic_types.ToolParam(
name="get_current_time",
description="Gets the current time.",
input_schema={"type": "object", "properties": {}},
),
),
(
"function_with_one_optional_parameter",
types.FunctionDeclaration(
name="get_weather",
description="Gets weather information for a given location.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"location": types.Schema(
type=types.Type.STRING,
description="City and state, e.g., San Francisco, CA",
)
},
),
),
anthropic_types.ToolParam(
name="get_weather",
description="Gets weather information for a given location.",
input_schema={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": (
"City and state, e.g., San Francisco, CA"
),
}
},
},
),
),
(
"function_with_one_required_parameter",
types.FunctionDeclaration(
name="get_stock_price",
description="Gets the current price for a stock ticker.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"ticker": types.Schema(
type=types.Type.STRING,
description="The stock ticker, e.g., AAPL",
)
},
required=["ticker"],
),
),
anthropic_types.ToolParam(
name="get_stock_price",
description="Gets the current price for a stock ticker.",
input_schema={
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "The stock ticker, e.g., AAPL",
}
},
"required": ["ticker"],
},
),
),
(
"function_with_multiple_mixed_parameters",
types.FunctionDeclaration(
name="submit_order",
description="Submits a product order.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"product_id": types.Schema(
type=types.Type.STRING, description="The product ID"
),
"quantity": types.Schema(
type=types.Type.INTEGER,
description="The order quantity",
),
"notes": types.Schema(
type=types.Type.STRING,
description="Optional order notes",
),
},
required=["product_id", "quantity"],
),
),
anthropic_types.ToolParam(
name="submit_order",
description="Submits a product order.",
input_schema={
"type": "object",
"properties": {
"product_id": {
"type": "string",
"description": "The product ID",
},
"quantity": {
"type": "integer",
"description": "The order quantity",
},
"notes": {
"type": "string",
"description": "Optional order notes",
},
},
"required": ["product_id", "quantity"],
},
),
),
(
"function_with_complex_nested_parameter",
types.FunctionDeclaration(
name="create_playlist",
description="Creates a playlist from a list of songs.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"playlist_name": types.Schema(
type=types.Type.STRING,
description="The name for the new playlist",
),
"songs": types.Schema(
type=types.Type.ARRAY,
description="A list of songs to add to the playlist",
items=types.Schema(
type=types.Type.OBJECT,
properties={
"title": types.Schema(type=types.Type.STRING),
"artist": types.Schema(type=types.Type.STRING),
},
required=["title", "artist"],
),
),
},
required=["playlist_name", "songs"],
),
),
anthropic_types.ToolParam(
name="create_playlist",
description="Creates a playlist from a list of songs.",
input_schema={
"type": "object",
"properties": {
"playlist_name": {
"type": "string",
"description": "The name for the new playlist",
},
"songs": {
"type": "array",
"description": "A list of songs to add to the playlist",
"items": {
"type": "object",
"properties": {
"title": {"type": "string"},
"artist": {"type": "string"},
},
"required": ["title", "artist"],
},
},
},
"required": ["playlist_name", "songs"],
},
),
),
(
"function_with_nested_object_parameter",
types.FunctionDeclaration(
name="update_profile",
description="Updates a user profile.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"profile": types.Schema(
type=types.Type.OBJECT,
description="The profile data",
properties={
"name": types.Schema(
type=types.Type.STRING,
description="Full name",
),
"address": types.Schema(
type=types.Type.OBJECT,
description="Mailing address",
properties={
"city": types.Schema(
type=types.Type.STRING,
),
"state": types.Schema(
type=types.Type.STRING,
),
},
),
},
),
},
required=["profile"],
),
),
anthropic_types.ToolParam(
name="update_profile",
description="Updates a user profile.",
input_schema={
"type": "object",
"properties": {
"profile": {
"type": "object",
"description": "The profile data",
"properties": {
"name": {
"type": "string",
"description": "Full name",
},
"address": {
"type": "object",
"description": "Mailing address",
"properties": {
"city": {"type": "string"},
"state": {"type": "string"},
},
},
},
},
},
"required": ["profile"],
},
),
),
(
"function_with_any_of_parameter",
types.FunctionDeclaration(
name="set_value",
description="Sets a value that can be a string or integer.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"value": types.Schema(
description="A string or integer value",
any_of=[
types.Schema(type=types.Type.STRING),
types.Schema(type=types.Type.INTEGER),
],
),
},
required=["value"],
),
),
anthropic_types.ToolParam(
name="set_value",
description="Sets a value that can be a string or integer.",
input_schema={
"type": "object",
"properties": {
"value": {
"description": "A string or integer value",
"anyOf": [
{"type": "string"},
{"type": "integer"},
],
},
},
"required": ["value"],
},
),
),
(
"function_with_additional_properties_parameter",
types.FunctionDeclaration(
name="store_metadata",
description="Stores arbitrary key-value metadata.",
parameters=types.Schema(
type=types.Type.OBJECT,
properties={
"metadata": types.Schema(
type=types.Type.OBJECT,
description="Arbitrary metadata",
additional_properties=types.Schema(
type=types.Type.STRING,
),
),
},
required=["metadata"],
),
),
anthropic_types.ToolParam(
name="store_metadata",
description="Stores arbitrary key-value metadata.",
input_schema={
"type": "object",
"properties": {
"metadata": {
"type": "object",
"description": "Arbitrary metadata",
"additionalProperties": {"type": "string"},
},
},
"required": ["metadata"],
},
),
),
(
"function_with_parameters_json_schema_combinators",
types.FunctionDeclaration(
name="validate_payload",
description="Validates a payload with schema combinators.",
parameters_json_schema={
"type": "OBJECT",
"properties": {
"choice": {
"oneOf": [
{"type": "STRING"},
{"type": "INTEGER"},
],
},
"config": {
"allOf": [
{
"type": "OBJECT",
"properties": {
"enabled": {"type": "BOOLEAN"},
},
},
],
},
"blocked": {
"not": {
"type": "NULL",
},
},
"tuple_value": {
"type": "ARRAY",
"items": [
{"type": "STRING"},
{"type": "INTEGER"},
],
},
},
"required": ["choice"],
},
),
anthropic_types.ToolParam(
name="validate_payload",
description="Validates a payload with schema combinators.",
input_schema={
"type": "object",
"properties": {
"choice": {
"oneOf": [
{"type": "string"},
{"type": "integer"},
],
},
"config": {
"allOf": [
{
"type": "object",
"properties": {
"enabled": {"type": "boolean"},
},
},
],
},
"blocked": {
"not": {
"type": "null",
},
},
"tuple_value": {
"type": "array",
"items": [
{"type": "string"},
{"type": "integer"},
],
},
},
"required": ["choice"],
},
),
),
(
"function_with_parameters_json_schema",
types.FunctionDeclaration(
name="search_database",
description="Searches a database with given criteria.",
parameters_json_schema={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query",
},
"limit": {
"type": "integer",
"description": "Maximum number of results",
},
},
"required": ["query"],
},
),
anthropic_types.ToolParam(
name="search_database",
description="Searches a database with given criteria.",
input_schema={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query",
},
"limit": {
"type": "integer",
"description": "Maximum number of results",
},
},
"required": ["query"],
},
),
),
]
@pytest.mark.parametrize(
"_, function_declaration, expected_tool_param",
function_declaration_test_cases,
ids=[case[0] for case in function_declaration_test_cases],
)
async def test_function_declaration_to_tool_param(
_, function_declaration, expected_tool_param
):
"""Test function_declaration_to_tool_param."""
assert (
function_declaration_to_tool_param(function_declaration)
== expected_tool_param
)
@pytest.mark.asyncio
async def test_generate_content_async(
claude_llm, llm_request, generate_content_response, generate_llm_response
):
with mock.patch.object(claude_llm, "_anthropic_client") as mock_client:
with mock.patch.object(
anthropic_llm,
"message_to_generate_content_response",
return_value=generate_llm_response,
):
# Create a mock coroutine that returns the generate_content_response.
async def mock_coro():
return generate_content_response
# Assign the coroutine to the mocked method
mock_client.messages.create.return_value = mock_coro()
responses = [
resp
async for resp in claude_llm.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
assert isinstance(responses[0], LlmResponse)
assert responses[0].content.parts[0].text == "Hello, how can I help you?"
@pytest.mark.asyncio
async def test_anthropic_llm_generate_content_async(
llm_request, generate_content_response, generate_llm_response
):
anthropic_llm_instance = AnthropicLlm(model="claude-sonnet-4-20250514")
with mock.patch.object(
anthropic_llm_instance, "_anthropic_client"
) as mock_client:
with mock.patch.object(
anthropic_llm,
"message_to_generate_content_response",
return_value=generate_llm_response,
):
# Create a mock coroutine that returns the generate_content_response.
async def mock_coro():
return generate_content_response
# Assign the coroutine to the mocked method
mock_client.messages.create.return_value = mock_coro()
responses = [
resp
async for resp in anthropic_llm_instance.generate_content_async(
llm_request, stream=False
)
]
assert len(responses) == 1
assert isinstance(responses[0], LlmResponse)
assert responses[0].content.parts[0].text == "Hello, how can I help you?"
def test_claude_vertex_client_uses_tracking_headers():
"""Tests that Claude vertex client is called with tracking headers."""
with mock.patch.object(
anthropic_llm, "AsyncAnthropicVertex", autospec=True
) as mock_anthropic_vertex:
with mock.patch.dict(
os.environ,
{
"GOOGLE_CLOUD_PROJECT": "test-project",
"GOOGLE_CLOUD_LOCATION": "us-central1",
},
):
instance = Claude(model="claude-3-5-sonnet-v2@20241022")
_ = instance._anthropic_client
mock_anthropic_vertex.assert_called_once()
_, kwargs = mock_anthropic_vertex.call_args
assert "default_headers" in kwargs
assert "x-goog-api-client" in kwargs["default_headers"]
assert "user-agent" in kwargs["default_headers"]
assert (
f"google-adk/{adk_version.__version__}"
in kwargs["default_headers"]["user-agent"]
)
@pytest.mark.asyncio
async def test_generate_content_async_with_max_tokens(
llm_request, generate_content_response, generate_llm_response
):
claude_llm = Claude(model="claude-3-5-sonnet-v2@20241022", max_tokens=4096)
with mock.patch.object(claude_llm, "_anthropic_client") as mock_client:
with mock.patch.object(
anthropic_llm,
"message_to_generate_content_response",
return_value=generate_llm_response,
):
# Create a mock coroutine that returns the generate_content_response.
async def mock_coro():
return generate_content_response
# Assign the coroutine to the mocked method
mock_client.messages.create.return_value = mock_coro()
_ = [
resp
async for resp in claude_llm.generate_content_async(
llm_request, stream=False
)
]
mock_client.messages.create.assert_called_once()
_, kwargs = mock_client.messages.create.call_args
assert kwargs["max_tokens"] == 4096
def test_part_to_message_block_with_content():
"""Test that part_to_message_block handles content format."""
from google.adk.models.anthropic_llm import part_to_message_block
# Create a function response part with content array.
mcp_response_part = types.Part.from_function_response(
name="generate_sample_filesystem",
response={
"content": [{
"type": "text",
"text": '{"name":"root","node_type":"folder","children":[]}',
}]
},
)
mcp_response_part.function_response.id = "test_id_123"
result = part_to_message_block(mcp_response_part)
# ToolResultBlockParam is a TypedDict.
assert isinstance(result, dict)
assert result["tool_use_id"] == "test_id_123"
assert result["type"] == "tool_result"
assert not result["is_error"]
# Verify the content was extracted from the content format.
assert (
'{"name":"root","node_type":"folder","children":[]}' in result["content"]
)
def test_part_to_message_block_with_traditional_result():
"""Test that part_to_message_block handles traditional result format."""
from google.adk.models.anthropic_llm import part_to_message_block
# Create a function response part with traditional result format
traditional_response_part = types.Part.from_function_response(
name="some_tool",
response={
"result": "This is the result from the tool",
},
)
traditional_response_part.function_response.id = "test_id_456"
result = part_to_message_block(traditional_response_part)
# ToolResultBlockParam is a TypedDict.
assert isinstance(result, dict)
assert result["tool_use_id"] == "test_id_456"
assert result["type"] == "tool_result"
assert not result["is_error"]
# Verify the content was extracted from the traditional format
assert "This is the result from the tool" in result["content"]
def test_part_to_message_block_with_multiple_content_items():
"""Test content with multiple items."""
from google.adk.models.anthropic_llm import part_to_message_block
# Create a function response with multiple content items
multi_content_part = types.Part.from_function_response(
name="multi_response_tool",
response={
"content": [
{"type": "text", "text": "First part"},
{"type": "text", "text": "Second part"},
]
},
)
multi_content_part.function_response.id = "test_id_789"
result = part_to_message_block(multi_content_part)
# ToolResultBlockParam is a TypedDict.
assert isinstance(result, dict)
# Multiple text items should be joined with newlines
assert result["content"] == "First part\nSecond part"
def test_part_to_message_block_with_string_content():
"""Test that a plain string in the content key is passed through as-is.
LoadSkillResourceTool returns {"content": "<file text>"} where content is
a string, not a list. Iterating over a string yields individual characters,
so without an isinstance check the result would be "H\ne\nl\nl\no" instead
of "Hello".
"""
part = types.Part.from_function_response(
name="load_skill_resource",
response={
"skill_name": "my-skill",
"file_path": "references/doc.md",
"content": "Hello world",
},
)
part.function_response.id = "test_id_str"
result = part_to_message_block(part)
assert result["content"] == "Hello world"
def test_part_to_message_block_with_pdf_document():
"""Test that part_to_message_block handles PDF document parts."""
pdf_data = b"%PDF-1.4 fake pdf content"
part = Part(
inline_data=types.Blob(mime_type="application/pdf", data=pdf_data)
)
result = part_to_message_block(part)
assert isinstance(result, dict)
assert result["type"] == "document"
assert result["source"]["type"] == "base64"
assert result["source"]["media_type"] == "application/pdf"
assert result["source"]["data"] == base64.b64encode(pdf_data).decode()
def test_part_to_message_block_with_pdf_mime_type_parameters():
"""Test that PDF parts with MIME type parameters are handled correctly."""
pdf_data = b"%PDF-1.4 fake pdf content"
part = Part(
inline_data=types.Blob(
mime_type="application/pdf; name=doc.pdf", data=pdf_data
)
)
result = part_to_message_block(part)
assert isinstance(result, dict)
assert result["type"] == "document"
assert result["source"]["type"] == "base64"
assert result["source"]["media_type"] == "application/pdf; name=doc.pdf"
assert result["source"]["data"] == base64.b64encode(pdf_data).decode()
content_to_message_param_test_cases = [
(
"user_role_with_text_and_image",
Content(
role="user",
parts=[
Part.from_text(text="What's in this image?"),
Part(
inline_data=types.Blob(
mime_type="image/jpeg", data=b"fake_image_data"
)
),
],
),
"user",
2, # Expected content length
None, # No warning expected
),
(
"model_role_with_text_and_image",
Content(
role="model",
parts=[
Part.from_text(text="I see a cat."),
Part(
inline_data=types.Blob(
mime_type="image/png", data=b"fake_image_data"
)
),
],
),
"assistant",
1, # Image filtered out, only text remains
"Image data is not supported in Claude for assistant turns.",
),
(
"assistant_role_with_text_and_image",
Content(
role="assistant",
parts=[
Part.from_text(text="Here's what I found."),
Part(
inline_data=types.Blob(
mime_type="image/webp", data=b"fake_image_data"
)
),
],
),
"assistant",
1, # Image filtered out, only text remains
"Image data is not supported in Claude for assistant turns.",
),
(
"user_role_with_text_and_document",
Content(
role="user",
parts=[
Part.from_text(text="Summarize this document."),
Part(
inline_data=types.Blob(
mime_type="application/pdf", data=b"fake_pdf_data"
)
),
],
),
"user",
2, # Both text and document included
None, # No warning expected
),
(
"model_role_with_text_and_document",
Content(
role="model",
parts=[
Part.from_text(text="Here is the summary."),
Part(
inline_data=types.Blob(
mime_type="application/pdf", data=b"fake_pdf_data"
)
),
],
),
"assistant",
1, # Document filtered out, only text remains
"PDF data is not supported in Claude for assistant turns.",
),
]
@pytest.mark.parametrize(
"_, content, expected_role, expected_content_length, expected_warning",
content_to_message_param_test_cases,
ids=[case[0] for case in content_to_message_param_test_cases],
)
def test_content_to_message_param(
_, content, expected_role, expected_content_length, expected_warning
):
"""Test content_to_message_param handles images and documents based on role."""
with mock.patch("google.adk.models.anthropic_llm.logger") as mock_logger:
result = content_to_message_param(content)
assert result["role"] == expected_role
assert len(result["content"]) == expected_content_length
if expected_warning:
mock_logger.warning.assert_called_once_with(expected_warning)
else:
mock_logger.warning.assert_not_called()
# --- Tests for Bug #2: json.dumps for dict/list function results ---
def test_part_to_message_block_dict_result_serialized_as_json():
"""Dict results should be serialized with json.dumps, not str()."""
response_part = types.Part.from_function_response(
name="get_topic",
response={"result": {"topic": "travel", "active": True, "count": None}},
)
response_part.function_response.id = "test_id"
result = part_to_message_block(response_part)
content = result["content"]
# Must be valid JSON (json.dumps produces "true"/"null", not "True"/"None")
parsed = json.loads(content)
assert parsed["topic"] == "travel"
assert parsed["active"] is True
assert parsed["count"] is None
def test_part_to_message_block_list_result_serialized_as_json():
"""List results should be serialized with json.dumps."""
response_part = types.Part.from_function_response(
name="get_items",
response={"result": ["item1", "item2", "item3"]},
)
response_part.function_response.id = "test_id"
result = part_to_message_block(response_part)
content = result["content"]
parsed = json.loads(content)
assert parsed == ["item1", "item2", "item3"]
def test_part_to_message_block_empty_dict_result_not_dropped():
"""Empty dict results should produce '{}', not empty string."""
response_part = types.Part.from_function_response(
name="some_tool",
response={"result": {}},
)
response_part.function_response.id = "test_id"
result = part_to_message_block(response_part)
assert result["content"] == "{}"
def test_part_to_message_block_empty_list_result_not_dropped():
"""Empty list results should produce '[]', not empty string."""
response_part = types.Part.from_function_response(
name="some_tool",
response={"result": []},
)
response_part.function_response.id = "test_id"