Skip to content

Commit 9bd758c

Browse files
matthew29tangcopybara-github
authored andcommitted
fix: Check environment Vertex AI api key for credential precedence
PiperOrigin-RevId: 822733016
1 parent 5058422 commit 9bd758c

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

google/genai/_api_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,7 @@ def __init__(
599599
# Handle when to use Vertex AI in express mode (api key).
600600
# Explicit initializer arguments are already validated above.
601601
if self.vertexai:
602-
if credentials:
602+
if credentials and env_api_key:
603603
# Explicit credentials take precedence over implicit api_key.
604604
logger.info(
605605
'The user provided Google Cloud credentials will take precedence'

google/genai/tests/client/test_client_initialization.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,25 @@ def test_invalid_vertexai_constructor3(monkeypatch):
417417
Client(vertexai=True, project=project_id)
418418

419419

420+
def test_vertexai_explicit_credentials(monkeypatch):
421+
creds = credentials.AnonymousCredentials()
422+
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "fake_project_id")
423+
monkeypatch.setenv("GOOGLE_CLOUD_LOCATION", "fake-location")
424+
monkeypatch.setenv("GOOGLE_API_KEY", "env_api_key")
425+
426+
client = Client(
427+
vertexai=True,
428+
credentials=creds
429+
)
430+
431+
assert client.models._api_client.vertexai
432+
assert client.models._api_client.project
433+
assert client.models._api_client.location
434+
assert not client.models._api_client.api_key
435+
assert client.models._api_client._credentials is creds
436+
assert isinstance(client.models._api_client, api_client.BaseApiClient)
437+
438+
420439
def test_vertexai_explicit_arg_precedence1(monkeypatch):
421440
project_id = "constructor_project_id"
422441
location = "constructor-location"

0 commit comments

Comments
 (0)