Skip to content

Commit ee6acaf

Browse files
MarkDaoustcopybara-github
authored andcommitted
feat!: default Gemini API version to v1 instead of v1beta across SDKs
feat: support GOOGLE_GENAI_API_VERSION environment variable PiperOrigin-RevId: 970060591
1 parent 96f0f5a commit ee6acaf

9 files changed

Lines changed: 357 additions & 24 deletions

File tree

‎google/genai/_api_client.py‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@
148148
MAX_RETRY_COUNT = 3
149149
INITIAL_RETRY_DELAY = 1 # second
150150
DELAY_MULTIPLIER = 2
151+
GOOGLE_AI_API_DEFAULT_VERSION = 'v1'
151152

152153
_MULTI_REGIONAL_LOCATIONS = {'us', 'eu'}
153154

@@ -1043,7 +1044,9 @@ def __init__(
10431044
self._http_options.base_url = (
10441045
f'https://{self.location}-aiplatform.googleapis.com/'
10451046
)
1046-
self._http_options.api_version = 'v1beta1'
1047+
self._http_options.api_version = (
1048+
os.environ.get('GOOGLE_GENAI_API_VERSION', None) or 'v1beta1'
1049+
)
10471050
else: # Implicit initialization or missing arguments.
10481051
if not self.api_key:
10491052
raise ValueError(
@@ -1052,7 +1055,18 @@ def __init__(
10521055
' https://ai.google.dev/gemini-api/docs/api-key.'
10531056
)
10541057
self._http_options.base_url = 'https://generativelanguage.googleapis.com/'
1055-
self._http_options.api_version = 'v1beta'
1058+
self._http_options.api_version = (
1059+
os.environ.get('GOOGLE_GENAI_API_VERSION', None)
1060+
or GOOGLE_AI_API_DEFAULT_VERSION
1061+
)
1062+
# Whether the caller chose the API version (via http_options or the
1063+
# GOOGLE_GENAI_API_VERSION environment variable) instead of relying on the
1064+
# default. Resources that only exist in v1beta are pinned to v1beta unless
1065+
# the caller chose a version.
1066+
self._api_version_is_explicit = bool(
1067+
validated_http_options.api_version
1068+
or os.environ.get('GOOGLE_GENAI_API_VERSION', None)
1069+
)
10561070
# Default options for both clients.
10571071
self._http_options.headers = {'Content-Type': 'application/json'}
10581072
if self.api_key:

‎google/genai/_gaos/google_genai.py‎

Lines changed: 77 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,39 @@ def build_google_genai_async_client(
230230
return sdk
231231

232232

233+
# Gemini Developer API resources that are only served on v1beta (agents,
234+
# triggers, environments, credentials, webhooks, voices). Unless the caller
235+
# chose an API version explicitly, these are pinned to v1beta so they keep
236+
# working when the default API version is v1.
237+
_V1BETA_ONLY_API_VERSION = 'v1beta'
238+
239+
240+
def _v1beta_only_api_version(api_client: Any) -> Optional[str]:
241+
"""Returns the API version override for v1beta-only resources, if any."""
242+
if api_client.vertexai or getattr(
243+
api_client, '_api_version_is_explicit', False
244+
):
245+
return None
246+
return _V1BETA_ONLY_API_VERSION
247+
248+
249+
def _http_options_with_api_version(
250+
http_options: Optional[Any], api_version: Optional[str]
251+
) -> Optional[Any]:
252+
"""Sets `api_version` on per-request http_options unless already set."""
253+
if not api_version:
254+
return http_options
255+
if http_options is None:
256+
return {'api_version': api_version}
257+
if isinstance(http_options, dict):
258+
if http_options.get('api_version'):
259+
return http_options
260+
return {**http_options, 'api_version': api_version}
261+
if getattr(http_options, 'api_version', None):
262+
return http_options
263+
return http_options.model_copy(update={'api_version': api_version})
264+
265+
233266
class GeminiNextGenInteractions(GeneratedInteractions):
234267
"""Public interactions resource backed by the NextGen client.
235268
@@ -807,7 +840,9 @@ class GeminiNextGenWebhooks(GeneratedWebhooks):
807840
"""
808841

809842
def __init__(self, api_client: Any):
810-
sdk = build_google_genai_client(api_client)
843+
sdk = build_google_genai_client(
844+
api_client, api_version=_v1beta_only_api_version(api_client)
845+
)
811846
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
812847

813848
if not TYPE_CHECKING:
@@ -845,7 +880,9 @@ class AsyncGeminiNextGenWebhooks(GeneratedAsyncWebhooks):
845880
"""Async public webhooks resource backed by the NextGen client."""
846881

847882
def __init__(self, api_client: Any):
848-
sdk = build_google_genai_async_client(api_client)
883+
sdk = build_google_genai_async_client(
884+
api_client, api_version=_v1beta_only_api_version(api_client)
885+
)
849886
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
850887

851888
if not TYPE_CHECKING:
@@ -891,7 +928,9 @@ class GeminiNextGenCredentials(GeneratedCredentials):
891928
"""
892929

893930
def __init__(self, api_client: Any):
894-
sdk = build_google_genai_client(api_client)
931+
sdk = build_google_genai_client(
932+
api_client, api_version=_v1beta_only_api_version(api_client)
933+
)
895934
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
896935

897936
if not TYPE_CHECKING:
@@ -923,7 +962,9 @@ class AsyncGeminiNextGenCredentials(GeneratedAsyncCredentials):
923962
"""Async public credentials resource backed by the NextGen client."""
924963

925964
def __init__(self, api_client: Any):
926-
sdk = build_google_genai_async_client(api_client)
965+
sdk = build_google_genai_async_client(
966+
api_client, api_version=_v1beta_only_api_version(api_client)
967+
)
927968
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
928969

929970
if not TYPE_CHECKING:
@@ -961,7 +1002,9 @@ class GeminiNextGenVoices(GeneratedVoices):
9611002
"""
9621003

9631004
def __init__(self, api_client: Any):
964-
sdk = build_google_genai_client(api_client)
1005+
sdk = build_google_genai_client(
1006+
api_client, api_version=_v1beta_only_api_version(api_client)
1007+
)
9651008
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
9661009

9671010
if not TYPE_CHECKING:
@@ -990,7 +1033,9 @@ class AsyncGeminiNextGenVoices(GeneratedAsyncVoices):
9901033
"""Async voices resource backed by the NextGen client."""
9911034

9921035
def __init__(self, api_client: Any):
993-
sdk = build_google_genai_async_client(api_client)
1036+
sdk = build_google_genai_async_client(
1037+
api_client, api_version=_v1beta_only_api_version(api_client)
1038+
)
9941039
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
9951040

9961041
if not TYPE_CHECKING:
@@ -1025,7 +1070,9 @@ class GeminiNextGenAgents(GeneratedAgents):
10251070
"""
10261071

10271072
def __init__(self, api_client: Any):
1028-
sdk = build_google_genai_client(api_client)
1073+
sdk = build_google_genai_client(
1074+
api_client, api_version=_v1beta_only_api_version(api_client)
1075+
)
10291076
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
10301077

10311078
if not TYPE_CHECKING:
@@ -1054,7 +1101,9 @@ class AsyncGeminiNextGenAgents(GeneratedAsyncAgents):
10541101
"""Async public agents resource backed by the NextGen client."""
10551102

10561103
def __init__(self, api_client: Any):
1057-
sdk = build_google_genai_async_client(api_client)
1104+
sdk = build_google_genai_async_client(
1105+
api_client, api_version=_v1beta_only_api_version(api_client)
1106+
)
10581107
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
10591108

10601109
if not TYPE_CHECKING:
@@ -1089,7 +1138,9 @@ class GeminiNextGenTriggers(GeneratedTriggers):
10891138
"""
10901139

10911140
def __init__(self, api_client: Any):
1092-
sdk = build_google_genai_client(api_client)
1141+
sdk = build_google_genai_client(
1142+
api_client, api_version=_v1beta_only_api_version(api_client)
1143+
)
10931144
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
10941145

10951146
if not TYPE_CHECKING:
@@ -1131,7 +1182,9 @@ class AsyncGeminiNextGenTriggers(GeneratedAsyncTriggers):
11311182
"""Async public triggers resource backed by the NextGen client."""
11321183

11331184
def __init__(self, api_client: Any):
1134-
sdk = build_google_genai_async_client(api_client)
1185+
sdk = build_google_genai_async_client(
1186+
api_client, api_version=_v1beta_only_api_version(api_client)
1187+
)
11351188
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
11361189

11371190
if not TYPE_CHECKING:
@@ -1219,7 +1272,9 @@ def download(
12191272
download_path = f'{env_name}/files/{clean_path}?alt=media'
12201273
return self._api_client.download_file(
12211274
download_path,
1222-
http_options=http_options,
1275+
http_options=_http_options_with_api_version(
1276+
http_options, _v1beta_only_api_version(self._api_client)
1277+
),
12231278
)
12241279

12251280
def upload(
@@ -1275,6 +1330,7 @@ def upload(
12751330
if isinstance(http_options, dict)
12761331
else getattr(http_options, 'api_version', None)
12771332
)
1333+
or _v1beta_only_api_version(self._api_client)
12781334
or self._api_client._http_options.api_version
12791335
or 'v1alpha'
12801336
).lstrip('/')
@@ -1377,7 +1433,9 @@ async def download(
13771433
download_path = f'{env_name}/files/{clean_path}?alt=media'
13781434
return await self._api_client.async_download_file(
13791435
download_path,
1380-
http_options=http_options,
1436+
http_options=_http_options_with_api_version(
1437+
http_options, _v1beta_only_api_version(self._api_client)
1438+
),
13811439
)
13821440

13831441
async def upload(
@@ -1433,6 +1491,7 @@ async def upload(
14331491
if isinstance(http_options, dict)
14341492
else getattr(http_options, 'api_version', None)
14351493
)
1494+
or _v1beta_only_api_version(self._api_client)
14361495
or self._api_client._http_options.api_version
14371496
or 'v1alpha'
14381497
).lstrip('/')
@@ -1493,7 +1552,9 @@ class GeminiNextGenEnvironments(GeneratedEnvironments):
14931552

14941553
def __init__(self, api_client: Any):
14951554
self._api_client = api_client
1496-
sdk = build_google_genai_client(api_client)
1555+
sdk = build_google_genai_client(
1556+
api_client, api_version=_v1beta_only_api_version(api_client)
1557+
)
14971558
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
14981559

14991560
def _init_sdks(self) -> None:
@@ -1544,7 +1605,9 @@ class AsyncGeminiNextGenEnvironments(GeneratedAsyncEnvironments):
15441605

15451606
def __init__(self, api_client: Any):
15461607
self._api_client = api_client
1547-
sdk = build_google_genai_async_client(api_client)
1608+
sdk = build_google_genai_async_client(
1609+
api_client, api_version=_v1beta_only_api_version(api_client)
1610+
)
15481611
super().__init__(sdk.sdk_configuration, parent_ref=sdk)
15491612

15501613
def _init_sdks(self) -> None:

‎google/genai/client.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,7 @@ def __init__(
361361
enterprise: Optional[bool] = None,
362362
vertexai: Optional[bool] = None,
363363
api_key: Optional[str] = None,
364+
api_version: Optional[str] = None,
364365
credentials: Optional[google.auth.credentials.Credentials] = None,
365366
project: Optional[str] = None,
366367
location: Optional[str] = None,
@@ -379,6 +380,7 @@ def __init__(
379380
api_key (str): The `API key
380381
<https://ai.google.dev/gemini-api/docs/api-key>`_ to use for
381382
authentication. Applies to the Gemini Developer API only.
383+
api_version (str): The API version to use (e.g. 'v1' or 'v1beta').
382384
credentials (google.auth.credentials.Credentials): The credentials to use
383385
for authentication when calling the Vertex AI APIs. Credentials can be
384386
obtained from environment variables and default credentials. For more
@@ -411,6 +413,19 @@ def __init__(
411413

412414
if isinstance(http_options, dict):
413415
http_options = HttpOptions(**http_options)
416+
elif http_options is not None:
417+
http_options = http_options.model_copy()
418+
419+
if api_version is not None:
420+
if http_options and http_options.api_version is not None:
421+
raise ValueError(
422+
'api_version is set in both client constructor and http_options.'
423+
' Please specify api_version in only one place.'
424+
)
425+
if http_options:
426+
http_options.api_version = api_version
427+
else:
428+
http_options = HttpOptions(api_version=api_version)
414429

415430
base_url = get_base_url(resolved_vertexai or False, http_options)
416431
if base_url:

‎google/genai/tests/caches/constants.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,6 @@
2424
'base_url': 'https://us-central1-aiplatform.googleapis.com/',
2525
}
2626
MLDEV_HTTP_OPTIONS = {
27-
'api_version': 'v1beta',
27+
'api_version': 'v1',
2828
'base_url': 'https://generativelanguage.googleapis.com/',
2929
}

‎google/genai/tests/client/test_client_initialization.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import certifi
2929
import google.auth
3030
from google.auth import credentials
31+
import google.auth.transport.requests
3132
import httpx
3233
import pytest
3334
import requests
@@ -2484,3 +2485,68 @@ async def test_google_auth_async_respects_mtls_endpoint_env_override(
24842485
assert mock_session.request.call_args.kwargs["url"].startswith(
24852486
"https://us-central1-aiplatform.googleapis.com/"
24862487
)
2488+
2489+
2490+
def test_client_init_default_api_version(monkeypatch):
2491+
monkeypatch.delenv("GOOGLE_GENAI_API_VERSION", raising=False)
2492+
client = Client(api_key="test-api-key")
2493+
assert (
2494+
client._api_client._http_options.api_version
2495+
== api_client.GOOGLE_AI_API_DEFAULT_VERSION
2496+
)
2497+
2498+
2499+
def test_client_init_with_api_version():
2500+
client = Client(api_key="test-api-key", api_version="v1beta")
2501+
assert client._api_client._http_options.api_version == "v1beta"
2502+
2503+
2504+
def test_client_init_with_api_version_and_http_options():
2505+
client = Client(
2506+
api_key="test-api-key",
2507+
api_version="v1alpha",
2508+
http_options={"headers": {"custom": "header"}},
2509+
)
2510+
assert client._api_client._http_options.api_version == "v1alpha"
2511+
assert client._api_client._http_options.headers.get("custom") == "header"
2512+
2513+
2514+
def test_client_init_with_api_version_conflict():
2515+
with pytest.raises(
2516+
ValueError,
2517+
match="api_version is set in both client constructor and http_options",
2518+
):
2519+
Client(
2520+
api_key="test-api-key",
2521+
api_version="v1beta",
2522+
http_options={"api_version": "v1"},
2523+
)
2524+
2525+
2526+
def test_client_init_with_env_api_version(monkeypatch):
2527+
monkeypatch.setenv("GOOGLE_GENAI_API_VERSION", "v1alpha")
2528+
client = Client(api_key="test-api-key")
2529+
assert client._api_client._http_options.api_version == "v1alpha"
2530+
2531+
2532+
def test_client_init_vertexai_with_env_api_version(monkeypatch):
2533+
monkeypatch.setenv("GOOGLE_GENAI_API_VERSION", "v1")
2534+
client = Client(
2535+
vertexai=True, project="test-project", location="us-central1"
2536+
)
2537+
assert client._api_client._http_options.api_version == "v1"
2538+
2539+
2540+
def test_client_init_explicit_api_version_overrides_env(monkeypatch):
2541+
monkeypatch.setenv("GOOGLE_GENAI_API_VERSION", "v1alpha")
2542+
client = Client(api_key="test-api-key", api_version="v1")
2543+
assert client._api_client._http_options.api_version == "v1"
2544+
2545+
2546+
def test_client_init_http_options_api_version_overrides_env(monkeypatch):
2547+
monkeypatch.setenv("GOOGLE_GENAI_API_VERSION", "v1alpha")
2548+
client = Client(
2549+
api_key="test-api-key", http_options={"api_version": "v1"}
2550+
)
2551+
assert client._api_client._http_options.api_version == "v1"
2552+

0 commit comments

Comments
 (0)