-
Notifications
You must be signed in to change notification settings - Fork 813
Expand file tree
/
Copy path_api_client.py
More file actions
2153 lines (1916 loc) · 74.2 KB
/
_api_client.py
File metadata and controls
2153 lines (1916 loc) · 74.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Base client for calling HTTP APIs sending and receiving JSON.
The BaseApiClient is intended to be a private module and is subject to change.
"""
import asyncio
from collections.abc import Generator
import copy
from dataclasses import dataclass
import inspect
import io
import json
import logging
import math
import os
import random
import ssl
import sys
import threading
import time
from typing import Any, AsyncIterator, Iterator, Optional, TYPE_CHECKING, Tuple, Union
from urllib.parse import urlparse
from urllib.parse import urlunparse
import warnings
import anyio
import certifi
import google.auth
import google.auth.credentials
from google.auth.credentials import Credentials
from google.auth.transport import mtls
from google.auth.transport.requests import AuthorizedSession
import httpx
from pydantic import BaseModel
from pydantic import ValidationError
import requests
from requests.structures import CaseInsensitiveDict
import tenacity
from . import _common
from . import errors
from . import version
from .types import HttpOptions
from .types import HttpOptionsOrDict
from .types import HttpResponse as SdkHttpResponse
from .types import HttpRetryOptions
from .types import ResourceScope
try:
from websockets.asyncio.client import connect as ws_connect
except ModuleNotFoundError:
# This try/except is for TAP, mypy complains about it which is why we have the type: ignore
from websockets.client import connect as ws_connect # type: ignore
has_aiohttp = False
try:
import aiohttp
has_aiohttp = True
except ImportError:
pass
if TYPE_CHECKING:
from multidict import CIMultiDictProxy
from google.auth.aio.transport.sessions import AsyncAuthorizedSession
logger = logging.getLogger('google_genai._api_client')
CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB chunk size
READ_BUFFER_SIZE = 2**22
MAX_RETRY_COUNT = 3
INITIAL_RETRY_DELAY = 1 # second
DELAY_MULTIPLIER = 2
class EphemeralTokenAPIKeyError(ValueError):
"""Error raised when the API key is invalid."""
# This method checks for the API key in the environment variables. Google API
# key is precedenced over Gemini API key.
def get_env_api_key() -> Optional[str]:
"""Gets the API key from environment variables, prioritizing GOOGLE_API_KEY.
Returns:
The API key string if found, otherwise None. Empty string is considered
invalid.
"""
env_google_api_key = os.environ.get('GOOGLE_API_KEY', None)
env_gemini_api_key = os.environ.get('GEMINI_API_KEY', None)
if env_google_api_key and env_gemini_api_key:
logger.warning(
'Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.'
)
return env_google_api_key or env_gemini_api_key or None
def append_library_version_headers(headers: dict[str, str]) -> None:
"""Appends the telemetry header to the headers dict."""
library_label = f'google-genai-sdk/{version.__version__}'
language_label = 'gl-python/' + sys.version.split()[0]
version_header_value = f'{library_label} {language_label}'
if (
'user-agent' in headers
and version_header_value not in headers['user-agent']
):
headers['user-agent'] = f'{version_header_value} ' + headers['user-agent']
elif 'user-agent' not in headers:
headers['user-agent'] = version_header_value
if (
'x-goog-api-client' in headers
and version_header_value not in headers['x-goog-api-client']
):
headers['x-goog-api-client'] = (
f'{version_header_value} ' + headers['x-goog-api-client']
)
elif 'x-goog-api-client' not in headers:
headers['x-goog-api-client'] = version_header_value
def patch_http_options(
options: HttpOptions, patch_options: HttpOptions
) -> HttpOptions:
copy_option = options.model_copy()
options_headers = copy_option.headers or {}
patch_options_headers = patch_options.headers or {}
copy_option.headers = {
**options_headers,
**patch_options_headers,
}
http_options_keys = HttpOptions.model_fields.keys()
for key in http_options_keys:
if key == 'headers':
continue
patch_value = getattr(patch_options, key, None)
if patch_value is not None:
setattr(copy_option, key, patch_value)
else:
setattr(copy_option, key, getattr(options, key))
if copy_option.headers is not None:
append_library_version_headers(copy_option.headers)
return copy_option
def populate_server_timeout_header(
headers: dict[str, str], timeout_in_seconds: Optional[Union[float, int]]
) -> None:
"""Populates the server timeout header in the headers dict."""
if timeout_in_seconds and 'X-Server-Timeout' not in headers:
headers['X-Server-Timeout'] = str(math.ceil(timeout_in_seconds))
def join_url_path(base_url: str, path: str) -> str:
parsed_base = urlparse(base_url)
base_path = (
parsed_base.path[:-1]
if parsed_base.path.endswith('/')
else parsed_base.path
)
path = path[1:] if path.startswith('/') else path
return urlunparse(parsed_base._replace(path=base_path + '/' + path))
def load_auth(*, project: Union[str, None]) -> Tuple[Credentials, str]:
"""Loads google auth credentials and project id."""
credentials, loaded_project_id = google.auth.default( # type: ignore[no-untyped-call]
scopes=['https://www.googleapis.com/auth/cloud-platform'],
)
if not project:
project = loaded_project_id
if not project:
raise ValueError(
'Could not resolve project using application default credentials.'
)
return credentials, project
def refresh_auth(credentials: Credentials) -> Credentials:
from google.auth.transport.requests import Request
credentials.refresh(Request()) # type: ignore[no-untyped-call]
return credentials
def get_timeout_in_seconds(
timeout: Optional[Union[float, int]],
) -> Optional[float]:
"""Converts the timeout to seconds."""
if timeout:
# HttpOptions.timeout is in milliseconds. But httpx.Client.request()
# expects seconds.
timeout_in_seconds = timeout / 1000.0
else:
timeout_in_seconds = None
return timeout_in_seconds
@dataclass
class HttpRequest:
headers: dict[str, str]
url: str
method: str
data: Union[dict[str, object], bytes]
timeout: Optional[float] = None
class HttpResponse:
def __init__(
self,
headers: Union[
dict[str, str],
httpx.Headers,
'CIMultiDictProxy[str]',
CaseInsensitiveDict,
],
response_stream: Union[Any, str] = None,
byte_stream: Union[Any, bytes] = None,
):
if isinstance(headers, dict):
self.headers = headers
elif isinstance(headers, httpx.Headers):
self.headers = {
key: ', '.join(headers.get_list(key)) for key in headers.keys()
}
elif isinstance(headers, CaseInsensitiveDict):
self.headers = {key: value for key, value in headers.items()}
elif type(headers).__name__ == 'CIMultiDictProxy':
self.headers = {
key: ', '.join(headers.getall(key)) for key in headers.keys()
}
self.status_code: int = 200
self.response_stream = response_stream
self.byte_stream = byte_stream
# Async iterator for async streaming.
def __aiter__(self) -> 'HttpResponse':
self.segment_iterator = self.async_segments()
return self
async def __anext__(self) -> Any:
try:
return await self.segment_iterator.__anext__()
except StopIteration:
raise StopAsyncIteration
@property
def json(self) -> Any:
# Handle case where response_stream is not a list (e.g., aiohttp.ClientResponse)
# This can happen when the API returns an error and the response object
# is passed directly instead of being wrapped in a list.
# See: https://github.com/googleapis/python-genai/issues/1897
if not isinstance(self.response_stream, list):
return None
if not self.response_stream or not self.response_stream[0]: # Empty response
return ''
return self._load_json_from_response(self.response_stream[0])
def segments(self) -> Generator[Any, None, None]:
if isinstance(self.response_stream, list):
# list of objects retrieved from replay or from non-streaming API.
for chunk in self.response_stream:
yield self._load_json_from_response(chunk) if chunk else {}
elif self.response_stream is None:
yield from []
else:
# Iterator of objects retrieved from the API.
for chunk in self._iter_response_stream():
yield self._load_json_from_response(chunk)
async def async_segments(self) -> AsyncIterator[Any]:
if isinstance(self.response_stream, list):
# list of objects retrieved from replay or from non-streaming API.
for chunk in self.response_stream:
yield self._load_json_from_response(chunk) if chunk else {}
elif self.response_stream is None:
async for c in []: # type: ignore[attr-defined]
yield c
else:
# Iterator of objects retrieved from the API.
async for chunk in self._aiter_response_stream():
yield self._load_json_from_response(chunk)
def byte_segments(self) -> Generator[Union[bytes, Any], None, None]:
if isinstance(self.byte_stream, list):
# list of objects retrieved from replay or from non-streaming API.
yield from self.byte_stream
elif self.byte_stream is None:
yield from []
else:
raise ValueError(
'Byte segments are not supported for streaming responses.'
)
def _copy_to_dict(self, response_payload: dict[str, object]) -> None:
# Cannot pickle 'generator' object.
delattr(self, 'segment_iterator')
for attribute in dir(self):
response_payload[attribute] = copy.deepcopy(getattr(self, attribute))
def _iter_response_stream(self) -> Iterator[str]:
"""Iterates over chunks retrieved from the API."""
if not (
isinstance(self.response_stream, httpx.Response)
or isinstance(self.response_stream, requests.Response)
):
raise TypeError(
'Expected self.response_stream to be an httpx.Response object, '
f'but got {type(self.response_stream).__name__}.'
)
chunk = ''
balance = 0
if isinstance(self.response_stream, httpx.Response):
response_stream = self.response_stream.iter_lines()
else:
response_stream = self.response_stream.iter_lines(decode_unicode=True)
for line in response_stream:
if not line:
continue
# In streaming mode, the response of JSON is prefixed with "data: " which
# we must strip before parsing.
if line.startswith('data: '):
yield line[len('data: '):]
continue
# When API returns an error message, it comes line by line. So we buffer
# the lines until a complete JSON string is read. A complete JSON string
# is found when the balance is 0.
for c in line:
if c == '{':
balance += 1
elif c == '}':
balance -= 1
chunk += line
if balance == 0:
yield chunk
chunk = ''
# If there is any remaining chunk, yield it.
if chunk:
yield chunk
async def _aiter_response_stream(self) -> AsyncIterator[str]:
"""Asynchronously iterates over chunks retrieved from the API."""
is_valid_response = isinstance(self.response_stream, httpx.Response) or (
has_aiohttp and isinstance(self.response_stream, aiohttp.ClientResponse)
)
if not is_valid_response:
raise TypeError(
'Expected self.response_stream to be an httpx.Response or'
' aiohttp.ClientResponse object, but got'
f' {type(self.response_stream).__name__}.'
)
chunk = ''
balance = 0
# httpx.Response has a dedicated async line iterator.
if isinstance(self.response_stream, httpx.Response):
try:
async for line in self.response_stream.aiter_lines():
if not line:
continue
# In streaming mode, the response of JSON is prefixed with "data: "
# which we must strip before parsing.
if line.startswith('data: '):
yield line[len('data: '):]
continue
# When API returns an error message, it comes line by line. So we buffer
# the lines until a complete JSON string is read. A complete JSON string
# is found when the balance is 0.
for c in line:
if c == '{':
balance += 1
elif c == '}':
balance -= 1
chunk += line
if balance == 0:
yield chunk
chunk = ''
# If there is any remaining chunk, yield it.
if chunk:
yield chunk
finally:
# Close the response and release the connection.
await self.response_stream.aclose()
# aiohttp.ClientResponse uses a content stream that we read line by line.
elif has_aiohttp and isinstance(
self.response_stream, aiohttp.ClientResponse
):
try:
while True:
# Read a line from the stream. This returns bytes.
line_bytes = await self.response_stream.content.readline()
if not line_bytes:
break
# Decode the bytes and remove trailing whitespace and newlines.
line = line_bytes.decode('utf-8').rstrip()
if not line:
continue
# In streaming mode, the response of JSON is prefixed with "data: "
# which we must strip before parsing.
if line.startswith('data: '):
yield line[len('data: '):]
continue
# When API returns an error message, it comes line by line. So we
# buffer the lines until a complete JSON string is read. A complete
# JSON strings found when the balance is 0.
for c in line:
if c == '{':
balance += 1
elif c == '}':
balance -= 1
chunk += line
if balance == 0:
yield chunk
chunk = ''
# If there is any remaining chunk, yield it.
if chunk:
yield chunk
finally:
# Release the connection back to the pool for potential reuse.
self.response_stream.release()
@classmethod
def _load_json_from_response(cls, response: Any) -> Any:
"""Loads JSON from the response, or raises an error if the parsing fails."""
try:
return json.loads(response)
except json.JSONDecodeError as e:
raise errors.UnknownApiResponseError(
f'Failed to parse response as JSON. Raw response: {response}'
) from e
# Default retry options.
# The config is based on https://cloud.google.com/storage/docs/retry-strategy.
# By default, the client will retry 4 times with approximately 1.0, 2.0, 4.0,
# 8.0 seconds between each attempt.
_RETRY_ATTEMPTS = 5 # including the initial call.
_RETRY_INITIAL_DELAY = 1.0 # seconds
_RETRY_MAX_DELAY = 60.0 # seconds
_RETRY_EXP_BASE = 2
_RETRY_JITTER = 1
_RETRY_HTTP_STATUS_CODES = (
408, # Request timeout.
429, # Too many requests.
500, # Internal server error.
502, # Bad gateway.
503, # Service unavailable.
504, # Gateway timeout
)
def retry_args(options: Optional[HttpRetryOptions]) -> _common.StringDict:
"""Returns the retry args for the given http retry options.
Args:
options: The http retry options to use for the retry configuration. If None,
the 'never retry' stop strategy will be used.
Returns:
The arguments passed to the tenacity.(Async)Retrying constructor.
"""
if options is None:
return {'stop': tenacity.stop_after_attempt(1), 'reraise': True}
if options.attempts == 0:
options.attempts = 1
stop = tenacity.stop_after_attempt(options.attempts or _RETRY_ATTEMPTS)
retriable_codes = options.http_status_codes or _RETRY_HTTP_STATUS_CODES
retry = tenacity.retry_if_exception(
lambda e: isinstance(e, errors.APIError) and e.code in retriable_codes,
)
wait = tenacity.wait_exponential_jitter(
initial=options.initial_delay or _RETRY_INITIAL_DELAY,
max=options.max_delay or _RETRY_MAX_DELAY,
exp_base=options.exp_base or _RETRY_EXP_BASE,
jitter=options.jitter or _RETRY_JITTER,
)
return {
'stop': stop,
'retry': retry,
'reraise': True,
'wait': wait,
'before_sleep': tenacity.before_sleep_log(logger, logging.INFO),
}
class SyncHttpxClient(httpx.Client):
"""Sync httpx client."""
def __init__(self, **kwargs: Any) -> None:
"""Initializes the httpx client."""
kwargs.setdefault('follow_redirects', True)
super().__init__(**kwargs)
def __del__(self) -> None:
"""Closes the httpx client."""
try:
if self.is_closed:
return
except Exception:
pass
try:
self.close()
except Exception:
pass
class AsyncHttpxClient(httpx.AsyncClient):
"""Async httpx client."""
def __init__(self, **kwargs: Any) -> None:
"""Initializes the httpx client."""
kwargs.setdefault('follow_redirects', True)
super().__init__(**kwargs)
def __del__(self) -> None:
try:
if self.is_closed:
return
except Exception:
pass
try:
asyncio.get_running_loop().create_task(self.aclose())
except Exception:
pass
class BaseApiClient:
"""Client for calling HTTP APIs sending and receiving JSON."""
def __init__(
self,
vertexai: Optional[bool] = None,
api_key: Optional[str] = None,
credentials: Optional[google.auth.credentials.Credentials] = None,
project: Optional[str] = None,
location: Optional[str] = None,
http_options: Optional[HttpOptionsOrDict] = None,
):
self.vertexai = vertexai
self.custom_base_url = None
if self.vertexai is None:
if os.environ.get('GOOGLE_GENAI_USE_VERTEXAI', '0').lower() in [
'true',
'1',
]:
self.vertexai = True
# Validate explicitly set initializer values.
if (project or location) and api_key:
# API cannot consume both project/location and api_key.
raise ValueError(
'Project/location and API key are mutually exclusive in the client'
' initializer.'
)
elif credentials and api_key:
# API cannot consume both credentials and api_key.
raise ValueError(
'Credentials and API key are mutually exclusive in the client'
' initializer.'
)
# Validate http_options if it is provided.
validated_http_options = HttpOptions()
if isinstance(http_options, dict):
try:
validated_http_options = HttpOptions.model_validate(http_options)
except ValidationError as e:
raise ValueError('Invalid http_options') from e
elif http_options and _common.is_duck_type_of(http_options, HttpOptions):
validated_http_options = http_options
if (
validated_http_options.base_url_resource_scope
and not validated_http_options.base_url
):
# base_url_resource_scope is only valid when base_url is set.
raise ValueError(
'base_url must be set when base_url_resource_scope is set.'
)
# Retrieve implicitly set values from the environment.
env_project = os.environ.get('GOOGLE_CLOUD_PROJECT', None)
env_location = os.environ.get('GOOGLE_CLOUD_LOCATION', None)
env_api_key = get_env_api_key()
self.project = project or env_project
self.location = location or env_location
self.api_key = api_key or env_api_key
self._credentials = credentials
self._http_options = HttpOptions()
# Initialize the lock. This lock will be used to protect access to the
# credentials. This is crucial for thread safety when multiple coroutines
# might be accessing the credentials at the same time.
self._sync_auth_lock = threading.Lock()
self._async_auth_lock: Optional[asyncio.Lock] = None
self._async_auth_lock_creation_lock: Optional[asyncio.Lock] = None
# Handle when to use Vertex AI in express mode (api key).
# Explicit initializer arguments are already validated above.
if self.vertexai:
if credentials and env_api_key:
# Explicit credentials take precedence over implicit api_key.
logger.info(
'The user provided Google Cloud credentials will take precedence'
+ ' over the API key from the environment variable.'
)
self.api_key = None
elif (env_location or env_project) and api_key:
# Explicit api_key takes precedence over implicit project/location.
logger.info(
'The user provided Vertex AI API key will take precedence over the'
+ ' project/location from the environment variables.'
)
self.project = None
self.location = None
elif (project or location) and env_api_key:
# Explicit project/location takes precedence over implicit api_key.
logger.info(
'The user provided project/location will take precedence over the'
+ ' Vertex AI API key from the environment variable.'
)
self.api_key = None
elif (env_location or env_project) and env_api_key:
# Implicit project/location takes precedence over implicit api_key.
logger.info(
'The project/location from the environment variables will take'
+ ' precedence over the API key from the environment variables.'
)
self.api_key = None
self.custom_base_url = (
validated_http_options.base_url
if validated_http_options.base_url
else None
)
if (
not self.location
and not self.api_key
):
if not self.custom_base_url:
self.location = 'global'
elif self.custom_base_url.endswith('.googleapis.com'):
self.location = 'global'
# Skip fetching project from ADC if base url is provided in http options.
if (
not self.project
and not self.api_key
and not self.custom_base_url
):
credentials, self.project = load_auth(project=None)
if not self._credentials:
self._credentials = credentials
has_sufficient_auth = (self.project and self.location) or self.api_key
if not has_sufficient_auth and not self.custom_base_url:
# Skip sufficient auth check if base url is provided in http options.
raise ValueError(
'Project or API key must be set when using the Vertex AI API.'
)
if (
self.api_key or self.location == 'global'
) and not self.custom_base_url:
self._http_options.base_url = f'https://aiplatform.googleapis.com/'
elif self.location == 'us' and not self.custom_base_url:
self._http_options.base_url = (
f'https://aiplatform.{self.location}.rep.googleapis.com/'
)
elif (
self.custom_base_url
and not self.custom_base_url.endswith('.googleapis.com')
) and not ((project and location) or api_key):
# Avoid setting default base url and api version if base_url provided.
# API gateway proxy can use the auth in custom headers, not url.
# Enable custom url if auth is not sufficient.
self._http_options.base_url = self.custom_base_url
# Clear project and location if base_url is provided.
self.project = None
self.location = None
else:
self._http_options.base_url = (
f'https://{self.location}-aiplatform.googleapis.com/'
)
self._http_options.api_version = 'v1beta1'
else: # Implicit initialization or missing arguments.
if not self.api_key:
raise ValueError(
'No API key was provided. Please pass a valid API key. Learn how to'
' create an API key at'
' https://ai.google.dev/gemini-api/docs/api-key.'
)
self._http_options.base_url = 'https://generativelanguage.googleapis.com/'
self._http_options.api_version = 'v1beta'
# Default options for both clients.
self._http_options.headers = {'Content-Type': 'application/json'}
if self.api_key:
self.api_key = self.api_key.strip()
if self._http_options.headers is not None:
self._http_options.headers['x-goog-api-key'] = self.api_key
# Update the http options with the user provided http options.
if http_options:
self._http_options = patch_http_options(
self._http_options, validated_http_options
)
else:
if self._http_options.headers is not None:
append_library_version_headers(self._http_options.headers)
client_args, async_client_args = self._ensure_httpx_ssl_ctx(
self._http_options
)
self._async_httpx_client_args = async_client_args
self._authorized_session: Optional[AuthorizedSession] = None
if self._use_google_auth_sync():
self._httpx_client = None
elif self._http_options.httpx_client:
self._httpx_client = self._http_options.httpx_client
else:
self._httpx_client = SyncHttpxClient(**client_args)
if self._use_google_auth_async():
self._async_httpx_client = None
elif self._http_options.httpx_async_client:
self._async_httpx_client = self._http_options.httpx_async_client
else:
self._async_httpx_client = AsyncHttpxClient(**async_client_args)
if self._http_options.httpx_async_client:
self._async_httpx_client = self._http_options.httpx_async_client
else:
self._async_httpx_client = AsyncHttpxClient(**async_client_args)
# Initialize the aiohttp client session.
self._aiohttp_session: Optional[aiohttp.ClientSession] = None
if self._use_aiohttp():
try:
import aiohttp # pylint: disable=g-import-not-at-top
if self._http_options.aiohttp_client:
self._aiohttp_session = self._http_options.aiohttp_client
# Do it once at the genai.Client level. Share among all requests.
self._async_client_session_request_args = (
self._ensure_aiohttp_ssl_ctx(self._http_options)
)
if self._use_google_auth_async():
self._async_client_session_request_args['ssl'] = True # type: ignore[no-untyped-call]
self._async_client_session_request_args['max_allowed_time'] = float(
'inf'
) if self._http_options.timeout is None else float(
self._http_options.timeout
)
self._async_client_session_request_args['total_attempts'] = 1
except ImportError:
pass
retry_kwargs = retry_args(self._http_options.retry_options)
self._websocket_ssl_ctx = self._ensure_websocket_ssl_ctx(self._http_options)
self._retry = tenacity.Retrying(**retry_kwargs)
self._async_retry = tenacity.AsyncRetrying(**retry_kwargs)
# Test comment
def _use_google_auth_sync(self) -> bool:
if not hasattr(mtls, 'should_use_client_cert'):
return False
return bool(
self.vertexai
and mtls.should_use_client_cert() # type: ignore[no-untyped-call]
and mtls.has_default_client_cert_source() # type: ignore[no-untyped-call]
and not (
self._http_options.httpx_client or self._http_options.client_args
)
)
def _use_google_auth_async(self) -> bool:
try:
from google.auth.aio.credentials import StaticCredentials
from google.auth.aio.transport.sessions import AsyncAuthorizedSession
except ImportError:
return False
return bool(
has_aiohttp
and self.vertexai
and mtls.should_use_client_cert() # type: ignore[no-untyped-call]
and mtls.has_default_client_cert_source() # type: ignore[no-untyped-call]
and not self._http_options.httpx_async_client
)
async def _get_aiohttp_session(
self,
) -> Union['aiohttp.ClientSession', 'AsyncAuthorizedSession']:
"""Returns the aiohttp client session."""
if self._aiohttp_session is None and self._use_google_auth_async():
try:
from google.auth.aio.credentials import StaticCredentials
from google.auth.aio.transport.sessions import AsyncAuthorizedSession
async_creds = StaticCredentials(token=self._access_token()) # type: ignore[no-untyped-call]
self._aiohttp_session = AsyncAuthorizedSession(async_creds) # type: ignore[no-untyped-call]
return self._aiohttp_session
except ImportError:
pass
if not self._use_google_auth_async() and (
self._aiohttp_session is None
or self._aiohttp_session.closed
or self._aiohttp_session._loop.is_closed()
): # pylint: disable=protected-access
# Initialize the aiohttp client session if it's not set up or closed.
class AiohttpClientSession(aiohttp.ClientSession): # type: ignore[misc]
def __del__(self, _warnings: Any = warnings) -> None:
if not self.closed:
context = {
'client_session': self,
'message': 'Unclosed client session',
}
if self._source_traceback is not None:
context['source_traceback'] = self._source_traceback
# Remove this self._loop.call_exception_handler(context)
class AiohttpTCPConnector(aiohttp.TCPConnector): # type: ignore[misc]
def __del__(self, _warnings: Any = warnings) -> None:
if self._closed:
return
if not self._conns:
return
conns = [repr(c) for c in self._conns.values()]
# After v3.13.2, it may change to self._close_immediately()
self._close()
context = {
'connector': self,
'connections': conns,
'message': 'Unclosed connector',
}
if self._source_traceback is not None:
context['source_traceback'] = self._source_traceback
# Remove this self._loop.call_exception_handler(context)
self._aiohttp_session = AiohttpClientSession(
connector=AiohttpTCPConnector(limit=0),
trust_env=True,
read_bufsize=READ_BUFFER_SIZE,
)
return self._aiohttp_session
@staticmethod
def _ensure_httpx_ssl_ctx(
options: HttpOptions,
) -> Tuple[_common.StringDict, _common.StringDict]:
"""Ensures the SSL context is present in the HTTPX client args.
Creates a default SSL context if one is not provided.
Args:
options: The http options to check for SSL context.
Returns:
A tuple of sync/async httpx client args.
"""
verify = 'verify'
args = options.client_args
async_args = options.async_client_args
ctx = (
args.get(verify)
if args
else None or async_args.get(verify)
if async_args
else None
)
if not ctx:
# Initialize the SSL context for the httpx client.
# Unlike requests, the httpx package does not automatically pull in the
# environment variables SSL_CERT_FILE or SSL_CERT_DIR. They need to be
# enabled explicitly.
ctx = ssl.create_default_context(
cafile=os.environ.get('SSL_CERT_FILE', certifi.where()),
capath=os.environ.get('SSL_CERT_DIR'),
)
def _maybe_set(
args: Optional[_common.StringDict],
ctx: ssl.SSLContext,
) -> _common.StringDict:
"""Sets the SSL context in the client args if not set.
Does not override the SSL context if it is already set.
Args:
args: The client args to to check for SSL context.
ctx: The SSL context to set.
Returns:
The client args with the SSL context included.
"""
if not args or not args.get(verify):
args = (args or {}).copy()
args[verify] = ctx
# Drop the args that isn't used by the httpx client.
copied_args = args.copy()
for key in copied_args.copy():
if key not in inspect.signature(httpx.Client.__init__).parameters:
del copied_args[key]
return copied_args
return (
_maybe_set(args, ctx),
_maybe_set(async_args, ctx),
)
@staticmethod
def _ensure_aiohttp_ssl_ctx(options: HttpOptions) -> _common.StringDict:
"""Ensures the SSL context is present in the async client args.
Creates a default SSL context if one is not provided.
Args:
options: The http options to check for SSL context.
Returns:
An async aiohttp ClientSession._request args.
"""
verify = 'ssl' # keep it consistent with aiohttp.
async_args = options.async_client_args
ctx = async_args.get(verify) if async_args else None
if not ctx:
ctx = ssl.create_default_context(
cafile=os.environ.get('SSL_CERT_FILE', certifi.where()),
capath=os.environ.get('SSL_CERT_DIR'),
)
def _maybe_set(
args: Optional[_common.StringDict],
ctx: ssl.SSLContext,
) -> _common.StringDict:
"""Sets the SSL context in the client args if not set.
Does not override the SSL context if it is already set.
Args:
args: The client args to to check for SSL context.
ctx: The SSL context to set.
Returns:
The client args with the SSL context included.
"""
if not args or not args.get(verify):
args = (args or {}).copy()
args[verify] = ctx
# Drop the args that isn't in the aiohttp RequestOptions.
copied_args = args.copy()
for key in copied_args.copy():
if (
key
not in inspect.signature(aiohttp.ClientSession._request).parameters