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
63 changes: 58 additions & 5 deletions packages/genkit-openai/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Genkit OpenAI Plugin

OpenAI-compatible model provider for Genkit (OpenAI, Azure OpenAI, and other
compatible endpoints).
OpenAI model provider for Genkit, plus `OpenAICompatible` for any other server
that speaks the OpenAI API.

> **Building with a coding agent? Install the Genkit Python skill first.**
>
Expand Down Expand Up @@ -43,18 +43,20 @@ if __name__ == '__main__':
```

Set `OPENAI_API_KEY` in the environment, or pass `api_key=` to `OpenAI()`.
`base_url=` points the plugin at another OpenAI-compatible server. Pass the URL
up to and including `/v1`; the SDK appends `/chat/completions`. Any other
`base_url=` points the plugin at a proxy or gateway in front of OpenAI. Pass the
URL up to and including `/v1`; the SDK appends `/chat/completions`. Any other
`AsyncOpenAI` setting goes in `client_options`:

```python
OpenAI(
api_key=key,
base_url='https://openrouter.ai/api/v1',
base_url='https://llm-gateway.example.com/v1',
client_options={'organization': 'org-123', 'timeout': 30, 'max_retries': 5},
)
```

For a server that isn't OpenAI, use `OpenAICompatible` below.

## Tools on reasoning models

On Chat Completions, some reasoning models, such as `gpt-6-sol`, accept
Expand Down Expand Up @@ -85,6 +87,57 @@ alias.
On `gpt-image-2` and older GPT Image models they fail before the request is
sent. To send one anyway, pass it as `extra={'quality': 'xhigh'}`.

## Any OpenAI-compatible server

`OpenAICompatible` connects any server that speaks the OpenAI API (OpenRouter,
Together, Groq, vLLM, LiteLLM, a local model server) under a name you pick.
Models register as `<name>/<id>`, and `<id>` is sent exactly as the server
spells it.

```python
from genkit import Genkit
from genkit_openai import OpenAI, OpenAICompatible

# 1. Name the server; its models become openrouter/<id>
openrouter = OpenAICompatible(name='openrouter', base_url='https://openrouter.ai/api/v1', api_key=key)

# 2. Run it beside OpenAI's own API
ai = Genkit(plugins=[OpenAI(), openrouter])

# 3. Use the server's own ids, slashes and all
res = await ai.generate(model=openrouter.model('meta-llama/llama-3.3-70b-instruct'), prompt='Name a bakery.')
print(res.text)
# => Rise & Shine Bakehouse

# 4. Embedders resolve the same way
vectors = await ai.embed(embedder='openrouter/openai/text-embedding-3-small', content='Mushroom Risotto')
```

- There's no built-in model list. Any id resolves when you call it, and the
Dev UI lists what the server's `/models` returns. A server without `/models`
lists nothing; calls still work.
- Give each server its own `name`. Several `OpenAICompatible` plugins and an
`OpenAI()` can run in one app.
- `api_key=None` is for servers that need no key. `OPENAI_API_KEY`,
`OPENAI_ORG_ID`, and `OPENAI_PROJECT_ID` are never read, so OpenAI account
credentials and headers don't go to another server.
- `model(id)` never strips `<name>/` from `id`, so provider-prefixed server ids
such as `openrouter.model('openrouter/auto')` go out unchanged.
- For a token that expires, pass an async function as `api_key`. The SDK
awaits it before each request:

```python
async def gateway_token() -> str:
return await token_cache.get()

OpenAICompatible(name='gateway', base_url='https://llm-gateway.example.com/v1', api_key=gateway_token)
```

- A per-request key in `context={'secrets': {'api_key': ...}}` replaces the
plugin key for that call.
- `OpenAIConfig` is the config for every model. A server may ignore fields it
doesn't support, or reject them.

## Mistral

`Mistral()` registers Mistral's models and embedders under `mistral/`, as the
Expand Down
2 changes: 1 addition & 1 deletion packages/genkit-openai/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ classifiers = [
"Typing :: Typed",
"License :: OSI Approved :: Apache Software License",
]
dependencies = ["genkit>=0.14.0,<2", "openai>=1.99.2,<3", "strenum>=0.4.15; python_version < '3.11'"]
dependencies = ["genkit>=0.14.0,<2", "openai>=1.106.0,<3", "strenum>=0.4.15; python_version < '3.11'"]
description = "OpenAI-compatible models on Genkit"
keywords = [
"genkit",
Expand Down
9 changes: 6 additions & 3 deletions packages/genkit-openai/src/genkit_openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@

Registers OpenAI chat, image, text-to-speech, transcription, and embedding
models under ``openai/``, using the official OpenAI Python SDK. ``base_url=``
points it at any OpenAI-compatible server, such as Azure OpenAI or Together AI.
points it at a proxy or gateway in front of OpenAI.
``Mistral()`` (or ``OpenAI(provider='mistral')``) registers Mistral's chat
models and embedders under ``mistral/``.
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.

Example:
```python
Expand Down Expand Up @@ -60,7 +62,8 @@ async def main() -> None:
- OpenAI documentation: https://platform.openai.com/docs/
"""

from ._compatible import OpenAICompatible
from ._openai_plugin import Mistral, OpenAI
from ._typing import OpenAIConfig

__all__ = ['Mistral', 'OpenAI', 'OpenAIConfig']
__all__ = ['Mistral', 'OpenAI', 'OpenAICompatible', 'OpenAIConfig']
262 changes: 262 additions & 0 deletions packages/genkit-openai/src/genkit_openai/_compatible.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
# 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

"""Any server that speaks the OpenAI API, registered under a name you pick."""

from collections.abc import Mapping
from typing import Any

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._models._handler import OpenAIModelHandler
from genkit_openai._models._mistral import is_mistral
from genkit_openai._models._model import OpenAIModel
from genkit_openai._openai_plugin import (
ApiKey,
_build_compatible_client,
_client_kwargs,
_split_tenant_headers,
_with_tenant_key,
embed_texts,
)
from genkit_openai._secrets import context_api_key
from genkit_openai._typing import OpenAIConfig

logger = get_logger(__name__)

# Sent when the server needs no key. AsyncOpenAI requires one, and without a
# value it would read OPENAI_API_KEY and send an OpenAI key to another server.
_NO_KEY = 'no-key'

# Generic OpenAI-compatible chat capabilities. Constrained JSON schema stays
# unset so Genkit keeps schema instructions in the prompt for servers that only
# support prompt-guided or schema-less JSON mode.
_COMPATIBLE_SUPPORTS = ModelSupports(
multiturn=True,
media=True,
tools=True,
tool_choice=True,
system_role=True,
output=['json', 'text'],
)


def _validate_name(name: object) -> str:
"""Validate that a plugin namespace is a single segment without ``/``, ``:``, whitespace, or control chars."""
if (
not isinstance(name, str)
or not name
or '/' in name
or ':' in name
or any(ch.isspace() or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in name)
):
raise ValueError(
"OpenAICompatible name must be a non-empty string without '/', ':', whitespace, or control characters, "
f'got {name!r}'
)
return name


class OpenAICompatible(Plugin):
"""Any OpenAI-compatible server (OpenRouter, Together, Groq, vLLM, LiteLLM) under a name you pick.

Models and embedders register as ``<name>/<id>``, and ``<id>`` goes to the
server exactly as written, so ids with slashes (``meta-llama/...``,
``openai/gpt-4o``) need no escaping. There's no built-in model list:
any id resolves when you call it, and the Dev UI lists what the server's
``/models`` returns. Several instances, and an ``OpenAI()``, can run side
by side because each has its own name.

Example:
```python
from genkit import Genkit
from genkit_openai import 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)
ai = Genkit(plugins=[OpenAI(), openrouter])

# 2. The id is OpenRouter's own, sent as written
res = await ai.generate(model=openrouter.model('meta-llama/llama-3.3-70b-instruct'), prompt='Name a bakery.')
print(res.text)
# => Rise & Shine Bakehouse

# 3. A local server that needs no key
local = OpenAICompatible(name='local', base_url='http://localhost:8000/v1')
# => models resolve as local/<id>
```
"""

def __init__(
self,
*,
name: str,
base_url: str,
api_key: ApiKey | None = None,
client_options: Mapping[str, Any] | None = None,
) -> None:
"""Point the plugin at one OpenAI-compatible server.

Args:
name: The namespace for this server's models and embedders, e.g.
``'openrouter'`` gives ``openrouter/<id>``.
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``.
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.
client_options: Other ``AsyncOpenAI`` settings, such as
``timeout``, ``max_retries``, ``default_headers``, or
``http_client``.

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.
"""
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__}'
)
self.name = resolved_name
self._options = options
self._tenant_headers, self._pins_authorization = _split_tenant_headers(options.get('default_headers'))
self._list_actions_cache: list[Action] | None = None

def model(self, name: str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]:
"""Typed ref for one of this server's chat models, e.g. ``openrouter.model('openai/gpt-4o')``.

Unlike ``OpenAI.gpt()``, this never strips ``<name>/`` from ``name``:
providers such as OpenRouter have model ids that begin with their own
name (e.g. ``openrouter/auto``).

Args:
name: The id the server knows the model by, sent as written.
config: Default config for calls through this ref.
"""
if not isinstance(name, str) or not name.strip():
raise GenkitError(
status='INVALID_ARGUMENT', message=f'{self.name}.model: model name must be a non-empty string.'
)
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 init(self) -> list[Action]:
"""Nothing up front: every id resolves on demand."""
return []

async def resolve(self, action_type: ActionKind, name: str) -> Action | None:
"""Build the action for ``name``, by the kind the caller asked for.

Args:
action_type: ``MODEL`` for chat, ``EMBEDDER`` for embeddings.
name: The server's id, without this plugin's prefix.
"""
if action_type == ActionKind.MODEL:
return self._model_action(name)
if action_type == ActionKind.EMBEDDER:
return self._embedder_action(name)
return None

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)
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)
return await embed_texts(client, model_id, request, mistral=is_mistral(client))

return Embedder(
f'{self.name}/{model_id}',
_embed,
info=EmbedderInfo(label=f'{self.name} - {model_id}', supports=EmbedderSupports(input=['text'])),
)

async def list_actions(self) -> list[Action]:
"""What the server's ``/models`` 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.
"""
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]
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)
)
return []
seen: set[str] = set()
actions: list[Action] = []
for model_id in model_ids:
if model_id in seen:
continue
seen.add(model_id)
actions.append(
self._embedder_action(model_id) if 'embed' in model_id.lower() else self._model_action(model_id)
)
self._list_actions_cache = actions
return actions
Loading
Loading