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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions packages/genkit-openai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
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']
160 changes: 124 additions & 36 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
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 All @@ -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.

Expand All @@ -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)
Expand All @@ -67,48 +118,92 @@ 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 ``/``, 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]:
Expand All @@ -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."""
Expand All @@ -155,15 +244,15 @@ 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)

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 @@ -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
Loading
Loading