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 5cb2e0e
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions google/generativeai/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import os
import contextlib
import dataclasses
import pathlib
import types
Expand All @@ -12,6 +13,7 @@

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 @@ -184,12 +198,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 5cb2e0e

Please sign in to comment.