Skip to content

Commit

Permalink
patch colab credentials
Browse files Browse the repository at this point in the history
Change-Id: I5a3cb3168448a565eb3cdc8a0063ae041c41a260
  • Loading branch information
MarkDaoust committed May 20, 2024
1 parent a046138 commit 374ca2c
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions google/generativeai/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@
GENAI_API_DISCOVERY_URL = "https://generativelanguage.googleapis.com/$discovery/rest"


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

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


class FileServiceClient(glm.FileServiceClient):
def __init__(self, *args, **kwargs):
self._discovery_api = None
Expand Down Expand Up @@ -184,12 +196,15 @@ def make_client(self, name):
configure()

try:
client = cls(**self.client_config)
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.",)
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:
Expand Down

0 comments on commit 374ca2c

Please sign in to comment.