Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve the no-credentials error message, fail fast for no-credentials in colab. #352

Merged
merged 3 commits into from
May 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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():
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is super-sketchy but it works.

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
Loading