Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions packages/genkit-openai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<publisher>/<model>`).
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
Expand Down Expand Up @@ -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.
4 changes: 4 additions & 0 deletions packages/genkit-openai/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 5 additions & 1 deletion packages/genkit-openai/src/genkit_openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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']
193 changes: 141 additions & 52 deletions packages/genkit-openai/src/genkit_openai/_compatible.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@
"""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

from genkit import GenkitError, ModelResponse, get_logger
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
Expand Down Expand Up @@ -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.

Expand All @@ -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)
Expand All @@ -101,56 +157,106 @@ 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/<id>

# 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,
*,
name: str,
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/<id>``.
``'openrouter'`` gives ``openrouter/<id>``. 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]:
Expand All @@ -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."""
Expand All @@ -209,15 +301,15 @@ 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)

return Model(f'{self.name}/{model_id}', _generate, config_schema=OpenAIConfig, info=info)

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(
Expand All @@ -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)
Expand Down
Loading
Loading