forked from microsoft/agent-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_gemini_client.py
More file actions
2043 lines (1549 loc) · 82.3 KB
/
Copy pathtest_gemini_client.py
File metadata and controls
2043 lines (1549 loc) · 82.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
# Copyright (c) Microsoft. All rights reserved.
from __future__ import annotations
import datetime
import logging
import os
from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from agent_framework import Agent, Content, FunctionTool, Message
from google.genai import types
from pydantic import BaseModel
from agent_framework_gemini import GeminiChatClient, GeminiChatOptions, ThinkingConfig
def _has_gemini_integration_credentials() -> bool:
"""Return whether integration credentials for either Gemini API or Vertex AI appear to be configured."""
if os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY"):
return True
if os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "").lower() in {"true", "1", "yes", "on"}:
return bool(
os.getenv("GOOGLE_CLOUD_PROJECT")
or os.getenv("GOOGLE_APPLICATION_CREDENTIALS")
or os.getenv("GOOGLE_API_KEY")
)
return False
skip_if_no_credentials = pytest.mark.skipif(
not _has_gemini_integration_credentials(),
reason="Gemini Developer API or Vertex AI credentials not set; skipping integration tests.",
)
_TEST_MODEL = os.getenv("GOOGLE_MODEL") or os.getenv("GEMINI_MODEL", "gemini-2.5-flash-lite")
# stub helpers
def _make_part(
*,
text: str | None = None,
thought: bool = False,
function_call: tuple[str | None, str, dict[str, Any]] | None = None,
executable_code: str | None = None,
code_execution_result: str | None = None,
) -> MagicMock:
"""Build a mock types.Part.
Args:
text: Text content of the part.
thought: Whether this is a thinking/reasoning part.
function_call: Tuple of (id, name, args) if this is a function call part.
executable_code: Source code string for a code execution part.
code_execution_result: Output string for a code execution result part.
"""
part = MagicMock()
part.text = text
part.thought = thought
part.function_response = None
part.executable_code = None
part.code_execution_result = None
if function_call:
mock_function_call = MagicMock()
mock_function_call.id, mock_function_call.name, mock_function_call.args = function_call
part.function_call = mock_function_call
else:
part.function_call = None
if executable_code is not None:
mock_exec = MagicMock()
mock_exec.code = executable_code
part.executable_code = mock_exec
if code_execution_result is not None:
mock_result = MagicMock()
mock_result.output = code_execution_result
part.code_execution_result = mock_result
return part
def _make_response(
parts: list[MagicMock],
*,
finish_reason: str | None = "STOP",
model_version: str = "gemini-2.5-flash-001",
prompt_tokens: int | None = 10,
output_tokens: int | None = 5,
total_tokens: int | None = 15,
cached_tokens: int | None = None,
thoughts_tokens: int | None = None,
) -> MagicMock:
"""Build a mock types.GenerateContentResponse."""
response = MagicMock()
candidate = MagicMock()
candidate.content.parts = parts
if finish_reason:
candidate.finish_reason.name = finish_reason
else:
candidate.finish_reason = None
response.candidates = [candidate]
response.finish_reason = finish_reason
response.model_version = model_version
if prompt_tokens is not None or output_tokens is not None:
usage = MagicMock()
usage.prompt_token_count = prompt_tokens
usage.candidates_token_count = output_tokens
usage.total_token_count = total_tokens
usage.cached_content_token_count = cached_tokens
usage.thoughts_token_count = thoughts_tokens
response.usage_metadata = usage
else:
response.usage_metadata = None
return response
async def _async_iter(items: list[Any]):
"""Async generator used to simulate generate_content_stream results."""
for item in items:
yield item
def _make_gemini_client(
model: str | None = "gemini-2.5-flash",
mock_client: MagicMock | None = None,
) -> tuple[GeminiChatClient, MagicMock]:
"""Return a (GeminiChatClient, mock_genai_client) pair."""
mock = mock_client or MagicMock()
mock._api_client.vertexai = False
mock._api_client._http_options.base_url = "https://generativelanguage.googleapis.com/"
client = GeminiChatClient(client=mock, model=model)
return client, mock
def _parts(content: types.Content) -> list[types.Part]:
assert content.parts is not None
return content.parts
def _function_calling_config(config: types.GenerateContentConfig) -> types.FunctionCallingConfig:
assert config.tool_config is not None
function_calling_config = config.tool_config.function_calling_config
assert function_calling_config is not None
return function_calling_config
def _first_function_declaration(config: types.GenerateContentConfig) -> types.FunctionDeclaration:
assert config.tools is not None
tool = cast(types.Tool, config.tools[0])
assert tool.function_declarations is not None
return tool.function_declarations[0]
# settings & initialisation
def test_model_stored_on_instance() -> None:
"""Stores the model identifier on the instance so it can be read back."""
client, _ = _make_gemini_client(model="gemini-2.5-pro")
assert client.model == "gemini-2.5-pro"
def test_client_created_from_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""Initialises successfully when the API key is supplied via environment variable."""
monkeypatch.setenv("GEMINI_API_KEY", "test-key-123")
client = GeminiChatClient(model="gemini-2.5-flash")
assert client.model == "gemini-2.5-flash"
def test_client_created_from_google_api_key_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Initialises successfully when the SDK-standard Google API key environment variable is set."""
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GEMINI_MODEL", raising=False)
monkeypatch.delenv("GOOGLE_GENAI_USE_VERTEXAI", raising=False)
monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
monkeypatch.setenv("GOOGLE_API_KEY", "test-key-123")
monkeypatch.setenv("GOOGLE_MODEL", "gemini-2.5-flash-lite")
mock_client = MagicMock()
mock_client._api_client.vertexai = False
mock_client._api_client._http_options.base_url = "https://generativelanguage.googleapis.com/"
with patch("agent_framework_gemini._chat_client.genai.Client") as client_factory:
client_factory.return_value = mock_client
client = GeminiChatClient()
assert client_factory.call_args.kwargs["api_key"] == "test-key-123"
assert "vertexai" not in client_factory.call_args.kwargs
assert client.model == "gemini-2.5-flash-lite"
assert client.service_url() == "https://generativelanguage.googleapis.com"
def test_client_created_from_vertex_ai_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Initialises a Vertex AI client when the SDK-standard Vertex AI environment variables are set."""
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "test-project")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "global")
mock_client = MagicMock()
mock_client._api_client.vertexai = True
mock_client._api_client._http_options.base_url = "https://aiplatform.googleapis.com/"
with patch("agent_framework_gemini._chat_client.genai.Client", return_value=mock_client) as client_factory:
client = GeminiChatClient()
assert client_factory.call_args.kwargs["vertexai"] is True
assert client_factory.call_args.kwargs["project"] == "test-project"
assert client_factory.call_args.kwargs["location"] == "global"
assert "api_key" not in client_factory.call_args.kwargs
assert client.service_url() == "https://aiplatform.googleapis.com"
def test_google_settings_take_precedence_over_gemini_aliases(monkeypatch: pytest.MonkeyPatch) -> None:
"""Prefers SDK-standard ``GOOGLE_*`` settings when both env families are present."""
monkeypatch.setenv("GEMINI_API_KEY", "gemini-key")
monkeypatch.setenv("GEMINI_MODEL", "gemini-model")
monkeypatch.setenv("GOOGLE_API_KEY", "google-key")
monkeypatch.setenv("GOOGLE_MODEL", "google-model")
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "google-project")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "global")
mock_client = MagicMock()
mock_client._api_client.vertexai = True
mock_client._api_client._http_options.base_url = "https://aiplatform.googleapis.com/"
with patch("agent_framework_gemini._chat_client.genai.Client", return_value=mock_client) as client_factory:
client = GeminiChatClient()
assert client_factory.call_args.kwargs["vertexai"] is True
assert client_factory.call_args.kwargs["project"] == "google-project"
assert client_factory.call_args.kwargs["location"] == "global"
assert "api_key" not in client_factory.call_args.kwargs
assert client.model == "google-model"
assert client.service_url() == "https://aiplatform.googleapis.com"
def test_missing_api_key_raises_when_no_client_injected(monkeypatch: pytest.MonkeyPatch) -> None:
"""Raises ValueError at construction when neither Gemini API nor Vertex AI settings are available."""
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GEMINI_MODEL", raising=False)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
monkeypatch.delenv("GOOGLE_GENAI_USE_VERTEXAI", raising=False)
monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
with pytest.raises(ValueError, match="requires an API key when Vertex AI is not enabled"):
GeminiChatClient(model="gemini-2.5-flash")
def test_vertex_ai_express_mode_uses_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""Passes the API key in Vertex AI express mode when no project/location pair is configured."""
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GEMINI_MODEL", raising=False)
monkeypatch.setenv("GOOGLE_API_KEY", "test-key-123")
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
mock_client = MagicMock()
mock_client._api_client.vertexai = True
mock_client._api_client._http_options.base_url = "https://aiplatform.googleapis.com/"
with patch("agent_framework_gemini._chat_client.genai.Client", return_value=mock_client) as client_factory:
client = GeminiChatClient(model="gemini-2.5-flash-lite")
assert client_factory.call_args.kwargs["vertexai"] is True
assert client_factory.call_args.kwargs["api_key"] == "test-key-123"
assert "project" not in client_factory.call_args.kwargs
assert "location" not in client_factory.call_args.kwargs
assert client.service_url() == "https://aiplatform.googleapis.com"
def test_vertex_ai_requires_configuration(monkeypatch: pytest.MonkeyPatch) -> None:
"""Raises a deterministic error when Vertex AI is enabled without any auth configuration."""
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
with pytest.raises(ValueError, match="requires Vertex AI credentials or configuration"):
GeminiChatClient(model="gemini-2.5-flash")
def test_vertex_ai_requires_project_and_location_together(monkeypatch: pytest.MonkeyPatch) -> None:
"""Raises a deterministic error when only one Vertex AI location setting is present."""
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "test-project")
monkeypatch.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
with pytest.raises(ValueError, match="requires both GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_LOCATION"):
GeminiChatClient(model="gemini-2.5-flash")
async def test_missing_model_raises_on_get_response(monkeypatch: pytest.MonkeyPatch) -> None:
"""Raises ValueError at call time when no model is set on the client or in options."""
monkeypatch.delenv("GEMINI_MODEL", raising=False)
monkeypatch.delenv("GOOGLE_MODEL", raising=False)
client, mock = _make_gemini_client(model=None) # type: ignore[arg-type]
mock.aio.models.generate_content = AsyncMock()
with pytest.raises(ValueError, match="model"):
await client.get_response(messages=[Message(role="user", contents=[Content.from_text("hi")])])
# text response
async def test_get_response_returns_text() -> None:
"""Returns the model's text reply in the first message of the response."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hello!")]))
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert response.messages[0].text == "Hello!"
async def test_get_response_model_from_response() -> None:
"""Populates ChatResponse.model from the model_version field in the API response."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response([_make_part(text="Hi")], model_version="gemini-2.5-pro-002")
)
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert response.model == "gemini-2.5-pro-002"
async def test_get_response_uses_model_from_options() -> None:
"""Uses the model specified in options, overriding the client's default."""
client, mock = _make_gemini_client(model="gemini-2.5-flash")
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"model": "gemini-2.5-pro"},
)
call_kwargs = mock.aio.models.generate_content.call_args.kwargs
assert call_kwargs["model"] == "gemini-2.5-pro"
async def test_get_response_usage_details() -> None:
"""Surfaces input, output, and total token counts from the API usage metadata."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response(
[_make_part(text="Hi")],
prompt_tokens=20,
output_tokens=8,
total_tokens=28,
)
)
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert response.usage_details is not None
assert response.usage_details["input_token_count"] == 20
assert response.usage_details["output_token_count"] == 8
assert response.usage_details["total_token_count"] == 28
async def test_get_response_usage_details_includes_cached_and_reasoning_tokens() -> None:
"""Surfaces Gemini cached-content and thinking token counts into the canonical usage fields."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response(
[_make_part(text="Hi")],
prompt_tokens=20,
output_tokens=8,
total_tokens=28,
cached_tokens=12,
thoughts_tokens=6,
)
)
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert response.usage_details is not None
assert response.usage_details["cache_read_input_token_count"] == 12
assert response.usage_details["reasoning_output_token_count"] == 6
async def test_get_response_no_usage_when_metadata_absent() -> None:
"""Returns None for usage_details when the API response includes no usage metadata."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response([_make_part(text="Hi")], prompt_tokens=None, output_tokens=None)
)
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert not response.usage_details
# finish reasons
@pytest.mark.parametrize(
("gemini_reason", "expected"),
[
("STOP", "stop"),
("MAX_TOKENS", "length"),
("SAFETY", "content_filter"),
("RECITATION", "content_filter"),
("BLOCKLIST", "content_filter"),
("PROHIBITED_CONTENT", "content_filter"),
("SPII", "content_filter"),
("MALFORMED_FUNCTION_CALL", "tool_calls"),
("OTHER", None),
],
)
async def test_finish_reason_mapping(gemini_reason: str, expected: str | None) -> None:
"""Maps Gemini finish reason strings to the correct FinishReasonLiteral values."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response([_make_part(text="Hi")], finish_reason=gemini_reason)
)
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert response.finish_reason == expected
# message conversion
async def test_system_message_extracted_to_system_instruction() -> None:
"""Extracts a system role message from the conversation and sends it as the system instruction."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[
Message(role="system", contents=[Content.from_text("You are concise.")]),
Message(role="user", contents=[Content.from_text("Hi")]),
]
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.system_instruction == "You are concise."
async def test_multiple_system_messages_concatenated() -> None:
"""Joins multiple system messages into a single system instruction string."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[
Message(role="system", contents=[Content.from_text("Be concise.")]),
Message(role="system", contents=[Content.from_text("Use bullet points.")]),
Message(role="user", contents=[Content.from_text("Hi")]),
]
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert isinstance(config.system_instruction, str)
assert "Be concise." in config.system_instruction
assert "Use bullet points." in config.system_instruction
async def test_instructions_option_merged_with_system_instruction() -> None:
"""Prepends the instructions option to the system message when both are present."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[
Message(role="system", contents=[Content.from_text("Be concise.")]),
Message(role="user", contents=[Content.from_text("Hi")]),
],
options={"instructions": "Always respond in French."},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert isinstance(config.system_instruction, str)
assert "Always respond in French." in config.system_instruction
assert "Be concise." in config.system_instruction
async def test_instructions_option_without_system_message() -> None:
"""Uses the instructions option as the sole system instruction when no system message is present."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"instructions": "Be helpful."},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.system_instruction == "Be helpful."
async def test_assistant_role_mapped_to_model() -> None:
"""Maps the framework 'assistant' role to the 'model' role expected by the Gemini API."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Sure")]))
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_text("Hello")]),
Message(role="assistant", contents=[Content.from_text("Hi there")]),
Message(role="user", contents=[Content.from_text("Follow up")]),
]
)
contents: list[types.Content] = mock.aio.models.generate_content.call_args.kwargs["contents"]
roles = [c.role for c in contents]
assert roles == ["user", "model", "user"]
async def test_tool_messages_collapsed_into_single_user_message() -> None:
"""Consecutive tool messages must be collapsed into one role='user' message
with multiple functionResponse parts (parallel tool call pattern).
"""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Done")]))
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_text("Run both")]),
Message(
role="assistant",
contents=[
Content.from_function_call(call_id="c1", name="tool_a", arguments={}),
Content.from_function_call(call_id="c2", name="tool_b", arguments={}),
],
),
Message(role="tool", contents=[Content.from_function_result(call_id="c1", result="res_a")]),
Message(role="tool", contents=[Content.from_function_result(call_id="c2", result="res_b")]),
]
)
contents: list[types.Content] = mock.aio.models.generate_content.call_args.kwargs["contents"]
# user, model (with 2 function calls), user (with 2 function responses)
assert contents[-1].role == "user"
assert len(_parts(contents[-1])) == 2
async def test_function_result_name_resolved_from_call_history() -> None:
"""function_result name must come from the matching function_call in history."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Done")]))
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_text("Go")]),
Message(
role="assistant",
contents=[Content.from_function_call(call_id="call-42", name="get_weather", arguments={})],
),
Message(role="tool", contents=[Content.from_function_result(call_id="call-42", result="sunny")]),
]
)
contents: list[types.Content] = mock.aio.models.generate_content.call_args.kwargs["contents"]
tool_user_msg = contents[-1]
assert tool_user_msg.role == "user"
function_response = _parts(tool_user_msg)[0].function_response
assert function_response is not None
assert function_response.name == "get_weather"
assert function_response.id == "call-42"
async def test_function_result_resolved_when_call_id_was_generated() -> None:
"""When a function_call has no call_id and a fallback is generated, the subsequent
function_result referencing that generated ID must still resolve the function name.
"""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Done")]))
generated_id = "tool-call-generated-123"
with patch.object(client, "_generate_tool_call_id", return_value=generated_id):
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_text("Go")]),
Message(
role="assistant",
contents=[Content.from_function_call(call_id=cast(str, None), name="get_weather", arguments={})],
),
Message(
role="tool",
contents=[Content.from_function_result(call_id=generated_id, result="sunny")],
),
]
)
contents: list[types.Content] = mock.aio.models.generate_content.call_args.kwargs["contents"]
tool_turn = next(c for c in contents if c.role == "user" and any(p.function_response for p in _parts(c)))
function_response = _parts(tool_turn)[0].function_response
assert function_response is not None
assert function_response.name == "get_weather"
assert function_response.id == generated_id
async def test_function_result_without_matching_call_is_skipped(caplog: pytest.LogCaptureFixture) -> None:
"""A function_result with no prior function_call in history should be skipped with a warning."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Done")]))
with caplog.at_level(logging.WARNING, logger="agent_framework.gemini"):
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_text("Go")]),
Message(
role="tool",
contents=[Content.from_function_result(call_id="unknown-id", result="oops")],
),
Message(role="user", contents=[Content.from_text("What happened?")]),
]
)
assert any("unknown-id" in r.message or "function_result" in r.message.lower() for r in caplog.records)
async def test_message_with_only_unsupported_content_type_is_skipped() -> None:
"""A user message whose contents produce no convertible parts is dropped from the request."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Done")]))
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_function_result(call_id="x", result="y")]),
Message(role="user", contents=[Content.from_text("Follow up")]),
]
)
contents: list[types.Content] = mock.aio.models.generate_content.call_args.kwargs["contents"]
assert len(contents) == 1
assert _parts(contents[0])[0].text == "Follow up"
async def test_non_function_result_content_in_tool_message_is_skipped() -> None:
"""Unexpected content types inside a tool message are silently ignored."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Done")]))
await client.get_response(
messages=[
Message(role="user", contents=[Content.from_text("Hi")]),
Message(role="tool", contents=[Content.from_text("unexpected")]),
]
)
contents: list[types.Content] = mock.aio.models.generate_content.call_args.kwargs["contents"]
assert len(contents) == 1
# thinking parts
async def test_thinking_parts_are_silently_skipped() -> None:
"""Excludes thought-summary parts from ChatResponse.contents, returning only the final answer."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response([
_make_part(text="I should think first...", thought=True),
_make_part(text="The answer is 42."),
])
)
response = await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("What is the answer?")])]
)
assert len(response.messages[0].contents) == 1
assert response.messages[0].text == "The answer is 42."
def test_function_call_part_preserves_thought_signature_from_raw_part() -> None:
"""Reuses the original Gemini Part so tool loops retain thought_signature metadata."""
client, _ = _make_gemini_client()
raw_part = types.Part(
function_call=types.FunctionCall(id="call-1", name="get_weather", args={"location": "Paris"}),
thought_signature=b"sig-123",
)
content = Content.from_function_call(
call_id="call-1",
name="get_weather",
arguments={"location": "Paris"},
raw_representation=raw_part,
)
parts = client._convert_message_contents([content], {})
assert len(parts) == 1
assert parts[0].thought_signature == b"sig-123"
assert parts[0].function_call is not None
assert parts[0].function_call.id == "call-1"
assert parts[0].function_call.name == "get_weather"
assert parts[0].function_call.args == {"location": "Paris"}
# code execution parts
async def test_executable_code_part_is_included_as_text() -> None:
"""executable_code parts are surfaced as text content so callers can see what code was run."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(
return_value=_make_response([
_make_part(executable_code="print(sum(range(10)))"),
_make_part(code_execution_result="45"),
_make_part(text="The sum of 0 through 9 is 45."),
])
)
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Sum 0 to 9")])])
texts = [c.text for c in response.messages[0].contents if c.text]
assert "print(sum(range(10)))" in texts
assert "45" in texts
assert "The sum of 0 through 9 is 45." in texts
async def test_unknown_part_type_is_skipped() -> None:
"""Parts with no recognised field set are silently skipped."""
client, mock = _make_gemini_client()
unknown_part = MagicMock()
unknown_part.thought = False
unknown_part.text = None
unknown_part.function_call = None
unknown_part.function_response = None
unknown_part.executable_code = None
unknown_part.code_execution_result = None
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([unknown_part, _make_part(text="Hi")]))
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert len(response.messages[0].contents) == 1
assert response.messages[0].text == "Hi"
async def test_empty_executable_code_part_is_skipped() -> None:
"""executable_code parts with no code string produce no Content entry."""
client, mock = _make_gemini_client()
mock_part = MagicMock()
mock_part.text = None
mock_part.thought = False
mock_part.function_call = None
mock_part.function_response = None
mock_part.code_execution_result = None
mock_part.executable_code = MagicMock()
mock_part.executable_code.code = ""
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([mock_part, _make_part(text="Done.")]))
response = await client.get_response(messages=[Message(role="user", contents=[Content.from_text("Hi")])])
assert len(response.messages[0].contents) == 1
assert response.messages[0].text == "Done."
# generation config options
async def test_prepare_config_temperature() -> None:
"""Forwards the temperature option to GenerateContentConfig.temperature."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"temperature": 0.3},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.temperature == 0.3
async def test_prepare_config_max_tokens() -> None:
"""Forwards max_tokens to GenerateContentConfig.max_output_tokens."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"max_tokens": 512},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.max_output_tokens == 512
async def test_prepare_config_top_p_and_top_k() -> None:
"""Forwards top_p and top_k to their respective GenerateContentConfig fields."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"top_p": 0.9, "top_k": 40},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.top_p == 0.9
assert config.top_k == 40
async def test_prepare_config_stop_sequences() -> None:
"""Forwards the stop option to GenerateContentConfig.stop_sequences."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"stop": ["END", "STOP"]},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.stop_sequences == ["END", "STOP"]
async def test_prepare_config_seed() -> None:
"""Forwards the seed option to GenerateContentConfig.seed for reproducible outputs."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"seed": 42},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.seed == 42
async def test_prepare_config_frequency_and_presence_penalty() -> None:
"""Forwards frequency_penalty and presence_penalty to their GenerateContentConfig equivalents."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"frequency_penalty": 0.5, "presence_penalty": 0.2},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.frequency_penalty == 0.5
assert config.presence_penalty == 0.2
async def test_prepare_config_unknown_key_is_forwarded() -> None:
"""Keys absent from _OPTION_EXCLUDE_KEYS and _OPTION_TRANSLATIONS are forwarded as-is."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
with patch("agent_framework_gemini._chat_client.types.GenerateContentConfig") as mock_config:
mock_config.return_value = MagicMock()
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options=cast(Any, {"some_future_param": "value"}),
)
assert mock_config.call_args.kwargs.get("some_future_param") == "value"
async def test_prepare_config_consumed_keys_are_excluded() -> None:
"""Keys consumed upstream (model, instructions) are not forwarded to GenerateContentConfig."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
with patch("agent_framework_gemini._chat_client.types.GenerateContentConfig") as mock_config:
mock_config.return_value = MagicMock()
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"model": "gemini-2.5-pro", "instructions": "Be helpful."},
)
kwargs = mock_config.call_args.kwargs
assert "model" not in kwargs
assert "instructions" not in kwargs
# thinking config
async def test_thinking_config_budget() -> None:
"""Passes thinking_budget through to GenerateContentConfig.thinking_config."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
tc: ThinkingConfig = {"thinking_budget": 1024}
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"thinking_config": tc},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert isinstance(config.thinking_config, types.ThinkingConfig)
assert config.thinking_config.thinking_budget == 1024
async def test_thinking_config_level() -> None:
"""Passes thinking_level through to GenerateContentConfig.thinking_config."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="Hi")]))
tc: ThinkingConfig = {"thinking_level": types.ThinkingLevel.HIGH}
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"thinking_config": tc},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert isinstance(config.thinking_config, types.ThinkingConfig)
assert config.thinking_config.thinking_level == types.ThinkingLevel.HIGH
# structured output
async def test_response_format_sets_json_mime_type() -> None:
"""Sets response_mime_type to application/json when response_format is given."""
from pydantic import BaseModel
class Reply(BaseModel):
text: str
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="{}")]))
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"response_format": Reply},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.response_mime_type == "application/json"
async def test_response_format_populates_value_on_chat_response() -> None:
"""When response_format is a Pydantic model, ChatResponse.value must be parsed from the response text."""
from pydantic import BaseModel
class Reply(BaseModel):
text: str
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text='{"text": "hello"}')]))
response = await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"response_format": Reply},
)
assert response.value == Reply(text="hello")
async def test_response_format_mapping_populates_value_on_chat_response() -> None:
"""When response_format is a JSON schema mapping, ChatResponse.value must parse the response text."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text='{"text": "hello"}')]))
schema = {"type": "object", "properties": {"text": {"type": "string"}}}
response = await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"response_format": schema},
)
assert response.value == {"text": "hello"}
async def test_response_schema_added_to_config() -> None:
"""Sets both response_mime_type and the raw schema on the config when response_schema is given."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text="{}")]))
schema = {"type": "object", "properties": {"name": {"type": "string"}}}
await client.get_response(
messages=[Message(role="user", contents=[Content.from_text("Hi")])],
options={"response_schema": schema},
)
config: types.GenerateContentConfig = mock.aio.models.generate_content.call_args.kwargs["config"]
assert config.response_mime_type == "application/json"
assert config.response_schema == schema
async def test_response_format_raw_json_schema_added_to_config() -> None:
"""For declarative outputSchema, response_format may already be a raw JSON schema mapping."""
client, mock = _make_gemini_client()
mock.aio.models.generate_content = AsyncMock(return_value=_make_response([_make_part(text='{"answer": "hello"}')]))