Skip to content

Commit

Permalink
improve the no-credentials error message, fail fast for no-credential…
Browse files Browse the repository at this point in the history
…s in colab. (#352)

* improve the no-credentials error message

Change-Id: I294bd094b56287ed923716dce9ea705ef3135f5b

* patch colab credentials

Change-Id: I5a3cb3168448a565eb3cdc8a0063ae041c41a260

* format

Change-Id: I013d506bdcb64092daddedcf3e30f3728a8f3e30
  • Loading branch information
MarkDaoust authored May 21, 2024
1 parent 05877f7 commit f987fde
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions google/generativeai/client.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from __future__ import annotations

import os
import contextlib
import dataclasses
import pathlib
import re
import types
from typing import Any, cast
from collections.abc import Sequence
Expand All @@ -12,6 +12,8 @@
import google.ai.generativelanguage as glm

from google.auth import credentials as ga_credentials
from google.auth import exceptions as ga_exceptions
from google import auth
from google.api_core import client_options as client_options_lib
from google.api_core import gapic_v1
from google.api_core import operations_v1
Expand All @@ -30,6 +32,18 @@
GENAI_API_DISCOVERY_URL = "https://generativelanguage.googleapis.com/$discovery/rest"


@contextlib.contextmanager
def patch_colab_gce_credentials():
get_gce = auth._default._get_gce_credentials
if "COLAB_RELEASE_TAG" in os.environ:
auth._default._get_gce_credentials = lambda *args, **kwargs: (None, None)

try:
yield
finally:
auth._default._get_gce_credentials = get_gce


class FileServiceClient(glm.FileServiceClient):
def __init__(self, *args, **kwargs):
self._discovery_api = None
Expand Down Expand Up @@ -183,7 +197,17 @@ def make_client(self, name):
if not self.client_config:
configure()

client = cls(**self.client_config)
try:
with patch_colab_gce_credentials():
client = cls(**self.client_config)
except ga_exceptions.DefaultCredentialsError as e:
e.args = (
"\n No API_KEY or ADC found. Please either:\n"
" - Set the `GOOGLE_API_KEY` environment variable.\n"
" - Manually pass the key with `genai.configure(api_key=my_api_key)`.\n"
" - Or set up Application Default Credentials, see https://ai.google.dev/gemini-api/docs/oauth for more information.",
)
raise e

if not self.default_metadata:
return client
Expand Down

0 comments on commit f987fde

Please sign in to comment.