From 9a7d5b37cac32870ad9634729fdea336456eb2a3 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Mon, 30 Nov 2026 19:54:28 +0000 Subject: [PATCH] feat(py): serve Model Garden's OpenAI-compatible models via OpenAICompatible(backend=GoogleCloud()) --- packages/genkit-openai/README.md | 50 ++ packages/genkit-openai/pyproject.toml | 4 + .../src/genkit_openai/__init__.py | 6 +- .../src/genkit_openai/_compatible.py | 160 ++++-- .../src/genkit_openai/_google_cloud.py | 286 +++++++++++ .../src/genkit_openai/_openai_plugin.py | 18 +- .../openai_compatible_google_cloud_test.py | 485 ++++++++++++++++++ uv.lock | 7 + 8 files changed, 975 insertions(+), 41 deletions(-) create mode 100644 packages/genkit-openai/src/genkit_openai/_google_cloud.py create mode 100644 packages/genkit-openai/tests/openai_compatible_google_cloud_test.py diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 3d674bd2..4b0c3401 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -135,6 +135,56 @@ 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`, then + `us-central1`; most open models are regional. +- `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 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 a470b35b..fcc75996 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 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 @@ -40,6 +41,50 @@ _NO_KEY = 'no-key' +def _validate_name(name: object) -> str: + """Validate that a plugin namespace is a single non-empty segment.""" + if not isinstance(name, str) or not name or '/' in name: + raise ValueError(f"OpenAICompatible name must be a non-empty string without '/', got {name!r}") + 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 + + @loop_local_client + def _client(self) -> AsyncOpenAI: + return AsyncOpenAI(**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() + return client.with_options(api_key=api_key) if api_key else client + + async def model_ids(self) -> list[str]: + """What the server's ``/models`` lists.""" + page = await self._client().models.list() + return [m.id for m in page.data if m.id] + + class OpenAICompatible(Plugin): """Any OpenAI-compatible server (OpenRouter, Together, Groq, vLLM, LiteLLM) under a name you pick. @@ -50,10 +95,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) @@ -67,9 +118,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, *, @@ -77,38 +134,76 @@ 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 ``/``, or ``base_url`` is empty. - TypeError: 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 ``/``, or ``api_key`` with + ``GoogleCloud``. + TypeError: ``backend`` isn't a ``GoogleCloud``, or a + ``client_options`` key ``AsyncOpenAI`` doesn't take. + ImportError: ``backend=GoogleCloud(...)`` without the ``google-cloud`` extra. """ - if not isinstance(name, str) or not name or '/' in name: - raise ValueError(f"OpenAICompatible name must be a non-empty string without '/', got {name!r}") - if not base_url: - 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' - ) - options.setdefault('api_key', _NO_KEY) - self.name = name - self._options = options + if backend is None: + resolved_name = _validate_name(name) + if not base_url: + 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' + ) + options.setdefault('api_key', _NO_KEY) + self._server: _Server = _BaseUrlServer(options) + self.name = resolved_name + else: + if not isinstance(backend, GoogleCloud): + raise TypeError( + f'OpenAICompatible backend must be GoogleCloud(...) or None, got {type(backend).__name__}' + ) + 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]: @@ -124,15 +219,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 AsyncOpenAI(**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() - return client.with_options(api_key=key) if key else client + 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.""" @@ -155,7 +244,7 @@ def _model_action(self, model_id: str) -> Action: info = ModelInfo(label=f'{self.name} - {model_id}', supports=get_default_openai_model_info(model_id).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) @@ -163,7 +252,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( @@ -173,24 +262,23 @@ 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`` are listed as embedders, everything else as chat models; either can still be called as the other kind. A server without ``/models``, or one that rejects the call, lists nothing and - logs why; that isn't cached, so the next listing tries again. + logs why; that isn't cached, so the next listing tries 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() + model_ids = await self._server.model_ids() except (APIError, GenkitError) as e: logger.warning( 'Could not list models; the Dev UI shows none for this plugin', plugin=self.name, error=str(e) ) return [] - actions = [ - self._embedder_action(m.id) if 'embed' in m.id else self._model_action(m.id) for m in page.data if m.id - ] + actions = [self._embedder_action(m) if 'embed' in m else self._model_action(m) for m in model_ids] self._list_actions_cache = actions return actions 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..fa5fa29f --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_google_cloud.py @@ -0,0 +1,286 @@ +# 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 +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, _client_kwargs + +# 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`` isn't installed. + """ + # Optional dependency: google-auth ships with the [google-cloud] extra only. + try: + import google.auth # noqa: F401, PLC0415 + except ModuleNotFoundError 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)) + except default_error as e: + raise _missing_credentials(e) from e + except transport_error as e: + raise provider_error(e, status='UNAVAILABLE') from e + try: + credentials.refresh(Request()) + 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 + + async def __call__(self) -> str: + """A valid token, refreshing first if needed. + + Raises: + GenkitError: FAILED_PRECONDITION when the refresh is rejected; + UNAVAILABLE when the refresh hit a transient network failure. + """ + 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: + await asyncio.to_thread(self._credentials.refresh, Request()) + except (transport_error, refresh_error) as e: + raise _refresh_failure(e, transport_error) from e + return self._credentials.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; Google Cloud doesn't use one. + 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. + self._base_url: str | None = options.pop('base_url', None) + 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 project and token. + project = cast(str, self._project) + base_url = self._base_url or model_garden_base_url(project=project, location=self._location) + return AsyncOpenAI(base_url=base_url, api_key=cast(AdcToken, self._token), **self._options) + + 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 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 6c8dc7f8..335b8985 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -107,19 +107,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..eb39846c --- /dev/null +++ b/packages/genkit-openai/tests/openai_compatible_google_cloud_test.py @@ -0,0 +1,485 @@ +# 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 builtins +import json +from collections.abc import Iterator +from typing import Any, cast +from unittest.mock import MagicMock, patch + +import httpx +import pytest +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') + + +@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_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'})) + + +def test_without_google_auth_names_the_extra() -> None: + """A missing google-auth fails on the constructor line with the install command.""" + real_import = builtins.__import__ + + def _no_google_auth(name: str, *args: Any, **kwargs: Any) -> Any: # noqa: ANN401 + if name == 'google.auth' or name.startswith('google.auth.'): + raise ModuleNotFoundError(name=name) + return real_import(name, *args, **kwargs) + + with ( + patch('builtins.__import__', _no_google_auth), + 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 diff --git a/uv.lock b/uv.lock index 705192b3..e4f5de51 100644 --- a/uv.lock +++ b/uv.lock @@ -1951,12 +1951,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"