diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 6b8b6fd8..4e2e5eae 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -138,6 +138,59 @@ vectors = await ai.embed(embedder='openrouter/openai/text-embedding-3-small', co - `OpenAIConfig` is the config for every model. A server may ignore fields it doesn't support, or reject them. +### Model Garden on Google Cloud + +Instead of wiring `base_url=` and a token function by hand, pass +`backend=GoogleCloud()` to serve Model Garden's OpenAI-compatible models +(Llama, Mistral, and others) billed to your Google Cloud project with +application default credentials. + +```bash +uv add 'genkit-openai[google-cloud]' +``` + +```python +from genkit import Genkit +from genkit_openai import GoogleCloud, OpenAICompatible + +# 1. Model Garden through your gcloud login; the endpoint and token are handled +garden = OpenAICompatible(backend=GoogleCloud(project='bistro-prod', location='us-central1')) +ai = Genkit(plugins=[garden]) + +# 2. The ref helper gives the ref for any Model Garden model on the OpenAI-compatible endpoint +res = await ai.generate(model=garden.model('meta/llama-3.3-70b-instruct-maas'), prompt='Suggest a dish.') +print(res.text) +# => Grilled salmon with lemon and dill +``` + +First-time setup: + +1. Log in and pick a project with billing: `gcloud auth login`, then + `gcloud config set project YOUR_PROJECT_ID`. +2. Turn on the API: `gcloud services enable aiplatform.googleapis.com`. +3. Enable the model on its Model Garden card in the Google Cloud console, and + accept its terms. You do this once per model, per project. +4. Give your code access to your login: `gcloud auth application-default login`. + +- `project` comes from `GoogleCloud(project=...)`, then `GCLOUD_PROJECT`, + `GOOGLE_CLOUD_PROJECT`, then your credentials. `location` comes from + `GoogleCloud(location=...)`, then `GOOGLE_CLOUD_LOCATION` (not + `GOOGLE_CLOUD_REGION`), then `us-central1`; most open models are regional. +- Pass `base_url=` to override the derived endpoint (for example, Private + Service Connect) while keeping Google Cloud credentials; `project` is not + required when `base_url=` is set. +- `name` defaults to `modelgarden` (refs are `modelgarden//`). + Pass another `name=` to use a different namespace, for example to run two + regions or projects side by side. +- Model Garden has no model list endpoint, so the Dev UI lists nothing for + this plugin. Any model id resolves when you call it. +- A missing or stale login fails the call with `FAILED_PRECONDITION` and the + `gcloud` command that fixes it. The next call retries after you log in. +- A key in `context={'secrets': {'api_key': ...}}` fails with + `FAILED_PRECONDITION`: every call bills the project. +- For Claude on Google Cloud, use `Anthropic(backend=GoogleCloud())` from + `genkit-anthropic[google-cloud]`. + ## Mistral `Mistral()` registers Mistral's models and embedders under `mistral/`, as the @@ -292,3 +345,6 @@ res = await ai.generate( - Embedders read the same key: `ai.embed(..., context={'secrets': {'api_key': tenant_key}})`. A call without one runs on the plugin's key. +- `OpenAICompatible(backend=GoogleCloud())` refuses `context.secrets` keys with + `FAILED_PRECONDITION`: every call authenticates with Google Cloud credentials + and bills the project. diff --git a/packages/genkit-openai/pyproject.toml b/packages/genkit-openai/pyproject.toml index e883c4e9..f544afd5 100644 --- a/packages/genkit-openai/pyproject.toml +++ b/packages/genkit-openai/pyproject.toml @@ -55,6 +55,10 @@ readme = "README.md" requires-python = ">=3.10" version = "0.14.0" +[project.optional-dependencies] +# OpenAICompatible(backend=GoogleCloud()): google-auth for application default credentials. +google-cloud = ["google-auth[requests]>=2.14.1"] + [project.urls] "Bug Tracker" = "https://github.com/genkit-ai/genkit-python/issues" Changelog = "https://github.com/genkit-ai/genkit-python/releases" diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py index e5307def..d2302645 100644 --- a/packages/genkit-openai/src/genkit_openai/__init__.py +++ b/packages/genkit-openai/src/genkit_openai/__init__.py @@ -24,6 +24,9 @@ models and embedders under ``mistral/``. ``OpenAICompatible(name=..., base_url=...)`` registers any other OpenAI-compatible server (OpenRouter, Together, Groq, vLLM) under the name you give it, with no OpenAI catalog. +``OpenAICompatible(backend=GoogleCloud())`` serves Model Garden's +OpenAI-compatible models (Llama, Mistral and others) under ``modelgarden/`` +by default, or any ``name=`` you pick (``uv add 'genkit-openai[google-cloud]'``). Example: ```python @@ -63,7 +66,8 @@ async def main() -> None: """ from ._compatible import OpenAICompatible +from ._google_cloud import GoogleCloud from ._openai_plugin import Mistral, OpenAI from ._typing import OpenAIConfig -__all__ = ['Mistral', 'OpenAI', 'OpenAICompatible', 'OpenAIConfig'] +__all__ = ['GoogleCloud', 'Mistral', 'OpenAI', 'OpenAICompatible', 'OpenAIConfig'] diff --git a/packages/genkit-openai/src/genkit_openai/_compatible.py b/packages/genkit-openai/src/genkit_openai/_compatible.py index 0450f3c9..027f76a3 100644 --- a/packages/genkit-openai/src/genkit_openai/_compatible.py +++ b/packages/genkit-openai/src/genkit_openai/_compatible.py @@ -17,7 +17,7 @@ """Any server that speaks the OpenAI API, registered under a name you pick.""" from collections.abc import Mapping -from typing import Any +from typing import Any, Protocol, overload from openai import APIError, AsyncOpenAI @@ -25,6 +25,7 @@ from genkit.embedder import EmbedContext, Embedder, EmbedderInfo, EmbedderSupports, EmbedRequest, EmbedResponse from genkit.model import Model, ModelContext, ModelInfo, ModelRef, ModelRequest, ModelSupports from genkit.plugin_api import Action, ActionKind, Plugin, loop_local_client +from genkit_openai._google_cloud import MODEL_GARDEN_NAME, GoogleCloud, GoogleCloudServer from genkit_openai._models._handler import OpenAIModelHandler from genkit_openai._models._mistral import is_mistral from genkit_openai._models._model import OpenAIModel @@ -74,6 +75,55 @@ def _validate_name(name: object) -> str: return name +class _Server(Protocol): + """Where an OpenAICompatible plugin sends its calls, and how they're authenticated.""" + + async def request_client(self, api_key: str | None) -> AsyncOpenAI: + """The client for one call, given the caller's ``context.secrets`` key, if any.""" + ... + + async def model_ids(self) -> list[str]: + """Ids for the Dev UI list. + + Raises: + APIError: The server rejected the listing. + """ + ... + + +class _BaseUrlServer: + """A server named by ``base_url``, with a static key, a token function, or no key.""" + + def __init__(self, options: dict[str, Any]) -> None: + self._options = options + self._tenant_headers, self._pins_authorization = _split_tenant_headers(options.get('default_headers')) + + @loop_local_client + def _client(self) -> AsyncOpenAI: + return _build_compatible_client(self._options) + + async def request_client(self, api_key: str | None) -> AsyncOpenAI: + """The plugin's client, or a copy on the caller's key.""" + client = self._client() + if not api_key: + return client + return _with_tenant_key( + client, + api_key, + tenant_headers=self._tenant_headers, + pins_authorization=self._pins_authorization, + plugin='OpenAICompatible', + ) + + async def model_ids(self) -> list[str]: + """What the server's ``/models`` lists.""" + page = await self._client().models.list() + data = getattr(page, 'data', None) + if not isinstance(data, list): + raise TypeError(f'/models returned unexpected data: {type(page).__name__}') + return [m.id for m in data if isinstance(getattr(m, 'id', None), str) and m.id] + + class OpenAICompatible(Plugin): """Any OpenAI-compatible server (OpenRouter, Together, Groq, vLLM, LiteLLM) under a name you pick. @@ -84,10 +134,16 @@ class OpenAICompatible(Plugin): ``/models`` returns. Several instances, and an ``OpenAI()``, can run side by side because each has its own name. + For Google Cloud Model Garden's OpenAI-compatible models (Llama, Mistral + and others), pass ``backend=GoogleCloud(...)`` instead of ``base_url=`` and + ``api_key=``. The backend handles the endpoint and application default + credentials, registering under ``modelgarden/`` by default (or any + ``name=`` you pass). + Example: ```python from genkit import Genkit - from genkit_openai import OpenAI, OpenAICompatible + from genkit_openai import GoogleCloud, OpenAI, OpenAICompatible # 1. OpenAI's API, plus OpenRouter under its own name openrouter = OpenAICompatible(name='openrouter', base_url='https://openrouter.ai/api/v1', api_key=key) @@ -101,9 +157,15 @@ class OpenAICompatible(Plugin): # 3. A local server that needs no key local = OpenAICompatible(name='local', base_url='http://localhost:8000/v1') # => models resolve as local/ + + # 4. Or use the built-in Google Cloud backend for Model Garden + garden = OpenAICompatible(backend=GoogleCloud(project='bistro-prod')) + garden.model('meta/llama-3.3-70b-instruct-maas') + # => ModelRef(name='modelgarden/meta/llama-3.3-70b-instruct-maas', ...) ``` """ + @overload def __init__( self, *, @@ -111,46 +173,90 @@ def __init__( base_url: str, api_key: ApiKey | None = None, client_options: Mapping[str, Any] | None = None, + backend: None = None, + ) -> None: ... + @overload + def __init__( + self, + *, + backend: GoogleCloud, + name: str | None = None, + base_url: str | None = None, + client_options: Mapping[str, Any] | None = None, + ) -> None: ... + def __init__( + self, + *, + name: str | None = None, + base_url: str | None = None, + api_key: ApiKey | None = None, + client_options: Mapping[str, Any] | None = None, + backend: GoogleCloud | None = None, ) -> None: - """Point the plugin at one OpenAI-compatible server. + """Point the plugin at one OpenAI-compatible server, or at Model Garden. Args: name: The namespace for this server's models and embedders, e.g. - ``'openrouter'`` gives ``openrouter/``. + ``'openrouter'`` gives ``openrouter/``. Required without a + backend. With ``backend=GoogleCloud(...)`` it defaults to + ``'modelgarden'``; pass another name to use a different + namespace (for example, to run two regions or projects side by + side). base_url: The server's API base URL up to and including ``/v1``, e.g. ``https://openrouter.ai/api/v1``; the SDK appends - ``/chat/completions``. + ``/chat/completions``. Required without a backend. With + ``backend=GoogleCloud(...)`` it overrides the Model Garden endpoint. api_key: The server's key, or an async function that returns one before each request (for a token that expires). ``None`` sends no real key, for local servers. ``OPENAI_API_KEY`` is never - read. + read. Not used with ``backend=GoogleCloud(...)``. client_options: Other ``AsyncOpenAI`` settings, such as ``timeout``, ``max_retries``, ``default_headers``, or ``http_client``. + backend: ``GoogleCloud(project=..., location=...)`` serves Model + Garden's OpenAI-compatible models with application default + credentials. Needs the ``google-cloud`` extra. Raises: - ValueError: ``name`` is empty or contains ``/``, ``:``, whitespace, - or control characters, or ``base_url`` is empty. - TypeError: ``api_key`` isn't a string, async callable, or ``None``, - a ``client_options`` key ``AsyncOpenAI`` doesn't take, or - ``api_key``/``base_url`` repeated there. + ValueError: ``name`` or ``base_url`` missing without a backend, a + ``name`` that is empty or contains ``/``, ``:``, whitespace, or + control characters, a blank ``base_url``, ``api_key`` with + ``GoogleCloud``, or a pinned ``Authorization`` header with + ``GoogleCloud``. + TypeError: ``backend`` isn't a ``GoogleCloud``, ``api_key`` isn't a + string, async callable, or ``None``, or a ``client_options`` + key ``AsyncOpenAI`` doesn't take. + ImportError: ``backend=GoogleCloud(...)`` without the ``google-cloud`` extra. """ - resolved_name = _validate_name(name) - if not isinstance(base_url, str) or not base_url.strip(): - raise ValueError("OpenAICompatible needs base_url, e.g. 'https://openrouter.ai/api/v1'") - options = _client_kwargs( - api_key=api_key, base_url=base_url, client_options=client_options, plugin='OpenAICompatible' - ) - raw_key = options.get('api_key') - if raw_key is None: - options['api_key'] = _NO_KEY - elif not isinstance(raw_key, str) and not callable(raw_key): - raise TypeError( - f'OpenAICompatible api_key must be a string, an async callable, or None, got {type(raw_key).__name__}' + if backend is None: + resolved_name = _validate_name(name) + if not isinstance(base_url, str) or not base_url.strip(): + raise ValueError("OpenAICompatible needs base_url, e.g. 'https://openrouter.ai/api/v1'") + options = _client_kwargs( + api_key=api_key, base_url=base_url, client_options=client_options, plugin='OpenAICompatible' ) - self.name = resolved_name - self._options = options - self._tenant_headers, self._pins_authorization = _split_tenant_headers(options.get('default_headers')) + raw_key = options.get('api_key') + if raw_key is None: + options['api_key'] = _NO_KEY + elif not isinstance(raw_key, str) and not callable(raw_key): + raise TypeError( + 'OpenAICompatible api_key must be a string, an async callable, or None, ' + f'got {type(raw_key).__name__}' + ) + self._server: _Server = _BaseUrlServer(options) + self.name = resolved_name + else: + if not isinstance(backend, GoogleCloud): + got = type(backend) + hint = ( + f'{got.__module__}.{got.__name__}; import GoogleCloud from genkit_openai' + if got.__name__ == 'GoogleCloud' + else got.__name__ + ) + raise TypeError(f'OpenAICompatible backend must be GoogleCloud(...) or None, got {hint}') + resolved_name = _validate_name(MODEL_GARDEN_NAME if name is None else name) + self._server = GoogleCloudServer(backend, api_key=api_key, base_url=base_url, client_options=client_options) + self.name = resolved_name self._list_actions_cache: list[Action] | None = None def model(self, name: str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]: @@ -170,23 +276,9 @@ def model(self, name: str, *, config: OpenAIConfig | None = None) -> ModelRef[Op ) return ModelRef(name=f'{self.name}/{name}', config_schema=OpenAIConfig, config=config) - @loop_local_client - def _client(self) -> AsyncOpenAI: - return _build_compatible_client(self._options) - - def _client_for(self, context: Mapping[str, Any] | None) -> AsyncOpenAI: - """The plugin's client, or a copy on the caller's ``context.secrets`` key.""" - key = context_api_key(context) - client = self._client() - if not key: - return client - return _with_tenant_key( - client, - key, - tenant_headers=self._tenant_headers, - pins_authorization=self._pins_authorization, - plugin='OpenAICompatible', - ) + async def _client_for(self, context: Mapping[str, Any] | None) -> AsyncOpenAI: + """The server's client for one call, given the caller's context.""" + return await self._server.request_client(context_api_key(context)) async def init(self) -> list[Action]: """Nothing up front: every id resolves on demand.""" @@ -209,7 +301,7 @@ def _model_action(self, model_id: str) -> Action: info = ModelInfo(label=f'{self.name} - {model_id}', supports=_COMPATIBLE_SUPPORTS) async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> ModelResponse: - client = self._client_for(ctx.context) + client = await self._client_for(ctx.context) model = OpenAIModel(model_id, client, supports=info.supports, mistral=is_mistral(client)) return await OpenAIModelHandler(model).generate(request, ctx) @@ -217,7 +309,7 @@ async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> M def _embedder_action(self, model_id: str) -> Action: async def _embed(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: - client = self._client_for(ctx.context) + client = await self._client_for(ctx.context) return await embed_texts(client, model_id, request, mistral=is_mistral(client)) return Embedder( @@ -227,23 +319,20 @@ async def _embed(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: ) async def list_actions(self) -> list[Action]: - """What the server's ``/models`` lists, as models and embedders. + """What the server lists, as models and embedders. Ids containing ``embed`` (case-insensitive) are listed as embedders, everything else as chat models; either can still be called as the other kind. Duplicate ids are deduplicated in server order. A server without ``/models``, or one that rejects the call or returns an unexpected body, lists nothing and logs why; that isn't cached, so the next listing tries - again. + again. Model Garden has no ``/models``, so it lists nothing and any id + resolves. """ if self._list_actions_cache is not None: return self._list_actions_cache try: - page = await self._client().models.list() - data = getattr(page, 'data', None) - if not isinstance(data, list): - raise TypeError(f'/models returned unexpected data: {type(page).__name__}') - model_ids = [m.id for m in data if isinstance(getattr(m, 'id', None), str) and m.id] + model_ids = await self._server.model_ids() except (APIError, GenkitError, AttributeError, TypeError, ValueError) as e: logger.warning( 'Could not list models; the Dev UI shows none for this plugin', plugin=self.name, error=str(e) diff --git a/packages/genkit-openai/src/genkit_openai/_google_cloud.py b/packages/genkit-openai/src/genkit_openai/_google_cloud.py new file mode 100644 index 00000000..ac5c93ed --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_google_cloud.py @@ -0,0 +1,310 @@ +# 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 + +"""Model Garden's OpenAI-compatible models on Google Cloud, as a backend for OpenAICompatible.""" + +import asyncio +import os +import threading +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Any, cast + +from openai import AsyncOpenAI + +from genkit import GenkitError +from genkit.plugin_api import loop_local_client, provider_error +from genkit_openai._openai_plugin import ApiKey, _build_compatible_client, _client_kwargs, _split_tenant_headers + +# Model Garden's open models are mostly regional; ModelGarden in genkit-vertexai used the same default. +DEFAULT_LOCATION = 'us-central1' +# Default namespace for OpenAICompatible(backend=GoogleCloud()) when name= isn't passed. +MODEL_GARDEN_NAME = 'modelgarden' +_SCOPES = ('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' +) +# GoogleCloudServer supplies AdcToken as api_key, so client_options cannot set it. +_SET_BY_GOOGLE_CLOUD = frozenset({'api_key'}) + + +@dataclass(frozen=True, kw_only=True) +class GoogleCloud: + """Serve Model Garden's OpenAI-compatible models (Llama, Mistral and others) from Google Cloud. + + Pass it as ``OpenAICompatible(backend=GoogleCloud(...))``. Requests + authenticate with application default credentials and bill the project, + so there's no API key. Models register as ``modelgarden//`` + by default, or ``//`` when you pass ``name=`` to + ``OpenAICompatible``. + + Example: + ```python + from genkit import Genkit + from genkit_openai import GoogleCloud, OpenAICompatible + + # 1. Model Garden through your gcloud login + garden = OpenAICompatible(backend=GoogleCloud(project='bistro-prod')) + ai = Genkit(plugins=[garden]) + + # 2. The ref for any Model Garden model on the OpenAI-compatible endpoint + res = await ai.generate(model=garden.model('meta/llama-3.3-70b-instruct-maas'), prompt='Suggest a dish.') + print(res.text) + # => Grilled salmon with lemon and dill + ``` + + Attributes: + project: Google Cloud project. Defaults to ``GCLOUD_PROJECT``, then + ``GOOGLE_CLOUD_PROJECT``, then the credentials' project. + location: Google Cloud location. Defaults to ``GOOGLE_CLOUD_LOCATION``, + then ``us-central1``. + """ + + project: str | None = None + location: str | None = None + + +def resolve_project(config: GoogleCloud) -> str | None: + """The project from the argument or the environment; None means ask the credentials.""" + return config.project or os.environ.get('GCLOUD_PROJECT') or os.environ.get('GOOGLE_CLOUD_PROJECT') or None + + +def resolve_location(config: GoogleCloud) -> str: + """The location from the argument or the environment, else ``us-central1``.""" + return config.location or os.environ.get('GOOGLE_CLOUD_LOCATION') or DEFAULT_LOCATION + + +def model_garden_base_url(*, project: str, location: str) -> str: + """Model Garden's OpenAI-compatible endpoint; the SDK appends ``/chat/completions``.""" + host = 'aiplatform.googleapis.com' if location == 'global' else f'{location}-aiplatform.googleapis.com' + return f'https://{host}/v1beta1/projects/{project}/locations/{location}/endpoints/openapi' + + +def require_google_auth() -> None: + """Fail at setup, on the user's line, when the google-cloud extra isn't installed. + + Raises: + ImportError: ``google-auth`` or its ``requests`` transport isn't installed. + """ + # Optional dependency: google-auth[requests] ships with the [google-cloud] extra only. + try: + import google.auth # noqa: F401, PLC0415 + import google.auth.transport.requests # noqa: F401, PLC0415 + except ImportError as e: + raise ImportError( + "OpenAICompatible(backend=GoogleCloud()) needs the google-cloud extra: uv add 'genkit-openai[google-cloud]'" + ) from e + + +def _auth_errors() -> tuple[type[Exception], type[Exception], type[Exception]]: + # Optional dependency, checked by require_google_auth at setup. + from google.auth.exceptions import DefaultCredentialsError, RefreshError, TransportError # noqa: PLC0415 + + return DefaultCredentialsError, RefreshError, TransportError + + +def _missing_credentials(e: Exception) -> GenkitError: + return GenkitError( + status='FAILED_PRECONDITION', + message=f'OpenAICompatible(backend=GoogleCloud()) found no Google Cloud credentials: {_LOGIN_FIX}', + cause=e, + ) + + +def _refresh_failure(e: Exception, transport_error: type[Exception]) -> GenkitError: + """Map a credential refresh failure: transient blips to UNAVAILABLE, rejected logins to FAILED_PRECONDITION.""" + if isinstance(e, transport_error) or getattr(e, 'retryable', False) or isinstance(e.__cause__, transport_error): + return provider_error(e, status='UNAVAILABLE') + return GenkitError( + status='FAILED_PRECONDITION', + message=f'OpenAICompatible(backend=GoogleCloud()) could not refresh Google Cloud credentials: {_LOGIN_FIX}', + cause=e, + ) + + +def load_adc() -> tuple[Any, str | None]: # noqa: ANN401 - google.auth credentials are untyped + """Application default credentials, refreshed, and their project (blocking: may hit the metadata server). + + Refreshing here makes a missing or stale login fail on the first call + with the command that fixes it, instead of as an unmapped google.auth + error inside the SDK. + + Raises: + GenkitError: FAILED_PRECONDITION when there are no credentials or + they need a fresh login; UNAVAILABLE when the refresh hit a + transient network or metadata-server failure. + """ + # 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, transport_error = _auth_errors() + try: + credentials, project = google.auth.default(scopes=list(_SCOPES)) + credentials.refresh(Request()) + except default_error as e: + raise _missing_credentials(e) from e + except (transport_error, refresh_error) as e: + raise _refresh_failure(e, transport_error) from e + return credentials, project + + +class AdcToken: + """The bearer token for each request, refreshed in a thread when it has expired. + + Passed to ``AsyncOpenAI`` as ``api_key``; the SDK awaits it before every + request, so a long-lived server keeps one client and never sends a dead + token. + """ + + def __init__(self, credentials: Any) -> None: # noqa: ANN401 - google.auth credentials are untyped + """Hold credentials that ``load_adc`` already refreshed.""" + self._credentials = credentials + self._lock = threading.Lock() + + def _refresh_if_needed(self) -> str | None: + """Refresh once under a thread lock so concurrent callers don't race on google-auth credentials.""" + with self._lock: + 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, transport_error = _auth_errors() + try: + self._credentials.refresh(Request()) + except (transport_error, refresh_error) as e: + raise _refresh_failure(e, transport_error) from e + return self._credentials.token + + async def __call__(self) -> str: + """A valid token, refreshing first if needed. + + Raises: + GenkitError: FAILED_PRECONDITION when the refresh is rejected or + yields no token; UNAVAILABLE when the refresh hit a transient + network failure. + """ + token: str | None = ( + self._credentials.token if self._credentials.valid else await asyncio.to_thread(self._refresh_if_needed) + ) + if not token: + raise GenkitError( + status='FAILED_PRECONDITION', + message=f'OpenAICompatible(backend=GoogleCloud()) got no Google Cloud access token: {_LOGIN_FIX}', + ) + return token + + +class GoogleCloudServer: + """Model Garden's OpenAI-compatible endpoint, authenticated with application default credentials.""" + + def __init__( + self, + config: GoogleCloud, + *, + api_key: ApiKey | None, + base_url: str | None, + client_options: Mapping[str, Any] | None, + ) -> None: + """Validate Google Cloud settings at setup, on the user's line. + + Raises: + ValueError: ``api_key`` was passed, ``base_url`` is blank, or + ``client_options['default_headers']`` pins an ``Authorization`` + header. + ImportError: The ``google-cloud`` extra isn't installed. + TypeError: An unknown, reserved, or repeated ``client_options`` key. + """ + if api_key is not None: + raise ValueError( + 'OpenAICompatible(backend=GoogleCloud()) authenticates with Google Cloud credentials; drop api_key' + ) + require_google_auth() + options = _client_kwargs( + api_key=None, + base_url=base_url, + client_options=client_options, + plugin='OpenAICompatible', + reserved=_SET_BY_GOOGLE_CLOUD, + ) + # Pop base_url so _client() never passes it both explicitly and via **self._options. + raw_base_url = options.pop('base_url', None) + if raw_base_url is not None and (not isinstance(raw_base_url, str) or not raw_base_url.strip()): + raise ValueError('OpenAICompatible(backend=GoogleCloud()) base_url must be a non-empty string when passed') + _, pins_authorization = _split_tenant_headers(options.get('default_headers')) + if pins_authorization: + raise ValueError( + 'OpenAICompatible(backend=GoogleCloud()) authenticates with Google Cloud credentials; ' + "drop the Authorization header from client_options['default_headers']" + ) + self._base_url: str | None = raw_base_url + self._options = options + # An explicit setting beats the environment; the credentials' project fills in last. + self._project = resolve_project(config) + self._location = resolve_location(config) + self._token: AdcToken | None = None + + @loop_local_client + def _client(self) -> AsyncOpenAI: + # Only request_client builds the client, after _prepare set the token (and project if needed). + base_url = self._base_url or model_garden_base_url(project=cast(str, self._project), location=self._location) + return _build_compatible_client({**self._options, 'base_url': base_url, 'api_key': cast(AdcToken, self._token)}) + + async def request_client(self, api_key: str | None) -> AsyncOpenAI: + """The client, once credentials and project are known. + + Raises: + GenkitError: FAILED_PRECONDITION for a ``context.secrets`` key, + missing or stale credentials, or no project; UNAVAILABLE on a + transient credential refresh failure. + """ + if api_key is not None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'A per-request API key from context.secrets cannot be used: ' + 'OpenAICompatible(backend=GoogleCloud()) authenticates with Google Cloud credentials.' + ), + ) + await self._prepare() + return self._client() + + async def model_ids(self) -> list[str]: + """Nothing: Model Garden's endpoint has no ``/models``, and any id resolves when called.""" + return [] + + async def _prepare(self) -> None: + """Load credentials once (in a thread: it can hit the metadata server); a failure isn't cached. + + Two first calls racing both load; the second result is equivalent, so + there's no lock (an asyncio.Lock would bind to one event loop). + """ + if self._token is not None: + return + credentials, adc_project = await asyncio.to_thread(load_adc) + project = self._project or adc_project + if self._base_url is None and project is None: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + 'OpenAICompatible(backend=GoogleCloud()) needs a Google Cloud project: ' + 'pass GoogleCloud(project=...), set GOOGLE_CLOUD_PROJECT, ' + 'or run `gcloud config set project PROJECT_ID`' + ), + ) + self._project = project + self._token = AdcToken(credentials) diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 74e0ef3c..911d8b79 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -110,19 +110,29 @@ def _client_kwargs( base_url: str | None, client_options: Mapping[str, Any] | None, plugin: str = 'OpenAI', + reserved: frozenset[str] = frozenset(), ) -> dict[str, Any]: """Merge the typed settings into ``client_options`` for ``AsyncOpenAI``. + Args: + api_key: Typed ``api_key`` argument; None means unset. + base_url: Typed ``base_url`` argument; None means unset. + client_options: Caller's ``client_options`` mapping. + plugin: Plugin name for error messages. + reserved: Constructor keys the backend owns itself, so callers can't set them. + Raises: - TypeError: A ``client_options`` key ``AsyncOpenAI`` doesn't take, or - ``api_key``/``base_url`` given both as an argument and in ``client_options``. + TypeError: A ``client_options`` key ``AsyncOpenAI`` doesn't take (or that + the backend reserves), or ``api_key``/``base_url`` given both as an + argument and in ``client_options``. """ + allowed = _CLIENT_OPTION_KEYS - reserved options = dict(client_options or {}) for key in options: - if key not in _CLIENT_OPTION_KEYS: + if key not in allowed: raise TypeError( f'{plugin} got an unexpected client_options key {key!r}; ' - f'AsyncOpenAI accepts {", ".join(sorted(k for k in _CLIENT_OPTION_KEYS if not k.startswith("_")))}' + f'AsyncOpenAI accepts {", ".join(sorted(k for k in allowed if not k.startswith("_")))}' ) for name, value in (('api_key', api_key), ('base_url', base_url)): if value is None: diff --git a/packages/genkit-openai/tests/openai_compatible_google_cloud_test.py b/packages/genkit-openai/tests/openai_compatible_google_cloud_test.py new file mode 100644 index 00000000..551a3d8c --- /dev/null +++ b/packages/genkit-openai/tests/openai_compatible_google_cloud_test.py @@ -0,0 +1,687 @@ +# 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 + +"""OpenAICompatible(backend=GoogleCloud()): Model Garden's OpenAI-compatible models, against a fake endpoint.""" + +import asyncio +import builtins +import json +import threading +from collections.abc import Iterator +from dataclasses import FrozenInstanceError +from typing import Any, cast +from unittest.mock import MagicMock, patch + +import httpx +import pytest +from genkit_middleware import Retry +from genkit_openai import GoogleCloud, OpenAI, OpenAICompatible +from genkit_openai._google_cloud import AdcToken, load_adc, model_garden_base_url +from google.auth.exceptions import DefaultCredentialsError, RefreshError, TransportError + +from genkit import Genkit, GenkitError + +LLAMA = 'meta/llama-3.3-70b-instruct-maas' +_ENV = ( + 'GCLOUD_PROJECT', + 'GOOGLE_CLOUD_PROJECT', + 'GOOGLE_CLOUD_LOCATION', + 'OPENAI_API_KEY', + 'OPENAI_ORG_ID', + 'OPENAI_PROJECT_ID', +) + + +@pytest.fixture(autouse=True) +def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None: + for name in _ENV: + monkeypatch.delenv(name, raising=False) + + +FAKE_TOKEN = 'adc-token' # noqa: S105 - test double, not a credential + + +def _credentials() -> MagicMock: + credentials = MagicMock(name='adc-credentials') + credentials.valid = True + credentials.token = FAKE_TOKEN + return credentials + + +@pytest.fixture(autouse=True) +def fake_adc() -> Iterator[MagicMock]: + """Stands in for the machine's ADC so no test reads real credentials or calls Google.""" + with patch('genkit_openai._google_cloud.load_adc', return_value=(_credentials(), None)) as adc: + yield adc + + +class FakeGarden: + """Answers chat completions like Model Garden's OpenAI-compatible endpoint, and records requests.""" + + def __init__(self) -> None: + self.requests: list[httpx.Request] = [] + + def handler(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + body = json.loads(request.content) + return httpx.Response( + 200, + json={ + 'id': 'chatcmpl-1', + 'object': 'chat.completion', + 'created': 0, + 'model': body['model'], + 'choices': [ + {'index': 0, 'message': {'role': 'assistant', 'content': 'Grilled salmon'}, 'finish_reason': 'stop'} + ], + 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}, + }, + ) + + +def _garden(server: FakeGarden, **config: Any) -> OpenAICompatible: # noqa: ANN401 + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return OpenAICompatible(backend=GoogleCloud(**config), client_options={'http_client': http_client}) + + +@pytest.mark.asyncio +async def test_generate_goes_to_model_gardens_endpoint_with_the_adc_token() -> None: + """`modelgarden//` posts to the project's openapi endpoint with a Google bearer token.""" + server = FakeGarden() + garden = _garden(server, project='bistro-prod', location='us-east5') + ai = Genkit(plugins=[garden]) + + response = await ai.generate(model=garden.model(LLAMA), prompt='Suggest a dish.') + + assert response.text == 'Grilled salmon' + request = server.requests[-1] + assert str(request.url) == ( + 'https://us-east5-aiplatform.googleapis.com/v1beta1/projects/bistro-prod/locations/us-east5/endpoints/openapi' + '/chat/completions' + ) + assert request.headers['authorization'] == 'Bearer adc-token' + assert json.loads(request.content)['model'] == LLAMA + + +def test_refs_are_modelgarden_publisher_model() -> None: + """The ref helper gives the same refs genkit-vertexai's ModelGarden used for these models.""" + garden = OpenAICompatible(backend=GoogleCloud(project='p')) + + assert garden.name == 'modelgarden' + assert garden.model(LLAMA).name == f'modelgarden/{LLAMA}' + + +@pytest.mark.parametrize( + ('location', 'url'), + [ + ( + 'us-central1', + 'https://us-central1-aiplatform.googleapis.com/v1beta1/projects/p/locations/us-central1/endpoints/openapi', + ), + ('global', 'https://aiplatform.googleapis.com/v1beta1/projects/p/locations/global/endpoints/openapi'), + ], +) +def test_endpoint_url_per_location(location: str, url: str) -> None: + """Regional endpoints carry the region in the host; the global one doesn't.""" + assert model_garden_base_url(project='p', location=location) == url + + +@pytest.mark.asyncio +async def test_location_defaults_to_us_central1_and_project_to_adc(fake_adc: MagicMock) -> None: + """With nothing set, the project comes from the credentials and the location is us-central1.""" + fake_adc.return_value = (_credentials(), 'adc-project') + server = FakeGarden() + ai = Genkit(plugins=[_garden(server)]) + + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + fake_adc.assert_called_once() + assert server.requests[-1].url.host == 'us-central1-aiplatform.googleapis.com' + assert '/projects/adc-project/' in server.requests[-1].url.path + + +@pytest.mark.asyncio +async def test_env_project_and_location(monkeypatch: pytest.MonkeyPatch) -> None: + """GCLOUD_PROJECT wins over GOOGLE_CLOUD_PROJECT; GOOGLE_CLOUD_LOCATION sets the region.""" + monkeypatch.setenv('GCLOUD_PROJECT', 'from-gcloud') + monkeypatch.setenv('GOOGLE_CLOUD_PROJECT', 'from-google-cloud') + monkeypatch.setenv('GOOGLE_CLOUD_LOCATION', 'europe-west4') + server = FakeGarden() + ai = Genkit(plugins=[_garden(server)]) + + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + assert str(server.requests[-1].url).startswith( + 'https://europe-west4-aiplatform.googleapis.com/v1beta1/projects/from-gcloud/locations/europe-west4/' + ) + + +@pytest.mark.asyncio +async def test_no_project_anywhere_fails_with_the_fix(fake_adc: MagicMock) -> None: + """No project is a setup problem: FAILED_PRECONDITION naming three ways to set one.""" + fake_adc.return_value = (_credentials(), None) + server = FakeGarden() + ai = Genkit(plugins=[_garden(server)]) + + response = await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'GOOGLE_CLOUD_PROJECT' in response.error.message + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_missing_credentials_fail_and_are_retried_after_login(fake_adc: MagicMock) -> None: + """A failed credential load surfaces as FAILED_PRECONDITION and isn't cached.""" + fake_adc.side_effect = [GenkitError(status='FAILED_PRECONDITION', message='no creds'), (_credentials(), None)] + server = FakeGarden() + ai = Genkit(plugins=[_garden(server, project='p')]) + + first = await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + second = await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + assert first.error is not None and first.error.status == 'FAILED_PRECONDITION' + assert second.text == 'Grilled salmon' + assert fake_adc.call_count == 2 + + +@pytest.mark.asyncio +async def test_secrets_key_is_refused_before_loading_credentials(fake_adc: MagicMock) -> None: + """A context.secrets key can't bill a Google Cloud project, so the call fails without touching ADC.""" + server = FakeGarden() + ai = Genkit(plugins=[_garden(server, project='p')]) + + response = await ai.generate( + model=f'modelgarden/{LLAMA}', prompt='hi', context={'secrets': {'api_key': 'sk-tenant'}} + ) + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'Google Cloud credentials' in response.error.message + assert 'sk-tenant' not in response.error.message + fake_adc.assert_not_called() + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_lists_nothing_and_calls_no_models_endpoint() -> None: + """Model Garden has no /models, so the Dev UI lists nothing for it and no request goes out.""" + server = FakeGarden() + garden = _garden(server, project='p') + + assert await garden.list_actions() == [] + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_runs_beside_openai_and_a_named_compatible_server() -> None: + """modelgarden/, openai/ and a named server's namespace don't collide.""" + garden_server = FakeGarden() + ai = Genkit( + plugins=[ + OpenAI(api_key='sk-openai'), + OpenAICompatible(name='openrouter', base_url='https://openrouter.ai/api/v1', api_key='sk-or'), + _garden(garden_server, project='p'), + ] + ) + + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + assert json.loads(garden_server.requests[-1].content)['model'] == LLAMA + assert await ai.lookup_model('openrouter/meta-llama/llama-3.3-70b-instruct') is not None + assert await ai.lookup_model('openai/gpt-4o') is not None + + +@pytest.mark.asyncio +async def test_base_url_overrides_the_endpoint() -> None: + """base_url replaces the derived endpoint, e.g. for Private Service Connect; auth stays Google's.""" + server = FakeGarden() + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + garden = OpenAICompatible( + backend=GoogleCloud(project='p'), + base_url='https://psc.example.internal/v1', + client_options={'http_client': http_client}, + ) + ai = Genkit(plugins=[garden]) + + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + assert str(server.requests[-1].url) == 'https://psc.example.internal/v1/chat/completions' + assert server.requests[-1].headers['authorization'] == 'Bearer adc-token' + + +@pytest.mark.parametrize( + ('name', 'expected'), + [(None, 'modelgarden'), ('modelgarden', 'modelgarden'), ('vertex', 'vertex')], +) +def test_name_defaults_to_modelgarden_and_accepts_custom_names(name: str | None, expected: str) -> None: + """With GoogleCloud the namespace defaults to modelgarden, and any other valid name is allowed.""" + garden = OpenAICompatible(backend=GoogleCloud(project='p'), name=name) + + assert garden.name == expected + assert garden.model(LLAMA).name == f'{expected}/{LLAMA}' + + +@pytest.mark.asyncio +async def test_custom_names_allow_multiple_google_cloud_instances() -> None: + """Custom names let two Google Cloud regions or projects run side by side in one app.""" + us_server, eu_server = FakeGarden(), FakeGarden() + us = OpenAICompatible( + name='garden-us', + backend=GoogleCloud(project='us-proj', location='us-central1'), + client_options={'http_client': httpx.AsyncClient(transport=httpx.MockTransport(us_server.handler))}, + ) + eu = OpenAICompatible( + name='garden-eu', + backend=GoogleCloud(project='eu-proj', location='europe-west4'), + client_options={'http_client': httpx.AsyncClient(transport=httpx.MockTransport(eu_server.handler))}, + ) + ai = Genkit(plugins=[us, eu]) + + await ai.generate(model=us.model(LLAMA), prompt='hi') + await ai.generate(model=eu.model(LLAMA), prompt='hi') + + assert str(us_server.requests[-1].url).startswith( + 'https://us-central1-aiplatform.googleapis.com/v1beta1/projects/us-proj/locations/us-central1/' + ) + assert str(eu_server.requests[-1].url).startswith( + 'https://europe-west4-aiplatform.googleapis.com/v1beta1/projects/eu-proj/locations/europe-west4/' + ) + assert json.loads(us_server.requests[-1].content)['model'] == LLAMA + assert json.loads(eu_server.requests[-1].content)['model'] == LLAMA + + +@pytest.mark.parametrize('bad_name', ['', 'garden/eu']) +def test_invalid_name_with_google_cloud_raises(bad_name: str) -> None: + """Custom names with GoogleCloud still enforce the single-segment namespace rule.""" + with pytest.raises(ValueError, match='non-empty string without'): + OpenAICompatible(backend=GoogleCloud(project='p'), name=bad_name) + + +def test_api_key_with_google_cloud_raises() -> None: + """An API key can't authenticate a Google Cloud call, so passing one fails at setup.""" + with pytest.raises(ValueError, match='drop api_key'): + OpenAICompatible(backend=GoogleCloud(project='p'), **cast(Any, {'api_key': 'sk-x'})) + + +def test_client_options_reserves_api_key_and_rejects_duplicate_base_url() -> None: + """GoogleCloud owns api_key, and base_url passed twice fails at setup instead of on first generate.""" + with pytest.raises(TypeError, match="unexpected client_options key 'api_key'"): + OpenAICompatible(backend=GoogleCloud(project='p'), client_options={'api_key': 'sk-x'}) + + with pytest.raises(TypeError, match='base_url both as an argument and in client_options'): + OpenAICompatible( + backend=GoogleCloud(project='p'), + base_url='https://a.example.internal/v1', + client_options={'base_url': 'https://b.example.internal/v1'}, + ) + + +@pytest.mark.asyncio +async def test_client_options_base_url_overrides_endpoint_cleanly() -> None: + """base_url supplied only via client_options overrides the derived URL without colliding on AsyncOpenAI.""" + server = FakeGarden() + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + garden = OpenAICompatible( + backend=GoogleCloud(project='p'), + client_options={'base_url': 'https://psc.example.internal/v1', 'http_client': http_client}, + ) + ai = Genkit(plugins=[garden]) + + await ai.generate(model=garden.model(LLAMA), prompt='hi') + + assert str(server.requests[-1].url) == 'https://psc.example.internal/v1/chat/completions' + assert server.requests[-1].headers['authorization'] == 'Bearer adc-token' + + +def test_backend_must_be_google_cloud() -> None: + """A backend that isn't GoogleCloud fails at setup.""" + with pytest.raises(TypeError, match='GoogleCloud'): + OpenAICompatible(backend=cast(Any, 'google_cloud')) + + +def test_backend_rejects_google_cloud_from_another_package() -> None: + """Passing another plugin's GoogleCloud names the module and tells the caller where to import it.""" + foreign_google_cloud = type('GoogleCloud', (), {'__module__': 'genkit_anthropic._google_cloud'})() + + with pytest.raises( + TypeError, + match=r'genkit_anthropic\._google_cloud\.GoogleCloud; import GoogleCloud from genkit_openai', + ): + OpenAICompatible(backend=cast(Any, foreign_google_cloud)) + + +def test_google_cloud_is_frozen() -> None: + """GoogleCloud is a frozen value, so one instance can be shared safely.""" + backend = GoogleCloud(project='bistro-prod') + with pytest.raises(FrozenInstanceError): + backend.project = 'other' # type: ignore[misc] + + +def test_without_backend_name_and_base_url_are_still_required() -> None: + """The generic plugin has no default name or server, as in JS and Go.""" + with pytest.raises(ValueError, match='non-empty string'): + OpenAICompatible(**cast(Any, {'base_url': 'https://openrouter.ai/api/v1'})) + with pytest.raises(ValueError, match='needs base_url'): + OpenAICompatible(**cast(Any, {'name': 'openrouter'})) + + +@pytest.mark.parametrize( + ('blocked', 'exc'), + [ + ('google.auth', ModuleNotFoundError("No module named 'google.auth'", name='google.auth')), + ( + 'google.auth.transport.requests', + ImportError('The requests library is not installed from please install the requests package'), + ), + ], + ids=['no-google-auth', 'no-requests-transport'], +) +def test_without_google_auth_names_the_extra(blocked: str, exc: ImportError) -> None: + """A missing google-auth or requests transport fails on the constructor line with the install command.""" + real_import = builtins.__import__ + + def _blocked_import(name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + if name == blocked or name.startswith(f'{blocked}.'): + raise exc + return real_import(name, *args, **kwargs) + + with ( + patch('builtins.__import__', _blocked_import), + pytest.raises(ImportError, match=r'genkit-openai\[google-cloud\]'), + ): + OpenAICompatible(backend=GoogleCloud(project='p')) + + +def test_load_adc_refreshes_and_returns_project() -> None: + """load_adc asks for the cloud-platform scope and refreshes now, so a stale login fails on the first call.""" + credentials = MagicMock(name='user-credentials') + with patch('google.auth.default', return_value=(credentials, 'gcloud-project')) as default: + assert load_adc() == (credentials, 'gcloud-project') + + assert default.call_args.kwargs['scopes'] == ['https://www.googleapis.com/auth/cloud-platform'] + credentials.refresh.assert_called_once() + + +@pytest.mark.parametrize('stale', [False, True], ids=['no-adc', 'stale-login']) +def test_load_adc_failures_name_the_login_command(stale: bool) -> None: + """A missing or stale login is a setup problem, reported with the command that fixes it.""" + credentials = MagicMock(name='user-credentials') + if stale: + credentials.refresh.side_effect = RefreshError('Reauthentication is needed.') + default = patch('google.auth.default', return_value=(credentials, None)) + else: + default = patch('google.auth.default', side_effect=DefaultCredentialsError('not found')) + + with default, pytest.raises(GenkitError) as exc_info: + load_adc() + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'gcloud auth application-default login' in str(exc_info.value) + + +def _refresh_caused_by_transport() -> RefreshError: + err = RefreshError('Metadata server unreachable.') + err.__cause__ = TransportError('connection reset') + return err + + +@pytest.mark.parametrize( + 'failure', + [ + TransportError('connection reset'), + RefreshError('Temporary backend error.', retryable=True), + _refresh_caused_by_transport(), + ], + ids=['transport-error', 'retryable-refresh', 'refresh-caused-by-transport'], +) +def test_load_adc_transient_failures_are_unavailable(failure: Exception) -> None: + """Transient network or metadata-server blips map to UNAVAILABLE so Retry middleware retries them.""" + credentials = MagicMock(name='user-credentials') + credentials.refresh.side_effect = failure + + with patch('google.auth.default', return_value=(credentials, None)), pytest.raises(GenkitError) as exc_info: + load_adc() + + assert exc_info.value.status == 'UNAVAILABLE' + + +@pytest.mark.parametrize( + 'failure', + [ + TransportError('connection reset'), + RefreshError('Temporary backend error.', retryable=True), + _refresh_caused_by_transport(), + ], + ids=['transport-error', 'retryable-refresh', 'refresh-caused-by-transport'], +) +@pytest.mark.asyncio +async def test_token_transient_refresh_failures_are_unavailable(failure: Exception) -> None: + """A transient refresh blip mid-run maps to UNAVAILABLE so Retry middleware can retry.""" + credentials = MagicMock(name='adc-credentials') + credentials.valid = False + credentials.refresh.side_effect = failure + + with pytest.raises(GenkitError) as exc_info: + await AdcToken(credentials)() + + assert exc_info.value.status == 'UNAVAILABLE' + + +@pytest.mark.asyncio +async def test_token_refreshes_only_when_expired() -> None: + """The token function refreshes an expired credential and reuses a valid one.""" + credentials = MagicMock(name='adc-credentials') + credentials.valid = False + credentials.token = 'fresh' + token = AdcToken(credentials) + + assert await token() == 'fresh' + credentials.refresh.assert_called_once() + + credentials.valid = True + assert await token() == 'fresh' + credentials.refresh.assert_called_once() + + +@pytest.mark.asyncio +async def test_token_refresh_rejected_names_the_login_command() -> None: + """A refresh rejected mid-run fails the call with FAILED_PRECONDITION and the fix.""" + credentials = MagicMock(name='adc-credentials') + credentials.valid = False + credentials.refresh.side_effect = RefreshError('Reauthentication is needed.') + + with pytest.raises(GenkitError) as exc_info: + await AdcToken(credentials)() + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'gcloud auth application-default login' in str(exc_info.value) + + +@pytest.mark.asyncio +async def test_explicit_project_beats_the_credentials_project(fake_adc: MagicMock) -> None: + """GoogleCloud(project=...) wins over the project the credentials carry.""" + fake_adc.return_value = (_credentials(), 'adc-project') + server = FakeGarden() + ai = Genkit(plugins=[_garden(server, project='bistro-prod')]) + + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + assert '/projects/bistro-prod/' in server.requests[-1].url.path + + +@pytest.mark.asyncio +async def test_base_url_override_does_not_require_project(fake_adc: MagicMock) -> None: + """With an explicit base_url (e.g. Private Service Connect), no Google Cloud project is needed.""" + fake_adc.return_value = (_credentials(), None) + server = FakeGarden() + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + garden = OpenAICompatible( + backend=GoogleCloud(), + base_url='https://psc.example.internal/v1', + client_options={'http_client': http_client}, + ) + ai = Genkit(plugins=[garden]) + + res = await ai.generate(model=garden.model(LLAMA), prompt='hi') + + assert res.text == 'Grilled salmon' + assert str(server.requests[-1].url) == 'https://psc.example.internal/v1/chat/completions' + + +@pytest.mark.parametrize('bad_url', ['', ' ']) +def test_blank_base_url_raises_at_setup(bad_url: str) -> None: + """An empty or whitespace base_url fails at setup instead of silently falling back to the derived URL.""" + with pytest.raises(ValueError, match='base_url must be a non-empty string'): + OpenAICompatible(backend=GoogleCloud(project='p'), base_url=bad_url) + with pytest.raises(ValueError, match='base_url must be a non-empty string'): + OpenAICompatible(backend=GoogleCloud(project='p'), client_options={'base_url': bad_url}) + + +@pytest.mark.parametrize('header_name', ['Authorization', 'authorization']) +def test_pinned_authorization_header_raises_at_setup(header_name: str) -> None: + """Pinning Authorization would override Google ADC bearer tokens, so it fails at setup.""" + with pytest.raises(ValueError, match='drop the Authorization header'): + OpenAICompatible( + backend=GoogleCloud(project='p'), + client_options={'default_headers': {header_name: 'Bearer pinned'}}, + ) + + +@pytest.mark.asyncio +async def test_ambient_openai_org_and_project_never_leak(monkeypatch: pytest.MonkeyPatch) -> None: + """OPENAI_ORG_ID and OPENAI_PROJECT_ID never go out on Google Cloud Model Garden requests.""" + monkeypatch.setenv('OPENAI_ORG_ID', 'org-secret') + monkeypatch.setenv('OPENAI_PROJECT_ID', 'proj-secret') + server = FakeGarden() + ai = Genkit(plugins=[_garden(server, project='p')]) + + await ai.generate(model=f'modelgarden/{LLAMA}', prompt='hi') + + headers = server.requests[-1].headers + assert 'openai-organization' not in headers + assert 'openai-project' not in headers + + +@pytest.mark.asyncio +async def test_embed_refuses_secrets_key_before_loading_credentials(fake_adc: MagicMock) -> None: + """`ai.embed` enforces the same context.secrets refusal as generate.""" + server = FakeGarden() + ai = Genkit(plugins=[_garden(server, project='p')]) + + with pytest.raises(GenkitError) as exc_info: + await ai.embed( + embedder='modelgarden/some/embedder', + content='hello', + context={'secrets': {'api_key': 'sk-tenant'}}, + ) + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'Google Cloud credentials' in exc_info.value.message + fake_adc.assert_not_called() + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_token_serializes_concurrent_refreshes() -> None: + """Concurrent callers hitting an expired credential refresh once instead of racing.""" + entered = threading.Event() + release = threading.Event() + refresh_count = 0 + + class _FakeCreds: + valid = False + token: str | None = None + + def refresh(self, _request: Any) -> None: # noqa: ANN401 + nonlocal refresh_count + refresh_count += 1 + entered.set() + release.wait(timeout=2) + self.token = 'refreshed-once' + self.valid = True + + token = AdcToken(_FakeCreds()) + tasks = [asyncio.create_task(token()) for _ in range(4)] + await asyncio.to_thread(entered.wait, 2) + release.set() + results = await asyncio.gather(*tasks) + + assert results == ['refreshed-once'] * 4 + assert refresh_count == 1 + + +@pytest.mark.parametrize('empty_token', [None, '']) +@pytest.mark.asyncio +async def test_token_guards_empty_or_none_token(empty_token: str | None) -> None: + """A credential with no usable token fails with FAILED_PRECONDITION instead of leaking None.""" + credentials = MagicMock(name='adc-credentials') + credentials.valid = True + credentials.token = empty_token + + with pytest.raises(GenkitError) as exc_info: + await AdcToken(credentials)() + + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert 'no Google Cloud access token' in exc_info.value.message + + +def test_load_adc_maps_refresh_error_from_default() -> None: + """RefreshError raised directly from google.auth.default() maps like refresh() failures.""" + with ( + patch('google.auth.default', side_effect=RefreshError('Transient metadata error.', retryable=True)), + pytest.raises(GenkitError) as exc_info, + ): + load_adc() + assert exc_info.value.status == 'UNAVAILABLE' + + with ( + patch('google.auth.default', side_effect=RefreshError('Reauthentication is needed.')), + pytest.raises(GenkitError) as exc_info, + ): + load_adc() + assert exc_info.value.status == 'FAILED_PRECONDITION' + + +@pytest.mark.asyncio +async def test_retry_middleware_retries_unavailable_but_not_failed_precondition(fake_adc: MagicMock) -> None: + """Retry middleware retries transient UNAVAILABLE ADC failures and stops on FAILED_PRECONDITION.""" + fake_adc.side_effect = [GenkitError(status='UNAVAILABLE', message='metadata blip'), (_credentials(), None)] + server = FakeGarden() + ai = Genkit(plugins=[_garden(server, project='p')]) + + res = await ai.generate( + model=f'modelgarden/{LLAMA}', + prompt='hi', + use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True)], + ) + assert res.text == 'Grilled salmon' + assert fake_adc.call_count == 2 + + fake_adc.reset_mock() + fake_adc.side_effect = GenkitError(status='FAILED_PRECONDITION', message='not logged in') + server2 = FakeGarden() + ai2 = Genkit(plugins=[_garden(server2, project='p')]) + res2 = await ai2.generate( + model=f'modelgarden/{LLAMA}', + prompt='hi', + use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True)], + ) + assert res2.error is not None + assert res2.error.status == 'FAILED_PRECONDITION' + assert fake_adc.call_count == 1 diff --git a/uv.lock b/uv.lock index 6e16282a..b35a6394 100644 --- a/uv.lock +++ b/uv.lock @@ -1558,12 +1558,19 @@ dependencies = [ { name = "strenum", marker = "python_full_version < '3.11'" }, ] +[package.optional-dependencies] +google-cloud = [ + { name = "google-auth", extra = ["requests"] }, +] + [package.metadata] requires-dist = [ { name = "genkit", editable = "packages/genkit" }, + { name = "google-auth", extras = ["requests"], marker = "extra == 'google-cloud'", specifier = ">=2.14.1" }, { name = "openai", specifier = ">=1.106.0,<3" }, { name = "strenum", marker = "python_full_version < '3.11'", specifier = ">=0.4.15" }, ] +provides-extras = ["google-cloud"] [[package]] name = "genkit-otel"