diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index d8793358..6b8b6fd8 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,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 `/`, 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`, + `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 `/` 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 diff --git a/packages/genkit-openai/pyproject.toml b/packages/genkit-openai/pyproject.toml index ecfdf7b1..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.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", 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..0450f3c9 --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_compatible.py @@ -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 ``/``, 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 ``/``, ``:``, 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 ``/`` 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 diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index aaac9504..74e0ef3c 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 @@ -100,8 +100,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``. @@ -113,18 +121,134 @@ 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 +def _build_compatible_client(options: Mapping[str, Any]) -> AsyncOpenAI: + """Build an ``AsyncOpenAI`` client without inheriting ambient OpenAI org/project env vars. + + ``AsyncOpenAI`` reads ``OPENAI_ORG_ID`` and ``OPENAI_PROJECT_ID`` whenever + ``organization`` or ``project`` isn't passed, and sends ``OpenAI-Organization`` + and ``OpenAI-Project`` headers. Clearing them unless explicitly passed keeps + OpenAI account headers off third-party and Google Cloud endpoints. + """ + client = AsyncOpenAI(**options) + if options.get('organization') is None: + client.organization = None + if options.get('project') is None: + client.project = None + return client + + +def _split_tenant_headers(default_headers: Mapping[str, str] | None) -> tuple[dict[str, str], bool]: + """Split ``default_headers`` into tenant-safe headers and whether ``Authorization`` is pinned.""" + plugin_headers: dict[str, str] = dict(default_headers or {}) + tenant_headers = {k: v for k, v in plugin_headers.items() if k.lower() not in _PLUGIN_ACCOUNT_HEADERS} + pins_authorization = any(k.lower() == 'authorization' for k in plugin_headers) + return tenant_headers, pins_authorization + + +def _with_tenant_key( + client: AsyncOpenAI, + key: str, + *, + tenant_headers: Mapping[str, str], + pins_authorization: bool, + plugin: str = 'OpenAI', +) -> AsyncOpenAI: + """Return a copy of ``client`` that authenticates as the tenant and nothing else. + + The tenant's key picks its own organization and project, so the plugin's + ``organization``, ``project`` (including ``OPENAI_ORG_ID`` and + ``OPENAI_PROJECT_ID``) and the matching ``default_headers`` are left off. + ``base_url``, timeouts, retries and other headers carry over. + """ + if pins_authorization: + raise GenkitError( + status='FAILED_PRECONDITION', + message=( + f"{plugin}(client_options={{'default_headers': ...}}) pins an Authorization header, which would " + 'replace the context.secrets key. Drop that header to serve per-request keys.' + ), + ) + tenant = client.with_options(api_key=key, set_default_headers=tenant_headers) + tenant.organization = None + tenant.project = None + return tenant + + +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 + # The embeddings endpoint rejects requests with more than + # _MAX_EMBED_INPUTS inputs, so large batches go out in chunks. + data: list[Any] = [] + try: + for start in range(0, len(texts), _MAX_EMBED_INPUTS): + response = await client.embeddings.create( + model=model, + input=texts[start : start + _MAX_EMBED_INPUTS], + **create_kwargs, + ) + data.extend(response.data) + except APIError as e: + reraise_openai_error(e) + + return EmbedResponse(embeddings=[Embedding(embedding=item.embedding) for item in 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. @@ -455,9 +579,7 @@ def __init__( # OpenAI plugin and a Mistral one don't clash. self.name = MISTRAL_NAMESPACE if self._targets_mistral() else 'openai' self._plugin_api_key: str | None = options.get('api_key') - plugin_headers: dict[str, str] = dict(options.get('default_headers') or {}) - self._tenant_headers = {k: v for k, v in plugin_headers.items() if k.lower() not in _PLUGIN_ACCOUNT_HEADERS} - self._pins_authorization = any(k.lower() == 'authorization' for k in plugin_headers) + self._tenant_headers, self._pins_authorization = _split_tenant_headers(options.get('default_headers')) self._list_actions_cache: list[Action] | None = None # Supports read from Mistral's /models capabilities, so a listed model # resolves with the info it was listed with. @@ -642,18 +764,13 @@ def _with_tenant_key(self, client: AsyncOpenAI, key: str) -> AsyncOpenAI: project when the tenant is a member. ``base_url``, timeouts, retries and other headers carry over. """ - if self._pins_authorization: - raise GenkitError( - status='FAILED_PRECONDITION', - message=( - "OpenAI(client_options={'default_headers': ...}) pins an Authorization header, which would replace " - 'the context.secrets key. Drop that header to serve per-request keys.' - ), - ) - tenant = client.with_options(api_key=key, set_default_headers=self._tenant_headers) - tenant.organization = None - tenant.project = None - return tenant + return _with_tenant_key( + client, + key, + tenant_headers=self._tenant_headers, + pins_authorization=self._pins_authorization, + plugin='OpenAI', + ) def _embed_client(self, context: dict[str, Any]) -> AsyncOpenAI: """Same key order as models: ``context.secrets``, then the plugin key. @@ -747,62 +864,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 - - # The embeddings endpoint rejects requests with more than - # _MAX_EMBED_INPUTS inputs, so large batches go out in chunks. - data: list[Any] = [] - try: - for start in range(0, len(texts), _MAX_EMBED_INPUTS): - response = await client.embeddings.create( - model=name, - input=texts[start : start + _MAX_EMBED_INPUTS], - **create_kwargs, - ) - data.extend(response.data) - except APIError as e: - reraise_openai_error(e) - - # Convert OpenAI response to Genkit format - embeddings = [Embedding(embedding=item.embedding) for item in 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..62f135b2 --- /dev/null +++ b/packages/genkit-openai/tests/openai_compatible_test.py @@ -0,0 +1,583 @@ +# 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 collections.abc import Callable +from typing import Any, cast + +import httpx +import pytest +from genkit_openai import OpenAI, OpenAICompatible, OpenAIConfig +from pydantic import BaseModel + +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, + models_response: httpx.Response | None = None, + chat_handler: Callable[[dict[str, Any]], httpx.Response] | None = None, + ) -> None: + self.requests: list[httpx.Request] = [] + self._model_ids = model_ids + self._models_response = models_response + self._chat_handler = chat_handler + + def handler(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + path = request.url.path + if path.endswith('/models'): + if self._models_response is not None: + return self._models_response + 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}, + }, + ) + if self._chat_handler is not None: + return self._chat_handler(body) + 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', + client_options: dict[str, Any] | None = None, + **kwargs: Any, # noqa: ANN401 +) -> OpenAICompatible: + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + merged = {'http_client': http_client, **(client_options or {})} + return OpenAICompatible(name=name, base_url=BASE_URL, client_options=merged, **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', 'router:v1', 'open router', 'router\t', 'router\x00']) +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 '/', ':', whitespace, or control chars.""" + with pytest.raises(ValueError, match='non-empty string without'): + OpenAICompatible(name=bad_name, base_url=BASE_URL) + + +@pytest.mark.parametrize('bad_url', ['', ' ', cast(Any, None)]) +def test_base_url_is_required(bad_url: Any) -> None: # noqa: ANN401 + """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=bad_url) + + +def test_api_key_rejects_invalid_type() -> None: + """A non-string, non-callable api_key fails on the constructor line.""" + with pytest.raises(TypeError, match='api_key must be a string, an async callable, or None'): + OpenAICompatible(name='router', base_url=BASE_URL, api_key=cast(Any, 123)) + + +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'}) + + +@pytest.mark.parametrize('bad_id', ['', ' ']) +def test_model_ref_rejects_an_empty_name(bad_id: str) -> None: + """An empty or blank id would mint an unusable ref.""" + router = OpenAICompatible(name='router', base_url=BASE_URL) + with pytest.raises(GenkitError, match='model name must be a non-empty string'): + router.model(bad_id) + + +def test_model_ref_never_strips_plugin_prefix() -> None: + """Providers like OpenRouter have ids starting with their own name (e.g. openrouter/auto).""" + openrouter = OpenAICompatible(name='openrouter', base_url=BASE_URL) + assert openrouter.model('openrouter/auto').name == 'openrouter/openrouter/auto' + + +@pytest.mark.asyncio +async def test_ambient_openai_env_vars_and_explicit_none_key_never_leak(monkeypatch: pytest.MonkeyPatch) -> None: + """OPENAI_API_KEY, OPENAI_ORG_ID, and OPENAI_PROJECT_ID never go out, even with client_options={'api_key': None}.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai-secret') + monkeypatch.setenv('OPENAI_ORG_ID', 'org-openai-secret') + monkeypatch.setenv('OPENAI_PROJECT_ID', 'proj-openai-secret') + server = FakeServer() + ai = Genkit(plugins=[_plugin(server, name='local', client_options={'api_key': None})]) + + await ai.generate(model='local/qwen3-8b', prompt='hi') + + headers = server.requests[-1].headers + assert 'sk-openai-secret' not in (headers.get('authorization') or '') + assert 'openai-organization' not in headers + assert 'openai-project' not in headers + + +@pytest.mark.asyncio +async def test_explicit_organization_and_project_are_sent_on_plugin_calls_but_stripped_for_tenant_keys( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Explicit org/project go out on plugin calls, and are stripped when a tenant brings context.secrets.""" + monkeypatch.setenv('OPENAI_ORG_ID', 'org-env') + monkeypatch.setenv('OPENAI_PROJECT_ID', 'proj-env') + server = FakeServer() + router = _plugin( + server, + api_key='sk-plugin', + client_options={ + 'organization': 'org-explicit', + 'project': 'proj-explicit', + 'default_headers': { + 'X-Trace': 'keep-me', + 'OpenAI-Organization': 'org-hdr', + 'OpenAI-Project': 'proj-hdr', + }, + }, + ) + ai = Genkit(plugins=[router]) + + await ai.generate(model='router/x', prompt='plugin call') + await ai.generate(model='router/x', prompt='tenant call', context={'secrets': {'api_key': 'sk-tenant'}}) + + assert server.requests[0].headers.get('openai-organization') == 'org-hdr' + assert server.requests[0].headers.get('openai-project') == 'proj-hdr' + assert server.requests[0].headers.get('x-trace') == 'keep-me' + + tenant_headers = server.requests[1].headers + assert tenant_headers.get('authorization') == 'Bearer sk-tenant' + assert tenant_headers.get('x-trace') == 'keep-me' + assert 'openai-organization' not in tenant_headers + assert 'openai-project' not in tenant_headers + + +@pytest.mark.asyncio +async def test_secrets_key_refuses_pinned_authorization_header() -> None: + """A pinned Authorization header would override context.secrets, so tenant calls fail before sending.""" + server = FakeServer() + router = _plugin(server, api_key='sk-plugin', client_options={'default_headers': {'Authorization': 'Bearer pin'}}) + ai = Genkit(plugins=[router]) + + res = await ai.generate(model='router/x', prompt='hi', context={'secrets': {'api_key': 'sk-tenant'}}) + + assert res.error is not None + assert res.error.status == 'FAILED_PRECONDITION' + assert 'Authorization' in res.error.message + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_embed_uses_secrets_key_and_refuses_pinned_authorization() -> None: + """`ai.embed` honors context.secrets and enforces the same Authorization guard as generate.""" + server = FakeServer() + ai = Genkit(plugins=[_plugin(server, api_key='sk-plugin')]) + + await ai.embed(embedder='router/embed-1', content='hello', context={'secrets': {'api_key': 'sk-tenant'}}) + assert server.auth() == 'Bearer sk-tenant' + + pinned_server = FakeServer() + pinned_ai = Genkit( + plugins=[ + _plugin( + pinned_server, + api_key='sk-plugin', + client_options={'default_headers': {'authorization': 'Bearer pin'}}, + ) + ] + ) + with pytest.raises(GenkitError) as exc_info: + await pinned_ai.embed(embedder='router/embed-1', content='hello', context={'secrets': {'api_key': 'sk-tenant'}}) + assert exc_info.value.status == 'FAILED_PRECONDITION' + assert pinned_server.requests == [] + + +@pytest.mark.asyncio +async def test_resolved_model_declares_chat_capabilities_without_constrained_schema() -> None: + """Resolved models advertise tools, media, systemRole, and json output for the Dev UI without constrained.""" + router = _plugin(FakeServer(), api_key='k') + action = await router.resolve(ActionKind.MODEL, 'meta-llama/llama-3.3-70b-instruct') + + assert action is not None + assert action.metadata is not None + supports = cast(dict[str, Any], action.metadata['model'])['supports'] + assert supports == { + 'multiturn': True, + 'media': True, + 'tools': True, + 'toolChoice': True, + 'systemRole': True, + 'output': ['json', 'text'], + } + assert 'constrained' not in supports + + +@pytest.mark.asyncio +async def test_list_actions_handles_mixed_case_embedders_and_deduplicates() -> None: + """Embedder matching is case-insensitive, and duplicate ids keep first-seen order.""" + server = FakeServer( + model_ids=[ + 'Qwen/Qwen3-Embedding-8B', + 'nvidia/NV-Embed-v2', + 'openai/gpt-4o', + 'openai/gpt-4o', + 'Qwen/Qwen3-Embedding-8B', + ] + ) + router = _plugin(server, api_key='k') + + actions = await router.list_actions() + + assert [(a.name, a.kind) for a in actions] == [ + ('router/Qwen/Qwen3-Embedding-8B', ActionKind.EMBEDDER), + ('router/nvidia/NV-Embed-v2', ActionKind.EMBEDDER), + ('router/openai/gpt-4o', ActionKind.MODEL), + ] + + +@pytest.mark.parametrize( + 'models_response', + [ + httpx.Response(200, text='login', headers={'content-type': 'text/html'}), + httpx.Response(200, json={}), + httpx.Response(200, json={'object': 'list', 'data': None}), + httpx.Response(200, json=['not', 'a', 'page']), + ], + ids=['html-200', 'empty-object', 'null-data', 'json-array'], +) +@pytest.mark.asyncio +async def test_list_actions_survives_malformed_200_payloads(models_response: httpx.Response) -> None: + """A non-standard 200 /models body logs and returns [] instead of crashing, and isn't cached.""" + server = FakeServer(models_response=models_response) + router = _plugin(server, api_key='k') + + assert await router.list_actions() == [] + assert await router.list_actions() == [] + assert len(server.requests) == 2 + + +@pytest.mark.asyncio +async def test_generate_supports_tools_structured_output_streaming_and_error_mapping() -> None: + """Core model flows (tools, structured output, streaming, HTTP error mapping) work end to end.""" + tool_calls = 0 + + def tool_chat(body: dict[str, Any]) -> httpx.Response: + nonlocal tool_calls + tool_calls += 1 + if tool_calls == 1: + assert body['tools'][0]['function']['name'] == 'get_special' + return httpx.Response( + 200, + json={ + 'id': 'chatcmpl-t1', + 'object': 'chat.completion', + 'created': 0, + 'model': body['model'], + 'choices': [ + { + 'index': 0, + 'message': { + 'role': 'assistant', + 'content': None, + 'tool_calls': [ + { + 'id': 'call_1', + 'type': 'function', + 'function': {'name': 'get_special', 'arguments': '{}'}, + } + ], + }, + 'finish_reason': 'tool_calls', + } + ], + }, + ) + return httpx.Response( + 200, + json={ + 'id': 'chatcmpl-t2', + 'object': 'chat.completion', + 'created': 0, + 'model': body['model'], + 'choices': [ + { + 'index': 0, + 'message': {'role': 'assistant', 'content': 'Special is Risotto'}, + 'finish_reason': 'stop', + } + ], + }, + ) + + tool_server = FakeServer(chat_handler=tool_chat) + tool_ai = Genkit(plugins=[_plugin(tool_server, api_key='k')]) + + @tool_ai.tool() + async def get_special() -> str: + """Return today's special.""" + return 'Risotto' + + tool_res = await tool_ai.generate(model='router/x', prompt='What is the special?', tools=['get_special']) + assert tool_res.text == 'Special is Risotto' + assert tool_calls == 2 + + class Dish(BaseModel): + name: str + + json_server = FakeServer( + chat_handler=lambda body: httpx.Response( + 200, + json={ + 'id': 'chatcmpl-j1', + 'object': 'chat.completion', + 'created': 0, + 'model': body['model'], + 'choices': [ + { + 'index': 0, + 'message': {'role': 'assistant', 'content': '{"name": "Risotto"}'}, + 'finish_reason': 'stop', + } + ], + }, + ) + ) + json_ai = Genkit(plugins=[_plugin(json_server, api_key='k')]) + json_res = await json_ai.generate(model='router/x', prompt='Dish', output_schema=Dish) + assert json_res.output == Dish(name='Risotto') + + sse_payload = ( + 'data: {"id":"chatcmpl-s1","object":"chat.completion.chunk","created":0,"model":"x",' + '"choices":[{"index":0,"delta":{"role":"assistant","content":"Rise "},"finish_reason":null}]}\n\n' + 'data: {"id":"chatcmpl-s1","object":"chat.completion.chunk","created":0,"model":"x",' + '"choices":[{"index":0,"delta":{"content":"& Shine"},"finish_reason":"stop"}]}\n\n' + 'data: [DONE]\n\n' + ) + stream_server = FakeServer( + chat_handler=lambda _body: httpx.Response( + 200, content=sse_payload, headers={'content-type': 'text/event-stream'} + ) + ) + stream_ai = Genkit(plugins=[_plugin(stream_server, api_key='k')]) + stream = stream_ai.generate_stream(model='router/x', prompt='hi') + texts = [chunk.text async for chunk in stream] + final_res = await stream.response + assert ''.join(texts) == 'Rise & Shine' + assert final_res.text == 'Rise & Shine' + + err_server = FakeServer( + chat_handler=lambda _body: httpx.Response(429, json={'error': {'message': 'Rate limit', 'type': 'rate_limit'}}) + ) + err_ai = Genkit(plugins=[_plugin(err_server, api_key='k', client_options={'max_retries': 0})]) + err_res = await err_ai.generate(model='router/x', prompt='hi') + assert err_res.error is not None + assert err_res.error.status == 'RESOURCE_EXHAUSTED' + + +@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 cd40be77..10c31706 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.99.2,<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.99.2,<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 0366e6d8..6e16282a 100644 --- a/uv.lock +++ b/uv.lock @@ -1561,7 +1561,7 @@ dependencies = [ [package.metadata] requires-dist = [ { name = "genkit", editable = "packages/genkit" }, - { name = "openai", specifier = ">=1.99.2,<3" }, + { name = "openai", specifier = ">=1.106.0,<3" }, { name = "strenum", marker = "python_full_version < '3.11'", specifier = ">=0.4.15" }, ]