-
Notifications
You must be signed in to change notification settings - Fork 608
Expand file tree
/
Copy pathtest_google_genai.py
More file actions
2214 lines (1849 loc) · 75.3 KB
/
test_google_genai.py
File metadata and controls
2214 lines (1849 loc) · 75.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import pytest
from unittest import mock
from google import genai
from google.genai import types as genai_types
from google.genai.types import Content, Part
from sentry_sdk import start_transaction
from sentry_sdk._types import BLOB_DATA_SUBSTITUTE
from sentry_sdk.consts import OP, SPANDATA
from sentry_sdk.integrations.google_genai import GoogleGenAIIntegration
from sentry_sdk.integrations.google_genai.utils import extract_contents_messages
@pytest.fixture
def mock_genai_client():
"""Fixture that creates a real genai.Client with mocked HTTP responses."""
client = genai.Client(api_key="test-api-key")
return client
def create_mock_http_response(response_body):
"""
Create a mock HTTP response that the API client's request() method would return.
Args:
response_body: The JSON body as a string or dict
Returns:
An HttpResponse object with headers and body
"""
if isinstance(response_body, dict):
response_body = json.dumps(response_body)
return genai_types.HttpResponse(
headers={
"content-type": "application/json; charset=UTF-8",
},
body=response_body,
)
def create_mock_streaming_responses(response_chunks):
"""
Create a generator that yields mock HTTP responses for streaming.
Args:
response_chunks: List of dicts, each representing a chunk's JSON body
Returns:
A generator that yields HttpResponse objects
"""
for chunk in response_chunks:
yield create_mock_http_response(chunk)
# Sample API response JSON (based on real API format from user)
EXAMPLE_API_RESPONSE_JSON = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "Hello! How can I help you today?"}],
},
"finishReason": "STOP",
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 20,
"totalTokenCount": 30,
"cachedContentTokenCount": 5,
"thoughtsTokenCount": 3,
},
"modelVersion": "gemini-1.5-flash",
"responseId": "response-id-123",
}
def create_test_config(
temperature=None,
top_p=None,
top_k=None,
max_output_tokens=None,
presence_penalty=None,
frequency_penalty=None,
seed=None,
system_instruction=None,
tools=None,
):
"""Create a GenerateContentConfig."""
config_dict = {}
if temperature is not None:
config_dict["temperature"] = temperature
if top_p is not None:
config_dict["top_p"] = top_p
if top_k is not None:
config_dict["top_k"] = top_k
if max_output_tokens is not None:
config_dict["max_output_tokens"] = max_output_tokens
if presence_penalty is not None:
config_dict["presence_penalty"] = presence_penalty
if frequency_penalty is not None:
config_dict["frequency_penalty"] = frequency_penalty
if seed is not None:
config_dict["seed"] = seed
if system_instruction is not None:
config_dict["system_instruction"] = system_instruction
if tools is not None:
config_dict["tools"] = tools
return genai_types.GenerateContentConfig(**config_dict)
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[
(True, True),
(True, False),
(False, True),
(False, False),
],
)
def test_nonstreaming_generate_content(
sentry_init, capture_events, send_default_pii, include_prompts, mock_genai_client
):
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
# Mock the HTTP response at the _api_client.request() level
mock_http_response = create_mock_http_response(EXAMPLE_API_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client,
"request",
return_value=mock_http_response,
):
with start_transaction(name="google_genai"):
config = create_test_config(temperature=0.7, max_output_tokens=100)
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Tell me a joke", config=config
)
assert len(events) == 1
(event,) = events
assert event["type"] == "transaction"
assert event["transaction"] == "google_genai"
assert len(event["spans"]) == 1
chat_span = event["spans"][0]
# Check chat span
assert chat_span["op"] == OP.GEN_AI_CHAT
assert chat_span["description"] == "chat gemini-1.5-flash"
assert chat_span["data"][SPANDATA.GEN_AI_OPERATION_NAME] == "chat"
assert chat_span["data"][SPANDATA.GEN_AI_SYSTEM] == "gcp.gemini"
assert chat_span["data"][SPANDATA.GEN_AI_REQUEST_MODEL] == "gemini-1.5-flash"
if send_default_pii and include_prompts:
# Response text is stored as a JSON array
response_text = chat_span["data"][SPANDATA.GEN_AI_RESPONSE_TEXT]
# Parse the JSON array
response_texts = json.loads(response_text)
assert response_texts == ["Hello! How can I help you today?"]
else:
assert SPANDATA.GEN_AI_RESPONSE_TEXT not in chat_span["data"]
# Check token usage
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS] == 10
# Output tokens now include reasoning tokens: candidates_token_count (20) + thoughts_token_count (3) = 23
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 23
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 30
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHED] == 5
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 3
@pytest.mark.parametrize("generate_content_config", (False, True))
@pytest.mark.parametrize(
"system_instructions,expected_texts",
[
(None, None),
({}, []),
(Content(role="system", parts=[]), []),
({"parts": []}, []),
("You are a helpful assistant.", ["You are a helpful assistant."]),
(Part(text="You are a helpful assistant."), ["You are a helpful assistant."]),
(
Content(role="system", parts=[Part(text="You are a helpful assistant.")]),
["You are a helpful assistant."],
),
({"text": "You are a helpful assistant."}, ["You are a helpful assistant."]),
(
{"parts": [Part(text="You are a helpful assistant.")]},
["You are a helpful assistant."],
),
(
{"parts": [{"text": "You are a helpful assistant."}]},
["You are a helpful assistant."],
),
(["You are a helpful assistant."], ["You are a helpful assistant."]),
([Part(text="You are a helpful assistant.")], ["You are a helpful assistant."]),
([{"text": "You are a helpful assistant."}], ["You are a helpful assistant."]),
],
)
def test_generate_content_with_system_instruction(
sentry_init,
capture_events,
mock_genai_client,
generate_content_config,
system_instructions,
expected_texts,
):
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
mock_http_response = create_mock_http_response(EXAMPLE_API_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
config = {
"system_instruction": system_instructions,
"temperature": 0.5,
}
if generate_content_config:
config = create_test_config(**config)
mock_genai_client.models.generate_content(
model="gemini-1.5-flash",
contents="What is 2+2?",
config=config,
)
(event,) = events
invoke_span = event["spans"][0]
if expected_texts is None:
assert SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS not in invoke_span["data"]
return
# (PII is enabled and include_prompts is True in this test)
system_instructions = json.loads(
invoke_span["data"][SPANDATA.GEN_AI_SYSTEM_INSTRUCTIONS]
)
assert system_instructions == [
{"type": "text", "content": text} for text in expected_texts
]
def test_generate_content_with_tools(sentry_init, capture_events, mock_genai_client):
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
# Create a mock tool function
def get_weather(location: str) -> str:
"""Get the weather for a location"""
return f"The weather in {location} is sunny"
# Create a tool with function declarations using real types
function_declaration = genai_types.FunctionDeclaration(
name="get_weather_tool",
description="Get weather information (tool object)",
parameters=genai_types.Schema(
type=genai_types.Type.OBJECT,
properties={
"location": genai_types.Schema(
type=genai_types.Type.STRING,
description="The location to get weather for",
)
},
required=["location"],
),
)
mock_tool = genai_types.Tool(function_declarations=[function_declaration])
# API response for tool usage
tool_response_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "I'll check the weather."}],
},
"finishReason": "STOP",
}
],
"usageMetadata": {
"promptTokenCount": 15,
"candidatesTokenCount": 10,
"totalTokenCount": 25,
},
}
mock_http_response = create_mock_http_response(tool_response_json)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
config = create_test_config(tools=[get_weather, mock_tool])
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="What's the weather?", config=config
)
(event,) = events
invoke_span = event["spans"][0]
# Check that tools are recorded (data is serialized as a string)
tools_data_str = invoke_span["data"][SPANDATA.GEN_AI_REQUEST_AVAILABLE_TOOLS]
# Parse the JSON string to verify content
tools_data = json.loads(tools_data_str)
assert len(tools_data) == 2
# The order of tools may not be guaranteed, so sort by name and description for comparison
sorted_tools = sorted(
tools_data, key=lambda t: (t.get("name", ""), t.get("description", ""))
)
# The function tool
assert sorted_tools[0]["name"] == "get_weather"
assert sorted_tools[0]["description"] == "Get the weather for a location"
# The FunctionDeclaration tool
assert sorted_tools[1]["name"] == "get_weather_tool"
assert sorted_tools[1]["description"] == "Get weather information (tool object)"
def test_tool_execution(sentry_init, capture_events):
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Create a mock tool function
def get_weather(location: str) -> str:
"""Get the weather for a location"""
return f"The weather in {location} is sunny"
# Create wrapped version of the tool
from sentry_sdk.integrations.google_genai.utils import wrapped_tool
wrapped_weather = wrapped_tool(get_weather)
# Execute the wrapped tool
with start_transaction(name="test_tool"):
result = wrapped_weather("San Francisco")
assert result == "The weather in San Francisco is sunny"
(event,) = events
assert len(event["spans"]) == 1
tool_span = event["spans"][0]
assert tool_span["op"] == OP.GEN_AI_EXECUTE_TOOL
assert tool_span["description"] == "execute_tool get_weather"
assert tool_span["data"][SPANDATA.GEN_AI_TOOL_NAME] == "get_weather"
assert tool_span["data"][SPANDATA.GEN_AI_TOOL_TYPE] == "function"
assert (
tool_span["data"][SPANDATA.GEN_AI_TOOL_DESCRIPTION]
== "Get the weather for a location"
)
def test_error_handling(sentry_init, capture_events, mock_genai_client):
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
# Mock an error at the HTTP level
with mock.patch.object(
mock_genai_client._api_client, "request", side_effect=Exception("API Error")
):
with start_transaction(name="google_genai"):
with pytest.raises(Exception, match="API Error"):
mock_genai_client.models.generate_content(
model="gemini-1.5-flash",
contents="This will fail",
config=create_test_config(),
)
# Should have both transaction and error events
assert len(events) == 2
error_event, transaction_event = events
assert error_event["level"] == "error"
assert error_event["exception"]["values"][0]["type"] == "Exception"
assert error_event["exception"]["values"][0]["value"] == "API Error"
assert error_event["exception"]["values"][0]["mechanism"]["type"] == "google_genai"
def test_streaming_generate_content(sentry_init, capture_events, mock_genai_client):
"""Test streaming with generate_content_stream, verifying chunk accumulation."""
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Create streaming chunks - simulating a multi-chunk response
# Chunk 1: First part of text with partial usage metadata
chunk1_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "Hello! "}],
},
# No finishReason in intermediate chunks
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 2,
"totalTokenCount": 12,
},
"responseId": "response-id-stream-123",
"modelVersion": "gemini-1.5-flash",
}
# Chunk 2: Second part of text with intermediate usage metadata
chunk2_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "How can I "}],
},
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 3,
"totalTokenCount": 13,
},
}
# Chunk 3: Final part with finish reason and complete usage metadata
chunk3_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "help you today?"}],
},
"finishReason": "STOP",
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 7,
"totalTokenCount": 25,
"cachedContentTokenCount": 5,
"thoughtsTokenCount": 3,
},
}
# Create streaming mock responses
stream_chunks = [chunk1_json, chunk2_json, chunk3_json]
mock_stream = create_mock_streaming_responses(stream_chunks)
with mock.patch.object(
mock_genai_client._api_client, "request_streamed", return_value=mock_stream
):
with start_transaction(name="google_genai"):
config = create_test_config()
stream = mock_genai_client.models.generate_content_stream(
model="gemini-1.5-flash", contents="Stream me a response", config=config
)
# Consume the stream (this is what users do with the integration wrapper)
collected_chunks = list(stream)
# Verify we got all chunks
assert len(collected_chunks) == 3
assert collected_chunks[0].candidates[0].content.parts[0].text == "Hello! "
assert collected_chunks[1].candidates[0].content.parts[0].text == "How can I "
assert collected_chunks[2].candidates[0].content.parts[0].text == "help you today?"
(event,) = events
assert len(event["spans"]) == 1
chat_span = event["spans"][0]
# Check that streaming flag is set on both spans
assert chat_span["data"][SPANDATA.GEN_AI_RESPONSE_STREAMING] is True
# Verify accumulated response text (all chunks combined)
expected_full_text = "Hello! How can I help you today?"
# Response text is stored as a JSON string
chat_response_text = json.loads(chat_span["data"][SPANDATA.GEN_AI_RESPONSE_TEXT])
assert chat_response_text == [expected_full_text]
# Verify finish reasons (only the final chunk has a finish reason)
# When there's a single finish reason, it's stored as a plain string (not JSON)
assert SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS in chat_span["data"]
assert chat_span["data"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS] == "STOP"
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS] == 10
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS] == 10
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS] == 25
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_INPUT_TOKENS_CACHED] == 5
assert chat_span["data"][SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS_REASONING] == 3
# Verify model name
assert chat_span["data"][SPANDATA.GEN_AI_REQUEST_MODEL] == "gemini-1.5-flash"
def test_span_origin(sentry_init, capture_events, mock_genai_client):
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
mock_http_response = create_mock_http_response(EXAMPLE_API_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
config = create_test_config()
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Test origin", config=config
)
(event,) = events
assert event["contexts"]["trace"]["origin"] == "manual"
for span in event["spans"]:
assert span["origin"] == "auto.ai.google_genai"
def test_response_without_usage_metadata(
sentry_init, capture_events, mock_genai_client
):
"""Test handling of responses without usage metadata"""
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
# Response without usage metadata
response_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "No usage data"}],
},
"finishReason": "STOP",
}
],
}
mock_http_response = create_mock_http_response(response_json)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
config = create_test_config()
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Test", config=config
)
(event,) = events
chat_span = event["spans"][0]
# Usage data should not be present
assert SPANDATA.GEN_AI_USAGE_INPUT_TOKENS not in chat_span["data"]
assert SPANDATA.GEN_AI_USAGE_OUTPUT_TOKENS not in chat_span["data"]
assert SPANDATA.GEN_AI_USAGE_TOTAL_TOKENS not in chat_span["data"]
def test_multiple_candidates(sentry_init, capture_events, mock_genai_client):
"""Test handling of multiple response candidates"""
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
# Response with multiple candidates
multi_candidate_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "Response 1"}],
},
"finishReason": "STOP",
},
{
"content": {
"role": "model",
"parts": [{"text": "Response 2"}],
},
"finishReason": "MAX_TOKENS",
},
],
"usageMetadata": {
"promptTokenCount": 5,
"candidatesTokenCount": 15,
"totalTokenCount": 20,
},
}
mock_http_response = create_mock_http_response(multi_candidate_json)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
config = create_test_config()
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Generate multiple", config=config
)
(event,) = events
chat_span = event["spans"][0]
# Should capture all responses
# Response text is stored as a JSON string when there are multiple responses
response_text = chat_span["data"][SPANDATA.GEN_AI_RESPONSE_TEXT]
if isinstance(response_text, str) and response_text.startswith("["):
# It's a JSON array
response_list = json.loads(response_text)
assert response_list == ["Response 1", "Response 2"]
else:
# It's concatenated
assert response_text == "Response 1\nResponse 2"
# Finish reasons are serialized as JSON
finish_reasons = json.loads(
chat_span["data"][SPANDATA.GEN_AI_RESPONSE_FINISH_REASONS]
)
assert finish_reasons == ["STOP", "MAX_TOKENS"]
def test_all_configuration_parameters(sentry_init, capture_events, mock_genai_client):
"""Test that all configuration parameters are properly recorded"""
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
mock_http_response = create_mock_http_response(EXAMPLE_API_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
config = create_test_config(
temperature=0.8,
top_p=0.95,
top_k=40,
max_output_tokens=2048,
presence_penalty=0.1,
frequency_penalty=0.2,
seed=12345,
)
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Test all params", config=config
)
(event,) = events
invoke_span = event["spans"][0]
# Check all parameters are recorded
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_TEMPERATURE] == 0.8
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_TOP_P] == 0.95
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_TOP_K] == 40
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_MAX_TOKENS] == 2048
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_PRESENCE_PENALTY] == 0.1
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_FREQUENCY_PENALTY] == 0.2
assert invoke_span["data"][SPANDATA.GEN_AI_REQUEST_SEED] == 12345
def test_empty_response(sentry_init, capture_events, mock_genai_client):
"""Test handling of minimal response with no content"""
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
# Minimal response with empty candidates array
minimal_response_json = {"candidates": []}
mock_http_response = create_mock_http_response(minimal_response_json)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
response = mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Test", config=create_test_config()
)
# Response will have an empty candidates list
assert response is not None
assert len(response.candidates) == 0
(event,) = events
# Should still create spans even with empty candidates
assert len(event["spans"]) == 1
def test_response_with_different_id_fields(
sentry_init, capture_events, mock_genai_client
):
"""Test handling of different response ID field names"""
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
# Response with response_id and model_version
response_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": "Test"}],
},
"finishReason": "STOP",
}
],
"responseId": "resp-456",
"modelVersion": "gemini-1.5-flash-001",
}
mock_http_response = create_mock_http_response(response_json)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents="Test", config=create_test_config()
)
(event,) = events
chat_span = event["spans"][0]
assert chat_span["data"][SPANDATA.GEN_AI_RESPONSE_ID] == "resp-456"
assert chat_span["data"][SPANDATA.GEN_AI_RESPONSE_MODEL] == "gemini-1.5-flash-001"
def test_tool_with_async_function(sentry_init, capture_events):
"""Test that async tool functions are properly wrapped"""
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
capture_events()
# Create an async tool function
async def async_tool(param: str) -> str:
"""An async tool"""
return f"Async result: {param}"
# Import is skipped in sync tests, but we can test the wrapping logic
from sentry_sdk.integrations.google_genai.utils import wrapped_tool
# The wrapper should handle async functions
wrapped_async_tool = wrapped_tool(async_tool)
assert wrapped_async_tool != async_tool # Should be wrapped
assert hasattr(wrapped_async_tool, "__wrapped__") # Should preserve original
def test_contents_as_none(sentry_init, capture_events, mock_genai_client):
"""Test handling when contents parameter is None"""
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
mock_http_response = create_mock_http_response(EXAMPLE_API_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
mock_genai_client.models.generate_content(
model="gemini-1.5-flash", contents=None, config=create_test_config()
)
(event,) = events
invoke_span = event["spans"][0]
# Should handle None contents gracefully
messages = invoke_span["data"].get(SPANDATA.GEN_AI_REQUEST_MESSAGES, [])
# Should only have system message if any, not user message
assert all(msg["role"] != "user" or msg["content"] is not None for msg in messages)
def test_tool_calls_extraction(sentry_init, capture_events, mock_genai_client):
"""Test extraction of tool/function calls from response"""
sentry_init(
integrations=[GoogleGenAIIntegration()],
traces_sample_rate=1.0,
)
events = capture_events()
# Response with function calls
function_call_response_json = {
"candidates": [
{
"content": {
"role": "model",
"parts": [
{"text": "I'll help you with that."},
{
"functionCall": {
"name": "get_weather",
"args": {
"location": "San Francisco",
"unit": "celsius",
},
}
},
{
"functionCall": {
"name": "get_time",
"args": {"timezone": "PST"},
}
},
],
},
"finishReason": "STOP",
}
],
"usageMetadata": {
"promptTokenCount": 20,
"candidatesTokenCount": 30,
"totalTokenCount": 50,
},
}
mock_http_response = create_mock_http_response(function_call_response_json)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
mock_genai_client.models.generate_content(
model="gemini-1.5-flash",
contents="What's the weather and time?",
config=create_test_config(),
)
(event,) = events
chat_span = event["spans"][0] # The chat span
# Check that tool calls are extracted and stored
assert SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS in chat_span["data"]
# Parse the JSON string to verify content
tool_calls = json.loads(chat_span["data"][SPANDATA.GEN_AI_RESPONSE_TOOL_CALLS])
assert len(tool_calls) == 2
# First tool call
assert tool_calls[0]["name"] == "get_weather"
assert tool_calls[0]["type"] == "function_call"
# Arguments are serialized as JSON strings
assert json.loads(tool_calls[0]["arguments"]) == {
"location": "San Francisco",
"unit": "celsius",
}
# Second tool call
assert tool_calls[1]["name"] == "get_time"
assert tool_calls[1]["type"] == "function_call"
# Arguments are serialized as JSON strings
assert json.loads(tool_calls[1]["arguments"]) == {"timezone": "PST"}
def test_google_genai_message_truncation(
sentry_init, capture_events, mock_genai_client
):
"""Test that large messages are truncated properly in Google GenAI integration."""
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=True)],
traces_sample_rate=1.0,
send_default_pii=True,
)
events = capture_events()
large_content = (
"This is a very long message that will exceed our size limits. " * 1000
)
small_content = "This is a small user message"
mock_http_response = create_mock_http_response(EXAMPLE_API_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client, "request", return_value=mock_http_response
):
with start_transaction(name="google_genai"):
mock_genai_client.models.generate_content(
model="gemini-1.5-flash",
contents=[large_content, small_content],
config=create_test_config(),
)
(event,) = events
invoke_span = event["spans"][0]
assert SPANDATA.GEN_AI_REQUEST_MESSAGES in invoke_span["data"]
messages_data = invoke_span["data"][SPANDATA.GEN_AI_REQUEST_MESSAGES]
assert isinstance(messages_data, str)
parsed_messages = json.loads(messages_data)
assert isinstance(parsed_messages, list)
assert len(parsed_messages) == 1
assert parsed_messages[0]["role"] == "user"
# What "small content" becomes because the large message used the entire character limit
assert "..." in parsed_messages[0]["content"][1]["text"]
# Sample embed content API response JSON
EXAMPLE_EMBED_RESPONSE_JSON = {
"embeddings": [
{
"values": [0.1, 0.2, 0.3, 0.4, 0.5], # Simplified embedding vector
"statistics": {
"tokenCount": 10,
"truncated": False,
},
},
{
"values": [0.2, 0.3, 0.4, 0.5, 0.6],
"statistics": {
"tokenCount": 15,
"truncated": False,
},
},
],
"metadata": {
"billableCharacterCount": 42,
},
}
@pytest.mark.parametrize(
"send_default_pii, include_prompts",
[
(True, True),
(True, False),
(False, True),
(False, False),
],
)
def test_embed_content(
sentry_init, capture_events, send_default_pii, include_prompts, mock_genai_client
):
sentry_init(
integrations=[GoogleGenAIIntegration(include_prompts=include_prompts)],
traces_sample_rate=1.0,
send_default_pii=send_default_pii,
)
events = capture_events()
# Mock the HTTP response at the _api_client.request() level
mock_http_response = create_mock_http_response(EXAMPLE_EMBED_RESPONSE_JSON)
with mock.patch.object(
mock_genai_client._api_client,
"request",
return_value=mock_http_response,
):