From 10b6038b51b3143e20825edf6a48b393db916a73 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Wed, 25 Nov 2026 14:46:13 -0800 Subject: [PATCH] feat(py): add OpenAICompatible for any OpenAI-compatible server, matching JS and Go OpenAICompatible(name=..., base_url=..., api_key=...) registers a server's models and embedders as / and sends as written. No built-in catalog or OpenAI-only filters; the Dev UI lists /models and survives a server without it. api_key takes a string, an async function, or None (never reads OPENAI_API_KEY). OpenAI and OpenAICompatible share one embed helper. The openai floor moves to 1.106.0, the first release with async api_key. --- packages/genkit-openai/README.md | 60 +++- packages/genkit-openai/pyproject.toml | 2 +- .../src/genkit_openai/__init__.py | 9 +- .../src/genkit_openai/_compatible.py | 196 +++++++++++++ .../src/genkit_openai/_openai_plugin.py | 116 ++++---- .../tests/openai_compatible_test.py | 272 ++++++++++++++++++ tests/version_bounds_guard_test.py | 4 +- uv.lock | 2 +- 8 files changed, 600 insertions(+), 61 deletions(-) create mode 100644 packages/genkit-openai/src/genkit_openai/_compatible.py create mode 100644 packages/genkit-openai/tests/openai_compatible_test.py diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index d8793358..3d674bd2 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -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.** > @@ -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 @@ -85,6 +87,54 @@ 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 `/`, and `` 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/ +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` is never + read, so an OpenAI key doesn't go to another server. +- 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 diff --git a/packages/genkit-openai/pyproject.toml b/packages/genkit-openai/pyproject.toml index aec8fff7..e883c4e9 100644 --- a/packages/genkit-openai/pyproject.toml +++ b/packages/genkit-openai/pyproject.toml @@ -43,7 +43,7 @@ classifiers = [ "Typing :: Typed", "License :: OSI Approved :: Apache Software License", ] -dependencies = ["genkit>=0.14.0,<2", "openai>=1.60.0,<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", diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py index e15180d4..e5307def 100644 --- a/packages/genkit-openai/src/genkit_openai/__init__.py +++ b/packages/genkit-openai/src/genkit_openai/__init__.py @@ -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 @@ -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'] diff --git a/packages/genkit-openai/src/genkit_openai/_compatible.py b/packages/genkit-openai/src/genkit_openai/_compatible.py new file mode 100644 index 00000000..a470b35b --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_compatible.py @@ -0,0 +1,196 @@ +# 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 +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._models._model_info import get_default_openai_model_info +from genkit_openai._openai_plugin import ApiKey, _client_kwargs, 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' + + +class OpenAICompatible(Plugin): + """Any OpenAI-compatible server (OpenRouter, Together, Groq, vLLM, LiteLLM) under a name you pick. + + Models and embedders register as ``/``, and ```` 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/ + ``` + """ + + 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/``. + 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 ``/``, or ``base_url`` is empty. + TypeError: A ``client_options`` key ``AsyncOpenAI`` doesn't take, + or ``api_key``/``base_url`` repeated there. + """ + 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 + 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')``. + + 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: + 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 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 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=get_default_openai_model_info(model_id).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`` 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. + """ + if self._list_actions_cache is not None: + return self._list_actions_cache + try: + page = await self._client().models.list() + 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 + ] + self._list_actions_cache = actions + return actions diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 141010d6..6c8dc7f8 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -21,7 +21,7 @@ import inspect import os import re -from collections.abc import Mapping +from collections.abc import Awaitable, Callable, Mapping from typing import Any, Literal, TypeAlias, cast from openai import APIError, AsyncOpenAI @@ -97,8 +97,16 @@ _CLIENT_OPTION_KEYS = frozenset(inspect.signature(AsyncOpenAI.__init__).parameters) - {'self'} +# A static key, or an async function the SDK awaits before each request (e.g. a refreshed token). +ApiKey: TypeAlias = str | Callable[[], Awaitable[str]] + + def _client_kwargs( - *, api_key: str | None, base_url: str | None, client_options: Mapping[str, Any] | None + *, + api_key: ApiKey | None, + base_url: str | None, + client_options: Mapping[str, Any] | None, + plugin: str = 'OpenAI', ) -> dict[str, Any]: """Merge the typed settings into ``client_options`` for ``AsyncOpenAI``. @@ -110,18 +118,72 @@ def _client_kwargs( for key in options: if key not in _CLIENT_OPTION_KEYS: raise TypeError( - f'OpenAI got an unexpected client_options key {key!r}; ' + 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("_")))}' ) for name, value in (('api_key', api_key), ('base_url', base_url)): if value is None: continue if name in options: - raise TypeError(f'OpenAI got {name} both as an argument and in client_options; pass it once') + raise TypeError(f'{plugin} got {name} both as an argument and in client_options; pass it once') options[name] = value return options +async def embed_texts(client: AsyncOpenAI, model: str, request: EmbedRequest, *, mistral: bool) -> EmbedResponse: + """Call the embeddings endpoint for ``request`` and convert the reply. + + Shared by ``OpenAI`` and ``OpenAICompatible``. + + Args: + client: The client the call goes through, already carrying its key. + model: The id the server knows the embedder by. + request: The Genkit embed request. + mistral: Send Mistral's field names (``output_dimension``). + + Raises: + GenkitError: INVALID_ARGUMENT for a non-int ``dimensions``, or the + mapped provider error. + """ + texts = [''.join(part.text for part in doc.content if part.text) for doc in request.input] + + # Get optional parameters (omit when None; OpenAI create() uses Omit, not None) + dimensions: int | None = None + encoding_format: Literal['float'] | None = None + dim_val = request.options.get('dimensions') + if dim_val is not None: + # bool is an int subclass, so True would otherwise pass as 1. + if not isinstance(dim_val, int) or isinstance(dim_val, bool): + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'dimensions must be an int, got {dim_val!r}', + ) + dimensions = dim_val + # 'base64' is deliberately not forwarded: the SDK sends base64 either + # way and only decodes the response when it was not asked explicitly. + if request.options.get('encodingFormat') == 'float': + encoding_format = 'float' + + # Only set options go out; the SDK's sentinel for an unset one + # differs across the openai versions this package supports. + create_kwargs: dict[str, Any] = {} + if dimensions is not None: + if mistral: + # Mistral names it output_dimension and rejects dimensions. + # The SDK has no output_dimension kwarg, so it rides in extra_body. + create_kwargs['extra_body'] = {'output_dimension': dimensions} + else: + create_kwargs['dimensions'] = dimensions + if encoding_format is not None: + create_kwargs['encoding_format'] = encoding_format + try: + response = await client.embeddings.create(model=model, input=texts, **create_kwargs) + except APIError as e: + reraise_openai_error(e) + + return EmbedResponse(embeddings=[Embedding(embedding=item.embedding) for item in response.data]) + + def _missing_key_error(env: str) -> GenkitError: # A Mistral target used to fall back to OPENAI_API_KEY; say why a key # that is set there no longer counts. @@ -744,52 +806,8 @@ def _create_embedder_action(self, name: str) -> Action: async def embed_fn(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: """Embedder function that calls OpenAI embeddings API.""" - # Extract text from document content - texts = [] - for doc in request.input: - doc_text = ''.join( # type: ignore[arg-type] - part.text for part in doc.content if part.text is not None and part.text - ) - texts.append(doc_text) - - # Get optional parameters (omit when None; OpenAI create() uses Omit, not None) - dimensions: int | None = None - encoding_format: Literal['float'] | None = None - dim_val = request.options.get('dimensions') - if dim_val is not None: - # bool is an int subclass, so True would otherwise pass as 1. - if not isinstance(dim_val, int) or isinstance(dim_val, bool): - raise GenkitError( - status='INVALID_ARGUMENT', - message=f'dimensions must be an int, got {dim_val!r}', - ) - dimensions = dim_val - # 'base64' is deliberately not forwarded: the SDK sends base64 either - # way and only decodes the response when it was not asked explicitly. - if request.options.get('encodingFormat') == 'float': - encoding_format = 'float' - - # Only set options go out; the SDK's sentinel for an unset one - # differs across the openai versions this package supports. client = self._embed_client(ctx.context) - create_kwargs: dict[str, Any] = {} - if dimensions is not None: - if self._uses_mistral_names(client): - # Mistral names it output_dimension and rejects dimensions. - # The SDK has no output_dimension kwarg, so it rides in extra_body. - create_kwargs['extra_body'] = {'output_dimension': dimensions} - else: - create_kwargs['dimensions'] = dimensions - if encoding_format is not None: - create_kwargs['encoding_format'] = encoding_format - try: - response = await client.embeddings.create(model=name, input=texts, **create_kwargs) - except APIError as e: - reraise_openai_error(e) - - # Convert OpenAI response to Genkit format - embeddings = [Embedding(embedding=item.embedding) for item in response.data] - return EmbedResponse(embeddings=embeddings) + return await embed_texts(client, name, request, mistral=self._uses_mistral_names(client)) return Embedder( self._action_name(name), diff --git a/packages/genkit-openai/tests/openai_compatible_test.py b/packages/genkit-openai/tests/openai_compatible_test.py new file mode 100644 index 00000000..5f23253e --- /dev/null +++ b/packages/genkit-openai/tests/openai_compatible_test.py @@ -0,0 +1,272 @@ +# 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 against a fake OpenAI-compatible server, driven through ai.generate and ai.embed.""" + +import json +from typing import Any + +import httpx +import pytest +from genkit_openai import OpenAI, OpenAICompatible, OpenAIConfig + +from genkit import Genkit, GenkitError +from genkit.plugin_api import ActionKind + +BASE_URL = 'https://router.example.com/api/v1' + + +class FakeServer: + """Answers chat, embeddings and /models like an OpenAI-compatible server, and records requests.""" + + def __init__(self, *, model_ids: list[str] | None = None) -> None: + self.requests: list[httpx.Request] = [] + self._model_ids = model_ids + + def handler(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + path = request.url.path + if path.endswith('/models'): + if self._model_ids is None: + return httpx.Response(404, json={'error': {'message': 'Not found', 'type': 'not_found'}}) + data = [{'id': i, 'object': 'model', 'created': 0, 'owned_by': 'x'} for i in self._model_ids] + return httpx.Response(200, json={'object': 'list', 'data': data}) + body = json.loads(request.content) + if path.endswith('/embeddings'): + data = [{'object': 'embedding', 'index': i, 'embedding': [0.1, 0.2]} for i, _ in enumerate(body['input'])] + return httpx.Response( + 200, + json={ + 'object': 'list', + 'data': data, + 'model': body['model'], + 'usage': {'prompt_tokens': 1, 'total_tokens': 1}, + }, + ) + return httpx.Response( + 200, + json={ + 'id': 'chatcmpl-1', + 'object': 'chat.completion', + 'created': 0, + 'model': body['model'], + 'choices': [ + {'index': 0, 'message': {'role': 'assistant', 'content': 'Rise & Shine'}, 'finish_reason': 'stop'} + ], + 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}, + }, + ) + + def body(self, index: int = -1) -> dict[str, Any]: + return json.loads(self.requests[index].content) + + def auth(self, index: int = -1) -> str | None: + return self.requests[index].headers.get('authorization') + + +def _plugin(server: FakeServer, *, name: str = 'router', **kwargs: Any) -> OpenAICompatible: # noqa: ANN401 + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return OpenAICompatible(name=name, base_url=BASE_URL, client_options={'http_client': http_client}, **kwargs) + + +@pytest.mark.parametrize( + 'server_id', + ['meta-llama/llama-3.3-70b-instruct', 'openai/gpt-4o', 'google/gemini-2.5-pro'], + ids=['vendor-slash', 'openai-prefixed', 'pro-suffix'], +) +@pytest.mark.asyncio +async def test_generate_sends_the_server_id_as_written(server_id: str) -> None: + """`/` sends `` untouched, including ids that start with openai/ or end in -pro.""" + server = FakeServer() + router = _plugin(server, api_key='sk-router') + ai = Genkit(plugins=[router]) + + by_string = await ai.generate(model=f'router/{server_id}', prompt='Name a bakery.') + by_ref = await ai.generate(model=router.model(server_id), prompt='Name a bakery.') + + assert by_string.text == by_ref.text == 'Rise & Shine' + assert [server.body(0)['model'], server.body(1)['model']] == [server_id, server_id] + assert str(server.requests[0].url) == f'{BASE_URL}/chat/completions' + assert server.auth() == 'Bearer sk-router' + + +@pytest.mark.asyncio +async def test_model_ref_carries_typed_config() -> None: + """`router.model(id, config=...)` is an OpenAIConfig ref; its config reaches the request.""" + server = FakeServer() + router = _plugin(server, api_key='k') + ai = Genkit(plugins=[router]) + + await ai.generate(model=router.model('qwen/qwen3', config=OpenAIConfig(temperature=0.2)), prompt='hi') + + assert router.model('qwen/qwen3').config_schema is OpenAIConfig + assert server.body()['temperature'] == 0.2 + + +@pytest.mark.asyncio +async def test_runs_beside_openai_and_another_instance() -> None: + """Each instance has its own namespace, so OpenAI() and two compatible servers coexist.""" + router_server, local_server = FakeServer(), FakeServer() + ai = Genkit( + plugins=[ + OpenAI(api_key='sk-openai'), + _plugin(router_server, name='router', api_key='sk-router'), + _plugin(local_server, name='local'), + ] + ) + + await ai.generate(model='router/openai/gpt-4o', prompt='hi') + await ai.generate(model='local/qwen3-8b', prompt='hi') + + assert router_server.body()['model'] == 'openai/gpt-4o' + assert local_server.body()['model'] == 'qwen3-8b' + assert await ai.lookup_model('openai/gpt-4o') is not None + + +@pytest.mark.asyncio +async def test_registers_no_built_in_catalog() -> None: + """No OpenAI models show up for another server: init registers nothing.""" + assert await _plugin(FakeServer(), api_key='k').init() == [] + + +@pytest.mark.asyncio +async def test_list_actions_lists_the_servers_models_without_openai_filters() -> None: + """The Dev UI lists /models under the plugin's name; embed ids as embedders; -pro ids aren't dropped.""" + server = FakeServer(model_ids=['google/gemini-2.5-pro', 'openai/gpt-4o', 'nomic/nomic-embed-text', '']) + router = _plugin(server, api_key='k') + + actions = await router.list_actions() + again = await router.list_actions() + + assert [(a.name, a.kind) for a in actions] == [ + ('router/google/gemini-2.5-pro', ActionKind.MODEL), + ('router/openai/gpt-4o', ActionKind.MODEL), + ('router/nomic/nomic-embed-text', ActionKind.EMBEDDER), + ] + assert again is actions + + +@pytest.mark.asyncio +async def test_list_actions_on_a_server_without_models_lists_nothing_and_retries() -> None: + """A 404 from /models lists nothing instead of raising, and isn't cached.""" + server = FakeServer(model_ids=None) + router = _plugin(server, api_key='k') + + assert await router.list_actions() == [] + assert await router.list_actions() == [] + assert len([r for r in server.requests if r.url.path.endswith('/models')]) == 2 + + +@pytest.mark.asyncio +async def test_no_key_never_sends_openai_api_key(monkeypatch: pytest.MonkeyPatch) -> None: + """A keyless local server never gets OPENAI_API_KEY, even when it's set.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai-secret') + server = FakeServer() + ai = Genkit(plugins=[_plugin(server, name='local')]) + + await ai.generate(model='local/qwen3-8b', prompt='hi') + + assert 'sk-openai-secret' not in (server.auth() or '') + + +@pytest.mark.asyncio +async def test_async_api_key_is_awaited_before_each_request() -> None: + """A token function runs before every call, so an expiring token stays fresh.""" + tokens = iter(['tok-1', 'tok-2']) + + async def token() -> str: + return next(tokens) + + server = FakeServer() + ai = Genkit(plugins=[_plugin(server, api_key=token)]) + + await ai.generate(model='router/meta/llama-3.3-70b-instruct-maas', prompt='hi') + await ai.generate(model='router/meta/llama-3.3-70b-instruct-maas', prompt='hi') + + assert [server.auth(0), server.auth(1)] == ['Bearer tok-1', 'Bearer tok-2'] + + +@pytest.mark.asyncio +async def test_secrets_key_replaces_the_plugin_key_for_that_call() -> None: + """`context={'secrets': {'api_key': ...}}` authenticates one call; the next goes back to the plugin key.""" + server = FakeServer() + ai = Genkit(plugins=[_plugin(server, api_key='sk-plugin')]) + + await ai.generate(model='router/x', prompt='hi', context={'secrets': {'api_key': 'sk-tenant'}}) + await ai.generate(model='router/x', prompt='hi') + + assert [server.auth(0), server.auth(1)] == ['Bearer sk-tenant', 'Bearer sk-plugin'] + + +@pytest.mark.asyncio +async def test_embed_sends_the_server_id_and_dimensions() -> None: + """`ai.embed(embedder='router/')` resolves by kind, with the id and dimensions sent as given.""" + server = FakeServer() + ai = Genkit(plugins=[_plugin(server, api_key='k')]) + + result = await ai.embed( + embedder='router/nomic/nomic-embed-text', content='Mushroom Risotto', config={'dimensions': 2} + ) + + assert result[0].embedding == [0.1, 0.2] + assert server.body()['model'] == 'nomic/nomic-embed-text' + assert server.body()['dimensions'] == 2 + assert str(server.requests[-1].url) == f'{BASE_URL}/embeddings' + + +@pytest.mark.parametrize('bad_name', ['', 'open/router']) +def test_name_must_be_a_single_segment(bad_name: str) -> None: + """The name is the namespace, so it can't be empty or contain the separator.""" + with pytest.raises(ValueError, match='non-empty string without'): + OpenAICompatible(name=bad_name, base_url=BASE_URL) + + +def test_base_url_is_required() -> None: + """Without a server there's nothing to be compatible with; OpenAI() is for OpenAI's API.""" + with pytest.raises(ValueError, match='needs base_url'): + OpenAICompatible(name='router', base_url='') + + +def test_unknown_client_option_names_this_plugin() -> None: + """A bad client_options key fails on the constructor line, naming OpenAICompatible.""" + with pytest.raises(TypeError, match="OpenAICompatible got an unexpected client_options key 'region'"): + OpenAICompatible(name='router', base_url=BASE_URL, client_options={'region': 'us'}) + + +def test_model_ref_rejects_an_empty_name() -> None: + """An empty id would mint `router/`, which resolves to nothing.""" + router = OpenAICompatible(name='router', base_url=BASE_URL) + with pytest.raises(GenkitError, match='model name must be a non-empty string'): + router.model('') + + +@pytest.mark.asyncio +async def test_mistral_host_gets_mistrals_embedding_field_name() -> None: + """Pointed at Mistral's own host, dimensions go out as output_dimension, which Mistral requires.""" + server = FakeServer() + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + gateway = OpenAICompatible( + name='mistral-direct', + base_url='https://api.mistral.ai/v1', + api_key='k', + client_options={'http_client': http_client}, + ) + ai = Genkit(plugins=[gateway]) + + await ai.embed(embedder='mistral-direct/mistral-embed', content='Mushroom Risotto', config={'dimensions': 2}) + + assert server.body()['output_dimension'] == 2 + assert 'dimensions' not in server.body() diff --git a/tests/version_bounds_guard_test.py b/tests/version_bounds_guard_test.py index c0058d7f..35ec1a75 100644 --- a/tests/version_bounds_guard_test.py +++ b/tests/version_bounds_guard_test.py @@ -178,11 +178,11 @@ def test_real_workspace_passes_consistency_and_extras_contract() -> None: } assert referenced_plugins == all_plugins - # genkit-openai bounds openai>=1.60.0,<3. + # genkit-openai bounds openai>=1.106.0,<3; async-function api_key landed in 1.106. openai_project = consistency.load_pyproject(str(PY_DIR / 'packages' / 'genkit-openai' / 'pyproject.toml'))[ 'project' ] - assert 'openai>=1.60.0,<3' in openai_project['dependencies'] + assert 'openai>=1.106.0,<3' in openai_project['dependencies'] def test_bump_transition_0_12_0_to_0_13_0_rolls_floors_and_advances_minor_cap(tmp_path: Path) -> None: diff --git a/uv.lock b/uv.lock index b9c6bde4..7ede4112 100644 --- a/uv.lock +++ b/uv.lock @@ -1942,7 +1942,7 @@ dependencies = [ [package.metadata] requires-dist = [ { name = "genkit", editable = "packages/genkit" }, - { name = "openai", specifier = ">=1.60.0,<3" }, + { name = "openai", specifier = ">=1.106.0,<3" }, { name = "strenum", marker = "python_full_version < '3.11'", specifier = ">=0.4.15" }, ]