Skip to content
Closed
Show file tree
Hide file tree
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
5 changes: 3 additions & 2 deletions packages/genkit/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,9 @@ DEP002 = [
"genkit-vertexai",
]
# Standard library on Python 3.14+; imported behind a version check.
DEP001 = ["annotationlib"]
DEP003 = ["pydantic_core"]
# google-auth is optional and supplied by plugins' [google-cloud] extras (DEP001 bare, DEP003 in workspace).
DEP001 = ["annotationlib", "google"]
DEP003 = ["pydantic_core", "google"]

[tool.hatch.build.targets.wheel]
packages = ["src/genkit"]
Expand Down
193 changes: 193 additions & 0 deletions packages/genkit/src/genkit/_core/_google_cloud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

"""Shared Google Cloud backend configuration and ADC helpers for Genkit plugins.

Plugins such as ``OpenAICompatible(backend=GoogleCloud(...))`` and
``Anthropic(backend=GoogleCloud(...))`` share one :class:`GoogleCloud` config
object and one ADC loading path, while keeping ``google-auth`` as an optional
dependency installed via each plugin's ``[google-cloud]`` extra.
"""

import asyncio
import os
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any

from genkit._core._error import GenkitError

_CLOUD_PLATFORM_SCOPES: tuple[str, ...] = ('https://www.googleapis.com/auth/cloud-platform',)
_LOGIN_FIX = (
'run `gcloud auth application-default login` on your machine, '
'or give the service account roles/aiplatform.user when running on Google Cloud'
)


@dataclass(frozen=True, kw_only=True)
class GoogleCloud:
"""Route a Genkit model plugin through Google Cloud using application default credentials.

Pass a ``GoogleCloud(...)`` instance as ``backend=`` to supported plugins
such as ``OpenAICompatible(backend=GoogleCloud(...))`` or
``Anthropic(backend=GoogleCloud(...))``. Plugins re-export this class so
one instance can be shared across multiple plugins in the same app without
import collisions. Requests authenticate with application default
credentials and bill the Google Cloud project, so no provider API key is
needed.

Example:
```python
from genkit import Genkit
from genkit_openai import GoogleCloud, OpenAICompatible

gcp = GoogleCloud(project='bistro-prod')
garden = OpenAICompatible(backend=gcp)
ai = Genkit(plugins=[garden])
```

Attributes:
project: Google Cloud project ID. Defaults to ``GCLOUD_PROJECT``, then
``GOOGLE_CLOUD_PROJECT``, then the credentials' project.
location: Google Cloud location (for example ``'us-central1'`` or
``'global'``). Defaults to ``GOOGLE_CLOUD_LOCATION``, then each
plugin's own default location.
"""

project: str | None = None
location: str | None = None


def resolve_google_cloud_project(config: GoogleCloud) -> str | None:
"""Resolve the project from ``config`` or environment variables; ``None`` means fall back to ADC."""
return config.project or os.environ.get('GCLOUD_PROJECT') or os.environ.get('GOOGLE_CLOUD_PROJECT') or None


def resolve_google_cloud_location(config: GoogleCloud, *, default: str) -> str:
"""Resolve the location from ``config``, ``GOOGLE_CLOUD_LOCATION``, or ``default``."""
return config.location or os.environ.get('GOOGLE_CLOUD_LOCATION') or default


def require_google_auth(*, caller: str, extra: str) -> None:
"""Fail at setup, on the user's line, when ``google-auth`` isn't installed.

Args:
caller: Plugin constructor expression shown in the error, e.g.
``'OpenAICompatible(backend=GoogleCloud())'``.
extra: Package extra install spec, e.g. ``'genkit-openai[google-cloud]'``.

Raises:
ImportError: ``google-auth`` isn't installed.
"""
# Optional dependency: supplied by each plugin's [google-cloud] extra.
try:
import google.auth # noqa: F401, PLC0415
except ModuleNotFoundError as e:
raise ImportError(f"{caller} needs the google-cloud extra: uv add '{extra}'") from e


def _auth_errors() -> tuple[type[Exception], type[Exception]]:
# Optional dependency, checked by require_google_auth at setup.
from google.auth.exceptions import DefaultCredentialsError, RefreshError # noqa: PLC0415

return DefaultCredentialsError, RefreshError


def _missing_credentials(caller: str, e: Exception) -> GenkitError:
return GenkitError(
status='FAILED_PRECONDITION',
message=f'{caller} found no Google Cloud credentials: {_LOGIN_FIX}',
cause=e,
)


def _stale_credentials(caller: str, e: Exception) -> GenkitError:
return GenkitError(
status='FAILED_PRECONDITION',
message=f'{caller} could not refresh Google Cloud credentials: {_LOGIN_FIX}',
cause=e,
)


def load_google_adc(
*,
caller: str,
scopes: Sequence[str] = _CLOUD_PLATFORM_SCOPES,
) -> tuple[Any, str | None]: # noqa: ANN401 - google.auth credentials are untyped
"""Load and refresh application default credentials, returning ``(credentials, project)``.

Blocking: may contact the metadata server, so callers in async paths should
run it via ``asyncio.to_thread``. Refreshing here ensures a missing or stale
login fails on the first call with an actionable ``FAILED_PRECONDITION``
error instead of surfacing later as an unmapped ``google.auth`` error.

Args:
caller: Plugin constructor expression shown in error messages.
scopes: OAuth scopes to request (defaults to ``cloud-platform``).

Raises:
GenkitError: ``FAILED_PRECONDITION`` when there are no credentials, or
they need a fresh login.
"""
# Optional dependency, checked by require_google_auth at setup.
import google.auth # noqa: PLC0415
from google.auth.transport.requests import Request # noqa: PLC0415

default_error, refresh_error = _auth_errors()
try:
credentials, project = google.auth.default(scopes=list(scopes))
except default_error as e:
raise _missing_credentials(caller, e) from e
try:
credentials.refresh(Request())
except refresh_error as e:
raise _stale_credentials(caller, e) from e
return credentials, project


class GoogleAdcToken:
"""Async bearer token callable backed by Google ADC, refreshed in a thread when expired.

Useful for SDK clients (such as ``AsyncOpenAI(api_key=...)``) that accept
an async callable returning the current bearer token before each request.
"""

def __init__(
self,
credentials: Any, # noqa: ANN401 - google.auth credentials are untyped
*,
caller: str,
) -> None:
"""Hold credentials already refreshed by :func:`load_google_adc`."""
self._credentials = credentials
self._caller = caller

async def __call__(self) -> str:
"""Return a valid bearer token, refreshing in a thread if expired.

Raises:
GenkitError: ``FAILED_PRECONDITION`` when the refresh is rejected.
"""
if not self._credentials.valid:
# Optional dependency, checked by require_google_auth at setup.
from google.auth.transport.requests import Request # noqa: PLC0415

_, refresh_error = _auth_errors()
try:
await asyncio.to_thread(self._credentials.refresh, Request())
except refresh_error as e:
raise _stale_credentials(self._caller, e) from e
return self._credentials.token
15 changes: 15 additions & 0 deletions packages/genkit/src/genkit/plugin_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@
from genkit._core._dap import DynamicActionProvider
from genkit._core._environment import is_dev_environment
from genkit._core._error import StatusName, provider_error
from genkit._core._google_cloud import (
GoogleAdcToken,
GoogleCloud,
load_google_adc,
require_google_auth,
resolve_google_cloud_location,
resolve_google_cloud_project,
)
from genkit._core._loop_cache import loop_local_client
from genkit._core._plugin import Plugin
from genkit._core._schema import to_json_schema
Expand All @@ -43,6 +51,13 @@
'StrEnum',
# Provider failures
'provider_error',
# Google Cloud backend helpers
'GoogleCloud',
'GoogleAdcToken',
'load_google_adc',
'require_google_auth',
'resolve_google_cloud_location',
'resolve_google_cloud_project',
# HTTP / version stamping
'GENKIT_USER_AGENT',
# Loop-local caching
Expand Down
Loading
Loading