-
Notifications
You must be signed in to change notification settings - Fork 852
Expand file tree
/
Copy pathtest_client_initialization.py
More file actions
1738 lines (1400 loc) · 55.7 KB
/
test_client_initialization.py
File metadata and controls
1738 lines (1400 loc) · 55.7 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 2025 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.
#
"""Tests for client initialization."""
import asyncio
import concurrent.futures
import logging
import os
import requests
import ssl
from unittest import mock
import certifi
import google.auth
from google.auth import credentials
import httpx
import pytest
from ... import _api_client as api_client
from ... import _base_url as base_url
from ... import _replay_api_client as replay_api_client
from ... import Client
from ... import types
try:
import aiohttp
AIOHTTP_NOT_INSTALLED = False
except ImportError:
AIOHTTP_NOT_INSTALLED = True
aiohttp = mock.MagicMock()
requires_aiohttp = pytest.mark.skipif(
AIOHTTP_NOT_INSTALLED, reason="aiohttp is not installed, skipping test."
)
@pytest.fixture(autouse=True)
def reset_has_aiohttp():
yield
api_client.has_aiohttp = False
def test_ml_dev_from_gemini_env_only(monkeypatch):
api_key = "gemini_api_key"
monkeypatch.setenv("GEMINI_API_KEY", api_key)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
client = Client()
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_ml_dev_from_gemini_env_with_google_env_empty(monkeypatch):
api_key = "gemini_api_key"
monkeypatch.setenv("GEMINI_API_KEY", api_key)
monkeypatch.setenv("GOOGLE_API_KEY", "")
client = Client()
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_ml_dev_from_google_env_only(monkeypatch):
api_key = "google_api_key"
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
client = Client()
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_ml_dev_both_env_key_set(monkeypatch, caplog):
caplog.set_level(logging.DEBUG, logger="google_genai._api_client")
google_api_key = "google_api_key"
gemini_api_key = "gemini_api_key"
monkeypatch.setenv("GOOGLE_API_KEY", google_api_key)
monkeypatch.setenv("GEMINI_API_KEY", gemini_api_key)
client = Client()
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == google_api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
assert (
"Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."
in caplog.text
)
def test_api_key_with_new_line(monkeypatch, caplog):
caplog.set_level(logging.DEBUG, logger="google_genai._api_client")
api_key = "gemini_api_key\r\n"
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
client = Client()
assert client.models._api_client.api_key == "gemini_api_key"
def test_ml_dev_from_constructor():
api_key = "google_api_key"
client = Client(api_key=api_key)
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
def test_constructor_with_http_options():
mldev_http_options = {
"api_version": "v1main",
"base_url": "https://placeholder-fake-url.com/",
"headers": {"X-Custom-Header": "custom_value_mldev"},
"timeout": 10000,
}
vertexai_http_options = {
"api_version": "v1",
"base_url": (
"https://{self.location}-aiplatform.googleapis.com/{{api_version}}/"
),
"headers": {"X-Custom-Header": "custom_value_vertexai"},
"timeout": 11000,
}
mldev_client = Client(
api_key="google_api_key", http_options=mldev_http_options
)
assert not mldev_client.models._api_client.vertexai
assert (
mldev_client.models._api_client.get_read_only_http_options()["base_url"]
== "https://placeholder-fake-url.com/"
)
assert (
mldev_client.models._api_client.get_read_only_http_options()[
"api_version"
]
== "v1main"
)
assert (
mldev_client.models._api_client.get_read_only_http_options()["headers"][
"X-Custom-Header"
]
== "custom_value_mldev"
)
assert (
mldev_client.models._api_client.get_read_only_http_options()["timeout"]
== 10000
)
vertexai_client = Client(
vertexai=True,
project="fake_project_id",
location="fake-location",
http_options=vertexai_http_options,
)
assert vertexai_client.models._api_client.vertexai
assert (
vertexai_client.models._api_client.get_read_only_http_options()[
"base_url"
]
== "https://{self.location}-aiplatform.googleapis.com/{{api_version}}/"
)
assert (
vertexai_client.models._api_client.get_read_only_http_options()[
"api_version"
]
== "v1"
)
assert (
vertexai_client.models._api_client.get_read_only_http_options()[
"headers"
]["X-Custom-Header"]
== "custom_value_vertexai"
)
assert (
vertexai_client.models._api_client.get_read_only_http_options()["timeout"]
== 11000
)
def test_constructor_with_invalid_http_options_key():
mldev_http_options = {
"invalid_version_key": "v1",
"base_url": "https://placeholder-fake-url.com/",
"headers": {"X-Custom-Header": "custom_value"},
}
vertexai_http_options = {
"api_version": "v1",
"base_url": (
"https://{self.location}-aiplatform.googleapis.com/{{api_version}}/"
),
"invalid_header_key": {"X-Custom-Header": "custom_value"},
}
# Expect value error when HTTPOptions is provided as a dict and contains
# an invalid key.
try:
_ = Client(api_key="google_api_key", http_options=mldev_http_options)
except Exception as e:
assert isinstance(e, ValueError)
assert "invalid_version_key" in str(e)
# Expect value error when HTTPOptions is provided as a dict and contains
# an invalid key.
try:
_ = Client(
vertexai=True,
project="fake_project_id",
location="fake-location",
http_options=vertexai_http_options,
)
except Exception as e:
assert isinstance(e, ValueError)
assert "invalid_header_key" in str(e)
def test_constructor_with_http_options_as_pydantic_type():
mldev_http_options = types.HttpOptions(
api_version="v1",
base_url="https://placeholder-fake-url.com/",
headers={"X-Custom-Header": "custom_value"},
)
vertexai_http_options = types.HttpOptions(
api_version="v1",
base_url=(
"https://{self.location}-aiplatform.googleapis.com/{{api_version}}/"
),
headers={"X-Custom-Header": "custom_value"},
)
# Test http_options for mldev client.
mldev_client = Client(
api_key="google_api_key", http_options=mldev_http_options
)
assert not mldev_client.models._api_client.vertexai
assert (
mldev_client.models._api_client.get_read_only_http_options()["base_url"]
== mldev_http_options.base_url
)
assert (
mldev_client.models._api_client.get_read_only_http_options()[
"api_version"
]
== mldev_http_options.api_version
)
assert (
mldev_client.models._api_client.get_read_only_http_options()["headers"][
"X-Custom-Header"
]
== mldev_http_options.headers["X-Custom-Header"]
)
# Test http_options for vertexai client.
vertexai_client = Client(
vertexai=True,
project="fake_project_id",
location="fake-location",
http_options=vertexai_http_options,
)
assert vertexai_client.models._api_client.vertexai
assert (
vertexai_client.models._api_client.get_read_only_http_options()[
"base_url"
]
== vertexai_http_options.base_url
)
assert (
vertexai_client.models._api_client.get_read_only_http_options()[
"api_version"
]
== vertexai_http_options.api_version
)
assert (
vertexai_client.models._api_client.get_read_only_http_options()[
"headers"
]["X-Custom-Header"]
== vertexai_http_options.headers["X-Custom-Header"]
)
def test_vertexai_from_env_1(monkeypatch):
project_id = "fake_project_id"
location = "fake-location"
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "1")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
client = Client()
assert client.models._api_client.vertexai
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
def test_vertexai_from_env_true(monkeypatch):
project_id = "fake_project_id"
location = "fake-location"
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "true")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
client = Client()
assert client.models._api_client.vertexai
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
def test_vertexai_from_constructor():
project_id = "fake_project_id"
location = "fake-location"
client = Client(
vertexai=True,
project=project_id,
location=location,
)
assert client.models._api_client.vertexai
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_invalid_vertexai_constructor_empty(monkeypatch):
with pytest.raises(ValueError):
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_API_KEY", "")
monkeypatch.setenv("GEMINI_API_KEY", "")
def mock_auth_default(scopes=None):
return None, None
monkeypatch.setattr(google.auth, "default", mock_auth_default)
Client(vertexai=True)
def test_vertexai_constructor_empty_base_url_override(monkeypatch):
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_API_KEY", "")
monkeypatch.setenv("GEMINI_API_KEY", "")
def mock_auth_default(scopes=None):
return None, None
monkeypatch.setattr(google.auth, "default", mock_auth_default)
# Including a base_url override skips the check for having proj/location or
# api_key set.
client = Client(vertexai=True, http_options={"base_url": "https://override.com/"})
assert client.models._api_client.location is None
def test_invalid_mldev_constructor_empty(monkeypatch):
with pytest.raises(ValueError):
monkeypatch.setenv("GOOGLE_API_KEY", "")
monkeypatch.setenv("GEMINI_API_KEY", "")
Client()
def test_invalid_vertexai_constructor1():
project_id = "fake_project_id"
location = "fake-location"
api_key = "fake-api_key"
try:
Client(
vertexai=True,
project=project_id,
location=location,
api_key=api_key,
)
except Exception as e:
assert isinstance(e, ValueError)
def test_invalid_vertexai_constructor2():
creds = credentials.AnonymousCredentials()
api_key = "fake-api_key"
with pytest.raises(ValueError):
Client(
vertexai=True,
credentials=creds,
api_key=api_key,
)
def test_vertexai_default_location_to_global(monkeypatch):
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
project_id = "fake_project_id"
client = Client(vertexai=True, project=project_id)
assert client.models._api_client.location == "global"
def test_vertexai_default_location_to_global_with_credentials(monkeypatch):
# Test case 1: When credentials are provided with project but no location
creds = credentials.AnonymousCredentials()
project_id = "fake_project_id"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
m.setenv("GOOGLE_API_KEY", "")
client = Client(vertexai=True, credentials=creds, project=project_id)
assert client.models._api_client.location == "global"
assert client.models._api_client.project == project_id
def test_vertexai_default_location_to_global_with_explicit_project_and_env_apikey(
monkeypatch,
):
# Test case 2: When explicit project is provided and env api_key exists
project_id = "explicit_project_id"
api_key = "env_api_key"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
m.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
m.setenv("GOOGLE_API_KEY", api_key)
client = Client(vertexai=True, project=project_id)
# Explicit project takes precedence over implicit api_key
assert client.models._api_client.location == "global"
assert client.models._api_client.project == project_id
assert not client.models._api_client.api_key
def test_vertexai_default_location_to_global_with_vertexai_base_url(
monkeypatch,
):
# Test case 4: When project and vertex base url are set
project_id = "env_project_id"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
m.setenv("GOOGLE_CLOUD_PROJECT", project_id)
client = Client(
vertexai=True,
http_options={'base_url': 'https://fake-url.googleapis.com'},
)
# Implicit project takes precedence over implicit api_key
assert client.models._api_client.location == "global"
assert client.models._api_client.project == project_id
def test_vertexai_default_location_to_global_with_arbitrary_base_url(
monkeypatch,
):
# Test case 5: When project and arbitrary base url (proxy) are set
project_id = "env_project_id"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
m.setenv("GOOGLE_CLOUD_PROJECT", project_id)
client = Client(
vertexai=True,
http_options={'base_url': 'https://fake-url.com'},
)
# Implicit project takes precedence over implicit api_key
assert not client.models._api_client.location
assert not client.models._api_client.project
def test_vertexai_default_location_to_global_with_env_project_and_env_apikey(
monkeypatch,
):
# Test case 3: When env project and env api_key both exist
project_id = "env_project_id"
api_key = "env_api_key"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
m.setenv("GOOGLE_CLOUD_PROJECT", project_id)
m.setenv("GOOGLE_API_KEY", api_key)
client = Client(vertexai=True)
# Implicit project takes precedence over implicit api_key
assert client.models._api_client.location == "global"
assert client.models._api_client.project == project_id
assert not client.models._api_client.api_key
def test_vertexai_no_default_location_when_location_explicitly_set(monkeypatch):
# Verify that location is NOT defaulted to global when explicitly set
project_id = "fake_project_id"
location = "us-central1"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
client = Client(vertexai=True, project=project_id, location=location)
assert client.models._api_client.location == location
assert client.models._api_client.project == project_id
def test_vertexai_no_default_location_when_env_location_set(monkeypatch):
# Verify that location is NOT defaulted to global when set via environment
project_id = "fake_project_id"
location = "us-west1"
with monkeypatch.context() as m:
m.setenv("GOOGLE_CLOUD_LOCATION", location)
m.setenv("GOOGLE_CLOUD_PROJECT", project_id)
client = Client(vertexai=True)
assert client.models._api_client.location == location
assert client.models._api_client.project == project_id
def test_vertexai_no_default_location_with_apikey_only(monkeypatch):
# Verify that location is NOT set when using API key mode (no project)
api_key = "vertexai_api_key"
with monkeypatch.context() as m:
m.delenv("GOOGLE_CLOUD_LOCATION", raising=False)
m.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
m.setenv("GOOGLE_API_KEY", "")
client = Client(vertexai=True, api_key=api_key)
assert not client.models._api_client.location
assert not client.models._api_client.project
assert client.models._api_client.api_key == api_key
def test_vertexai_explicit_credentials(monkeypatch):
creds = credentials.AnonymousCredentials()
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "fake_project_id")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "fake-location")
monkeypatch.setenv("GOOGLE_API_KEY", "env_api_key")
client = Client(
vertexai=True,
credentials=creds
)
assert client.models._api_client.vertexai
assert client.models._api_client.project
assert client.models._api_client.location
assert not client.models._api_client.api_key
assert client.models._api_client._credentials is creds
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_explicit_arg_precedence1(monkeypatch):
project_id = "constructor_project_id"
location = "constructor-location"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "env_project_id")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "env_location")
monkeypatch.setenv("GOOGLE_API_KEY", "")
client = Client(
vertexai=True,
project=project_id,
location=location,
)
assert client.models._api_client.vertexai
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
assert not client.models._api_client.api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_explicit_arg_precedence2(monkeypatch):
api_key = "constructor_apikey"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_API_KEY", "env_api_key")
client = Client(
vertexai=True,
api_key=api_key,
)
assert client.models._api_client.vertexai
assert not client.models._api_client.project
assert not client.models._api_client.location
assert client.models._api_client.api_key == api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_invalid_mldev_constructor():
project_id = "fake_project_id"
location = "fake-location"
api_key = "fake-api_key"
try:
Client(
project=project_id,
location=location,
api_key=api_key,
)
except Exception as e:
assert isinstance(e, ValueError)
def test_mldev_explicit_arg_precedence(monkeypatch, caplog):
caplog.set_level(logging.DEBUG, logger="google_genai._api_client")
api_key = "constructor_api_key"
monkeypatch.setenv("GOOGLE_API_KEY", "google_env_api_key")
monkeypatch.setenv("GEMINI_API_KEY", "gemini_env_api_key")
client = Client(api_key=api_key)
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert isinstance(client.models._api_client, api_client.BaseApiClient)
assert (
"Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."
in caplog.text
)
def test_replay_client_ml_dev_from_env(monkeypatch, use_vertex: bool):
api_key = "google_api_key"
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "replay")
api_type = "vertex" if use_vertex else "mldev"
monkeypatch.setenv("GOOGLE_GENAI_REPLAY_ID", "test_replay_id." + api_type)
monkeypatch.setenv("GOOGLE_GENAI_REPLAYS_DIRECTORY", "test_replay_data")
client = Client()
assert not client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert isinstance(
client.models._api_client, replay_api_client.ReplayApiClient
)
def test_replay_client_vertexai_from_env(monkeypatch, use_vertex: bool):
project_id = "fake_project_id"
location = "fake-location"
monkeypatch.setenv("GOOGLE_GENAI_USE_VERTEXAI", "1")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "replay")
api_type = "vertex" if use_vertex else "mldev"
monkeypatch.setenv("GOOGLE_GENAI_REPLAY_ID", "test_replay_id." + api_type)
monkeypatch.setenv("GOOGLE_GENAI_REPLAYS_DIRECTORY", "test_replay_data")
client = Client()
assert client.models._api_client.vertexai
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
assert isinstance(
client.models._api_client, replay_api_client.ReplayApiClient
)
def test_change_client_mode_from_env(monkeypatch, use_vertex: bool):
api_key = "google_api_key"
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "replay")
client1 = Client()
assert isinstance(
client1.models._api_client, replay_api_client.ReplayApiClient
)
monkeypatch.setenv("GOOGLE_GENAI_CLIENT_MODE", "")
client2 = Client()
assert isinstance(client2.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_from_constructor(monkeypatch):
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
# Due to proj/location taking precedence, need to clear proj/location env
# variables.
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
client = Client(api_key=api_key, vertexai=True)
assert client.models._api_client.vertexai
assert not client.models._api_client.project
assert not client.models._api_client.location
assert client.models._api_client.api_key == api_key
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_from_env_google_api_key_only(monkeypatch):
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
monkeypatch.delenv("GEMINI_API_KEY", raising=False)
# Due to proj/location taking precedence, need to clear proj/location env
# variables.
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
client = Client(vertexai=True)
assert client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert not client.models._api_client.project
assert not client.models._api_client.location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_from_env_gemini_api_key_only(monkeypatch):
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
monkeypatch.setenv("GEMINI_API_KEY", api_key)
monkeypatch.delenv("GOOGLE_API_KEY", raising=False)
# Due to proj/location taking precedence, need to clear proj/location env
# variables.
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
client = Client(vertexai=True)
assert client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert not client.models._api_client.project
assert not client.models._api_client.location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_from_env_gemini_api_key_with_google_api_key_empty(
monkeypatch,
):
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
monkeypatch.setenv("GEMINI_API_KEY", api_key)
monkeypatch.setenv("GOOGLE_API_KEY", "")
# Due to proj/location taking precedence, need to clear proj/location env
# variables.
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
client = Client(vertexai=True)
assert client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert not client.models._api_client.project
assert not client.models._api_client.location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_from_env_both_api_keys(monkeypatch, caplog):
caplog.set_level(logging.DEBUG, logger="google_genai._api_client")
# Vertex AI Express mode uses API key on Vertex AI.
google_api_key = "google_api_key"
gemini_api_key = "vertexai_api_key"
monkeypatch.setenv("GEMINI_API_KEY", gemini_api_key)
monkeypatch.setenv("GOOGLE_API_KEY", google_api_key)
# Due to proj/location taking precedence, need to clear proj/location env
# variables.
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
client = Client(vertexai=True)
assert client.models._api_client.vertexai
assert client.models._api_client.api_key == google_api_key
assert not client.models._api_client.project
assert not client.models._api_client.location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
assert (
"Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."
in caplog.text
)
def test_vertexai_apikey_invalid_constructor1():
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
project_id = "fake_project_id"
location = "fake-location"
with pytest.raises(ValueError):
Client(
api_key=api_key,
project=project_id,
location=location,
vertexai=True,
)
def test_vertexai_apikey_combo1(monkeypatch):
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
project_id = "fake_project_id"
location = "fake-location"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
monkeypatch.setenv("GOOGLE_API_KEY", "")
# Explicit api_key takes precedence over implicit project/location.
client = Client(vertexai=True, api_key=api_key)
assert client.models._api_client.vertexai
assert client.models._api_client.api_key == api_key
assert not client.models._api_client.project
assert not client.models._api_client.location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_combo2(monkeypatch):
# Vertex AI Express mode uses API key on Vertex AI.
api_key = "vertexai_api_key"
project_id = "fake_project_id"
location = "fake-location"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "")
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "")
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
# Explicit project/location takes precedence over implicit api_key.
client = Client(vertexai=True, project=project_id, location=location)
assert client.models._api_client.vertexai
assert not client.models._api_client.api_key
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_apikey_combo3(monkeypatch):
# Vertex AI Express mode uses API key on Vertex AI.
project_id = "fake_project_id"
location = "fake-location"
api_key = "vertexai_api_key"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
monkeypatch.setenv("GOOGLE_API_KEY", api_key)
# Implicit project/location takes precedence over implicit api_key.
client = Client(vertexai=True)
assert client.models._api_client.vertexai
assert not client.models._api_client.api_key
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
assert "aiplatform" in client._api_client._http_options.base_url
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_vertexai_global_endpoint(monkeypatch):
# Vertex AI uses global endpoint when location is global.
project_id = "fake_project_id"
location = "global"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
client = Client(vertexai=True, location=location)
assert client.models._api_client.vertexai
assert client.models._api_client.project == project_id
assert client.models._api_client.location == location
assert client.models._api_client._http_options.base_url == (
"https://aiplatform.googleapis.com/"
)
assert isinstance(client.models._api_client, api_client.BaseApiClient)
def test_client_logs_to_logger_instance(monkeypatch, caplog):
caplog.set_level(logging.DEBUG, logger="google_genai._api_client")
project_id = "fake_project_id"
location = "fake-location"
api_key = "vertexai_api_key"
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", project_id)
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", location)
_ = Client(vertexai=True, api_key=api_key)
assert "INFO" in caplog.text
assert (
"The user provided Vertex AI API key will take precedence" in caplog.text
)
def test_client_ssl_context_implicit_initialization():
client_args, async_client_args = (
api_client.BaseApiClient._ensure_httpx_ssl_ctx(types.HttpOptions())
)
assert client_args["verify"]
assert isinstance(client_args["verify"], ssl.SSLContext)
try:
import aiohttp # pylint: disable=g-import-not-at-top
async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx(
types.HttpOptions()
)
assert async_client_args["ssl"]
assert isinstance(async_client_args["ssl"], ssl.SSLContext)
except ImportError:
assert async_client_args["verify"]
assert isinstance(async_client_args["verify"], ssl.SSLContext)
def test_client_ssl_context_explicit_initialization_same_args():
ctx = ssl.create_default_context(
cafile=os.environ.get("SSL_CERT_FILE", certifi.where()),
capath=os.environ.get("SSL_CERT_DIR"),
)
options = types.HttpOptions(
client_args={"verify": ctx}, async_client_args={"verify": ctx}
)
client_args, async_client_args = (
api_client.BaseApiClient._ensure_httpx_ssl_ctx(options)
)
assert client_args["verify"] == ctx
try:
import aiohttp # pylint: disable=g-import-not-at-top
async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx(
options
)
assert async_client_args["ssl"]
assert isinstance(async_client_args["ssl"], ssl.SSLContext)
except ImportError:
assert async_client_args["verify"]
assert isinstance(async_client_args["verify"], ssl.SSLContext)
def test_client_ssl_context_explicit_initialization_separate_args():
ctx = ssl.create_default_context(
cafile=os.environ.get("SSL_CERT_FILE", certifi.where()),
capath=os.environ.get("SSL_CERT_DIR"),
)
async_ctx = ssl.create_default_context(
cafile=os.environ.get("SSL_CERT_FILE", certifi.where()),
capath=os.environ.get("SSL_CERT_DIR"),
)
options = types.HttpOptions(
client_args={"verify": ctx}, async_client_args={"verify": async_ctx}
)
client_args, async_client_args = (
api_client.BaseApiClient._ensure_httpx_ssl_ctx(options)
)
assert client_args["verify"] == ctx
try:
import aiohttp # pylint: disable=g-import-not-at-top
async_client_args = api_client.BaseApiClient._ensure_aiohttp_ssl_ctx(
options
)
assert async_client_args["ssl"]
assert isinstance(async_client_args["ssl"], ssl.SSLContext)
except ImportError:
assert async_client_args["verify"]
assert isinstance(async_client_args["verify"], ssl.SSLContext)
def test_client_ssl_context_explicit_initialization_sync_args():
ctx = ssl.create_default_context(
cafile=os.environ.get("SSL_CERT_FILE", certifi.where()),
capath=os.environ.get("SSL_CERT_DIR"),
)
options = types.HttpOptions(client_args={"verify": ctx})
client_args, async_client_args = (
api_client.BaseApiClient._ensure_httpx_ssl_ctx(options)
)