From a1510f85f5636a12200c459a04ad440a0fa7914c Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 19:57:19 +0000 Subject: [PATCH 01/22] feat(openai): send Mistral's field names when base_url is api.mistral.ai Mistral's OpenAI-compatible API rejects any field its schema doesn't declare. With base_url pointing at api.mistral.ai the plugin now: - drops stream_options on streaming calls - sends max_tokens instead of max_completion_tokens - sends seed as random_seed - sends an embedder's dimensions as output_dimension Requests to any other host are unchanged. --- .../src/genkit_openai/_models/_mistral.py | 65 +++++++++++++++++++ .../src/genkit_openai/_models/_model.py | 6 ++ .../src/genkit_openai/_openai_plugin.py | 19 +++++- 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 packages/genkit-openai/src/genkit_openai/_models/_mistral.py diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py new file mode 100644 index 000000000..71cf1e383 --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -0,0 +1,65 @@ +# 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 + +"""Request rewrites for Mistral's OpenAI-compatible API. + +``OpenAI(base_url='https://api.mistral.ai/v1')`` talks to Mistral. Its chat and +embeddings endpoints take the OpenAI shape with a few fields renamed or +missing, and reject any field they don't declare, so a body built for OpenAI +fails with a 422. The plugin derives the target from the client's base URL +and rewrites the few fields that differ; everything else goes out unchanged. + +Source: https://docs.mistral.ai/openapi.yaml (``ChatCompletionRequest``, +``EmbeddingRequest``). +""" + +from typing import Any + +from openai import AsyncOpenAI + +MISTRAL_HOST = 'api.mistral.ai' + + +def is_mistral(client: AsyncOpenAI) -> bool: + """Whether ``client`` sends its requests to Mistral's API.""" + return getattr(client.base_url, 'host', None) == MISTRAL_HOST + + +def mistral_chat_body(body: dict[str, Any]) -> dict[str, Any]: + """Rewrite ``chat.completions.create()`` kwargs into a body Mistral accepts. + + - ``stream_options`` is dropped. Mistral has no such field; it reports + usage on the last streamed chunk without being asked. + - ``max_completion_tokens`` goes out as ``max_tokens``, Mistral's only + reply cap, including when ``reasoning_effort`` is set. + - ``seed`` goes out as ``random_seed``. The SDK has no ``random_seed`` + kwarg, so it rides in ``extra_body``; a ``random_seed`` the caller put in + ``extra`` wins, as every ``extra`` key does. + + Args: + body: The kwargs the plugin built for OpenAI. Not modified. + + Returns: + A copy with Mistral's field names. + """ + out = dict(body) + out.pop('stream_options', None) + if 'max_completion_tokens' in out: + out['max_tokens'] = out.pop('max_completion_tokens') + if 'seed' in out: + seed = out.pop('seed') + out['extra_body'] = {'random_seed': seed, **(out.get('extra_body') or {})} + return out diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index 243486df6..fefea9d41 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -20,6 +20,7 @@ from collections.abc import Callable from typing import Any, cast +from genkit_openai._models._mistral import is_mistral, mistral_chat_body from genkit_openai._models._utils import ( OPENAI_CALL_ERRORS, DictMessageAdapter, @@ -261,6 +262,7 @@ def __init__(self, model: str, client: AsyncOpenAI, *, supports: ModelSupports | self._model = model self._openai_client = client self._supports = supports + self._mistral = is_mistral(client) @property def name(self) -> str: @@ -490,6 +492,8 @@ async def _generate(self, request: ModelRequest) -> ModelResponse: """ openai_config = await self._get_openai_request_config(request=request) openai_config.pop('stream_options', None) + if self._mistral: + openai_config = mistral_chat_body(openai_config) logger.debug('OpenAI generate request', model=self._model, streaming=False) response = await self._openai_client.chat.completions.create(**openai_config) if not response.choices: @@ -548,6 +552,8 @@ async def _generate_stream( **(openai_config.get('stream_options') or {}), 'include_usage': True, } + if self._mistral: + openai_config = mistral_chat_body(openai_config) stream = await self._openai_client.chat.completions.create(**openai_config) diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 4afde71e8..31c4fb35d 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -64,6 +64,7 @@ OpenAIGptImageConfig, OpenAIImageModel, ) +from genkit_openai._models._mistral import is_mistral from genkit_openai._models._model import OpenAIModel from genkit_openai._models._model_info import ( SUPPORTED_EMBEDDING_MODELS, @@ -603,7 +604,23 @@ async def embed_fn(request: EmbedRequest) -> EmbedResponse: # Call with only non-None optional params to satisfy strict typings client = self._embed_client() try: - if dimensions is not None and encoding_format is not None: + # Mistral names the setting output_dimension and rejects + # dimensions. The SDK has no output_dimension kwarg, so it + # rides in extra_body. + if dimensions is not None and encoding_format is not None and is_mistral(client): + response = await client.embeddings.create( + model=name, + input=texts, + encoding_format=encoding_format, + extra_body={'output_dimension': dimensions}, + ) + elif dimensions is not None and is_mistral(client): + response = await client.embeddings.create( + model=name, + input=texts, + extra_body={'output_dimension': dimensions}, + ) + elif dimensions is not None and encoding_format is not None: response = await client.embeddings.create( model=name, input=texts, From d375efbe24b43fd7404f00bfe02240e680e5545f Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 19:57:19 +0000 Subject: [PATCH 02/22] test(openai): cover Mistral request bodies against a fake server --- packages/genkit-openai/tests/mistral_test.py | 280 +++++++++++++++++++ 1 file changed, 280 insertions(+) create mode 100644 packages/genkit-openai/tests/mistral_test.py diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py new file mode 100644 index 000000000..d361fbc59 --- /dev/null +++ b/packages/genkit-openai/tests/mistral_test.py @@ -0,0 +1,280 @@ +# 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 + +"""What OpenAI(base_url='https://api.mistral.ai/v1') sends: the body Mistral's closed schema accepts.""" + +import base64 +import json +import struct +from typing import Any + +import httpx +import pytest +from genkit_openai import OpenAI + +from genkit import Genkit + +MISTRAL_URL = 'https://api.mistral.ai/v1' +PLUGIN_KEY = 'mistral-key' + + +def _completion() -> dict[str, Any]: + return { + 'id': 'cmpl-1', + 'object': 'chat.completion', + 'created': 0, + 'model': 'mistral-small-latest', + 'choices': [{'index': 0, 'finish_reason': 'stop', 'message': {'role': 'assistant', 'content': 'bonjour'}}], + 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5}, + } + + +def _stream_body() -> bytes: + # Mistral sends usage on the last chunk, beside finish_reason, without stream_options. + chunks = [ + { + 'id': 'cmpl-1', + 'object': 'chat.completion.chunk', + 'created': 0, + 'model': 'mistral-small-latest', + 'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': 'bon'}, 'finish_reason': None}], + }, + { + 'id': 'cmpl-1', + 'object': 'chat.completion.chunk', + 'created': 0, + 'model': 'mistral-small-latest', + 'choices': [{'index': 0, 'delta': {'content': 'jour'}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5}, + }, + ] + return b''.join(f'data: {json.dumps(c)}\n\n'.encode() for c in chunks) + b'data: [DONE]\n\n' + + +def _embeddings(body: dict[str, Any]) -> dict[str, Any]: + vector = [0.5, 0.25] + embedding: Any = vector + if body.get('encoding_format') == 'base64': + embedding = base64.b64encode(struct.pack(f'<{len(vector)}f', *vector)).decode() + return { + 'object': 'list', + 'model': body['model'], + 'data': [{'object': 'embedding', 'index': 0, 'embedding': embedding}], + 'usage': {'prompt_tokens': 1, 'total_tokens': 1}, + } + + +class _Server: + """A fake OpenAI-compatible endpoint that records every request it gets.""" + + def __init__(self) -> None: + self.requests: list[httpx.Request] = [] + + def handler(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + body = json.loads(request.content) + if request.url.path.endswith('/embeddings'): + return httpx.Response(200, json=_embeddings(body)) + if body.get('stream'): + return httpx.Response(200, content=_stream_body(), headers={'content-type': 'text/event-stream'}) + return httpx.Response(200, json=_completion()) + + def bodies(self) -> list[dict[str, Any]]: + return [json.loads(r.content) for r in self.requests] + + +@pytest.fixture +def server() -> _Server: + return _Server() + + +def _ai(server: _Server, base_url: str | None) -> Genkit: + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return Genkit( + plugins=[ + OpenAI( + api_key=PLUGIN_KEY, + base_url=base_url, + client_options={'http_client': http_client, 'max_retries': 0}, + ) + ] + ) + + +@pytest.fixture +def mistral(server: _Server) -> Genkit: + return _ai(server, MISTRAL_URL) + + +@pytest.fixture +def openai(server: _Server) -> Genkit: + return _ai(server, None) + + +@pytest.mark.asyncio +async def test_mistral_generate_goes_to_mistral_with_the_plugin_key(mistral: Genkit, server: _Server) -> None: + """`ai.generate(model='openai/mistral-small-latest')` posts to Mistral's chat endpoint with the plugin's key.""" + response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut') + + assert response.text == 'bonjour' + [request] = server.requests + assert str(request.url) == f'{MISTRAL_URL}/chat/completions' + assert request.headers['authorization'] == f'Bearer {PLUGIN_KEY}' + assert server.bodies()[0]['model'] == 'mistral-small-latest' + + +@pytest.mark.asyncio +async def test_mistral_stream_sends_no_stream_options_and_reads_usage(mistral: Genkit, server: _Server) -> None: + """A streamed call to Mistral sends no `stream_options`, and usage still comes back from the last chunk.""" + stream = mistral.generate_stream(model='openai/mistral-small-latest', prompt='salut') + chunks = [chunk.text async for chunk in stream.stream] + response = await stream.response + + assert chunks == ['bon', 'jour'] + assert response.text == 'bonjour' + assert response.usage is not None + assert (response.usage.input_tokens, response.usage.output_tokens) == (3, 2) + [body] = server.bodies() + assert body['stream'] is True + assert 'stream_options' not in body + + +@pytest.mark.asyncio +async def test_mistral_stream_drops_stream_options_from_config(mistral: Genkit, server: _Server) -> None: + """`config={'stream_options': {...}}` is not sent to Mistral, which has no such field.""" + stream = mistral.generate_stream( + model='openai/mistral-small-latest', + prompt='salut', + config={'stream_options': {'include_usage': True}}, + ) + await stream.response + + [body] = server.bodies() + assert 'stream_options' not in body + + +@pytest.mark.parametrize( + 'config', + [ + pytest.param({'max_output_tokens': 50}, id='chat'), + pytest.param({'max_output_tokens': 50, 'reasoning_effort': 'high'}, id='reasoning_effort'), + ], +) +@pytest.mark.asyncio +async def test_mistral_max_output_tokens_goes_out_as_max_tokens( + mistral: Genkit, server: _Server, config: dict[str, Any] +) -> None: + """`max_output_tokens` reaches Mistral as `max_tokens`, even with `reasoning_effort` set.""" + await mistral.generate(model='openai/magistral-medium-latest', prompt='salut', config=config) + + [body] = server.bodies() + caps_sent = {k: body[k] for k in ('max_tokens', 'max_completion_tokens') if k in body} + assert caps_sent == {'max_tokens': 50} + assert body.get('reasoning_effort') == config.get('reasoning_effort') + + +@pytest.mark.asyncio +async def test_mistral_seed_goes_out_as_random_seed(mistral: Genkit, server: _Server) -> None: + """`config={'seed': 7}` reaches Mistral as `random_seed`, beside the other settings.""" + await mistral.generate( + model='openai/mistral-small-latest', + prompt='salut', + config={'seed': 7, 'temperature': 0.2, 'extra': {'safe_prompt': True}}, + ) + + [body] = server.bodies() + assert body['random_seed'] == 7 + assert 'seed' not in body + assert body['temperature'] == 0.2 + assert body['safe_prompt'] is True + + +@pytest.mark.asyncio +async def test_mistral_random_seed_in_extra_wins_over_seed(mistral: Genkit, server: _Server) -> None: + """`extra={'random_seed': 9}` replaces `seed=7`, as any `extra` key replaces a setting of the same name.""" + await mistral.generate( + model='openai/mistral-small-latest', + prompt='salut', + config={'seed': 7, 'extra': {'random_seed': 9}}, + ) + + [body] = server.bodies() + assert body['random_seed'] == 9 + assert 'seed' not in body + + +@pytest.mark.asyncio +async def test_mistral_tenant_key_call_is_rewritten_too(mistral: Genkit, server: _Server) -> None: + """A call with a `context.secrets` key still goes to Mistral with Mistral's field names.""" + stream = mistral.generate_stream( + model='openai/mistral-small-latest', + prompt='salut', + config={'seed': 7}, + context={'secrets': {'api_key': 'tenant-key'}}, + ) + await stream.response + + [request] = server.requests + assert request.headers['authorization'] == 'Bearer tenant-key' + body = json.loads(request.content) + assert 'stream_options' not in body + assert body['random_seed'] == 7 + assert 'seed' not in body + + +@pytest.mark.asyncio +async def test_mistral_embed_dimensions_goes_out_as_output_dimension(mistral: Genkit, server: _Server) -> None: + """`config={'dimensions': 256}` reaches Mistral's embeddings endpoint as `output_dimension`.""" + response = await mistral.embed( + embedder='openai/codestral-embed', content='def f(): ...', config={'dimensions': 256} + ) + + assert response[0].embedding == [0.5, 0.25] + [request] = server.requests + assert str(request.url) == f'{MISTRAL_URL}/embeddings' + body = json.loads(request.content) + assert body['output_dimension'] == 256 + assert 'dimensions' not in body + + +@pytest.mark.asyncio +async def test_mistral_embed_float_encoding_still_goes_out(mistral: Genkit, server: _Server) -> None: + """`encodingFormat='float'` with `dimensions` sends both, `dimensions` under Mistral's name.""" + await mistral.embed( + embedder='openai/codestral-embed', + content='def f(): ...', + config={'dimensions': 256, 'encodingFormat': 'float'}, + ) + + [body] = server.bodies() + assert body['output_dimension'] == 256 + assert body['encoding_format'] == 'float' + assert 'dimensions' not in body + + +@pytest.mark.asyncio +async def test_openai_base_url_keeps_openai_field_names(openai: Genkit, server: _Server) -> None: + """Without Mistral's base URL the plugin still sends `stream_options`, `seed`, and `dimensions`.""" + stream = openai.generate_stream(model='openai/gpt-4o', prompt='hi', config={'seed': 7}) + await stream.response + await openai.embed(embedder='openai/text-embedding-3-small', content='hi', config={'dimensions': 256}) + + chat, embed = server.bodies() + assert chat['stream_options'] == {'include_usage': True} + assert chat['seed'] == 7 + assert 'random_seed' not in chat + assert embed['dimensions'] == 256 + assert 'output_dimension' not in embed From 9bed25881a37b1c1794fb8f8b074e21c423e1da4 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 19:57:19 +0000 Subject: [PATCH 03/22] docs(openai): document the Mistral base_url recipe --- packages/genkit-openai/README.md | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 4f10d5b75..1c425de3f 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -47,6 +47,43 @@ OpenAI( ) ``` +## Mistral + +Point `base_url` at Mistral's API and pass a Mistral key. Models keep the +`openai/` prefix: + +```python +import os + +from genkit import Genkit +from genkit_openai import OpenAI + +ai = Genkit( + plugins=[OpenAI(api_key=os.environ['MISTRAL_API_KEY'], base_url='https://api.mistral.ai/v1')] +) + +res = await ai.generate( + model='openai/mistral-small-latest', + prompt='Suggest 2 names for a French bakery.', + config={'temperature': 0.3, 'seed': 42, 'max_output_tokens': 200}, +) + +embeddings = await ai.embed(embedder='openai/mistral-embed', content='croissant') +``` + +Mistral rejects any request field it doesn't declare, so with that `base_url` +the plugin sends Mistral's names for the settings that differ: + +- `max_output_tokens` goes out as `max_tokens`, never `max_completion_tokens`, + even with `reasoning_effort` set. +- `seed` goes out as `random_seed`. +- Streaming sends no `stream_options`; Mistral reports usage on the last chunk. +- An embedder's `dimensions` goes out as `output_dimension`. + +Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given +and Mistral rejects them. Mistral-only fields like `safe_prompt` go in `extra`. +A gateway in front of Mistral on another host gets the OpenAI field names. + ## Config `config` takes the settings `OpenAIConfig` declares. Any other key raises From fbb75a850982e8eccea938e7970d053dbbad98d8 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 20:13:19 +0000 Subject: [PATCH 04/22] feat(py/openai): read Mistral thinking chunks, cover Codestral, forward top_k - Reply content that arrives as a list of chunks (Magistral) is split: thinking chunks become reasoning parts, text chunks the text, on the streamed and non-streamed paths. String content is unchanged. - codestral.mistral.ai gets the same rewrite as api.mistral.ai. - top_k goes out to Mistral, which declares it. - Streaming no longer adds stream_options for Mistral only to drop it. - The embedder makes one create() call with only the options that are set. - raw no longer warns when the reply content is a list. --- .../src/genkit_openai/_models/_mistral.py | 38 +++++++++---- .../src/genkit_openai/_models/_model.py | 40 ++++++++------ .../src/genkit_openai/_models/_utils.py | 45 ++++++++++++++-- .../src/genkit_openai/_openai_plugin.py | 54 +++++-------------- .../src/genkit_openai/_typing.py | 9 ++-- 5 files changed, 113 insertions(+), 73 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 71cf1e383..952de09e9 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -19,8 +19,15 @@ ``OpenAI(base_url='https://api.mistral.ai/v1')`` talks to Mistral. Its chat and embeddings endpoints take the OpenAI shape with a few fields renamed or missing, and reject any field they don't declare, so a body built for OpenAI -fails with a 422. The plugin derives the target from the client's base URL -and rewrites the few fields that differ; everything else goes out unchanged. +fails with a 422. The plugin rewrites the few fields that differ; everything +else goes out unchanged. + +The target is read from the client's base URL, not the model id as DeepSeek's +JSON handling is. Mistral's ids share no prefix (``mistral-``, ``magistral-``, +``codestral-``, ``pixtral-``, ...), and the same ids are served through other +OpenAI-compatible hosts that take OpenAI's names: Vertex Model Garden reuses +``OpenAIModel`` for ``mistralai/...`` models with a Vertex client, so it never +matches here. Source: https://docs.mistral.ai/openapi.yaml (``ChatCompletionRequest``, ``EmbeddingRequest``). @@ -30,27 +37,32 @@ from openai import AsyncOpenAI -MISTRAL_HOST = 'api.mistral.ai' +# Mistral's API hosts: the main one, and the one Codestral keys are issued for. +MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'codestral.mistral.ai'}) def is_mistral(client: AsyncOpenAI) -> bool: - """Whether ``client`` sends its requests to Mistral's API.""" - return getattr(client.base_url, 'host', None) == MISTRAL_HOST + """Whether ``client`` sends its requests to one of Mistral's API hosts.""" + return client.base_url.host in MISTRAL_HOSTS -def mistral_chat_body(body: dict[str, Any]) -> dict[str, Any]: +def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict[str, Any]: """Rewrite ``chat.completions.create()`` kwargs into a body Mistral accepts. - ``stream_options`` is dropped. Mistral has no such field; it reports usage on the last streamed chunk without being asked. - ``max_completion_tokens`` goes out as ``max_tokens``, Mistral's only reply cap, including when ``reasoning_effort`` is set. - - ``seed`` goes out as ``random_seed``. The SDK has no ``random_seed`` - kwarg, so it rides in ``extra_body``; a ``random_seed`` the caller put in - ``extra`` wins, as every ``extra`` key does. + - ``seed`` goes out as ``random_seed``. + - ``top_k``, which OpenAI has no field for, goes out as is. + + The SDK has no ``random_seed`` or ``top_k`` kwarg, so both ride in + ``extra_body``; the same key in the caller's ``extra`` wins, as every + ``extra`` key does. Args: body: The kwargs the plugin built for OpenAI. Not modified. + top_k: Genkit's ``top_k`` setting, which the OpenAI kwargs leave out. Returns: A copy with Mistral's field names. @@ -59,7 +71,11 @@ def mistral_chat_body(body: dict[str, Any]) -> dict[str, Any]: out.pop('stream_options', None) if 'max_completion_tokens' in out: out['max_tokens'] = out.pop('max_completion_tokens') + renamed: dict[str, Any] = {} if 'seed' in out: - seed = out.pop('seed') - out['extra_body'] = {'random_seed': seed, **(out.get('extra_body') or {})} + renamed['random_seed'] = out.pop('seed') + if top_k is not None: + renamed['top_k'] = top_k + if renamed: + out['extra_body'] = {**renamed, **(out.get('extra_body') or {})} return out diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index fefea9d41..6399757e8 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -29,6 +29,7 @@ check_extra_body, extract_response_metadata, reraise_openai_error, + split_reply_content, strip_markdown_fences, ) from genkit_openai._typing import OpenAIConfig @@ -94,7 +95,8 @@ def _openai_create_kwargs(*, config: OpenAIConfig, model: str | None = None) -> the JSON body, so a colliding key wins. ``max_output_tokens`` goes out as ``max_completion_tokens`` for reasoning models (or when ``reasoning_effort`` is set), since the OpenAI API rejects the deprecated - ``max_tokens`` there, and as ``max_tokens`` otherwise. + ``max_tokens`` there, and as ``max_tokens`` otherwise. ``_mistral.py`` + renames the fields Mistral spells differently after this runs. """ body: dict[str, Any] = {} for name in type(config).model_fields: @@ -471,14 +473,18 @@ async def _get_openai_request_config(self, request: ModelRequest) -> dict: if response_format: # pyrefly: ignore[bad-typed-dict-key] - response_format dict is valid for OpenAI API openai_config['response_format'] = response_format + top_k: int | None = None if request.config: config = ( request.config if isinstance(request.config, OpenAIConfig) else self._normalize_config(request.config) ) + top_k = config.top_k if config.version: openai_config['model'] = config.version effective_model = config.model or config.version or self._model openai_config.update(_openai_create_kwargs(config=config, model=effective_model)) + if self._mistral: + openai_config = mistral_chat_body(openai_config, top_k=top_k) return openai_config async def _generate(self, request: ModelRequest) -> ModelResponse: @@ -492,8 +498,6 @@ async def _generate(self, request: ModelRequest) -> ModelResponse: """ openai_config = await self._get_openai_request_config(request=request) openai_config.pop('stream_options', None) - if self._mistral: - openai_config = mistral_chat_body(openai_config) logger.debug('OpenAI generate request', model=self._model, streaming=False) response = await self._openai_client.chat.completions.create(**openai_config) if not response.choices: @@ -530,7 +534,10 @@ async def _generate(self, request: ModelRequest) -> ModelResponse: finish_message=finish_message, usage=_usage_from_completion(response.usage), custom=metadata or None, - raw=response.to_dict(), + # raw is the provider's reply as sent. A list content (Mistral's + # thinking chunks) doesn't fit the SDK's str field, which is not + # worth a serializer warning on every call. + raw=response.to_dict(warnings=False), ) return self._clean_json_response(result, request) @@ -548,12 +555,12 @@ async def _generate_stream( """ openai_config = await self._get_openai_request_config(request=request) openai_config['stream'] = True - openai_config['stream_options'] = { - **(openai_config.get('stream_options') or {}), - 'include_usage': True, - } - if self._mistral: - openai_config = mistral_chat_body(openai_config) + # Mistral has no stream_options and sends usage unasked. + if not self._mistral: + openai_config['stream_options'] = { + **(openai_config.get('stream_options') or {}), + 'include_usage': True, + } stream = await self._openai_client.chat.completions.create(**openai_config) @@ -595,9 +602,14 @@ async def _generate_stream( reasoning_parts.append(reasoning_part) parts.append(reasoning_part) - # Text content - if delta.content: - text_part = MessageConverter.text_part_to_genkit(delta.content) + # Text content; Mistral's reasoning models stream reasoning in it too. + thinking, text = split_reply_content(delta.content) + if thinking: + thinking_part = Part.from_reasoning(thinking) + reasoning_parts.append(thinking_part) + parts.append(thinking_part) + if text: + text_part = MessageConverter.text_part_to_genkit(text) text_parts.append(text_part) parts.append(text_part) @@ -680,8 +692,6 @@ def _normalize_config(config: object) -> OpenAIConfig: if isinstance(config, dict): config_dict = cast(dict[str, Any], config) - if config_dict.get('top_k'): - del config_dict['top_k'] return OpenAIConfig(**config_dict) raise ValueError(f'Expected request.config to be a dict or OpenAIConfig, got {type(config).__name__}.') diff --git a/packages/genkit-openai/src/genkit_openai/_models/_utils.py b/packages/genkit-openai/src/genkit_openai/_models/_utils.py index 2587b5a2c..6c996de72 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_utils.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_utils.py @@ -21,7 +21,7 @@ import json import re from collections.abc import Callable, Mapping -from typing import Any, NoReturn +from typing import Any, NoReturn, cast import httpx from openai import ( @@ -411,6 +411,42 @@ def _extract_media(request: ModelRequest) -> tuple[str, str]: return url, content_type +def split_reply_content(content: object) -> tuple[str, str]: + """The reasoning and the text in a reply's ``content``. + + OpenAI sends ``content`` as a string. Mistral's reasoning models send a + list of chunks instead, in full replies and in streamed deltas alike: + ``{'type': 'text', 'text': ...}`` for the answer and + ``{'type': 'thinking', 'thinking': [{'type': 'text', 'text': ...}]}`` for + the reasoning before it. Other chunk types carry no text and are skipped. + + Args: + content: A message's or delta's ``content`` as the SDK parsed it. + + Returns: + The reasoning text and the reply text, each empty when absent. + """ + if isinstance(content, str): + return '', content + if not isinstance(content, list): + return '', '' + reasoning: list[str] = [] + text: list[str] = [] + for chunk in cast(list[object], content): + if not isinstance(chunk, Mapping): + continue + chunk = cast(Mapping[str, object], chunk) + if chunk.get('type') == 'text' and isinstance(chunk.get('text'), str): + text.append(cast(str, chunk['text'])) + elif chunk.get('type') == 'thinking' and isinstance(chunk.get('thinking'), list): + for item in cast(list[object], chunk['thinking']): + if isinstance(item, Mapping): + item = cast(Mapping[str, object], item) + if item.get('type') == 'text' and isinstance(item.get('text'), str): + reasoning.append(cast(str, item['text'])) + return ''.join(reasoning), ''.join(text) + + class DictMessageAdapter: """Adapter for dictionary-based chat message objects with OpenAI-compatible fields.""" @@ -650,8 +686,11 @@ def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: if reasoning: content.append(Part.from_reasoning(reasoning)) - if message.content: - content.append(cls.text_part_to_genkit(message.content)) + thinking, text = split_reply_content(message.content) + if thinking: + content.append(Part.from_reasoning(thinking)) + if text: + content.append(cls.text_part_to_genkit(text)) for tool_call in message.tool_calls or []: content.append(cls.tool_call_to_genkit(tool_call, args_parser=json.loads)) diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 31c4fb35d..51ba81b7d 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -601,49 +601,21 @@ async def embed_fn(request: EmbedRequest) -> EmbedResponse: if request.options.get('encodingFormat') == 'float': encoding_format = 'float' - # Call with only non-None optional params to satisfy strict typings + # 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() - try: - # Mistral names the setting output_dimension and rejects - # dimensions. The SDK has no output_dimension kwarg, so it - # rides in extra_body. - if dimensions is not None and encoding_format is not None and is_mistral(client): - response = await client.embeddings.create( - model=name, - input=texts, - encoding_format=encoding_format, - extra_body={'output_dimension': dimensions}, - ) - elif dimensions is not None and is_mistral(client): - response = await client.embeddings.create( - model=name, - input=texts, - extra_body={'output_dimension': dimensions}, - ) - elif dimensions is not None and encoding_format is not None: - response = await client.embeddings.create( - model=name, - input=texts, - dimensions=dimensions, - encoding_format=encoding_format, - ) - elif dimensions is not None: - response = await client.embeddings.create( - model=name, - input=texts, - dimensions=dimensions, - ) - elif encoding_format is not None: - response = await client.embeddings.create( - model=name, - input=texts, - encoding_format=encoding_format, - ) + create_kwargs: dict[str, Any] = {} + if dimensions is not None: + if is_mistral(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: - response = await client.embeddings.create( - model=name, - input=texts, - ) + 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) diff --git a/packages/genkit-openai/src/genkit_openai/_typing.py b/packages/genkit-openai/src/genkit_openai/_typing.py index 24c9e4775..cbcf1619e 100644 --- a/packages/genkit-openai/src/genkit_openai/_typing.py +++ b/packages/genkit-openai/src/genkit_openai/_typing.py @@ -149,7 +149,8 @@ class OpenAIConfig(ModelConfig): top_logprobs: Number of top log probabilities to return (0-20). See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-top_logprobs - seed: Random seed for deterministic sampling (beta). + seed: Random seed for deterministic sampling (beta). Sent as + ``random_seed`` to Mistral (see ``_models/_mistral.py``). See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-seed safety_identifier: Stable identifier for detecting policy violations. @@ -193,7 +194,8 @@ class OpenAIConfig(ModelConfig): prediction: Predicted output content for regeneration. See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-prediction - stream_options: Streaming options (e.g., include_usage). + stream_options: Streaming options (e.g., include_usage). Not sent + to Mistral, which has no such field (see ``_models/_mistral.py``). See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-stream_options web_search_options: Web search tool configuration. @@ -201,7 +203,8 @@ class OpenAIConfig(ModelConfig): max_output_tokens: Genkit's cross-model reply cap (``maxOutputTokens`` in the Dev UI). Sent as ``max_tokens``, or ``max_completion_tokens`` - on reasoning models and when ``reasoning_effort`` is set. + on reasoning models and when ``reasoning_effort`` is set. Always + ``max_tokens`` to Mistral (see ``_models/_mistral.py``). stop_sequences: Genkit's cross-model stop strings. Sent as ``stop``. From 1c1d93088259131e8b7c20f67eed82e906da494b Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 20:13:19 +0000 Subject: [PATCH 05/22] test(py/openai): enforce Mistral's closed schema in the fake server --- packages/genkit-openai/tests/mistral_test.py | 268 ++++++++++++++++++- 1 file changed, 254 insertions(+), 14 deletions(-) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index d361fbc59..f067ec593 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -24,40 +24,98 @@ import httpx import pytest from genkit_openai import OpenAI +from genkit_openai._models._mistral import mistral_chat_body +from pydantic import BaseModel -from genkit import Genkit +from genkit import FinishReason, Genkit, Part MISTRAL_URL = 'https://api.mistral.ai/v1' +CODESTRAL_URL = 'https://codestral.mistral.ai/v1' PLUGIN_KEY = 'mistral-key' - -def _completion() -> dict[str, Any]: +# The fields Mistral's ChatCompletionRequest and EmbeddingRequest declare +# (https://docs.mistral.ai/openapi.yaml, as mirrored by the mistralai SDK). Mistral +# answers any other top-level field with a 422, and so does the fake below. +_CHAT_FIELDS = frozenset({ + 'model', + 'messages', + 'temperature', + 'top_p', + 'max_tokens', + 'stream', + 'stop', + 'random_seed', + 'metadata', + 'response_format', + 'tools', + 'tool_choice', + 'presence_penalty', + 'frequency_penalty', + 'min_tokens', + 'repetition_penalty', + 'top_k', + 'logprobs', + 'top_logprobs', + 'prompt_logprobs', + 'top_prompt_logprobs', + 'n', + 'prediction', + 'parallel_tool_calls', + 'reasoning_effort', + 'prompt_mode', + 'guardrails', + 'prompt_cache_key', + 'service_tier', + 'safe_prompt', +}) +_EMBEDDING_FIELDS = frozenset({'model', 'input', 'metadata', 'output_dimension', 'output_dtype', 'encoding_format'}) +_MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'codestral.mistral.ai'}) + +# A Magistral reply: reasoning in a thinking chunk, then the answer, in a content list. +_THINKING = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': 'Two loaves, one each.'}]} + + +def _content(model: str, text: str) -> Any: # noqa: ANN401 + if model.startswith('magistral'): + return [_THINKING, {'type': 'text', 'text': text}] + return text + + +def _completion(model: str) -> dict[str, Any]: return { 'id': 'cmpl-1', 'object': 'chat.completion', 'created': 0, - 'model': 'mistral-small-latest', - 'choices': [{'index': 0, 'finish_reason': 'stop', 'message': {'role': 'assistant', 'content': 'bonjour'}}], + 'model': model, + 'choices': [ + { + 'index': 0, + 'finish_reason': 'stop', + 'message': {'role': 'assistant', 'content': _content(model, 'bonjour')}, + } + ], 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5}, } -def _stream_body() -> bytes: +def _stream_body(model: str) -> bytes: # Mistral sends usage on the last chunk, beside finish_reason, without stream_options. + first: Any = [_THINKING] if model.startswith('magistral') else 'bon' + second: Any = [{'type': 'text', 'text': 'bonjour'}] if model.startswith('magistral') else 'jour' chunks = [ { 'id': 'cmpl-1', 'object': 'chat.completion.chunk', 'created': 0, - 'model': 'mistral-small-latest', - 'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': 'bon'}, 'finish_reason': None}], + 'model': model, + 'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': first}, 'finish_reason': None}], }, { 'id': 'cmpl-1', 'object': 'chat.completion.chunk', 'created': 0, - 'model': 'mistral-small-latest', - 'choices': [{'index': 0, 'delta': {'content': 'jour'}, 'finish_reason': 'stop'}], + 'model': model, + 'choices': [{'index': 0, 'delta': {'content': second}, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5}, }, ] @@ -77,8 +135,16 @@ def _embeddings(body: dict[str, Any]) -> dict[str, Any]: } +def _extra_forbidden(fields: list[str]) -> httpx.Response: + detail = [ + {'type': 'extra_forbidden', 'loc': ['body', f], 'msg': 'Extra inputs are not permitted', 'input': None} + for f in fields + ] + return httpx.Response(422, json={'object': 'error', 'message': {'detail': detail}, 'type': 'invalid_request_error'}) + + class _Server: - """A fake OpenAI-compatible endpoint that records every request it gets.""" + """A fake OpenAI-compatible endpoint that records every request and, on Mistral's hosts, enforces its schema.""" def __init__(self) -> None: self.requests: list[httpx.Request] = [] @@ -86,11 +152,18 @@ def __init__(self) -> None: def handler(self, request: httpx.Request) -> httpx.Response: self.requests.append(request) body = json.loads(request.content) - if request.url.path.endswith('/embeddings'): + embeddings = request.url.path.endswith('/embeddings') + if request.url.host in _MISTRAL_HOSTS: + allowed = _EMBEDDING_FIELDS if embeddings else _CHAT_FIELDS + if unknown := sorted(set(body) - allowed): + return _extra_forbidden(unknown) + if embeddings: return httpx.Response(200, json=_embeddings(body)) if body.get('stream'): - return httpx.Response(200, content=_stream_body(), headers={'content-type': 'text/event-stream'}) - return httpx.Response(200, json=_completion()) + return httpx.Response( + 200, content=_stream_body(body['model']), headers={'content-type': 'text/event-stream'} + ) + return httpx.Response(200, json=_completion(body['model'])) def bodies(self) -> list[dict[str, Any]]: return [json.loads(r.content) for r in self.requests] @@ -278,3 +351,170 @@ async def test_openai_base_url_keeps_openai_field_names(openai: Genkit, server: assert 'random_seed' not in chat assert embed['dimensions'] == 256 assert 'output_dimension' not in embed + + +@pytest.mark.asyncio +async def test_codestral_host_gets_mistral_field_names(server: _Server) -> None: + """OpenAI(base_url='https://codestral.mistral.ai/v1') sends Mistral's names too.""" + ai = _ai(server, CODESTRAL_URL) + + await ai.generate(model='openai/codestral-latest', prompt='def add(a, b):', config={'seed': 7}) + + [request] = server.requests + assert str(request.url) == f'{CODESTRAL_URL}/chat/completions' + body = json.loads(request.content) + assert body['random_seed'] == 7 + assert 'seed' not in body + + +@pytest.mark.asyncio +async def test_openai_base_url_env_pointing_at_mistral_gets_mistral_field_names( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """`OPENAI_BASE_URL=https://api.mistral.ai/v1` with no `base_url` argument still sends Mistral's names.""" + monkeypatch.setenv('OPENAI_BASE_URL', MISTRAL_URL) + ai = _ai(server, None) + + stream = ai.generate_stream(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + await stream.response + + [request] = server.requests + assert request.url.host == 'api.mistral.ai' + body = json.loads(request.content) + assert 'stream_options' not in body + assert body['random_seed'] == 7 + + +@pytest.mark.asyncio +async def test_mistral_generate_drops_stream_options_from_config(mistral: Genkit, server: _Server) -> None: + """`config={'stream_options': {...}}` on a non-streamed call is not sent to Mistral either.""" + await mistral.generate( + model='openai/mistral-small-latest', prompt='salut', config={'stream_options': {'include_usage': True}} + ) + + [body] = server.bodies() + assert 'stream_options' not in body + + +@pytest.mark.asyncio +async def test_mistral_top_k_goes_out(mistral: Genkit, server: _Server) -> None: + """`config={'top_k': 5}` reaches Mistral, which declares `top_k`; OpenAI never gets it.""" + await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'top_k': 5}) + + [body] = server.bodies() + assert body['top_k'] == 5 + + +@pytest.mark.asyncio +async def test_mistral_magistral_reply_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: + """A Magistral reply's `thinking` chunk comes back as a reasoning part, its `text` chunk as the text.""" + response = await mistral.generate(model='openai/magistral-medium-latest', prompt='Bread for two?') + + assert response.text == 'bonjour' + assert response.message is not None + assert [p.reasoning for p in response.message.content if p.reasoning] == ['Two loaves, one each.'] + + +@pytest.mark.asyncio +async def test_mistral_magistral_stream_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: + """Streamed `thinking` chunks arrive as reasoning parts, and the final response keeps reasoning before text.""" + stream = mistral.generate_stream(model='openai/magistral-medium-latest', prompt='Bread for two?') + chunks = [chunk async for chunk in stream.stream] + response = await stream.response + + assert [c.text for c in chunks] == ['', 'bonjour'] + assert chunks[0].content[0].reasoning == 'Two loaves, one each.' + assert response.text == 'bonjour' + assert response.message is not None + assert response.message.content[0].reasoning == 'Two loaves, one each.' + + +@pytest.mark.asyncio +async def test_mistral_tools_pass_the_schema(mistral: Genkit, server: _Server) -> None: + """A call with tools and `tool_choice` gets through Mistral's schema with the tool definitions.""" + + @mistral.tool(name='lookup_menu') + async def lookup_menu(dish: str) -> str: + return f'{dish}: in stock' + + response = await mistral.generate( + model='openai/mistral-small-latest', + prompt='Is the baguette in stock?', + tools=['lookup_menu'], + tool_choice='auto', + ) + + assert response.text == 'bonjour' + [body] = server.bodies() + assert [t['function']['name'] for t in body['tools']] == ['lookup_menu'] + assert body['tool_choice'] == 'auto' + + +class _Loaf(BaseModel): + name: str + grams: int + + +@pytest.mark.asyncio +async def test_mistral_output_schema_goes_out_as_json_schema(mistral: Genkit, server: _Server) -> None: + """`output_schema=` reaches Mistral as a `json_schema` response format.""" + await mistral.generate(model='openai/mistral-small-latest', prompt='Describe a loaf.', output_schema=_Loaf) + + [body] = server.bodies() + assert body['response_format']['type'] == 'json_schema' + assert set(body['response_format']['json_schema']['schema']['properties']) == {'name', 'grams'} + + +@pytest.mark.asyncio +async def test_mistral_image_input_goes_out_as_image_url(mistral: Genkit, server: _Server) -> None: + """An image part reaches Mistral as an `image_url` content block.""" + await mistral.generate( + model='openai/pixtral-large-latest', + prompt=[Part.from_text('What bread is this?'), Part.from_media('https://example.com/loaf.png', 'image/png')], + ) + + [body] = server.bodies() + blocks = body['messages'][-1]['content'] + assert {'type': 'image_url', 'image_url': {'url': 'https://example.com/loaf.png'}} in blocks + + +@pytest.mark.asyncio +async def test_mistral_rejects_an_openai_only_setting(mistral: Genkit, server: _Server) -> None: + """An OpenAI-only setting such as `verbosity` is sent as given, and Mistral's 422 fails the turn.""" + response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'verbosity': 'low'}) + + assert response.finish_reason == FinishReason.FAILED + assert 'verbosity' in str(response.error) + [body] = server.bodies() + assert body['verbosity'] == 'low' + + +@pytest.mark.asyncio +async def test_mistral_embed_without_options_sends_only_mistral_fields(mistral: Genkit, server: _Server) -> None: + """An embed call with no options sends `model`, `input`, and the SDK's default `encoding_format`.""" + response = await mistral.embed(embedder='openai/mistral-embed', content='croissant') + + assert response[0].embedding == [0.5, 0.25] + [body] = server.bodies() + assert set(body) == {'model', 'input', 'encoding_format'} + + +def test_mistral_chat_body_leaves_its_input_alone() -> None: + """`mistral_chat_body` returns a rewritten copy; the OpenAI kwargs it was given are unchanged.""" + body = { + 'model': 'mistral-small-latest', + 'seed': 7, + 'max_completion_tokens': 50, + 'stream_options': {'include_usage': True}, + 'extra_body': {'safe_prompt': True}, + } + before = json.loads(json.dumps(body)) + + out = mistral_chat_body(body, top_k=5) + + assert body == before + assert out == { + 'model': 'mistral-small-latest', + 'max_tokens': 50, + 'extra_body': {'random_seed': 7, 'top_k': 5, 'safe_prompt': True}, + } From 70c5c50ce6a1bca00f04fba9af81f1cfba915c1f Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 20:13:19 +0000 Subject: [PATCH 06/22] docs(py/openai): Codestral host, api_key, reasoning and embedder notes for Mistral --- packages/genkit-openai/README.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 1c425de3f..c90da03c6 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -71,18 +71,30 @@ res = await ai.generate( embeddings = await ai.embed(embedder='openai/mistral-embed', content='croissant') ``` -Mistral rejects any request field it doesn't declare, so with that `base_url` -the plugin sends Mistral's names for the settings that differ: +Pass `api_key=` explicitly. Without it the plugin falls back to +`OPENAI_API_KEY` and sends that key to Mistral. For Codestral keys, use +`base_url='https://codestral.mistral.ai/v1'`. + +Mistral rejects any request field it doesn't declare, so with either of those +hosts the plugin sends Mistral's names for the settings that differ: - `max_output_tokens` goes out as `max_tokens`, never `max_completion_tokens`, even with `reasoning_effort` set. - `seed` goes out as `random_seed`. +- `top_k` goes out as is. Mistral takes it; OpenAI never gets it. - Streaming sends no `stream_options`; Mistral reports usage on the last chunk. - An embedder's `dimensions` goes out as `output_dimension`. +Magistral replies carry their reasoning in `thinking` chunks; those come back +as reasoning parts, ahead of the text, streamed or not. + Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given -and Mistral rejects them. Mistral-only fields like `safe_prompt` go in `extra`. -A gateway in front of Mistral on another host gets the OpenAI field names. +and Mistral fails the call naming them. Mistral-only fields like `safe_prompt` +go in `extra`. A gateway in front of Mistral on any other host gets the OpenAI +field names. + +The plugin doesn't know Mistral's embedders, so their info reports the default +1536 dimensions; `mistral-embed` returns 1024. ## Config From 8a22747a9459485f182344e5b4da6d347cd81b89 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Thu, 12 Nov 2026 10:05:57 +0000 Subject: [PATCH 07/22] feat(py/openai): replay Mistral reasoning, map model_length, add EU/US hosts - On Mistral hosts, a model message's reasoning goes back on the next turn as one leading thinking chunk, with the signature the reply carried. Other hosts still drop reasoning. - A thinking chunk's signature is kept on the reasoning part as metadata.thoughtSignature. - finish_reason model_length maps to LENGTH. - api.eu.mistral.ai and api.us.mistral.ai get the Mistral rewrite. --- .../src/genkit_openai/_models/_mistral.py | 6 +- .../src/genkit_openai/_models/_model.py | 11 +- .../src/genkit_openai/_models/_utils.py | 100 +++++++++++++++--- 3 files changed, 94 insertions(+), 23 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 952de09e9..263fde9dd 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -37,8 +37,10 @@ from openai import AsyncOpenAI -# Mistral's API hosts: the main one, and the one Codestral keys are issued for. -MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'codestral.mistral.ai'}) +# Mistral's API hosts: global, EU and US, the servers in the mistralai SDK's +# sdkconfiguration.py. codestral.mistral.ai, for Codestral-only keys, is not in +# that list or the OpenAPI servers; it is kept since nothing else lives there. +MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'api.eu.mistral.ai', 'api.us.mistral.ai', 'codestral.mistral.ai'}) def is_mistral(client: AsyncOpenAI) -> bool: diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index 6399757e8..e48bf7046 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -213,6 +213,8 @@ def _failure_message(extras: dict[str, Any] | None) -> str | None: 'insufficient_system_resource': FinishReason.OTHER, 'length': FinishReason.LENGTH, 'model_context_window_exceeded': FinishReason.LENGTH, + # Mistral: the model's own length limit, as opposed to max_tokens. + 'model_length': FinishReason.LENGTH, 'network_error': FinishReason.OTHER, 'sensitive': FinishReason.BLOCKED, 'stop': FinishReason.STOP, @@ -286,7 +288,7 @@ def _get_messages(self, messages: list[Message]) -> list[dict]: """ openai_messages = [] for message in messages: - openai_messages.extend(MessageConverter.to_openai(message=message)) + openai_messages.extend(MessageConverter.to_openai(message=message, replay_thinking=self._mistral)) return openai_messages async def _get_tools_definition(self, tools: list[ToolDefinition]) -> list[dict]: @@ -604,10 +606,9 @@ async def _generate_stream( # Text content; Mistral's reasoning models stream reasoning in it too. thinking, text = split_reply_content(delta.content) - if thinking: - thinking_part = Part.from_reasoning(thinking) - reasoning_parts.append(thinking_part) - parts.append(thinking_part) + if thinking is not None: + reasoning_parts.append(thinking) + parts.append(thinking) if text: text_part = MessageConverter.text_part_to_genkit(text) text_parts.append(text_part) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_utils.py b/packages/genkit-openai/src/genkit_openai/_models/_utils.py index 6c996de72..d75cfd9f1 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_utils.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_utils.py @@ -411,26 +411,35 @@ def _extract_media(request: ModelRequest) -> tuple[str, str]: return url, content_type -def split_reply_content(content: object) -> tuple[str, str]: +# Where a reasoning part keeps the signature Mistral puts on a thinking chunk, +# under the same key the Anthropic and Google plugins use for theirs. +THOUGHT_SIGNATURE = 'thoughtSignature' + + +def split_reply_content(content: object) -> tuple[Part | None, str]: """The reasoning and the text in a reply's ``content``. - OpenAI sends ``content`` as a string. Mistral's reasoning models send a - list of chunks instead, in full replies and in streamed deltas alike: - ``{'type': 'text', 'text': ...}`` for the answer and - ``{'type': 'thinking', 'thinking': [{'type': 'text', 'text': ...}]}`` for - the reasoning before it. Other chunk types carry no text and are skipped. + OpenAI sends ``content`` as a string. Mistral sends a list of chunks + instead when it reasons (``reasoning_effort`` set), in full replies and in + streamed deltas alike: ``{'type': 'text', 'text': ...}`` for the answer and + ``{'type': 'thinking', 'thinking': [{'type': 'text', 'text': ...}], + 'signature': ...}`` for the reasoning before it. Other chunk types carry + no text and are skipped. Args: content: A message's or delta's ``content`` as the SDK parsed it. Returns: - The reasoning text and the reply text, each empty when absent. + A reasoning part, with the chunk's signature in + ``metadata['thoughtSignature']`` when it has one, or None when there is + no reasoning; and the reply text, empty when absent. """ if isinstance(content, str): - return '', content + return None, content if not isinstance(content, list): - return '', '' + return None, '' reasoning: list[str] = [] + signature: str | None = None text: list[str] = [] for chunk in cast(list[object], content): if not isinstance(chunk, Mapping): @@ -439,12 +448,48 @@ def split_reply_content(content: object) -> tuple[str, str]: if chunk.get('type') == 'text' and isinstance(chunk.get('text'), str): text.append(cast(str, chunk['text'])) elif chunk.get('type') == 'thinking' and isinstance(chunk.get('thinking'), list): + if isinstance(chunk.get('signature'), str): + signature = cast(str, chunk['signature']) for item in cast(list[object], chunk['thinking']): if isinstance(item, Mapping): item = cast(Mapping[str, object], item) if item.get('type') == 'text' and isinstance(item.get('text'), str): reasoning.append(cast(str, item['text'])) - return ''.join(reasoning), ''.join(text) + if not reasoning and signature is None: + return None, ''.join(text) + metadata = {THOUGHT_SIGNATURE: signature} if signature is not None else None + return Part.from_reasoning(''.join(reasoning), metadata=metadata), ''.join(text) + + +def thinking_chunk(parts: list[Part]) -> dict[str, Any] | None: + """One Mistral ``thinking`` chunk replaying a model message's reasoning parts. + + Mistral asks for the whole assistant message, reasoning included, on later + turns; stripping it degrades the answer. A streamed reply arrives as many + reasoning parts, so their text is joined into one chunk, carrying the last + signature seen. + + Args: + parts: The message's parts. + + Returns: + The chunk, or None when the message has no reasoning. + """ + texts: list[str] = [] + signature: str | None = None + for part in parts: + if part.reasoning is None: + continue + texts.append(part.reasoning) + value = (part.metadata or {}).get(THOUGHT_SIGNATURE) + if isinstance(value, str): + signature = value + if not texts: + return None + chunk: dict[str, Any] = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': ''.join(texts)}]} + if signature is not None: + chunk['signature'] = signature + return chunk class DictMessageAdapter: @@ -585,7 +630,7 @@ def _get_openai_role(cls, role: Role | str) -> str: return str(role) @classmethod - def to_openai(cls, message: Message) -> list[dict]: + def to_openai(cls, message: Message, *, replay_thinking: bool = False) -> list[dict]: """Converts an internal `Message` object to OpenAI-compatible chat messages. Handles text, media (images), tool requests, and tool responses. @@ -597,6 +642,9 @@ def to_openai(cls, message: Message) -> list[dict]: Args: message: The internal `Message` instance. + replay_thinking: Send a model message's reasoning back as a leading + Mistral ``thinking`` chunk in its content. Off, reasoning is + dropped, which is what OpenAI and DeepSeek need. Returns: A list of OpenAI-compatible message dictionaries. @@ -607,9 +655,8 @@ def to_openai(cls, message: Message) -> list[dict]: has_media = False for part in message.content: - # Reasoning must not be sent back in multi-turn context. - # DeepSeek's API rejects it, and assistant messages only - # replay text to the model. + # Reasoning is not replayed as text. DeepSeek's API rejects it; + # Mistral gets it back as a thinking chunk (replay_thinking). if part.reasoning is not None: continue @@ -664,8 +711,29 @@ def to_openai(cls, message: Message) -> list[dict]: }) result.extend(tool_messages) + if replay_thinking and message.role == Role.MODEL: + cls._prepend_thinking(result, message) return result + @classmethod + def _prepend_thinking(cls, result: list[dict[str, Any]], message: Message) -> None: + """Put the message's reasoning, as a thinking chunk, at the front of its first assistant message.""" + chunk = thinking_chunk(message.content) + if chunk is None: + return + role = cls._get_openai_role(message.role) + target = next((m for m in result if m.get('role') == role), None) + if target is None: + result.insert(0, {'role': role, 'content': [chunk]}) + return + content = target.get('content') + if isinstance(content, str): + target['content'] = [chunk, {'type': 'text', 'text': content}] + elif isinstance(content, list): + target['content'] = [chunk, *content] + else: + target['content'] = [chunk] + @classmethod def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: """Converts an OpenAI-style message into a Genkit `Message` object. @@ -687,8 +755,8 @@ def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: content.append(Part.from_reasoning(reasoning)) thinking, text = split_reply_content(message.content) - if thinking: - content.append(Part.from_reasoning(thinking)) + if thinking is not None: + content.append(thinking) if text: content.append(cls.text_part_to_genkit(text)) From b8c74fd512806958e43206b1790c723213017166 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Thu, 12 Nov 2026 10:05:57 +0000 Subject: [PATCH 08/22] test(py/openai): cover Mistral reasoning replay, regional hosts and model_length --- packages/genkit-openai/tests/mistral_test.py | 213 ++++++++++++++----- 1 file changed, 159 insertions(+), 54 deletions(-) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index f067ec593..7ab98afab 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -27,7 +27,7 @@ from genkit_openai._models._mistral import mistral_chat_body from pydantic import BaseModel -from genkit import FinishReason, Genkit, Part +from genkit import FinishReason, Genkit, Message, Part, Role MISTRAL_URL = 'https://api.mistral.ai/v1' CODESTRAL_URL = 'https://codestral.mistral.ai/v1' @@ -69,59 +69,90 @@ 'safe_prompt', }) _EMBEDDING_FIELDS = frozenset({'model', 'input', 'metadata', 'output_dimension', 'output_dtype', 'encoding_format'}) -_MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'codestral.mistral.ai'}) +_MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'api.eu.mistral.ai', 'api.us.mistral.ai', 'codestral.mistral.ai'}) +# Chunk types a message's content list may hold, and the keys a thinking chunk +# may carry (ContentChunk and ThinkChunk in the mistralai SDK). +_CHUNK_TYPES = frozenset({ + 'text', + 'image_url', + 'reference', + 'file', + 'input_audio', + 'document_url', + 'resource', + 'resource_link', + 'thinking', +}) +_THINKING_KEYS = frozenset({'type', 'thinking', 'signature', 'closed'}) -# A Magistral reply: reasoning in a thinking chunk, then the answer, in a content list. -_THINKING = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': 'Two loaves, one each.'}]} +SIGNATURE = 'sig-abc' +REASONING = 'Two loaves, one each.' -def _content(model: str, text: str) -> Any: # noqa: ANN401 - if model.startswith('magistral'): - return [_THINKING, {'type': 'text', 'text': text}] - return text +def _thinking(text: str, *, signature: str | None = None) -> dict[str, Any]: + chunk: dict[str, Any] = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': text}]} + if signature is not None: + chunk['signature'] = signature + return chunk -def _completion(model: str) -> dict[str, Any]: +def _completion(body: dict[str, Any], finish_reason: str) -> dict[str, Any]: + # With reasoning_effort set, Mistral puts the reasoning in a thinking chunk + # ahead of the answer, in a content list. + content: Any = 'bonjour' + if body.get('reasoning_effort'): + content = [_thinking(REASONING, signature=SIGNATURE), {'type': 'text', 'text': 'bonjour'}] return { 'id': 'cmpl-1', 'object': 'chat.completion', 'created': 0, - 'model': model, - 'choices': [ - { - 'index': 0, - 'finish_reason': 'stop', - 'message': {'role': 'assistant', 'content': _content(model, 'bonjour')}, - } - ], + 'model': body['model'], + 'choices': [{'index': 0, 'finish_reason': finish_reason, 'message': {'role': 'assistant', 'content': content}}], 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5}, } -def _stream_body(model: str) -> bytes: +def _stream_body(body: dict[str, Any]) -> bytes: # Mistral sends usage on the last chunk, beside finish_reason, without stream_options. - first: Any = [_THINKING] if model.startswith('magistral') else 'bon' - second: Any = [{'type': 'text', 'text': 'bonjour'}] if model.startswith('magistral') else 'jour' - chunks = [ - { - 'id': 'cmpl-1', - 'object': 'chat.completion.chunk', - 'created': 0, - 'model': model, - 'choices': [{'index': 0, 'delta': {'role': 'assistant', 'content': first}, 'finish_reason': None}], - }, - { + # With reasoning_effort set, deltas go: a list with a thinking chunk, a list + # with the closing thinking chunk and the first text chunk, then strings. + deltas: list[Any] = ['bon', 'jour'] + if body.get('reasoning_effort'): + deltas = [ + [_thinking('Two loaves,')], + [_thinking(' one each.', signature=SIGNATURE), {'type': 'text', 'text': 'bon'}], + 'jour', + ] + chunks = [] + for i, delta in enumerate(deltas): + last = i == len(deltas) - 1 + chunk: dict[str, Any] = { 'id': 'cmpl-1', 'object': 'chat.completion.chunk', 'created': 0, - 'model': model, - 'choices': [{'index': 0, 'delta': {'content': second}, 'finish_reason': 'stop'}], - 'usage': {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5}, - }, - ] + 'model': body['model'], + 'choices': [{'index': 0, 'delta': {'content': delta}, 'finish_reason': 'stop' if last else None}], + } + if last: + chunk['usage'] = {'prompt_tokens': 3, 'completion_tokens': 2, 'total_tokens': 5} + chunks.append(chunk) return b''.join(f'data: {json.dumps(c)}\n\n'.encode() for c in chunks) + b'data: [DONE]\n\n' +def _bad_chunks(body: dict[str, Any]) -> list[str]: + bad: list[str] = [] + for i, message in enumerate(body.get('messages', [])): + content = message.get('content') + if not isinstance(content, list): + continue + for j, chunk in enumerate(content): + if chunk.get('type') not in _CHUNK_TYPES: + bad.append(f'messages.{i}.content.{j}.type') + elif chunk['type'] == 'thinking' and set(chunk) - _THINKING_KEYS: + bad.append(f'messages.{i}.content.{j}') + return bad + + def _embeddings(body: dict[str, Any]) -> dict[str, Any]: vector = [0.5, 0.25] embedding: Any = vector @@ -148,6 +179,7 @@ class _Server: def __init__(self) -> None: self.requests: list[httpx.Request] = [] + self.finish_reason = 'stop' def handler(self, request: httpx.Request) -> httpx.Response: self.requests.append(request) @@ -155,15 +187,13 @@ def handler(self, request: httpx.Request) -> httpx.Response: embeddings = request.url.path.endswith('/embeddings') if request.url.host in _MISTRAL_HOSTS: allowed = _EMBEDDING_FIELDS if embeddings else _CHAT_FIELDS - if unknown := sorted(set(body) - allowed): + if unknown := sorted(set(body) - allowed) + _bad_chunks(body): return _extra_forbidden(unknown) if embeddings: return httpx.Response(200, json=_embeddings(body)) if body.get('stream'): - return httpx.Response( - 200, content=_stream_body(body['model']), headers={'content-type': 'text/event-stream'} - ) - return httpx.Response(200, json=_completion(body['model'])) + return httpx.Response(200, content=_stream_body(body), headers={'content-type': 'text/event-stream'}) + return httpx.Response(200, json=_completion(body, self.finish_reason)) def bodies(self) -> list[dict[str, Any]]: return [json.loads(r.content) for r in self.requests] @@ -251,7 +281,7 @@ async def test_mistral_max_output_tokens_goes_out_as_max_tokens( mistral: Genkit, server: _Server, config: dict[str, Any] ) -> None: """`max_output_tokens` reaches Mistral as `max_tokens`, even with `reasoning_effort` set.""" - await mistral.generate(model='openai/magistral-medium-latest', prompt='salut', config=config) + await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) [body] = server.bodies() caps_sent = {k: body[k] for k in ('max_tokens', 'max_completion_tokens') if k in body} @@ -265,14 +295,14 @@ async def test_mistral_seed_goes_out_as_random_seed(mistral: Genkit, server: _Se await mistral.generate( model='openai/mistral-small-latest', prompt='salut', - config={'seed': 7, 'temperature': 0.2, 'extra': {'safe_prompt': True}}, + config={'seed': 7, 'temperature': 0.2, 'extra': {'min_tokens': 5}}, ) [body] = server.bodies() assert body['random_seed'] == 7 assert 'seed' not in body assert body['temperature'] == 0.2 - assert body['safe_prompt'] is True + assert body['min_tokens'] == 5 @pytest.mark.asyncio @@ -405,28 +435,103 @@ async def test_mistral_top_k_goes_out(mistral: Genkit, server: _Server) -> None: assert body['top_k'] == 5 +_REASONING_CONFIG = {'reasoning_effort': 'high'} + + @pytest.mark.asyncio -async def test_mistral_magistral_reply_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: - """A Magistral reply's `thinking` chunk comes back as a reasoning part, its `text` chunk as the text.""" - response = await mistral.generate(model='openai/magistral-medium-latest', prompt='Bread for two?') +async def test_mistral_reasoning_reply_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: + """With `reasoning_effort` set, the reply's `thinking` chunk is a reasoning part and its `text` chunk the text.""" + response = await mistral.generate( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) assert response.text == 'bonjour' assert response.message is not None - assert [p.reasoning for p in response.message.content if p.reasoning] == ['Two loaves, one each.'] + [reasoning] = [p for p in response.message.content if p.reasoning] + assert reasoning.reasoning == REASONING + assert reasoning.metadata == {'thoughtSignature': SIGNATURE} @pytest.mark.asyncio -async def test_mistral_magistral_stream_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: - """Streamed `thinking` chunks arrive as reasoning parts, and the final response keeps reasoning before text.""" - stream = mistral.generate_stream(model='openai/magistral-medium-latest', prompt='Bread for two?') +async def test_mistral_reasoning_stream_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: + """Streamed thinking chunks arrive as reasoning parts, through all three delta shapes Mistral sends.""" + stream = mistral.generate_stream( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) chunks = [chunk async for chunk in stream.stream] response = await stream.response - assert [c.text for c in chunks] == ['', 'bonjour'] - assert chunks[0].content[0].reasoning == 'Two loaves, one each.' + assert [c.text for c in chunks] == ['', 'bon', 'jour'] + assert ''.join(p.reasoning for c in chunks for p in c.content if p.reasoning) == REASONING assert response.text == 'bonjour' assert response.message is not None - assert response.message.content[0].reasoning == 'Two loaves, one each.' + assert ''.join(p.reasoning for p in response.message.content if p.reasoning) == REASONING + + +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.asyncio +async def test_mistral_replays_reasoning_as_a_thinking_chunk(mistral: Genkit, server: _Server, streamed: bool) -> None: + """The next turn sends the reply's reasoning back as one leading `thinking` chunk, signature included.""" + if streamed: + stream = mistral.generate_stream( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + first = await stream.response + else: + first = await mistral.generate( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + + second = await mistral.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + + assert second.finish_reason == FinishReason.STOP + body = server.bodies()[-1] + [assistant] = [m for m in body['messages'] if m['role'] == 'assistant'] + assert assistant['content'] == [ + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}], 'signature': SIGNATURE}, + {'type': 'text', 'text': 'bonjour'}, + ] + + +@pytest.mark.asyncio +async def test_openai_host_does_not_replay_reasoning(openai: Genkit, server: _Server) -> None: + """On any other host a model message's reasoning is still left out of the next turn.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message(role=Role.MODEL, content=[Part.from_reasoning(REASONING), Part.from_text('bonjour')]), + ] + + await openai.generate(model='openai/gpt-4o', messages=history, prompt='And three?') + + [body] = server.bodies() + [assistant] = [m for m in body['messages'] if m['role'] == 'assistant'] + assert assistant['content'] == 'bonjour' + + +@pytest.mark.asyncio +async def test_mistral_model_length_finish_is_length(mistral: Genkit, server: _Server) -> None: + """Mistral's `model_length` finish reason comes back as LENGTH.""" + server.finish_reason = 'model_length' + + response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut') + + assert response.finish_reason == FinishReason.LENGTH + + +@pytest.mark.parametrize('host', ['api.eu.mistral.ai', 'api.us.mistral.ai']) +@pytest.mark.asyncio +async def test_mistral_regional_hosts_get_mistral_field_names(server: _Server, host: str) -> None: + """The EU and US endpoints get the same rewrite as the global one.""" + ai = _ai(server, f'https://{host}/v1') + + stream = ai.generate_stream(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + await stream.response + + [request] = server.requests + assert request.url.host == host + body = json.loads(request.content) + assert 'stream_options' not in body + assert body['random_seed'] == 7 @pytest.mark.asyncio @@ -506,7 +611,7 @@ def test_mistral_chat_body_leaves_its_input_alone() -> None: 'seed': 7, 'max_completion_tokens': 50, 'stream_options': {'include_usage': True}, - 'extra_body': {'safe_prompt': True}, + 'extra_body': {'min_tokens': 5}, } before = json.loads(json.dumps(body)) @@ -516,5 +621,5 @@ def test_mistral_chat_body_leaves_its_input_alone() -> None: assert out == { 'model': 'mistral-small-latest', 'max_tokens': 50, - 'extra_body': {'random_seed': 7, 'top_k': 5, 'safe_prompt': True}, + 'extra_body': {'random_seed': 7, 'top_k': 5, 'min_tokens': 5}, } From 904466d7bbc70e4e7fa3402ec242c51ad99e2a0e Mon Sep 17 00:00:00 2001 From: Adesina H Date: Thu, 12 Nov 2026 10:05:57 +0000 Subject: [PATCH 09/22] docs(py/openai): describe Mistral reasoning via reasoning_effort and regional hosts --- packages/genkit-openai/README.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index fb3521626..62b34150e 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -80,11 +80,12 @@ embeddings = await ai.embed(embedder='openai/mistral-embed', content='croissant' ``` Pass `api_key=` explicitly. Without it the plugin falls back to -`OPENAI_API_KEY` and sends that key to Mistral. For Codestral keys, use -`base_url='https://codestral.mistral.ai/v1'`. +`OPENAI_API_KEY` and sends that key to Mistral. The EU and US endpoints, +`https://api.eu.mistral.ai/v1` and `https://api.us.mistral.ai/v1`, work the +same way. -Mistral rejects any request field it doesn't declare, so with either of those -hosts the plugin sends Mistral's names for the settings that differ: +Mistral rejects any request field it doesn't declare, so with a Mistral host +the plugin sends Mistral's names for the settings that differ: - `max_output_tokens` goes out as `max_tokens`, never `max_completion_tokens`, even with `reasoning_effort` set. @@ -93,11 +94,12 @@ hosts the plugin sends Mistral's names for the settings that differ: - Streaming sends no `stream_options`; Mistral reports usage on the last chunk. - An embedder's `dimensions` goes out as `output_dimension`. -Magistral replies carry their reasoning in `thinking` chunks; those come back -as reasoning parts, ahead of the text, streamed or not. +With `reasoning_effort` set, replies carry their reasoning in `thinking` +chunks. Those come back as reasoning parts, ahead of the text, streamed or not, +and go back to Mistral as a `thinking` chunk on the next turn, as Mistral asks. Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given -and Mistral fails the call naming them. Mistral-only fields like `safe_prompt` +and Mistral fails the call naming them. Mistral-only fields like `min_tokens` go in `extra`. A gateway in front of Mistral on any other host gets the OpenAI field names. From f78956632154799d6c8f241778573a66fbd2f853 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Fri, 13 Nov 2026 12:54:53 +0000 Subject: [PATCH 10/22] fix(py/openai): refuse top_k for Mistral before the request goes out A live call shows every Mistral model rejects top_k ("top_k sampling is not enabled for this model"). mistral_chat_body now raises INVALID_ARGUMENT for it, so the turn fails naming the setting and nothing is sent. Its docstring also gives the current reason stream_options is dropped: Mistral accepts it now, but reports usage on the last chunk without it. --- packages/genkit-openai/README.md | 6 +++-- .../src/genkit_openai/_models/_mistral.py | 24 ++++++++++++------- packages/genkit-openai/tests/mistral_test.py | 15 ++++++------ 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 62b34150e..c6823b3be 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -90,8 +90,10 @@ the plugin sends Mistral's names for the settings that differ: - `max_output_tokens` goes out as `max_tokens`, never `max_completion_tokens`, even with `reasoning_effort` set. - `seed` goes out as `random_seed`. -- `top_k` goes out as is. Mistral takes it; OpenAI never gets it. -- Streaming sends no `stream_options`; Mistral reports usage on the last chunk. +- `top_k` is refused before the request goes out: Mistral's models reject + `top_k` sampling. +- Streaming sends no `stream_options`; Mistral reports usage on the last chunk + without it. - An embedder's `dimensions` goes out as `output_dimension`. With `reasoning_effort` set, replies carry their reasoning in `thinking` diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 263fde9dd..02527165d 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -37,6 +37,8 @@ from openai import AsyncOpenAI +from genkit import GenkitError + # Mistral's API hosts: global, EU and US, the servers in the mistralai SDK's # sdkconfiguration.py. codestral.mistral.ai, for Codestral-only keys, is not in # that list or the OpenAPI servers; it is kept since nothing else lives there. @@ -51,16 +53,16 @@ def is_mistral(client: AsyncOpenAI) -> bool: def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict[str, Any]: """Rewrite ``chat.completions.create()`` kwargs into a body Mistral accepts. - - ``stream_options`` is dropped. Mistral has no such field; it reports - usage on the last streamed chunk without being asked. + - ``stream_options`` is dropped. Mistral reports usage on the last + streamed chunk without being asked, so it isn't needed. - ``max_completion_tokens`` goes out as ``max_tokens``, Mistral's only reply cap, including when ``reasoning_effort`` is set. - ``seed`` goes out as ``random_seed``. - - ``top_k``, which OpenAI has no field for, goes out as is. + - ``top_k`` is refused. Mistral's schema declares it, but its models + answer "top_k sampling is not enabled for this model". - The SDK has no ``random_seed`` or ``top_k`` kwarg, so both ride in - ``extra_body``; the same key in the caller's ``extra`` wins, as every - ``extra`` key does. + The SDK has no ``random_seed`` kwarg, so it rides in ``extra_body``; the + same key in the caller's ``extra`` wins, as every ``extra`` key does. Args: body: The kwargs the plugin built for OpenAI. Not modified. @@ -68,7 +70,15 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict Returns: A copy with Mistral's field names. + + Raises: + GenkitError: ``INVALID_ARGUMENT`` when ``top_k`` is set. """ + if top_k is not None: + raise GenkitError( + status='INVALID_ARGUMENT', + message="Mistral doesn't support top_k: its models reject top_k sampling. Remove top_k from the config.", + ) out = dict(body) out.pop('stream_options', None) if 'max_completion_tokens' in out: @@ -76,8 +86,6 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict renamed: dict[str, Any] = {} if 'seed' in out: renamed['random_seed'] = out.pop('seed') - if top_k is not None: - renamed['top_k'] = top_k if renamed: out['extra_body'] = {**renamed, **(out.get('extra_body') or {})} return out diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 7ab98afab..ec399b1fd 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -427,12 +427,13 @@ async def test_mistral_generate_drops_stream_options_from_config(mistral: Genkit @pytest.mark.asyncio -async def test_mistral_top_k_goes_out(mistral: Genkit, server: _Server) -> None: - """`config={'top_k': 5}` reaches Mistral, which declares `top_k`; OpenAI never gets it.""" - await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'top_k': 5}) +async def test_mistral_refuses_top_k(mistral: Genkit, server: _Server) -> None: + """`config={'top_k': 5}` fails the turn before the request goes out: Mistral's models reject `top_k`.""" + response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'top_k': 5}) - [body] = server.bodies() - assert body['top_k'] == 5 + assert response.finish_reason == FinishReason.FAILED + assert 'top_k' in str(response.error) + assert server.bodies() == [] _REASONING_CONFIG = {'reasoning_effort': 'high'} @@ -615,11 +616,11 @@ def test_mistral_chat_body_leaves_its_input_alone() -> None: } before = json.loads(json.dumps(body)) - out = mistral_chat_body(body, top_k=5) + out = mistral_chat_body(body) assert body == before assert out == { 'model': 'mistral-small-latest', 'max_tokens': 50, - 'extra_body': {'random_seed': 7, 'top_k': 5, 'min_tokens': 5}, + 'extra_body': {'random_seed': 7, 'min_tokens': 5}, } From f446cad7e65fb029be7a55c95bca54145dbee3be Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 10:03:41 +0000 Subject: [PATCH 11/22] fix(py/openai): replay only Mistral's reasoning, read MISTRAL_API_KEY, add provider='mistral' - Reasoning parts read from Mistral's thinking chunks are now marked metadata['reasoningSource'] = 'mistral', and only those go back to Mistral. Reasoning another model left in a mixed history (Gemini or Claude, with their thoughtSignature) is dropped, as it is for OpenAI. The mark lives on the part, so it survives a JSON round trip. - With a Mistral target and no api_key, the plugin key comes from MISTRAL_API_KEY instead of OPENAI_API_KEY, so an OpenAI key is never sent to Mistral. An explicit api_key still wins. - seed, max_completion_tokens and stream_options in extra get the same renames as in config instead of a 422 from Mistral. - OpenAI(provider='mistral') applies the Mistral rewrites on any host, for a gateway in front of Mistral. - Tests for replaying onto a tool-call-only turn (no content), a reasoning-only turn, and list content on a non-Mistral host. - README notes that JS and Dart register these models as mistral/... --- packages/genkit-openai/README.md | 36 ++- .../src/genkit_openai/__init__.py | 3 +- .../src/genkit_openai/_models/_mistral.py | 33 +- .../src/genkit_openai/_models/_model.py | 13 +- .../src/genkit_openai/_models/_utils.py | 27 +- .../src/genkit_openai/_openai_plugin.py | 49 ++- packages/genkit-openai/tests/mistral_test.py | 295 +++++++++++++++++- 7 files changed, 408 insertions(+), 48 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index c6823b3be..c02521b5a 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -57,18 +57,16 @@ OpenAI( ## Mistral -Point `base_url` at Mistral's API and pass a Mistral key. Models keep the -`openai/` prefix: +Point `base_url` at Mistral's API. Models keep the `openai/` prefix here; the +JS and Dart SDKs register them as `mistral/...`, so a model id written for one +SDK (in a `.prompt` file, say) doesn't resolve in the other: ```python -import os - from genkit import Genkit from genkit_openai import OpenAI -ai = Genkit( - plugins=[OpenAI(api_key=os.environ['MISTRAL_API_KEY'], base_url='https://api.mistral.ai/v1')] -) +# The key comes from MISTRAL_API_KEY. +ai = Genkit(plugins=[OpenAI(base_url='https://api.mistral.ai/v1')]) res = await ai.generate( model='openai/mistral-small-latest', @@ -79,13 +77,23 @@ res = await ai.generate( embeddings = await ai.embed(embedder='openai/mistral-embed', content='croissant') ``` -Pass `api_key=` explicitly. Without it the plugin falls back to -`OPENAI_API_KEY` and sends that key to Mistral. The EU and US endpoints, +With a Mistral target the plugin key comes from `api_key=` or +`MISTRAL_API_KEY`, never `OPENAI_API_KEY`. The EU and US endpoints, `https://api.eu.mistral.ai/v1` and `https://api.us.mistral.ai/v1`, work the same way. +A gateway in front of Mistral on another host needs `provider='mistral'`; +without it the plugin can't tell the API behind it is Mistral's and sends +OpenAI's field names, which Mistral rejects. Pass the gateway's own key as +`api_key=`, or the plugin reads `MISTRAL_API_KEY`: + +```python +OpenAI(base_url='https://llm-gateway.example.com/v1', api_key=gateway_key, provider='mistral') +``` + Mistral rejects any request field it doesn't declare, so with a Mistral host -the plugin sends Mistral's names for the settings that differ: +(or `provider='mistral'`) the plugin sends Mistral's names for the settings +that differ: - `max_output_tokens` goes out as `max_tokens`, never `max_completion_tokens`, even with `reasoning_effort` set. @@ -95,15 +103,19 @@ the plugin sends Mistral's names for the settings that differ: - Streaming sends no `stream_options`; Mistral reports usage on the last chunk without it. - An embedder's `dimensions` goes out as `output_dimension`. +- `extra` gets the same renames: `seed` and `max_completion_tokens` there go + out as `random_seed` and `max_tokens`, and `stream_options` is dropped. With `reasoning_effort` set, replies carry their reasoning in `thinking` chunks. Those come back as reasoning parts, ahead of the text, streamed or not, and go back to Mistral as a `thinking` chunk on the next turn, as Mistral asks. +Only reasoning that came from Mistral goes back: each such part is marked +`metadata['reasoningSource'] == 'mistral'`, which survives saving the history +as JSON. Reasoning another model left in a mixed history is dropped. Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given and Mistral fails the call naming them. Mistral-only fields like `min_tokens` -go in `extra`. A gateway in front of Mistral on any other host gets the OpenAI -field names. +go in `extra`. The plugin doesn't know Mistral's embedders, so their info reports the default 1536 dimensions; `mistral-embed` returns 1024. diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py index 2d2964d8d..3e1d45854 100644 --- a/packages/genkit-openai/src/genkit_openai/__init__.py +++ b/packages/genkit-openai/src/genkit_openai/__init__.py @@ -48,7 +48,8 @@ async def main() -> None: ``` Credentials: - The plugin key comes from ``api_key=`` or ``OPENAI_API_KEY``. A + The plugin key comes from ``api_key=`` or ``OPENAI_API_KEY`` + (``MISTRAL_API_KEY`` when the target is Mistral). A ``generate()`` or ``embed()`` call can bring its own key as ``context={'secrets': {'api_key': ...}}``; a plugin with no key of its own serves only those calls. diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 02527165d..665ba04fa 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -23,7 +23,8 @@ else goes out unchanged. The target is read from the client's base URL, not the model id as DeepSeek's -JSON handling is. Mistral's ids share no prefix (``mistral-``, ``magistral-``, +JSON handling is, or set with ``OpenAI(provider='mistral')`` for a gateway in +front of Mistral on another host. Mistral's ids share no prefix (``mistral-``, ``magistral-``, ``codestral-``, ``pixtral-``, ...), and the same ids are served through other OpenAI-compatible hosts that take OpenAI's names: Vertex Model Garden reuses ``OpenAIModel`` for ``mistralai/...`` models with a Vertex client, so it never @@ -35,6 +36,7 @@ from typing import Any +import httpx from openai import AsyncOpenAI from genkit import GenkitError @@ -45,9 +47,25 @@ MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'api.eu.mistral.ai', 'api.us.mistral.ai', 'codestral.mistral.ai'}) +# The key Mistral's own SDKs, and Genkit's JS and Dart plugins, read. +MISTRAL_API_KEY_ENV = 'MISTRAL_API_KEY' + + +def is_mistral_url(url: str | httpx.URL) -> bool: + """Whether ``url`` is on one of Mistral's API hosts.""" + return httpx.URL(str(url)).host in MISTRAL_HOSTS + + def is_mistral(client: AsyncOpenAI) -> bool: """Whether ``client`` sends its requests to one of Mistral's API hosts.""" - return client.base_url.host in MISTRAL_HOSTS + return is_mistral_url(client.base_url) + + +def _rename(body: dict[str, Any], old: str, new: str) -> None: + """Move ``body[old]`` to ``body[new]``, unless ``new`` is already set there.""" + if old in body: + value = body.pop(old) + body.setdefault(new, value) def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict[str, Any]: @@ -63,6 +81,9 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict The SDK has no ``random_seed`` kwarg, so it rides in ``extra_body``; the same key in the caller's ``extra`` wins, as every ``extra`` key does. + ``extra`` gets the same renames: its ``seed``, ``max_completion_tokens`` + and ``stream_options`` would otherwise reach Mistral as given and fail + with a 422. Where ``extra`` has both names, Mistral's wins. Args: body: The kwargs the plugin built for OpenAI. Not modified. @@ -86,6 +107,10 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict renamed: dict[str, Any] = {} if 'seed' in out: renamed['random_seed'] = out.pop('seed') - if renamed: - out['extra_body'] = {**renamed, **(out.get('extra_body') or {})} + extra = dict(out.pop('extra_body', None) or {}) + extra.pop('stream_options', None) + _rename(extra, 'max_completion_tokens', 'max_tokens') + _rename(extra, 'seed', 'random_seed') + if renamed or extra: + out['extra_body'] = {**renamed, **extra} return out diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index e48bf7046..d85edb376 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -252,7 +252,14 @@ def _finish_state( class OpenAIModel: """Handles OpenAI API interactions for the Genkit plugin.""" - def __init__(self, model: str, client: AsyncOpenAI, *, supports: ModelSupports | None = None) -> None: + def __init__( + self, + model: str, + client: AsyncOpenAI, + *, + supports: ModelSupports | None = None, + mistral: bool | None = None, + ) -> None: """Initializes the OpenAIModel instance with the specified model and OpenAI client parameters. Args: @@ -262,11 +269,13 @@ def __init__(self, model: str, client: AsyncOpenAI, *, supports: ModelSupports | ``supports.output`` means the endpoint accepts schema-less JSON mode. ``None`` (or an entry that omits ``output``) still sends ``json_object`` so a fine-tune keeps working. + mistral: Send Mistral's field names (see ``_mistral.py``). + ``None`` decides from the client's host. """ self._model = model self._openai_client = client self._supports = supports - self._mistral = is_mistral(client) + self._mistral = is_mistral(client) if mistral is None else mistral @property def name(self) -> str: diff --git a/packages/genkit-openai/src/genkit_openai/_models/_utils.py b/packages/genkit-openai/src/genkit_openai/_models/_utils.py index d75cfd9f1..7de18d12c 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_utils.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_utils.py @@ -415,6 +415,13 @@ def _extract_media(request: ModelRequest) -> tuple[str, str]: # under the same key the Anthropic and Google plugins use for theirs. THOUGHT_SIGNATURE = 'thoughtSignature' +# Marks a reasoning part read from a Mistral thinking chunk, so only those go +# back to Mistral: a history can hold reasoning from other models, whose text +# and signatures Mistral can't use. Part metadata, unlike the response that +# carried it, stays with the part through a JSON round trip of the history. +REASONING_SOURCE = 'reasoningSource' +MISTRAL_SOURCE = 'mistral' + def split_reply_content(content: object) -> tuple[Part | None, str]: """The reasoning and the text in a reply's ``content``. @@ -430,9 +437,10 @@ def split_reply_content(content: object) -> tuple[Part | None, str]: content: A message's or delta's ``content`` as the SDK parsed it. Returns: - A reasoning part, with the chunk's signature in - ``metadata['thoughtSignature']`` when it has one, or None when there is - no reasoning; and the reply text, empty when absent. + A reasoning part, marked ``metadata['reasoningSource'] = 'mistral'`` + and with the chunk's signature in ``metadata['thoughtSignature']`` when + it has one, or None when there is no reasoning; and the reply text, + empty when absent. """ if isinstance(content, str): return None, content @@ -457,7 +465,9 @@ def split_reply_content(content: object) -> tuple[Part | None, str]: reasoning.append(cast(str, item['text'])) if not reasoning and signature is None: return None, ''.join(text) - metadata = {THOUGHT_SIGNATURE: signature} if signature is not None else None + metadata: dict[str, Any] = {REASONING_SOURCE: MISTRAL_SOURCE} + if signature is not None: + metadata[THOUGHT_SIGNATURE] = signature return Part.from_reasoning(''.join(reasoning), metadata=metadata), ''.join(text) @@ -467,7 +477,9 @@ def thinking_chunk(parts: list[Part]) -> dict[str, Any] | None: Mistral asks for the whole assistant message, reasoning included, on later turns; stripping it degrades the answer. A streamed reply arrives as many reasoning parts, so their text is joined into one chunk, carrying the last - signature seen. + signature seen. Only parts read from Mistral's thinking chunks (marked + ``reasoningSource: 'mistral'``) go back; reasoning another model left in + the history is dropped, as it is for OpenAI. Args: parts: The message's parts. @@ -478,10 +490,11 @@ def thinking_chunk(parts: list[Part]) -> dict[str, Any] | None: texts: list[str] = [] signature: str | None = None for part in parts: - if part.reasoning is None: + metadata = part.metadata or {} + if part.reasoning is None or metadata.get(REASONING_SOURCE) != MISTRAL_SOURCE: continue texts.append(part.reasoning) - value = (part.metadata or {}).get(THOUGHT_SIGNATURE) + value = metadata.get(THOUGHT_SIGNATURE) if isinstance(value, str): signature = value if not texts: diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index d59fa5b3b..22c848cf2 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -64,7 +64,7 @@ OpenAIGptImageConfig, OpenAIImageModel, ) -from genkit_openai._models._mistral import is_mistral +from genkit_openai._models._mistral import MISTRAL_API_KEY_ENV, is_mistral, is_mistral_url from genkit_openai._models._model import OpenAIModel from genkit_openai._models._model_info import ( SUPPORTED_EMBEDDING_MODELS, @@ -108,11 +108,11 @@ def _client_kwargs( return options -def _missing_key_error() -> GenkitError: +def _missing_key_error(env: str) -> GenkitError: return GenkitError( status='FAILED_PRECONDITION', message=( - 'OpenAI needs an API key: set OPENAI_API_KEY or pass OpenAI(api_key=...), ' + f'OpenAI needs an API key: set {env} or pass OpenAI(api_key=...), ' "or send a per-request key as context={'secrets': {'api_key': ...}}." ), ) @@ -317,11 +317,13 @@ def __init__( api_key: str | None = None, base_url: str | None = None, client_options: Mapping[str, Any] | None = None, + provider: Literal['mistral'] | None = None, ) -> None: """Initializes the OpenAI plugin. Args: - api_key: OpenAI API key. Defaults to ``OPENAI_API_KEY``. + api_key: OpenAI API key. Defaults to ``OPENAI_API_KEY``, or + ``MISTRAL_API_KEY`` when the target is Mistral. base_url: OpenAI API base URL up to and including ``/v1``, e.g. ``https://openrouter.ai/api/v1``; the SDK appends ``/chat/completions``. Defaults to ``OPENAI_BASE_URL``, then the @@ -329,11 +331,18 @@ def __init__( client_options: Other ``AsyncOpenAI`` settings, such as ``organization``, ``project``, ``timeout``, ``max_retries``, ``default_headers``, or ``http_client``. + provider: ``'mistral'`` sends Mistral's field names whatever the + host, for a gateway in front of Mistral. Without it they go + out only when ``base_url`` is one of Mistral's own hosts. Raises: TypeError: If ``client_options`` has a key ``AsyncOpenAI`` doesn't take, or repeats ``api_key`` or ``base_url``. + ValueError: If ``provider`` is not ``'mistral'`` or None. """ + if provider not in (None, 'mistral'): + raise ValueError(f"OpenAI got provider={provider!r}; the only provider it knows is 'mistral'") + self._provider = provider options = _client_kwargs(api_key=api_key, base_url=base_url, client_options=client_options) self._options = options self._plugin_api_key: str | None = options.get('api_key') @@ -342,9 +351,28 @@ def __init__( self._pins_authorization = any(k.lower() == 'authorization' for k in plugin_headers) self._list_actions_cache: list[Action] | None = None + def _targets_mistral(self) -> bool: + """Whether calls go to Mistral's API: ``provider='mistral'`` or a Mistral base URL.""" + if self._provider == 'mistral': + return True + # The SDK's own fallback when base_url isn't given. + base_url = self._options.get('base_url') or os.environ.get('OPENAI_BASE_URL') + return bool(base_url) and is_mistral_url(base_url) + + def _key_env(self) -> str: + """The variable the plugin key falls back to. Mistral's, so an OpenAI key never goes to Mistral.""" + return MISTRAL_API_KEY_ENV if self._targets_mistral() else 'OPENAI_API_KEY' + + def _uses_mistral_names(self, client: AsyncOpenAI) -> bool: + return self._provider == 'mistral' or is_mistral(client) + @loop_local_client def _runtime_client(self) -> AsyncOpenAI: - return AsyncOpenAI(**self._options) + options: dict[str, Any] = self._options + if self._plugin_api_key is None and self._targets_mistral(): + # Otherwise the SDK reads OPENAI_API_KEY and sends it to Mistral. + options = {**options, 'api_key': os.environ.get(MISTRAL_API_KEY_ENV)} + return AsyncOpenAI(**options) @loop_local_client def _tenant_only_client(self) -> AsyncOpenAI: @@ -354,7 +382,7 @@ def _tenant_only_client(self) -> AsyncOpenAI: return AsyncOpenAI(**params) def _has_plugin_key(self) -> bool: - return bool(self._plugin_api_key or os.environ.get('OPENAI_API_KEY')) + return bool(self._plugin_api_key or os.environ.get(self._key_env())) async def init(self) -> list[Action]: """Initialize plugin. @@ -461,7 +489,7 @@ def _client_for_context(self, context: dict[str, Any]) -> AsyncOpenAI: client = self._runtime_client() return self._with_tenant_key(client, key) if key else client if key is None: - raise _missing_key_error() + raise _missing_key_error(self._key_env()) return self._with_tenant_key(self._tenant_only_client(), key) def _with_tenant_key(self, client: AsyncOpenAI, key: str) -> AsyncOpenAI: @@ -508,7 +536,10 @@ def _create_model_action(self, name: str) -> Action: async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> ModelResponse: catalog = SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)) supports = catalog.supports if catalog is not None else get_default_openai_model_info(name).supports - openai_model = OpenAIModelHandler(OpenAIModel(name, self._client_for_call(request, ctx), supports=supports)) + client = self._client_for_call(request, ctx) + openai_model = OpenAIModelHandler( + OpenAIModel(name, client, supports=supports, mistral=self._uses_mistral_names(client)) + ) return await openai_model.generate(request, ctx) return Model( @@ -599,7 +630,7 @@ async def embed_fn(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedRespons client = self._embed_client(ctx.context) create_kwargs: dict[str, Any] = {} if dimensions is not None: - if is_mistral(client): + 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} diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index ec399b1fd..a9e2c97fc 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -19,7 +19,7 @@ import base64 import json import struct -from typing import Any +from typing import Any, Literal, cast import httpx import pytest @@ -31,6 +31,8 @@ MISTRAL_URL = 'https://api.mistral.ai/v1' CODESTRAL_URL = 'https://codestral.mistral.ai/v1' +# A gateway that forwards to Mistral, so the fake enforces Mistral's schema on it too. +GATEWAY_URL = 'https://llm-gateway.example.com/v1' PLUGIN_KEY = 'mistral-key' # The fields Mistral's ChatCompletionRequest and EmbeddingRequest declare @@ -69,7 +71,13 @@ 'safe_prompt', }) _EMBEDDING_FIELDS = frozenset({'model', 'input', 'metadata', 'output_dimension', 'output_dtype', 'encoding_format'}) -_MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'api.eu.mistral.ai', 'api.us.mistral.ai', 'codestral.mistral.ai'}) +_MISTRAL_HOSTS = frozenset({ + 'api.mistral.ai', + 'api.eu.mistral.ai', + 'api.us.mistral.ai', + 'codestral.mistral.ai', + 'llm-gateway.example.com', +}) # Chunk types a message's content list may hold, and the keys a thinking chunk # may carry (ContentChunk and ThinkChunk in the mistralai SDK). _CHUNK_TYPES = frozenset({ @@ -96,12 +104,13 @@ def _thinking(text: str, *, signature: str | None = None) -> dict[str, Any]: return chunk -def _completion(body: dict[str, Any], finish_reason: str) -> dict[str, Any]: +def _completion(body: dict[str, Any], finish_reason: str, content: Any = None) -> dict[str, Any]: # noqa: ANN401 # With reasoning_effort set, Mistral puts the reasoning in a thinking chunk # ahead of the answer, in a content list. - content: Any = 'bonjour' - if body.get('reasoning_effort'): + if content is None and body.get('reasoning_effort'): content = [_thinking(REASONING, signature=SIGNATURE), {'type': 'text', 'text': 'bonjour'}] + elif content is None: + content = 'bonjour' return { 'id': 'cmpl-1', 'object': 'chat.completion', @@ -112,12 +121,13 @@ def _completion(body: dict[str, Any], finish_reason: str) -> dict[str, Any]: } -def _stream_body(body: dict[str, Any]) -> bytes: +def _stream_body(body: dict[str, Any], deltas: list[Any] | None = None) -> bytes: # Mistral sends usage on the last chunk, beside finish_reason, without stream_options. # With reasoning_effort set, deltas go: a list with a thinking chunk, a list # with the closing thinking chunk and the first text chunk, then strings. - deltas: list[Any] = ['bon', 'jour'] - if body.get('reasoning_effort'): + if deltas is None and not body.get('reasoning_effort'): + deltas = ['bon', 'jour'] + elif deltas is None: deltas = [ [_thinking('Two loaves,')], [_thinking(' one each.', signature=SIGNATURE), {'type': 'text', 'text': 'bon'}], @@ -180,6 +190,9 @@ class _Server: def __init__(self) -> None: self.requests: list[httpx.Request] = [] self.finish_reason = 'stop' + # Replaces the reply's content, or the streamed deltas, when set. + self.content: Any = None + self.deltas: list[Any] | None = None def handler(self, request: httpx.Request) -> httpx.Response: self.requests.append(request) @@ -192,8 +205,9 @@ def handler(self, request: httpx.Request) -> httpx.Response: if embeddings: return httpx.Response(200, json=_embeddings(body)) if body.get('stream'): - return httpx.Response(200, content=_stream_body(body), headers={'content-type': 'text/event-stream'}) - return httpx.Response(200, json=_completion(body, self.finish_reason)) + stream = _stream_body(body, self.deltas) + return httpx.Response(200, content=stream, headers={'content-type': 'text/event-stream'}) + return httpx.Response(200, json=_completion(body, self.finish_reason, self.content)) def bodies(self) -> list[dict[str, Any]]: return [json.loads(r.content) for r in self.requests] @@ -204,14 +218,21 @@ def server() -> _Server: return _Server() -def _ai(server: _Server, base_url: str | None) -> Genkit: +def _ai( + server: _Server, + base_url: str | None, + *, + api_key: str | None = PLUGIN_KEY, + provider: Literal['mistral'] | None = None, +) -> Genkit: http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) return Genkit( plugins=[ OpenAI( - api_key=PLUGIN_KEY, + api_key=api_key, base_url=base_url, client_options={'http_client': http_client, 'max_retries': 0}, + provider=provider, ) ] ) @@ -450,7 +471,7 @@ async def test_mistral_reasoning_reply_splits_reasoning_from_text(mistral: Genki assert response.message is not None [reasoning] = [p for p in response.message.content if p.reasoning] assert reasoning.reasoning == REASONING - assert reasoning.metadata == {'thoughtSignature': SIGNATURE} + assert reasoning.metadata == {'reasoningSource': 'mistral', 'thoughtSignature': SIGNATURE} @pytest.mark.asyncio @@ -624,3 +645,251 @@ def test_mistral_chat_body_leaves_its_input_alone() -> None: 'max_tokens': 50, 'extra_body': {'random_seed': 7, 'min_tokens': 5}, } + + +def _mistral_reasoning(text: str, signature: str | None = SIGNATURE) -> Part: + """A reasoning part as the plugin reads it from a Mistral thinking chunk.""" + metadata: dict[str, Any] = {'reasoningSource': 'mistral'} + if signature is not None: + metadata['thoughtSignature'] = signature + return Part.from_reasoning(text, metadata=metadata) + + +def _assistant_messages(body: dict[str, Any]) -> list[dict[str, Any]]: + return [m for m in body['messages'] if m['role'] == 'assistant'] + + +@pytest.mark.asyncio +async def test_mistral_replays_only_mistral_reasoning_from_a_mixed_history(mistral: Genkit, server: _Server) -> None: + """Reasoning another model left in the history, signed or not, is not sent to Mistral; Mistral's own is.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + # A Gemini or Claude turn: its reasoning carries a signature under the same key. + Message( + role=Role.MODEL, + content=[ + Part.from_reasoning('Gemini thinks.', metadata={'thoughtSignature': 'gemini-sig'}), + Part.from_text('Two loaves.'), + ], + ), + Message(role=Role.USER, content=[Part.from_text('And three?')]), + Message(role=Role.MODEL, content=[Part.from_reasoning('Unsigned, unmarked.'), Part.from_text('Three.')]), + Message(role=Role.USER, content=[Part.from_text('And four?')]), + Message(role=Role.MODEL, content=[_mistral_reasoning(REASONING), Part.from_text('Four.')]), + ] + + response = await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And five?') + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + gemini, unmarked, own = _assistant_messages(body) + assert gemini['content'] == 'Two loaves.' + assert unmarked['content'] == 'Three.' + assert own['content'] == [ + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}], 'signature': SIGNATURE}, + {'type': 'text', 'text': 'Four.'}, + ] + + +@pytest.mark.asyncio +async def test_mistral_reasoning_replays_after_a_json_round_trip(mistral: Genkit, server: _Server) -> None: + """A history saved as JSON and loaded back still replays Mistral's reasoning, signature included.""" + first = await mistral.generate( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + saved = json.dumps([m.model_dump(mode='json', by_alias=True, exclude_none=True) for m in first.messages]) + history = [Message.model_validate(m) for m in json.loads(saved)] + + await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And three?') + + [assistant] = _assistant_messages(server.bodies()[-1]) + assert assistant['content'][0] == { + 'type': 'thinking', + 'thinking': [{'type': 'text', 'text': REASONING}], + 'signature': SIGNATURE, + } + + +@pytest.mark.asyncio +async def test_mistral_replays_reasoning_onto_a_tool_call_message_with_no_content( + mistral: Genkit, server: _Server +) -> None: + """A turn with reasoning and only tool calls goes back as one assistant message: thinking chunk and calls.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Is the baguette in stock?')]), + Message( + role=Role.MODEL, + content=[ + _mistral_reasoning(REASONING), + Part.from_tool_request(name='lookup_menu', input={'dish': 'baguette'}, ref='call-1'), + ], + ), + Message( + role=Role.TOOL, + content=[Part.from_tool_response(name='lookup_menu', output='baguette: in stock', ref='call-1')], + ), + ] + + response = await mistral.generate(model='openai/mistral-small-latest', messages=history) + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + [assistant] = _assistant_messages(body) + assert assistant['content'] == [ + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}], 'signature': SIGNATURE} + ] + assert [c['id'] for c in assistant['tool_calls']] == ['call-1'] + + +@pytest.mark.asyncio +async def test_mistral_replays_a_reasoning_only_turn(mistral: Genkit, server: _Server) -> None: + """A turn that is only reasoning goes back as an assistant message holding just the thinking chunk.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message(role=Role.MODEL, content=[_mistral_reasoning(REASONING, signature=None)]), + ] + + await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='Well?') + + [assistant] = _assistant_messages(server.bodies()[0]) + assert assistant['content'] == [{'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}]}] + + +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.asyncio +async def test_openai_host_reads_list_content(openai: Genkit, server: _Server, streamed: bool) -> None: + """A non-Mistral host that answers with a list of text chunks gives back their text, with no reasoning part.""" + server.content = [{'type': 'text', 'text': 'bon'}, {'type': 'text', 'text': 'jour'}] + server.deltas = [[{'type': 'text', 'text': 'bon'}], 'jour'] + + if streamed: + stream = openai.generate_stream(model='openai/gpt-4o', prompt='hi') + chunks = [chunk.text async for chunk in stream.stream] + response = await stream.response + assert chunks == ['bon', 'jour'] + else: + response = await openai.generate(model='openai/gpt-4o', prompt='hi') + + assert response.text == 'bonjour' + assert response.message is not None + assert [p for p in response.message.content if p.reasoning is not None] == [] + + +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.asyncio +async def test_mistral_renames_openai_fields_in_extra(mistral: Genkit, server: _Server, streamed: bool) -> None: + """`extra` with `seed`, `max_completion_tokens` or `stream_options` goes out under Mistral's names, not as a 422.""" + config = {'extra': {'seed': 1, 'max_completion_tokens': 50, 'stream_options': {'include_usage': True}}} + if streamed: + stream = mistral.generate_stream(model='openai/mistral-small-latest', prompt='salut', config=config) + response = await stream.response + else: + response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + assert body['random_seed'] == 1 + assert body['max_tokens'] == 50 + assert not {'seed', 'max_completion_tokens', 'stream_options'} & set(body) + + +def test_mistral_chat_body_prefers_mistral_names_in_extra() -> None: + """With both names in `extra`, Mistral's own one is kept; `extra` still beats the config's `seed`.""" + out = mistral_chat_body({ + 'seed': 7, + 'extra_body': {'seed': 1, 'random_seed': 2, 'max_completion_tokens': 50, 'max_tokens': 60}, + }) + + assert out == {'extra_body': {'random_seed': 2, 'max_tokens': 60}} + + +@pytest.mark.asyncio +async def test_provider_mistral_sends_mistral_names_through_a_gateway(server: _Server) -> None: + """`OpenAI(base_url=, provider='mistral')` sends Mistral's names to a host that isn't Mistral's.""" + ai = _ai(server, GATEWAY_URL, provider='mistral') + + stream = ai.generate_stream( + model='openai/mistral-small-latest', prompt='Bread for two?', config={'seed': 7, **_REASONING_CONFIG} + ) + first = await stream.response + await ai.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + await ai.embed(embedder='openai/mistral-embed', content='croissant', config={'dimensions': 256}) + + streamed, replay, embed = server.requests + assert {r.url.host for r in server.requests} == {'llm-gateway.example.com'} + streamed_body = json.loads(streamed.content) + assert 'stream_options' not in streamed_body + assert streamed_body['random_seed'] == 7 + [assistant] = _assistant_messages(json.loads(replay.content)) + assert assistant['content'][0]['type'] == 'thinking' + assert json.loads(embed.content)['output_dimension'] == 256 + + +@pytest.mark.asyncio +async def test_gateway_without_provider_keeps_openai_names(server: _Server) -> None: + """Without `provider='mistral'` a gateway host gets OpenAI's names (and the fake Mistral behind it 422s).""" + ai = _ai(server, GATEWAY_URL) + + response = await ai.generate(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + + assert response.finish_reason == FinishReason.FAILED + assert server.bodies()[0]['seed'] == 7 + + +def test_unknown_provider_is_refused() -> None: + """`provider=` takes only `'mistral'`.""" + with pytest.raises(ValueError, match='mistral'): + OpenAI(api_key=PLUGIN_KEY, provider=cast(Any, 'cohere')) + + +@pytest.mark.parametrize( + ('base_url', 'provider'), + [ + pytest.param(MISTRAL_URL, None, id='mistral-host'), + pytest.param(GATEWAY_URL, 'mistral', id='provider'), + ], +) +@pytest.mark.asyncio +async def test_mistral_without_api_key_uses_mistral_api_key_env( + server: _Server, monkeypatch: pytest.MonkeyPatch, base_url: str, provider: Literal['mistral'] | None +) -> None: + """With no `api_key=`, a Mistral target sends MISTRAL_API_KEY, never OPENAI_API_KEY.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai') + monkeypatch.setenv('MISTRAL_API_KEY', 'mistral-env') + ai = _ai(server, base_url, api_key=None, provider=provider) + + await ai.generate(model='openai/mistral-small-latest', prompt='salut') + await ai.embed(embedder='openai/mistral-embed', content='croissant') + + assert [r.headers['authorization'] for r in server.requests] == ['Bearer mistral-env'] * 2 + + +@pytest.mark.asyncio +async def test_mistral_explicit_api_key_beats_mistral_api_key_env( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """`api_key=` wins over MISTRAL_API_KEY.""" + monkeypatch.setenv('MISTRAL_API_KEY', 'mistral-env') + ai = _ai(server, MISTRAL_URL) + + await ai.generate(model='openai/mistral-small-latest', prompt='salut') + + assert server.requests[0].headers['authorization'] == f'Bearer {PLUGIN_KEY}' + + +@pytest.mark.asyncio +async def test_mistral_without_any_key_does_not_send_openai_api_key( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """With only OPENAI_API_KEY set, a Mistral call fails naming MISTRAL_API_KEY and sends nothing.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai') + monkeypatch.delenv('MISTRAL_API_KEY', raising=False) + ai = _ai(server, MISTRAL_URL, api_key=None) + + response = await ai.generate(model='openai/mistral-small-latest', prompt='salut') + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'MISTRAL_API_KEY' in str(response.finish_message) + assert server.requests == [] From 0a8c4ca507df48a41c46f6a21b4584bd8a56398b Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 10:22:45 +0000 Subject: [PATCH 12/22] fix(py/openai): replay each Mistral reasoning part as its own thinking chunk Joining a turn's reasoning into one thinking chunk with the last signature paired that signature with text it didn't sign. Each Mistral-tagged reasoning part now goes back as its own thinking chunk, in order, with its own signature; parts with neither text nor a signature are skipped, and with none left no thinking chunk is sent. This matches the Go and JS plugins. On the response side, a reply with several thinking chunks now gives one reasoning part per chunk, each with its own signature. A streamed reply's final message joins the fragments of its thinking chunk back into one part, so the per-part replay doesn't split a signed chunk. --- packages/genkit-openai/README.md | 12 +- .../src/genkit_openai/_models/_model.py | 8 +- .../src/genkit_openai/_models/_utils.py | 144 +++++++++++------- packages/genkit-openai/tests/mistral_test.py | 85 +++++++++++ 4 files changed, 188 insertions(+), 61 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index c02521b5a..75cd2d1aa 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -107,11 +107,13 @@ that differ: out as `random_seed` and `max_tokens`, and `stream_options` is dropped. With `reasoning_effort` set, replies carry their reasoning in `thinking` -chunks. Those come back as reasoning parts, ahead of the text, streamed or not, -and go back to Mistral as a `thinking` chunk on the next turn, as Mistral asks. -Only reasoning that came from Mistral goes back: each such part is marked -`metadata['reasoningSource'] == 'mistral'`, which survives saving the history -as JSON. Reasoning another model left in a mixed history is dropped. +chunks. Each comes back as its own reasoning part, ahead of the text, with its +own signature in `metadata['thoughtSignature']`; a streamed reply's final +message joins each chunk's fragments back into one part. On the next turn each part goes back to Mistral as its own +`thinking` chunk, in order, as Mistral asks, so a signature stays with the text +it signs. Only reasoning that came from Mistral goes back: each such part is +marked `metadata['reasoningSource'] == 'mistral'`, which survives saving the +history as JSON. Reasoning another model left in a mixed history is dropped. Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given and Mistral fails the call naming them. Mistral-only fields like `min_tokens` diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index d85edb376..5bc3eed5a 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -28,6 +28,7 @@ MessageConverter, check_extra_body, extract_response_metadata, + merge_streamed_reasoning, reraise_openai_error, split_reply_content, strip_markdown_fences, @@ -615,9 +616,8 @@ async def _generate_stream( # Text content; Mistral's reasoning models stream reasoning in it too. thinking, text = split_reply_content(delta.content) - if thinking is not None: - reasoning_parts.append(thinking) - parts.append(thinking) + reasoning_parts.extend(thinking) + parts.extend(thinking) if text: text_part = MessageConverter.text_part_to_genkit(text) text_parts.append(text_part) @@ -648,7 +648,7 @@ async def _generate_stream( details={'usage': _usage_from_completion(usage).model_dump(exclude_none=True)}, ) - accumulated_content: list[Part] = [*reasoning_parts, *text_parts] + accumulated_content: list[Part] = [*merge_streamed_reasoning(reasoning_parts), *text_parts] if tool_calls: message = MessageConverter.to_genkit( DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL}) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_utils.py b/packages/genkit-openai/src/genkit_openai/_models/_utils.py index 7de18d12c..098012924 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_utils.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_utils.py @@ -423,7 +423,23 @@ def _extract_media(request: ModelRequest) -> tuple[str, str]: MISTRAL_SOURCE = 'mistral' -def split_reply_content(content: object) -> tuple[Part | None, str]: +def _mistral_reasoning(text: str, signature: str | None) -> Part: + metadata: dict[str, Any] = {REASONING_SOURCE: MISTRAL_SOURCE} + if signature is not None: + metadata[THOUGHT_SIGNATURE] = signature + return Part.from_reasoning(text, metadata=metadata) + + +def _is_mistral_reasoning(part: Part) -> bool: + return part.reasoning is not None and (part.metadata or {}).get(REASONING_SOURCE) == MISTRAL_SOURCE + + +def _signature(part: Part) -> str | None: + value = (part.metadata or {}).get(THOUGHT_SIGNATURE) + return value if isinstance(value, str) and value else None + + +def split_reply_content(content: object) -> tuple[list[Part], str]: """The reasoning and the text in a reply's ``content``. OpenAI sends ``content`` as a string. Mistral sends a list of chunks @@ -437,17 +453,16 @@ def split_reply_content(content: object) -> tuple[Part | None, str]: content: A message's or delta's ``content`` as the SDK parsed it. Returns: - A reasoning part, marked ``metadata['reasoningSource'] = 'mistral'`` - and with the chunk's signature in ``metadata['thoughtSignature']`` when - it has one, or None when there is no reasoning; and the reply text, - empty when absent. + One reasoning part per thinking chunk with text or a signature, in + order, each marked ``metadata['reasoningSource'] = 'mistral'`` and + holding its own chunk's signature in ``metadata['thoughtSignature']``; + and the reply text, empty when absent. """ if isinstance(content, str): - return None, content + return [], content if not isinstance(content, list): - return None, '' - reasoning: list[str] = [] - signature: str | None = None + return [], '' + reasoning: list[Part] = [] text: list[str] = [] for chunk in cast(list[object], content): if not isinstance(chunk, Mapping): @@ -456,53 +471,78 @@ def split_reply_content(content: object) -> tuple[Part | None, str]: if chunk.get('type') == 'text' and isinstance(chunk.get('text'), str): text.append(cast(str, chunk['text'])) elif chunk.get('type') == 'thinking' and isinstance(chunk.get('thinking'), list): - if isinstance(chunk.get('signature'), str): - signature = cast(str, chunk['signature']) + signature = chunk.get('signature') + signature = signature if isinstance(signature, str) and signature else None + thought: list[str] = [] for item in cast(list[object], chunk['thinking']): if isinstance(item, Mapping): item = cast(Mapping[str, object], item) if item.get('type') == 'text' and isinstance(item.get('text'), str): - reasoning.append(cast(str, item['text'])) - if not reasoning and signature is None: - return None, ''.join(text) - metadata: dict[str, Any] = {REASONING_SOURCE: MISTRAL_SOURCE} - if signature is not None: - metadata[THOUGHT_SIGNATURE] = signature - return Part.from_reasoning(''.join(reasoning), metadata=metadata), ''.join(text) + thought.append(cast(str, item['text'])) + if thought or signature is not None: + reasoning.append(_mistral_reasoning(''.join(thought), signature)) + return reasoning, ''.join(text) -def thinking_chunk(parts: list[Part]) -> dict[str, Any] | None: - """One Mistral ``thinking`` chunk replaying a model message's reasoning parts. +def merge_streamed_reasoning(parts: list[Part]) -> list[Part]: + """Join a stream's Mistral reasoning fragments back into one part per thinking chunk. + + A streamed thinking chunk arrives in many deltas, each read as its own + reasoning part, and its signature, if any, rides on one of them. Replayed + one part per chunk, the fragments would pair the signature with a piece + of the text it signs. Runs of adjacent Mistral reasoning parts are joined + into one, carrying the last signature seen, as the Go plugin does; other + parts are kept as they are. + """ + merged: list[Part] = [] + run: list[Part] = [] + + def flush() -> None: + if run: + signature = next((sig for sig in map(_signature, reversed(run)) if sig is not None), None) + merged.append(_mistral_reasoning(''.join(p.reasoning or '' for p in run), signature)) + run.clear() + + for part in parts: + if _is_mistral_reasoning(part): + run.append(part) + continue + flush() + merged.append(part) + flush() + return merged + + +def thinking_chunks(parts: list[Part]) -> list[dict[str, Any]]: + """Mistral ``thinking`` chunks replaying a model message's reasoning parts. Mistral asks for the whole assistant message, reasoning included, on later - turns; stripping it degrades the answer. A streamed reply arrives as many - reasoning parts, so their text is joined into one chunk, carrying the last - signature seen. Only parts read from Mistral's thinking chunks (marked - ``reasoningSource: 'mistral'``) go back; reasoning another model left in - the history is dropped, as it is for OpenAI. + turns; stripping it degrades the answer. Each reasoning part goes back as + its own chunk, in order, with its own signature, so a signature is never + paired with text it didn't sign. Only parts read from Mistral's thinking + chunks (marked ``reasoningSource: 'mistral'``) go back; reasoning another + model left in the history is dropped, as it is for OpenAI. A part with + neither text nor a signature has nothing to send and is skipped. Args: parts: The message's parts. Returns: - The chunk, or None when the message has no reasoning. + The chunks, empty when the message has no Mistral reasoning. """ - texts: list[str] = [] - signature: str | None = None + chunks: list[dict[str, Any]] = [] for part in parts: - metadata = part.metadata or {} - if part.reasoning is None or metadata.get(REASONING_SOURCE) != MISTRAL_SOURCE: + if not _is_mistral_reasoning(part): continue - texts.append(part.reasoning) - value = metadata.get(THOUGHT_SIGNATURE) - if isinstance(value, str): - signature = value - if not texts: - return None - chunk: dict[str, Any] = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': ''.join(texts)}]} - if signature is not None: - chunk['signature'] = signature - return chunk + text = part.reasoning or '' + signature = _signature(part) + if not text and signature is None: + continue + chunk: dict[str, Any] = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': text}]} + if signature is not None: + chunk['signature'] = signature + chunks.append(chunk) + return chunks class DictMessageAdapter: @@ -655,9 +695,10 @@ def to_openai(cls, message: Message, *, replay_thinking: bool = False) -> list[d Args: message: The internal `Message` instance. - replay_thinking: Send a model message's reasoning back as a leading - Mistral ``thinking`` chunk in its content. Off, reasoning is - dropped, which is what OpenAI and DeepSeek need. + replay_thinking: Send a model message's Mistral reasoning back as + leading ``thinking`` chunks in its content, one per reasoning + part. Off, reasoning is dropped, which is what OpenAI and + DeepSeek need. Returns: A list of OpenAI-compatible message dictionaries. @@ -730,22 +771,22 @@ def to_openai(cls, message: Message, *, replay_thinking: bool = False) -> list[d @classmethod def _prepend_thinking(cls, result: list[dict[str, Any]], message: Message) -> None: - """Put the message's reasoning, as a thinking chunk, at the front of its first assistant message.""" - chunk = thinking_chunk(message.content) - if chunk is None: + """Put the message's reasoning, as thinking chunks, at the front of its first assistant message.""" + chunks = thinking_chunks(message.content) + if not chunks: return role = cls._get_openai_role(message.role) target = next((m for m in result if m.get('role') == role), None) if target is None: - result.insert(0, {'role': role, 'content': [chunk]}) + result.insert(0, {'role': role, 'content': chunks}) return content = target.get('content') if isinstance(content, str): - target['content'] = [chunk, {'type': 'text', 'text': content}] + target['content'] = [*chunks, {'type': 'text', 'text': content}] elif isinstance(content, list): - target['content'] = [chunk, *content] + target['content'] = [*chunks, *content] else: - target['content'] = [chunk] + target['content'] = chunks @classmethod def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: @@ -768,8 +809,7 @@ def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: content.append(Part.from_reasoning(reasoning)) thinking, text = split_reply_content(message.content) - if thinking is not None: - content.append(thinking) + content.extend(thinking) if text: content.append(cls.text_part_to_genkit(text)) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index a9e2c97fc..c91bf57ba 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -893,3 +893,88 @@ async def test_mistral_without_any_key_does_not_send_openai_api_key( assert response.error.status == 'FAILED_PRECONDITION' assert 'MISTRAL_API_KEY' in str(response.finish_message) assert server.requests == [] + + +def _signed_thinking(text: str, signature: str) -> dict[str, Any]: + return {'type': 'thinking', 'thinking': [{'type': 'text', 'text': text}], 'signature': signature} + + +@pytest.mark.asyncio +async def test_mistral_replays_each_reasoning_part_as_its_own_thinking_chunk(mistral: Genkit, server: _Server) -> None: + """Each Mistral reasoning part goes back as its own chunk with its own signature; others are left out.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message( + role=Role.MODEL, + content=[ + _mistral_reasoning('First, count.', signature='sig-1'), + Part.from_reasoning('Gemini thinks.', metadata={'thoughtSignature': 'gemini-sig'}), + Part.from_reasoning('Unmarked.'), + _mistral_reasoning('', signature=None), + _mistral_reasoning('Unsigned middle.', signature=None), + _mistral_reasoning('Then, answer.', signature='sig-2'), + Part.from_text('Two loaves.'), + ], + ), + ] + + await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And three?') + + [assistant] = _assistant_messages(server.bodies()[0]) + assert assistant['content'] == [ + _signed_thinking('First, count.', 'sig-1'), + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': 'Unsigned middle.'}]}, + _signed_thinking('Then, answer.', 'sig-2'), + {'type': 'text', 'text': 'Two loaves.'}, + ] + + +@pytest.mark.asyncio +async def test_mistral_sends_no_thinking_chunk_when_reasoning_parts_are_empty(mistral: Genkit, server: _Server) -> None: + """Mistral reasoning parts with neither text nor a signature leave the turn as plain text.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message(role=Role.MODEL, content=[_mistral_reasoning('', signature=None), Part.from_text('Two loaves.')]), + ] + + await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And three?') + + [assistant] = _assistant_messages(server.bodies()[0]) + assert assistant['content'] == 'Two loaves.' + + +@pytest.mark.asyncio +async def test_mistral_reply_with_two_thinking_chunks_gives_two_reasoning_parts( + mistral: Genkit, server: _Server +) -> None: + """Two thinking chunks in a reply come back as two reasoning parts, each with its own signature, and replay so.""" + server.content = [ + _signed_thinking('First, count.', 'sig-1'), + _signed_thinking('Then, answer.', 'sig-2'), + {'type': 'text', 'text': 'Two loaves.'}, + ] + + first = await mistral.generate(model='openai/mistral-small-latest', prompt='Bread for two?') + await mistral.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + + assert first.message is not None + assert [(p.reasoning, p.metadata) for p in first.message.content if p.reasoning is not None] == [ + ('First, count.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}), + ('Then, answer.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}), + ] + [assistant] = _assistant_messages(server.bodies()[-1]) + assert assistant['content'] == server.content + + +@pytest.mark.asyncio +async def test_mistral_stream_joins_a_thinking_chunks_fragments_into_one_part(mistral: Genkit, server: _Server) -> None: + """A streamed thinking chunk's fragments end up as one reasoning part, with the signature, in the final message.""" + stream = mistral.generate_stream( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + response = await stream.response + + assert response.message is not None + assert [(p.reasoning, p.metadata) for p in response.message.content if p.reasoning is not None] == [ + (REASONING, {'reasoningSource': 'mistral', 'thoughtSignature': SIGNATURE}) + ] From b85445e2ad8523ca813a69ee46e0142e23a3ee88 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 17:07:32 +0000 Subject: [PATCH 13/22] fix(py/openai): default provider='mistral' to Mistral's base URL With provider='mistral' and no base_url, the key switched to MISTRAL_API_KEY and the body took Mistral's field names, but the SDK still sent both to api.openai.com. Default to https://api.mistral.ai/v1, as JS's and Dart's mistral() do. An explicit base_url (argument or client_options) still wins; OPENAI_BASE_URL is not read for provider='mistral'. --- packages/genkit-openai/README.md | 3 ++ .../src/genkit_openai/_models/_mistral.py | 4 +++ .../src/genkit_openai/_openai_plugin.py | 9 +++-- packages/genkit-openai/tests/mistral_test.py | 34 +++++++++++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 75cd2d1aa..89989be80 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -91,6 +91,9 @@ OpenAI's field names, which Mistral rejects. Pass the gateway's own key as OpenAI(base_url='https://llm-gateway.example.com/v1', api_key=gateway_key, provider='mistral') ``` +`OpenAI(provider='mistral')` with no `base_url` goes to +`https://api.mistral.ai/v1`; `OPENAI_BASE_URL` isn't read then. + Mistral rejects any request field it doesn't declare, so with a Mistral host (or `provider='mistral'`) the plugin sends Mistral's names for the settings that differ: diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 665ba04fa..12e6a5d76 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -47,6 +47,10 @@ MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'api.eu.mistral.ai', 'api.us.mistral.ai', 'codestral.mistral.ai'}) +# Where OpenAI(provider='mistral') sends calls when no base_url is given, as +# JS's and Dart's mistral() do. +MISTRAL_BASE_URL = 'https://api.mistral.ai/v1' + # The key Mistral's own SDKs, and Genkit's JS and Dart plugins, read. MISTRAL_API_KEY_ENV = 'MISTRAL_API_KEY' diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 22c848cf2..114ad6851 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -64,7 +64,7 @@ OpenAIGptImageConfig, OpenAIImageModel, ) -from genkit_openai._models._mistral import MISTRAL_API_KEY_ENV, is_mistral, is_mistral_url +from genkit_openai._models._mistral import MISTRAL_API_KEY_ENV, MISTRAL_BASE_URL, is_mistral, is_mistral_url from genkit_openai._models._model import OpenAIModel from genkit_openai._models._model_info import ( SUPPORTED_EMBEDDING_MODELS, @@ -327,7 +327,8 @@ def __init__( base_url: OpenAI API base URL up to and including ``/v1``, e.g. ``https://openrouter.ai/api/v1``; the SDK appends ``/chat/completions``. Defaults to ``OPENAI_BASE_URL``, then the - public API. + public API; with ``provider='mistral'``, ``https://api.mistral.ai/v1`` + (``OPENAI_BASE_URL`` is not read then). client_options: Other ``AsyncOpenAI`` settings, such as ``organization``, ``project``, ``timeout``, ``max_retries``, ``default_headers``, or ``http_client``. @@ -344,6 +345,10 @@ def __init__( raise ValueError(f"OpenAI got provider={provider!r}; the only provider it knows is 'mistral'") self._provider = provider options = _client_kwargs(api_key=api_key, base_url=base_url, client_options=client_options) + if provider == 'mistral' and options.get('base_url') is None: + # Else the SDK's default, api.openai.com, would get the Mistral key + # and Mistral's field names. + options['base_url'] = MISTRAL_BASE_URL self._options = options self._plugin_api_key: str | None = options.get('api_key') plugin_headers: dict[str, str] = dict(options.get('default_headers') or {}) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index c91bf57ba..a7b0916ea 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -978,3 +978,37 @@ async def test_mistral_stream_joins_a_thinking_chunks_fragments_into_one_part(mi assert [(p.reasoning, p.metadata) for p in response.message.content if p.reasoning is not None] == [ (REASONING, {'reasoningSource': 'mistral', 'thoughtSignature': SIGNATURE}) ] + + +@pytest.mark.asyncio +async def test_provider_mistral_without_base_url_goes_to_mistral( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """`OpenAI(provider='mistral')` with no base_url sends to api.mistral.ai, not the SDK's api.openai.com.""" + monkeypatch.setenv('OPENAI_BASE_URL', 'https://api.openai.com/v1') + ai = _ai(server, None, provider='mistral') + + await ai.generate(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + + [request] = server.requests + assert str(request.url) == f'{MISTRAL_URL}/chat/completions' + assert json.loads(request.content)['random_seed'] == 7 + + +@pytest.mark.asyncio +async def test_provider_mistral_keeps_base_url_from_client_options(server: _Server) -> None: + """A base_url given in client_options still wins over the Mistral default.""" + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + ai = Genkit( + plugins=[ + OpenAI( + api_key=PLUGIN_KEY, + client_options={'http_client': http_client, 'max_retries': 0, 'base_url': GATEWAY_URL}, + provider='mistral', + ) + ] + ) + + await ai.generate(model='openai/mistral-small-latest', prompt='salut') + + assert server.requests[0].url.host == 'llm-gateway.example.com' From 667a87cb30e42360331da565e4487f09441c5ec2 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 17:08:22 +0000 Subject: [PATCH 14/22] fix(py/openai): explain an ignored OPENAI_API_KEY and never hand Mistral's client a None key A Mistral target reads MISTRAL_API_KEY, not OPENAI_API_KEY. Anyone who had pointed base_url at Mistral with the key in OPENAI_API_KEY now gets FAILED_PRECONDITION, so the error says OPENAI_API_KEY is set but not used for Mistral when it is. _runtime_client also raised nothing when MISTRAL_API_KEY was unset and passed api_key=None, which makes the SDK read OPENAI_API_KEY. _has_plugin_key keeps that unreachable today; raising there keeps it so after a refactor. --- .../src/genkit_openai/_openai_plugin.py | 17 ++++++++-- packages/genkit-openai/tests/mistral_test.py | 34 ++++++++++++++++++- 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 114ad6851..9d2168233 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -109,10 +109,17 @@ def _client_kwargs( 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. + ignored = ( + f"{env} is not set; OPENAI_API_KEY is set but isn't used for Mistral. " + if env == MISTRAL_API_KEY_ENV and os.environ.get('OPENAI_API_KEY') + else '' + ) return GenkitError( status='FAILED_PRECONDITION', message=( - f'OpenAI needs an API key: set {env} or pass OpenAI(api_key=...), ' + f'{ignored}OpenAI needs an API key: set {env} or pass OpenAI(api_key=...), ' "or send a per-request key as context={'secrets': {'api_key': ...}}." ), ) @@ -375,8 +382,12 @@ def _uses_mistral_names(self, client: AsyncOpenAI) -> bool: def _runtime_client(self) -> AsyncOpenAI: options: dict[str, Any] = self._options if self._plugin_api_key is None and self._targets_mistral(): - # Otherwise the SDK reads OPENAI_API_KEY and sends it to Mistral. - options = {**options, 'api_key': os.environ.get(MISTRAL_API_KEY_ENV)} + # Otherwise the SDK reads OPENAI_API_KEY and sends it to Mistral, + # so an unset MISTRAL_API_KEY must not reach it as api_key=None. + key = os.environ.get(MISTRAL_API_KEY_ENV) + if not key: + raise _missing_key_error(MISTRAL_API_KEY_ENV) + options = {**options, 'api_key': key} return AsyncOpenAI(**options) @loop_local_client diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index a7b0916ea..f5ae29a2b 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -27,7 +27,7 @@ from genkit_openai._models._mistral import mistral_chat_body from pydantic import BaseModel -from genkit import FinishReason, Genkit, Message, Part, Role +from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role MISTRAL_URL = 'https://api.mistral.ai/v1' CODESTRAL_URL = 'https://codestral.mistral.ai/v1' @@ -892,6 +892,7 @@ async def test_mistral_without_any_key_does_not_send_openai_api_key( assert response.error is not None assert response.error.status == 'FAILED_PRECONDITION' assert 'MISTRAL_API_KEY' in str(response.finish_message) + assert "OPENAI_API_KEY is set but isn't used for Mistral" in str(response.finish_message) assert server.requests == [] @@ -1012,3 +1013,34 @@ async def test_provider_mistral_keeps_base_url_from_client_options(server: _Serv await ai.generate(model='openai/mistral-small-latest', prompt='salut') assert server.requests[0].url.host == 'llm-gateway.example.com' + + +@pytest.mark.asyncio +async def test_mistral_missing_key_error_leaves_out_openai_api_key_when_unset( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """With neither key set, the error names MISTRAL_API_KEY and says nothing about OPENAI_API_KEY.""" + monkeypatch.delenv('OPENAI_API_KEY', raising=False) + monkeypatch.delenv('MISTRAL_API_KEY', raising=False) + ai = _ai(server, MISTRAL_URL, api_key=None) + + response = await ai.generate(model='openai/mistral-small-latest', prompt='salut') + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'MISTRAL_API_KEY' in str(response.finish_message) + assert 'OPENAI_API_KEY' not in str(response.finish_message) + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_mistral_runtime_client_raises_without_mistral_api_key(monkeypatch: pytest.MonkeyPatch) -> None: + """The Mistral client never falls through to the SDK's OPENAI_API_KEY default, even if called with no key.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai') + monkeypatch.delenv('MISTRAL_API_KEY', raising=False) + plugin = OpenAI(base_url=MISTRAL_URL) + + with pytest.raises(GenkitError, match='MISTRAL_API_KEY') as excinfo: + plugin._runtime_client() # pyright: ignore[reportPrivateUsage] + + assert excinfo.value.status == 'FAILED_PRECONDITION' From e5abec1bc930e348dce91cf50f8f8977bf9ad88b Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 17:08:54 +0000 Subject: [PATCH 15/22] fix(py/openai): keep streamed signed thinking chunks as separate parts A stream's Mistral reasoning fragments were joined into one part per run, so two signed thinking chunks came back as one part with the second signature, and on replay the first chunk's text went back under a signature that doesn't match it. A fragment carrying a signature now closes its part, so the stream ends with one part per signed chunk, as a non-streamed reply does. --- packages/genkit-openai/README.md | 3 +- .../src/genkit_openai/_models/_utils.py | 15 ++++++---- packages/genkit-openai/tests/mistral_test.py | 30 +++++++++++++++++++ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 89989be80..f873c66f2 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -112,7 +112,8 @@ that differ: With `reasoning_effort` set, replies carry their reasoning in `thinking` chunks. Each comes back as its own reasoning part, ahead of the text, with its own signature in `metadata['thoughtSignature']`; a streamed reply's final -message joins each chunk's fragments back into one part. On the next turn each part goes back to Mistral as its own +message joins each chunk's fragments back into one part, ending a part at +the fragment that carries a signature. On the next turn each part goes back to Mistral as its own `thinking` chunk, in order, as Mistral asks, so a signature stays with the text it signs. Only reasoning that came from Mistral goes back: each such part is marked `metadata['reasoningSource'] == 'mistral'`, which survives saving the diff --git a/packages/genkit-openai/src/genkit_openai/_models/_utils.py b/packages/genkit-openai/src/genkit_openai/_models/_utils.py index 098012924..4ba4edf64 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_utils.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_utils.py @@ -488,24 +488,27 @@ def merge_streamed_reasoning(parts: list[Part]) -> list[Part]: """Join a stream's Mistral reasoning fragments back into one part per thinking chunk. A streamed thinking chunk arrives in many deltas, each read as its own - reasoning part, and its signature, if any, rides on one of them. Replayed - one part per chunk, the fragments would pair the signature with a piece - of the text it signs. Runs of adjacent Mistral reasoning parts are joined - into one, carrying the last signature seen, as the Go plugin does; other + reasoning part, and its signature, if any, rides on its last fragment. + Replayed one part per fragment, the signature would be paired with a + piece of the text it signs. Runs of adjacent Mistral reasoning parts are + joined into one, and a fragment carrying a signature closes its part: the + next fragment starts a new one, so two signed thinking chunks stay two + parts, each with its own signature, as in a non-streamed reply. Other parts are kept as they are. """ merged: list[Part] = [] run: list[Part] = [] - def flush() -> None: + def flush(signature: str | None = None) -> None: if run: - signature = next((sig for sig in map(_signature, reversed(run)) if sig is not None), None) merged.append(_mistral_reasoning(''.join(p.reasoning or '' for p in run), signature)) run.clear() for part in parts: if _is_mistral_reasoning(part): run.append(part) + if (signature := _signature(part)) is not None: + flush(signature) continue flush() merged.append(part) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index f5ae29a2b..d193c8ba0 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -1044,3 +1044,33 @@ async def test_mistral_runtime_client_raises_without_mistral_api_key(monkeypatch plugin._runtime_client() # pyright: ignore[reportPrivateUsage] assert excinfo.value.status == 'FAILED_PRECONDITION' + + +@pytest.mark.asyncio +async def test_mistral_stream_keeps_two_signed_thinking_chunks_apart(mistral: Genkit, server: _Server) -> None: + """Two streamed signed thinking chunks end as two reasoning parts, each with its own text and signature.""" + server.deltas = [ + [_thinking('First,')], + [_thinking(' count.', signature='sig-1')], + [_thinking('Then,')], + [_thinking(' answer.', signature='sig-2'), {'type': 'text', 'text': 'Two'}], + ' loaves.', + ] + + stream = mistral.generate_stream( + model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + first = await stream.response + await mistral.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + + assert first.message is not None + assert [(p.reasoning, p.metadata) for p in first.message.content if p.reasoning is not None] == [ + ('First, count.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}), + ('Then, answer.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}), + ] + [assistant] = _assistant_messages(server.bodies()[-1]) + assert assistant['content'] == [ + _signed_thinking('First, count.', 'sig-1'), + _signed_thinking('Then, answer.', 'sig-2'), + {'type': 'text', 'text': 'Two loaves.'}, + ] From 7acd17e8bee3c787a7d86533e5e3965d096c7d30 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 17:09:38 +0000 Subject: [PATCH 16/22] fix(py/openai): accept reasoning_effort='max' for Mistral Mistral's ReasoningEffort declares 'max' (JS's Mistral config takes it), but OpenAIConfig stopped at 'xhigh', so it failed config validation. 'max' is now a ReasoningEffort value; for any target other than Mistral it is refused before the request, since OpenAI's API doesn't have it, with a pointer to extra={'reasoning_effort': 'max'} for a host that does. --- packages/genkit-openai/README.md | 4 +++ .../src/genkit_openai/_models/_model.py | 10 ++++++- .../src/genkit_openai/_typing.py | 3 +++ packages/genkit-openai/tests/mistral_test.py | 27 +++++++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index f873c66f2..114fba87a 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -103,6 +103,10 @@ that differ: - `seed` goes out as `random_seed`. - `top_k` is refused before the request goes out: Mistral's models reject `top_k` sampling. +- `reasoning_effort` also takes `'max'`, which Mistral's API declares and + OpenAI's doesn't; other targets refuse it before the request goes out. + Which values a model accepts varies: Mistral Small takes `none` and `high`, + Mistral Large `low`, `medium` and `high`. - Streaming sends no `stream_options`; Mistral reports usage on the last chunk without it. - An embedder's `dimensions` goes out as `output_dimension`. diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index 5bc3eed5a..edee4b4b2 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -33,7 +33,7 @@ split_reply_content, strip_markdown_fences, ) -from genkit_openai._typing import OpenAIConfig +from genkit_openai._typing import OpenAIConfig, ReasoningEffort from openai import AsyncOpenAI from openai.lib._pydantic import _ensure_strict_json_schema from openai.types import CompletionUsage @@ -491,6 +491,14 @@ async def _get_openai_request_config(self, request: ModelRequest) -> dict: request.config if isinstance(request.config, OpenAIConfig) else self._normalize_config(request.config) ) top_k = config.top_k + if config.reasoning_effort == ReasoningEffort.MAX and not self._mistral: + raise GenkitError( + status='INVALID_ARGUMENT', + message=( + "reasoning_effort='max' is Mistral's; OpenAI's API stops at 'xhigh'. For another host " + "that takes it, pass extra={'reasoning_effort': 'max'}." + ), + ) if config.version: openai_config['model'] = config.version effective_model = config.model or config.version or self._model diff --git a/packages/genkit-openai/src/genkit_openai/_typing.py b/packages/genkit-openai/src/genkit_openai/_typing.py index cbcf1619e..e70608f8d 100644 --- a/packages/genkit-openai/src/genkit_openai/_typing.py +++ b/packages/genkit-openai/src/genkit_openai/_typing.py @@ -53,6 +53,9 @@ class ReasoningEffort(StrEnum): MEDIUM = 'medium' HIGH = 'high' XHIGH = 'xhigh' + # Mistral only (its ReasoningEffort has it; OpenAI's doesn't). Refused + # before the request for any other target. + MAX = 'max' class Verbosity(StrEnum): diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index d193c8ba0..93e0eb42f 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -1074,3 +1074,30 @@ async def test_mistral_stream_keeps_two_signed_thinking_chunks_apart(mistral: Ge _signed_thinking('Then, answer.', 'sig-2'), {'type': 'text', 'text': 'Two loaves.'}, ] + + +@pytest.mark.asyncio +async def test_mistral_takes_reasoning_effort_max(mistral: Genkit, server: _Server) -> None: + """`reasoning_effort='max'`, in Mistral's ReasoningEffort, goes out to Mistral as given.""" + await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'reasoning_effort': 'max'}) + + assert server.bodies()[0]['reasoning_effort'] == 'max' + + +@pytest.mark.asyncio +async def test_openai_refuses_reasoning_effort_max(openai: Genkit, server: _Server) -> None: + """Other targets refuse `reasoning_effort='max'` before the request, pointing at `extra`.""" + response = await openai.generate(model='openai/gpt-5', prompt='salut', config={'reasoning_effort': 'max'}) + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert "extra={'reasoning_effort': 'max'}" in str(response.finish_message) + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_openai_reasoning_effort_max_through_extra(openai: Genkit, server: _Server) -> None: + """A non-Mistral host that takes 'max' gets it through `extra`.""" + await openai.generate(model='openai/gpt-5', prompt='salut', config={'extra': {'reasoning_effort': 'max'}}) + + assert server.bodies()[0]['reasoning_effort'] == 'max' From 19432fa90a7dce0c06d4fd03266d806ac3f66521 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Tue, 17 Nov 2026 17:10:48 +0000 Subject: [PATCH 17/22] fix(py/openai): refuse non-image media for Mistral before the request Every media part goes out as an image_url chunk, so a PDF reached Mistral as a broken image and failed there. For a Mistral target, media whose type (content_type, else a data: URL's header) isn't image/* now fails with INVALID_ARGUMENT naming the type, as JS's and Dart's Mistral plugins do. A remote URL with no known type is still sent as an image. --- packages/genkit-openai/README.md | 4 ++ .../src/genkit_openai/_models/_mistral.py | 28 +++++++++- .../src/genkit_openai/_models/_model.py | 4 +- packages/genkit-openai/tests/mistral_test.py | 56 +++++++++++++++++++ 4 files changed, 90 insertions(+), 2 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index 114fba87a..b4b85cac2 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -110,6 +110,10 @@ that differ: - Streaming sends no `stream_options`; Mistral reports usage on the last chunk without it. - An embedder's `dimensions` goes out as `output_dimension`. +- Media other than images, such as a PDF, is refused before the request goes + out: every media part goes out as `image_url`. The type comes from the part's + `content_type`, else a `data:` URL's header; a remote URL with neither is + sent as an image. - `extra` gets the same renames: `seed` and `max_completion_tokens` there go out as `random_seed` and `max_tokens`, and `stream_options` is dropped. diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 12e6a5d76..8875af420 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -37,9 +37,10 @@ from typing import Any import httpx +from genkit_openai._models._utils import parse_data_uri_content_type from openai import AsyncOpenAI -from genkit import GenkitError +from genkit import GenkitError, Message # Mistral's API hosts: global, EU and US, the servers in the mistralai SDK's # sdkconfiguration.py. codestral.mistral.ai, for Codestral-only keys, is not in @@ -118,3 +119,28 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict if renamed or extra: out['extra_body'] = {**renamed, **extra} return out + + +def refuse_non_image_media(messages: list[Message]) -> None: + """Refuse media Mistral's chat endpoint can't take as an image. + + Every media part goes out as an ``image_url`` chunk, so a PDF or audio + clip would reach Mistral as a broken image and fail there. The type is the + part's ``content_type``, else the one a ``data:`` URL declares; a remote + URL with neither is sent as is, since only the host knows what it serves. + + Raises: + GenkitError: ``INVALID_ARGUMENT`` naming the first non-image type. + """ + for message in messages: + for part in message.content: + media = part.media + if media is None: + continue + declared = media.content_type or parse_data_uri_content_type(media.url) + content_type = declared.split(';', 1)[0].strip().lower() + if content_type and not content_type.startswith('image/'): + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'Mistral only supports image media in chat requests, got {content_type}.', + ) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index edee4b4b2..f1906f6ef 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -20,7 +20,7 @@ from collections.abc import Callable from typing import Any, cast -from genkit_openai._models._mistral import is_mistral, mistral_chat_body +from genkit_openai._models._mistral import is_mistral, mistral_chat_body, refuse_non_image_media from genkit_openai._models._utils import ( OPENAI_CALL_ERRORS, DictMessageAdapter, @@ -296,6 +296,8 @@ def _get_messages(self, messages: list[Message]) -> list[dict]: Raises: ValueError: If no messages are provided in the request. """ + if self._mistral: + refuse_non_image_media(messages) openai_messages = [] for message in messages: openai_messages.extend(MessageConverter.to_openai(message=message, replay_thinking=self._mistral)) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 93e0eb42f..4bb9649bc 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -1101,3 +1101,59 @@ async def test_openai_reasoning_effort_max_through_extra(openai: Genkit, server: await openai.generate(model='openai/gpt-5', prompt='salut', config={'extra': {'reasoning_effort': 'max'}}) assert server.bodies()[0]['reasoning_effort'] == 'max' + + +@pytest.mark.parametrize( + ('url', 'content_type', 'expected'), + [ + pytest.param('data:application/pdf;base64,JVBERi0xLjQK', 'application/pdf', 'application/pdf', id='inline'), + pytest.param('data:application/pdf;base64,JVBERi0xLjQK', None, 'application/pdf', id='inline-untyped'), + pytest.param('https://example.com/menu.pdf', 'application/pdf', 'application/pdf', id='remote'), + pytest.param('https://example.com/song.mp3', 'audio/mpeg; charset=binary', 'audio/mpeg', id='params'), + ], +) +@pytest.mark.asyncio +async def test_mistral_refuses_non_image_media( + mistral: Genkit, server: _Server, url: str, content_type: str | None, expected: str +) -> None: + """Non-image media fails before the request instead of reaching Mistral as an image_url.""" + response = await mistral.generate( + model='openai/mistral-small-latest', + prompt=[Part.from_text('Summarize this.'), Part.from_media(url, content_type)], + ) + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert expected in str(response.finish_message) + assert server.requests == [] + + +@pytest.mark.parametrize( + ('url', 'content_type'), + [ + pytest.param('data:image/png;base64,iVBORw0KGgo=', None, id='inline-untyped'), + pytest.param('https://example.com/loaf', None, id='remote-untyped'), + pytest.param('https://example.com/loaf.jpg', 'IMAGE/JPEG', id='remote-typed'), + ], +) +@pytest.mark.asyncio +async def test_mistral_sends_image_media(mistral: Genkit, server: _Server, url: str, content_type: str | None) -> None: + """Images, and remote URLs whose type isn't known, still go out as image_url.""" + await mistral.generate( + model='openai/pixtral-large-latest', + prompt=[Part.from_text('What bread is this?'), Part.from_media(url, content_type)], + ) + + [body] = server.bodies() + assert {'type': 'image_url', 'image_url': {'url': url}} in body['messages'][-1]['content'] + + +@pytest.mark.asyncio +async def test_openai_host_still_sends_non_image_media(openai: Genkit, server: _Server) -> None: + """The guard is Mistral's: other hosts get the media part as before.""" + url = 'data:application/pdf;base64,JVBERi0xLjQK' + await openai.generate( + model='openai/gpt-4o', prompt=[Part.from_text('Summarize this.'), Part.from_media(url, 'application/pdf')] + ) + + assert len(server.requests) == 1 From 1351476b0f085fc6e934ef19f6ce210434856671 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 18 Nov 2026 10:49:27 +0000 Subject: [PATCH 18/22] fix(py/openai): keep Mistral reasoning and text in the order they came A Mistral reply can interleave thinking and text chunks. The streamed final message put every reasoning part ahead of every text part, and the full reply did the same. Both now keep the chunks' order; reasoning from its own field (DeepSeek's reasoning_content) still comes first, as before. --- .../src/genkit_openai/_models/_model.py | 25 +++++----- .../src/genkit_openai/_models/_utils.py | 45 ++++++++++-------- packages/genkit-openai/tests/mistral_test.py | 46 +++++++++++++++++++ 3 files changed, 84 insertions(+), 32 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index f1906f6ef..268b5f3de 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -29,8 +29,8 @@ check_extra_body, extract_response_metadata, merge_streamed_reasoning, + reply_content, reraise_openai_error, - split_reply_content, strip_markdown_fences, ) from genkit_openai._typing import OpenAIConfig, ReasoningEffort @@ -587,8 +587,12 @@ async def _generate_stream( stream = await self._openai_client.chat.completions.create(**openai_config) tool_calls: dict[int, Any] = {} - reasoning_parts: list[Part] = [] - text_parts: list[Part] = [] + # As a full reply is read (MessageConverter.to_genkit): reasoning from + # its own field (DeepSeek's reasoning_content) first, then the + # content's reasoning and text in the order they arrived (Mistral's + # thinking chunks can come between text chunks), then tool calls. + field_reasoning: list[Part] = [] + content_parts: list[Part] = [] metadata: dict[str, Any] = {} usage: CompletionUsage | None = None saw_choice = False @@ -621,17 +625,14 @@ async def _generate_stream( # Reasoning content (DeepSeek R1 / reasoner models). if reasoning_text := MessageAdapter(delta).reasoning_content: reasoning_part = Part.from_reasoning(reasoning_text) - reasoning_parts.append(reasoning_part) + field_reasoning.append(reasoning_part) parts.append(reasoning_part) # Text content; Mistral's reasoning models stream reasoning in it too. - thinking, text = split_reply_content(delta.content) - reasoning_parts.extend(thinking) - parts.extend(thinking) - if text: - text_part = MessageConverter.text_part_to_genkit(text) - text_parts.append(text_part) - parts.append(text_part) + for item in reply_content(delta.content): + part = MessageConverter.text_part_to_genkit(item) if isinstance(item, str) else item + content_parts.append(part) + parts.append(part) # Tool calls (partial function calls) if delta.tool_calls: @@ -658,7 +659,7 @@ async def _generate_stream( details={'usage': _usage_from_completion(usage).model_dump(exclude_none=True)}, ) - accumulated_content: list[Part] = [*merge_streamed_reasoning(reasoning_parts), *text_parts] + accumulated_content: list[Part] = [*field_reasoning, *merge_streamed_reasoning(content_parts)] if tool_calls: message = MessageConverter.to_genkit( DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL}) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_utils.py b/packages/genkit-openai/src/genkit_openai/_models/_utils.py index 4ba4edf64..e1769445c 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_utils.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_utils.py @@ -439,37 +439,43 @@ def _signature(part: Part) -> str | None: return value if isinstance(value, str) and value else None -def split_reply_content(content: object) -> tuple[list[Part], str]: - """The reasoning and the text in a reply's ``content``. +def reply_content(content: object) -> list[Part | str]: + """The reasoning and the text in a reply's ``content``, in the order they came. OpenAI sends ``content`` as a string. Mistral sends a list of chunks instead when it reasons (``reasoning_effort`` set), in full replies and in streamed deltas alike: ``{'type': 'text', 'text': ...}`` for the answer and ``{'type': 'thinking', 'thinking': [{'type': 'text', 'text': ...}], - 'signature': ...}`` for the reasoning before it. Other chunk types carry - no text and are skipped. + 'signature': ...}`` for reasoning. Other chunk types carry no text and are + skipped. Args: content: A message's or delta's ``content`` as the SDK parsed it. Returns: - One reasoning part per thinking chunk with text or a signature, in - order, each marked ``metadata['reasoningSource'] = 'mistral'`` and + In chunk order: one reasoning part per thinking chunk with text or a + signature, each marked ``metadata['reasoningSource'] = 'mistral'`` and holding its own chunk's signature in ``metadata['thoughtSignature']``; - and the reply text, empty when absent. + and the text, one string per run of adjacent text chunks. Empty text is + left out, so a plain empty string gives an empty list. """ if isinstance(content, str): - return [], content + return [content] if content else [] if not isinstance(content, list): - return [], '' - reasoning: list[Part] = [] - text: list[str] = [] + return [] + out: list[Part | str] = [] for chunk in cast(list[object], content): if not isinstance(chunk, Mapping): continue chunk = cast(Mapping[str, object], chunk) if chunk.get('type') == 'text' and isinstance(chunk.get('text'), str): - text.append(cast(str, chunk['text'])) + text = cast(str, chunk['text']) + if not text: + continue + if out and isinstance(out[-1], str): + out[-1] += text + else: + out.append(text) elif chunk.get('type') == 'thinking' and isinstance(chunk.get('thinking'), list): signature = chunk.get('signature') signature = signature if isinstance(signature, str) and signature else None @@ -480,8 +486,8 @@ def split_reply_content(content: object) -> tuple[list[Part], str]: if item.get('type') == 'text' and isinstance(item.get('text'), str): thought.append(cast(str, item['text'])) if thought or signature is not None: - reasoning.append(_mistral_reasoning(''.join(thought), signature)) - return reasoning, ''.join(text) + out.append(_mistral_reasoning(''.join(thought), signature)) + return out def merge_streamed_reasoning(parts: list[Part]) -> list[Part]: @@ -795,8 +801,9 @@ def _prepend_thinking(cls, result: list[dict[str, Any]], message: Message) -> No def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: """Converts an OpenAI-style message into a Genkit `Message` object. - Emits a reasoning part, a text part, and one tool request part per - tool call, in that order, for whichever of them the message carries. + Emits a reasoning part, the content's reasoning and text parts in the + order they came, and one tool request part per tool call, in that + order, for whichever of them the message carries. Args: message: A ChatCompletionMessageAdapter instance. @@ -811,10 +818,8 @@ def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: if reasoning: content.append(Part.from_reasoning(reasoning)) - thinking, text = split_reply_content(message.content) - content.extend(thinking) - if text: - content.append(cls.text_part_to_genkit(text)) + for item in reply_content(message.content): + content.append(cls.text_part_to_genkit(item) if isinstance(item, str) else item) for tool_call in message.tool_calls or []: content.append(cls.tool_call_to_genkit(tool_call, args_parser=json.loads)) diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 4bb9649bc..692253ac5 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -1157,3 +1157,49 @@ async def test_openai_host_still_sends_non_image_media(openai: Genkit, server: _ ) assert len(server.requests) == 1 + + +# Reply order + + +_INTERLEAVED = [ + _thinking('First, flour.', signature='sig-1'), + {'type': 'text', 'text': 'Flour.'}, + _thinking('Then, water.', signature='sig-2'), + {'type': 'text', 'text': ' Water.'}, +] + + +def _order(message: Message | None) -> list[tuple[str, str]]: + assert message is not None + return [ + ('reasoning', p.reasoning) if p.reasoning is not None else ('text', p.text or '') + for p in message.content + if p.reasoning is not None or p.text is not None + ] + + +@pytest.mark.asyncio +async def test_mistral_keeps_thinking_and_text_in_the_order_they_came(mistral: Genkit, server: _Server) -> None: + """thinking, text, thinking, text stays in that order, streamed or not.""" + server.content = _INTERLEAVED + server.deltas = [[chunk] for chunk in _INTERLEAVED] + expected = [ + ('reasoning', 'First, flour.'), + ('text', 'Flour.'), + ('reasoning', 'Then, water.'), + ('text', ' Water.'), + ] + + full = await mistral.generate(model='openai/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG) + streamed = await mistral.generate_stream( + model='openai/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG + ).response + + assert _order(full.message) == expected + assert _order(streamed.message) == expected + assert streamed.message is not None + assert [p.metadata for p in streamed.message.content if p.reasoning is not None] == [ + {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}, + {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}, + ] From 66e0b49597502e908d3b73a680acbccc5200bb28 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 18 Nov 2026 10:49:43 +0000 Subject: [PATCH 19/22] fix(py/openai): leave out OpenAI-only settings Mistral doesn't declare Mistral's chat schema is closed, and OpenAIConfig fields it doesn't declare went out as given and failed the call with a 422. Checked live: verbosity, safety_identifier, store, logit_bias, prompt_cache_retention and web_search_options are rejected. A Mistral body now keeps only the fields Mistral's ChatCompletionRequest declares (plus the renamed ones), as Dart's mistralChatBody drops user and verbosity, and logs a warning naming what it left out. logprobs, top_logprobs, service_tier and the other fields Mistral declares still go out; extra is still sent as written. --- .../src/genkit_openai/_models/_mistral.py | 54 ++++++++++- packages/genkit-openai/tests/mistral_test.py | 89 +++++++++++++++++-- 2 files changed, 135 insertions(+), 8 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 8875af420..3fe0c7697 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -40,7 +40,9 @@ from genkit_openai._models._utils import parse_data_uri_content_type from openai import AsyncOpenAI -from genkit import GenkitError, Message +from genkit import GenkitError, Message, get_logger + +logger = get_logger(__name__) # Mistral's API hosts: global, EU and US, the servers in the mistralai SDK's # sdkconfiguration.py. codestral.mistral.ai, for Codestral-only keys, is not in @@ -55,6 +57,43 @@ # The key Mistral's own SDKs, and Genkit's JS and Dart plugins, read. MISTRAL_API_KEY_ENV = 'MISTRAL_API_KEY' +# The top-level fields Mistral's ChatCompletionRequest declares +# (https://docs.mistral.ai/openapi.yaml). Its schema is closed: anything else +# is a 422 "Extra inputs are not permitted". ``extra_body`` is the SDK's +# passthrough, not a wire field, and is kept. +MISTRAL_CHAT_FIELDS = frozenset({ + 'model', + 'messages', + 'temperature', + 'top_p', + 'max_tokens', + 'stream', + 'stop', + 'random_seed', + 'metadata', + 'response_format', + 'tools', + 'tool_choice', + 'presence_penalty', + 'frequency_penalty', + 'min_tokens', + 'repetition_penalty', + 'top_k', + 'logprobs', + 'top_logprobs', + 'prompt_logprobs', + 'top_prompt_logprobs', + 'n', + 'prediction', + 'parallel_tool_calls', + 'reasoning_effort', + 'prompt_mode', + 'guardrails', + 'prompt_cache_key', + 'service_tier', + 'safe_prompt', +}) + def is_mistral_url(url: str | httpx.URL) -> bool: """Whether ``url`` is on one of Mistral's API hosts.""" @@ -83,12 +122,19 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict - ``seed`` goes out as ``random_seed``. - ``top_k`` is refused. Mistral's schema declares it, but its models answer "top_k sampling is not enabled for this model". + - Any other field Mistral's schema doesn't declare is dropped, as Dart's + ``mistralChatBody`` drops ``user`` and ``verbosity``: OpenAI-only + settings such as ``verbosity``, ``safety_identifier``, ``store``, + ``logit_bias``, ``prompt_cache_retention``, ``web_search_options``, + ``modalities`` and ``audio`` would otherwise fail the call with a 422. + ``logprobs`` and ``top_logprobs`` are Mistral fields and go out. The SDK has no ``random_seed`` kwarg, so it rides in ``extra_body``; the same key in the caller's ``extra`` wins, as every ``extra`` key does. ``extra`` gets the same renames: its ``seed``, ``max_completion_tokens`` and ``stream_options`` would otherwise reach Mistral as given and fail - with a 422. Where ``extra`` has both names, Mistral's wins. + with a 422. Where ``extra`` has both names, Mistral's wins. Nothing else + in ``extra`` is dropped: it is sent as the caller wrote it. Args: body: The kwargs the plugin built for OpenAI. Not modified. @@ -112,6 +158,10 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict renamed: dict[str, Any] = {} if 'seed' in out: renamed['random_seed'] = out.pop('seed') + if dropped := sorted(k for k in out if k not in MISTRAL_CHAT_FIELDS and k != 'extra_body'): + logger.warning('Mistral does not define these OpenAI settings; not sending them', fields=dropped) + for key in dropped: + del out[key] extra = dict(out.pop('extra_body', None) or {}) extra.pop('stream_options', None) _rename(extra, 'max_completion_tokens', 'max_tokens') diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 692253ac5..741973ed6 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -24,7 +24,7 @@ import httpx import pytest from genkit_openai import OpenAI -from genkit_openai._models._mistral import mistral_chat_body +from genkit_openai._models._mistral import MISTRAL_CHAT_FIELDS, mistral_chat_body from pydantic import BaseModel from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role @@ -605,15 +605,92 @@ async def test_mistral_image_input_goes_out_as_image_url(mistral: Genkit, server assert {'type': 'image_url', 'image_url': {'url': 'https://example.com/loaf.png'}} in blocks +# OpenAI settings Mistral's chat schema doesn't declare; each was checked +# live against api.mistral.ai, which answers it with a 422. +_OPENAI_ONLY_SETTINGS = { + 'verbosity': 'low', + 'safety_identifier': 'user-1', + 'store': False, + 'logit_bias': {'1': 1}, + 'prompt_cache_retention': '24h', + 'web_search_options': {}, + 'modalities': ['text'], + 'audio': {'voice': 'alloy', 'format': 'mp3'}, +} + + @pytest.mark.asyncio -async def test_mistral_rejects_an_openai_only_setting(mistral: Genkit, server: _Server) -> None: - """An OpenAI-only setting such as `verbosity` is sent as given, and Mistral's 422 fails the turn.""" - response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'verbosity': 'low'}) +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.parametrize('field', sorted(_OPENAI_ONLY_SETTINGS)) +async def test_mistral_drops_openai_only_settings(mistral: Genkit, server: _Server, field: str, streamed: bool) -> None: + """An OpenAI-only setting such as `verbosity` is left out, so Mistral answers instead of failing with a 422.""" + config = {field: _OPENAI_ONLY_SETTINGS[field]} + if streamed: + response = await mistral.generate_stream( + model='openai/mistral-small-latest', prompt='salut', config=config + ).response + else: + response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + assert field not in body + + +@pytest.mark.asyncio +async def test_mistral_sends_the_settings_it_declares(mistral: Genkit, server: _Server) -> None: + """Settings Mistral declares under the same name go out as given.""" + config = { + 'logprobs': True, + 'top_logprobs': 2, + 'service_tier': 'auto', + 'prompt_cache_key': 'bakery', + 'metadata': {'shop': 'paris'}, + 'prediction': {'type': 'content', 'content': 'bonjour'}, + 'parallel_tool_calls': False, + 'n': 1, + 'frequency_penalty': 0.1, + 'presence_penalty': 0.2, + } + + await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + + [body] = server.bodies() + assert {k: body[k] for k in config} == config + + +@pytest.mark.asyncio +async def test_openai_host_keeps_openai_only_settings(openai: Genkit, server: _Server) -> None: + """OpenAI's own settings still go out to OpenAI.""" + await openai.generate(model='openai/gpt-4o', prompt='hi', config={'verbosity': 'low', 'store': True}) - assert response.finish_reason == FinishReason.FAILED - assert 'verbosity' in str(response.error) [body] = server.bodies() assert body['verbosity'] == 'low' + assert body['store'] is True + + +def test_mistral_chat_body_keeps_only_declared_fields_and_extra() -> None: + """`mistral_chat_body` drops top-level fields Mistral doesn't declare but sends `extra` as written.""" + out = mistral_chat_body({ + 'model': 'mistral-small-latest', + 'messages': [], + 'verbosity': 'low', + 'safety_identifier': 'user-1', + 'logprobs': True, + 'extra_body': {'user': 'u', 'min_tokens': 3}, + }) + + assert out == { + 'model': 'mistral-small-latest', + 'messages': [], + 'logprobs': True, + 'extra_body': {'user': 'u', 'min_tokens': 3}, + } + + +def test_mistral_chat_fields_match_the_fake_servers_schema() -> None: + """The plugin's allowlist is Mistral's ChatCompletionRequest, the schema the fake enforces.""" + assert MISTRAL_CHAT_FIELDS == _CHAT_FIELDS @pytest.mark.asyncio From a1476d21ea43d2ac1549dbfbff57a5804c064d3b Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 18 Nov 2026 10:50:06 +0000 Subject: [PATCH 20/22] feat(py/openai): name a Mistral target mistral and list it by capabilities A Mistral target was the 'openai' plugin and registered OpenAI's catalog (gpt-*, dall-e, tts, whisper, text-embedding-3), so an app couldn't use OpenAI and Mistral together, and a Mistral app listed OpenAI models that all failed. Its /models listing was read by OpenAI's name rules too, so voxtral-mini-tts-latest became a TTS action and mistral-ocr and moderation models became chat models. - A Mistral target (provider='mistral', a Mistral base_url, or OPENAI_BASE_URL on a Mistral host) is now the 'mistral' plugin, with actions at mistral/ as in JS and Dart. New Mistral plugin, the same as OpenAI(provider='mistral'), with a Mistral.model() ref helper. - init registers Mistral's catalog (the chat models and embedders JS and Dart register), not OpenAI's. - list_actions reads each /models entry's capabilities: ids with embed are embedders, completion_chat entries are chat models with tools and media from function_calling and vision, the rest are skipped. resolve serves any id as a chat model or embedder, never OpenAI's image or audio endpoints. --- packages/genkit-openai/README.md | 77 +++-- .../src/genkit_openai/__init__.py | 6 +- .../src/genkit_openai/_models/_mistral.py | 115 ++++++- .../src/genkit_openai/_openai_plugin.py | 175 +++++++++- packages/genkit-openai/tests/mistral_test.py | 309 ++++++++++++++---- 5 files changed, 569 insertions(+), 113 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index b4b85cac2..e66e87048 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -57,42 +57,54 @@ OpenAI( ## Mistral -Point `base_url` at Mistral's API. Models keep the `openai/` prefix here; the -JS and Dart SDKs register them as `mistral/...`, so a model id written for one -SDK (in a `.prompt` file, say) doesn't resolve in the other: +`Mistral()` registers Mistral's models and embedders under `mistral/`, as the +JS and Dart SDKs do, so it can sit beside `OpenAI()`: ```python from genkit import Genkit -from genkit_openai import OpenAI +from genkit_openai import Mistral, OpenAI -# The key comes from MISTRAL_API_KEY. -ai = Genkit(plugins=[OpenAI(base_url='https://api.mistral.ai/v1')]) +# The Mistral key comes from MISTRAL_API_KEY, the OpenAI one from OPENAI_API_KEY. +ai = Genkit(plugins=[OpenAI(), Mistral()]) res = await ai.generate( - model='openai/mistral-small-latest', + model=Mistral.model('mistral-small-latest'), # or 'mistral/mistral-small-latest' prompt='Suggest 2 names for a French bakery.', config={'temperature': 0.3, 'seed': 42, 'max_output_tokens': 200}, ) -embeddings = await ai.embed(embedder='openai/mistral-embed', content='croissant') +embeddings = await ai.embed(embedder='mistral/mistral-embed', content='croissant') ``` -With a Mistral target the plugin key comes from `api_key=` or -`MISTRAL_API_KEY`, never `OPENAI_API_KEY`. The EU and US endpoints, -`https://api.eu.mistral.ai/v1` and `https://api.us.mistral.ai/v1`, work the -same way. - -A gateway in front of Mistral on another host needs `provider='mistral'`; -without it the plugin can't tell the API behind it is Mistral's and sends -OpenAI's field names, which Mistral rejects. Pass the gateway's own key as -`api_key=`, or the plugin reads `MISTRAL_API_KEY`: +`Mistral()` is `OpenAI(provider='mistral')`. `OpenAI(base_url=...)` with one of +Mistral's hosts (`OPENAI_BASE_URL` too) is the same plugin, also named +`mistral`. Its key comes from `api_key=` or `MISTRAL_API_KEY`, never +`OPENAI_API_KEY`. The EU and US endpoints, `https://api.eu.mistral.ai/v1` and +`https://api.us.mistral.ai/v1`, work the same way. + +At startup it registers Mistral's own catalog, not OpenAI's: +`mistral-large-latest`, `mistral-large-4`, `mistral-small-latest`, +`ministral-14b-latest`, `ministral-8b-latest`, `ministral-3b-latest`, +`codestral-latest` and `mistral-medium-latest` (deprecated by Mistral), and +the `mistral-embed` (1024 dimensions) and `codestral-embed` (1536) embedders. +The Dev UI's model list comes from Mistral's `/models`, read by each entry's +`capabilities`: ids with `embed` are embedders, entries with `completion_chat` +are chat models, and OCR, moderation, transcription and speech models are left +out. A model outside the catalog takes tool and image support from +`function_calling` and `vision`. Any other id still resolves as a chat model +when named, e.g. `mistral/magistral-medium-latest`. + +A gateway in front of Mistral on another host needs `Mistral(base_url=...)` +(or `provider='mistral'`); without it the plugin can't tell the API behind it +is Mistral's and sends OpenAI's field names, which Mistral rejects. Pass the +gateway's own key as `api_key=`, or the plugin reads `MISTRAL_API_KEY`: ```python -OpenAI(base_url='https://llm-gateway.example.com/v1', api_key=gateway_key, provider='mistral') +Mistral(base_url='https://llm-gateway.example.com/v1', api_key=gateway_key) ``` -`OpenAI(provider='mistral')` with no `base_url` goes to -`https://api.mistral.ai/v1`; `OPENAI_BASE_URL` isn't read then. +`Mistral()` with no `base_url` goes to `https://api.mistral.ai/v1`; +`OPENAI_BASE_URL` isn't read then. Mistral rejects any request field it doesn't declare, so with a Mistral host (or `provider='mistral'`) the plugin sends Mistral's names for the settings @@ -114,25 +126,30 @@ that differ: out: every media part goes out as `image_url`. The type comes from the part's `content_type`, else a `data:` URL's header; a remote URL with neither is sent as an image. +- OpenAI-only settings Mistral doesn't declare are left out of the request, + with a warning in the log: `verbosity`, `safety_identifier`, `store`, + `logit_bias`, `prompt_cache_retention`, `web_search_options`, `modalities` + and `audio`. Mistral would fail the call with a 422 naming them. + `logprobs`, `top_logprobs`, `service_tier`, `prompt_cache_key`, `metadata`, + `prediction` and `parallel_tool_calls` are Mistral fields too and go out as + given, though Mistral decides per model what it accepts (its current models + answer `logprobs` with "Logprobs are not enabled for this model", and + `service_tier` takes only `auto` or `standard_only`). - `extra` gets the same renames: `seed` and `max_completion_tokens` there go out as `random_seed` and `max_tokens`, and `stream_options` is dropped. + Nothing else in `extra` is dropped. With `reasoning_effort` set, replies carry their reasoning in `thinking` -chunks. Each comes back as its own reasoning part, ahead of the text, with its -own signature in `metadata['thoughtSignature']`; a streamed reply's final -message joins each chunk's fragments back into one part, ending a part at -the fragment that carries a signature. On the next turn each part goes back to Mistral as its own +chunks. Each comes back as its own reasoning part, in the order it came among +the text, with its own signature in `metadata['thoughtSignature']`; a streamed +reply's final message keeps the same order and joins each chunk's fragments +back into one part, ending a part at the fragment that carries a signature. On the next turn each part goes back to Mistral as its own `thinking` chunk, in order, as Mistral asks, so a signature stays with the text it signs. Only reasoning that came from Mistral goes back: each such part is marked `metadata['reasoningSource'] == 'mistral'`, which survives saving the history as JSON. Reasoning another model left in a mixed history is dropped. -Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given -and Mistral fails the call naming them. Mistral-only fields like `min_tokens` -go in `extra`. - -The plugin doesn't know Mistral's embedders, so their info reports the default -1536 dimensions; `mistral-embed` returns 1024. +Mistral-only fields like `min_tokens` go in `extra`. ## Config diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py index 3e1d45854..e15180d4b 100644 --- a/packages/genkit-openai/src/genkit_openai/__init__.py +++ b/packages/genkit-openai/src/genkit_openai/__init__.py @@ -20,6 +20,8 @@ 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. +``Mistral()`` (or ``OpenAI(provider='mistral')``) registers Mistral's chat +models and embedders under ``mistral/``. Example: ```python @@ -58,7 +60,7 @@ async def main() -> None: - OpenAI documentation: https://platform.openai.com/docs/ """ -from ._openai_plugin import OpenAI +from ._openai_plugin import Mistral, OpenAI from ._typing import OpenAIConfig -__all__ = ['OpenAI', 'OpenAIConfig'] +__all__ = ['Mistral', 'OpenAI', 'OpenAIConfig'] diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index 3fe0c7697..d8199174e 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -16,11 +16,12 @@ """Request rewrites for Mistral's OpenAI-compatible API. -``OpenAI(base_url='https://api.mistral.ai/v1')`` talks to Mistral. Its chat and -embeddings endpoints take the OpenAI shape with a few fields renamed or -missing, and reject any field they don't declare, so a body built for OpenAI -fails with a 422. The plugin rewrites the few fields that differ; everything -else goes out unchanged. +``Mistral()`` (``OpenAI(provider='mistral')``, or ``OpenAI`` with a Mistral +``base_url``) talks to Mistral. Its chat and embeddings endpoints take the +OpenAI shape with a few fields renamed or missing, and reject any field they +don't declare, so a body built for OpenAI fails with a 422. The plugin +renames the fields that differ and leaves out the OpenAI-only ones. This +module also holds the catalog and ``/models`` reading a Mistral target uses. The target is read from the client's base URL, not the model id as DeepSeek's JSON handling is, or set with ``OpenAI(provider='mistral')`` for a gateway in @@ -34,13 +35,15 @@ ``EmbeddingRequest``). """ -from typing import Any +from collections.abc import Mapping +from typing import Any, cast import httpx from genkit_openai._models._utils import parse_data_uri_content_type from openai import AsyncOpenAI from genkit import GenkitError, Message, get_logger +from genkit.model import ConstrainedSupport, ModelInfo, ModelStage, ModelSupports logger = get_logger(__name__) @@ -57,6 +60,9 @@ # The key Mistral's own SDKs, and Genkit's JS and Dart plugins, read. MISTRAL_API_KEY_ENV = 'MISTRAL_API_KEY' +# The plugin namespace for a Mistral target, as in JS and Dart: mistral/. +MISTRAL_NAMESPACE = 'mistral' + # The top-level fields Mistral's ChatCompletionRequest declares # (https://docs.mistral.ai/openapi.yaml). Its schema is closed: anything else # is a 422 "Extra inputs are not permitted". ``extra_body`` is the SDK's @@ -94,6 +100,103 @@ 'safe_prompt', }) +# Chat models with vision, tools and structured output (JS's +# MISTRAL_MODEL_INFO, Dart's multimodalSupports). +_MISTRAL_MULTIMODAL_SUPPORTS = ModelSupports( + multiturn=True, + media=True, + tools=True, + tool_choice=True, + system_role=True, + output=['json', 'text'], + constrained=ConstrainedSupport.ALL, +) + +# Codestral: the same without image input. +_MISTRAL_TEXT_SUPPORTS = ModelSupports( + multiturn=True, + media=False, + tools=True, + tool_choice=True, + system_role=True, + output=['json', 'text'], + constrained=ConstrainedSupport.ALL, +) + +# A model outside the catalog with no /models capabilities to go by: text in, +# text out, as JS's and Dart's unknown-model info. +MISTRAL_UNKNOWN_MODEL_SUPPORTS = ModelSupports( + multiturn=True, + media=False, + tools=False, + tool_choice=False, + system_role=True, + output=['text'], +) + +# The chat models a Mistral target registers at init, the set JS's +# SUPPORTED_MISTRAL_MODELS and Dart's KnownMistralModel register. +SUPPORTED_MISTRAL_MODELS: dict[str, ModelInfo] = { + 'mistral-large-latest': ModelInfo(label='Mistral Large', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'mistral-large-4': ModelInfo(label='Mistral Large 4', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'mistral-small-latest': ModelInfo(label='Mistral Small', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'ministral-14b-latest': ModelInfo(label='Ministral 14B', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'ministral-8b-latest': ModelInfo(label='Ministral 8B', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'ministral-3b-latest': ModelInfo(label='Ministral 3B', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'codestral-latest': ModelInfo(label='Codestral', supports=_MISTRAL_TEXT_SUPPORTS), + # Mistral Medium 3.5, which Mistral has deprecated (retiring 2027-04-30). + 'mistral-medium-latest': ModelInfo( + label='Mistral Medium', supports=_MISTRAL_MULTIMODAL_SUPPORTS, stage=ModelStage.LEGACY + ), +} + +# The embedders a Mistral target registers at init. +SUPPORTED_MISTRAL_EMBEDDERS: dict[str, dict[str, Any]] = { + 'mistral-embed': {'label': 'Mistral Embed', 'dimensions': 1024, 'supports': {'input': ['text']}}, + 'codestral-embed': {'label': 'Codestral Embed', 'dimensions': 1536, 'supports': {'input': ['text']}}, +} + + +def mistral_model_supports(name: str, capabilities: Mapping[str, object] | None = None) -> ModelSupports: + """What a Mistral chat model supports. + + The catalog's entry when ``name`` is in it; else read from the ``/models`` + entry's ``capabilities`` (``function_calling`` for tools, ``vision`` for + media), with text-only output since capabilities don't say whether the + model takes a JSON schema; else :data:`MISTRAL_UNKNOWN_MODEL_SUPPORTS`. + """ + if (known := SUPPORTED_MISTRAL_MODELS.get(name)) is not None and known.supports is not None: + return known.supports + if capabilities is None: + return MISTRAL_UNKNOWN_MODEL_SUPPORTS + tools = capabilities.get('function_calling') is True + return MISTRAL_UNKNOWN_MODEL_SUPPORTS.model_copy( + update={'tools': tools, 'tool_choice': tools, 'media': capabilities.get('vision') is True} + ) + + +def listed_capabilities(entry: object) -> Mapping[str, object] | None: + """The ``capabilities`` object of a Mistral ``/models`` entry, or None when it has none. + + It is a Mistral field, not part of OpenAI's ``Model``; the SDK keeps it in + ``model_extra``. + """ + extra = getattr(entry, 'model_extra', None) or {} + capabilities = extra.get('capabilities') if isinstance(extra, Mapping) else None + return cast(Mapping[str, object], capabilities) if isinstance(capabilities, Mapping) else None + + +def mistral_serves_chat(model_id: str, capabilities: Mapping[str, object] | None) -> bool: + """Whether a ``/models`` entry is a chat model, from ``capabilities.completion_chat``. + + That leaves out OCR, moderation, transcription and speech models. An + entry with no ``capabilities`` counts as chat unless its id names OCR, + which ``/v1/ocr`` serves, as Dart's plugin does. + """ + if capabilities is None: + return 'ocr' not in model_id.lower() + return capabilities.get('completion_chat') is True + def is_mistral_url(url: str | httpx.URL) -> bool: """Whether ``url`` is on one of Mistral's API hosts.""" diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 9d2168233..515792d6c 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -64,7 +64,18 @@ OpenAIGptImageConfig, OpenAIImageModel, ) -from genkit_openai._models._mistral import MISTRAL_API_KEY_ENV, MISTRAL_BASE_URL, is_mistral, is_mistral_url +from genkit_openai._models._mistral import ( + MISTRAL_API_KEY_ENV, + MISTRAL_BASE_URL, + MISTRAL_NAMESPACE, + SUPPORTED_MISTRAL_EMBEDDERS, + SUPPORTED_MISTRAL_MODELS, + is_mistral, + is_mistral_url, + listed_capabilities, + mistral_model_supports, + mistral_serves_chat, +) from genkit_openai._models._model import OpenAIModel from genkit_openai._models._model_info import ( SUPPORTED_EMBEDDING_MODELS, @@ -284,6 +295,8 @@ class OpenAI(Plugin): interaction with supported OpenAI models. """ + # The class default; an instance that targets Mistral is named 'mistral' + # (see __init__), so OpenAI and Mistral can be registered side by side. name = 'openai' @classmethod @@ -342,6 +355,10 @@ def __init__( provider: ``'mistral'`` sends Mistral's field names whatever the host, for a gateway in front of Mistral. Without it they go out only when ``base_url`` is one of Mistral's own hosts. + Either way, a Mistral target is named ``mistral``: its + actions are ``mistral/``, it registers Mistral's catalog + instead of OpenAI's, and it can sit beside an ``OpenAI()``. + ``Mistral()`` is the same plugin. Raises: TypeError: If ``client_options`` has a key ``AsyncOpenAI`` doesn't @@ -357,11 +374,27 @@ def __init__( # and Mistral's field names. options['base_url'] = MISTRAL_BASE_URL self._options = options + # Mistral's models live under mistral/, as in JS and Dart, so an + # 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._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. + self._listed_supports: dict[str, ModelSupports] = {} + + def _action_name(self, name: str) -> str: + """``name`` in this plugin's namespace: ``openai/`` or ``mistral/``.""" + return f'{self.name}/{name}' + + def _mistral_supports(self, name: str) -> ModelSupports: + """Catalog supports for a Mistral model, else what /models listed, else the text-only default.""" + if name in SUPPORTED_MISTRAL_MODELS or name not in self._listed_supports: + return mistral_model_supports(name) + return self._listed_supports[name] def _targets_mistral(self) -> bool: """Whether calls go to Mistral's API: ``provider='mistral'`` or a Mistral base URL.""" @@ -404,10 +437,16 @@ async def init(self) -> list[Action]: """Initialize plugin. Returns: - Actions for built-in OpenAI models, embedders, image, TTS, and STT. + Actions for built-in OpenAI models, embedders, image, TTS, and STT; + for a Mistral target, Mistral's chat models and embedders instead. """ actions = [] + if self._targets_mistral(): + actions.extend(self._create_model_action(name) for name in SUPPORTED_MISTRAL_MODELS) + actions.extend(self._create_embedder_action(name) for name in SUPPORTED_MISTRAL_EMBEDDERS) + return actions + # Add known chat models. for name in SUPPORTED_OPENAI_MODELS: actions.append(self._create_model_action(name)) @@ -442,6 +481,12 @@ def get_model_info(self, name: str) -> dict[str, Any] | None: is provided). The 'supports' key contains a dictionary representing the model's capabilities (e.g., tools, streaming). """ + if self._targets_mistral(): + known = SUPPORTED_MISTRAL_MODELS.get(name) + return { + 'label': known.label if known is not None else f'Mistral - {name}', + 'supports': self._mistral_supports(name).model_dump(by_alias=True, exclude_none=True), + } if model_supported := SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)): supports = ( model_supported.supports.model_dump(by_alias=True, exclude_none=True) @@ -465,14 +510,23 @@ async def resolve(self, action_type: ActionKind, name: str) -> Action | None: Uses name-based pattern matching (mirroring JS implementation) to route to the correct model type: image, TTS, STT, embedder, or chat. + A Mistral target serves only chat models and embedders, so an id is + never routed to OpenAI's image or audio endpoints there. Args: action_type: The kind of action to resolve. - name: The id without the ``openai/`` prefix. + name: The id without the plugin's ``openai/`` or ``mistral/`` prefix. Returns: Action object if found, None otherwise. """ + if self._targets_mistral(): + if action_type == ActionKind.EMBEDDER: + return self._create_embedder_action(name) + if action_type == ActionKind.MODEL: + return self._create_model_action(name) + return None + if action_type == ActionKind.EMBEDDER: if _classify_model(name) != _ModelType.EMBEDDER: return None @@ -550,8 +604,11 @@ def _create_model_action(self, name: str) -> Action: model_info = self.get_model_info(name) or {} async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> ModelResponse: - catalog = SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)) - supports = catalog.supports if catalog is not None else get_default_openai_model_info(name).supports + if self._targets_mistral(): + supports = self._mistral_supports(name) + else: + catalog = SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)) + supports = catalog.supports if catalog is not None else get_default_openai_model_info(name).supports client = self._client_for_call(request, ctx) openai_model = OpenAIModelHandler( OpenAIModel(name, client, supports=supports, mistral=self._uses_mistral_names(client)) @@ -559,7 +616,7 @@ async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> M return await openai_model.generate(request, ctx) return Model( - open_ai_name(name), + self._action_name(name), _generate, config_schema=OpenAIConfig, metadata={'model': model_info}, @@ -590,7 +647,7 @@ async def _generate(request: ModelRequest, ctx: ModelContext) -> ModelResponse: return await model_instance.generate(request, ctx) return Model( - open_ai_name(name), + self._action_name(name), _generate, config_schema=config_schema, info=info, @@ -605,14 +662,20 @@ def _create_embedder_action(self, name: str) -> Action: Returns: Action object for the embedder. """ - embedder_info = SUPPORTED_EMBEDDING_MODELS.get( - name, - { - 'label': f'OpenAI Embedding - {name}', - 'dimensions': 1536, - 'supports': {'input': ['text']}, - }, - ) + if self._targets_mistral(): + # No dimensions for an embedder outside the catalog: Mistral's differ. + embedder_info = SUPPORTED_MISTRAL_EMBEDDERS.get( + name, {'label': f'Mistral Embedding - {name}', 'supports': {'input': ['text']}} + ) + else: + embedder_info = SUPPORTED_EMBEDDING_MODELS.get( + name, + { + 'label': f'OpenAI Embedding - {name}', + 'dimensions': 1536, + 'supports': {'input': ['text']}, + }, + ) async def embed_fn(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedResponse: """Embedder function that calls OpenAI embeddings API.""" @@ -664,7 +727,7 @@ async def embed_fn(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedRespons return EmbedResponse(embeddings=embeddings) return Embedder( - open_ai_name(name), + self._action_name(name), embed_fn, info=EmbedderInfo( label=embedder_info['label'], @@ -678,6 +741,11 @@ async def list_actions(self) -> list[Action]: Uses pattern matching on model names (mirroring the JS implementation) to categorize models as embedders, image generators, TTS, STT, or chat. + A Mistral target reads each entry's ``capabilities`` instead, as the JS + and Dart plugins do: ids with ``embed`` are embedders, entries with + ``completion_chat`` are chat models with tools and media from + ``function_calling`` and ``vision``, and the rest (OCR, moderation, + transcription, speech) are skipped. Returns: list[Action]: A list of Action objects. Empty for a @@ -695,6 +763,10 @@ async def list_actions(self) -> list[Action]: except APIError as e: reraise_openai_error(e) models: list[OpenAIModelEntry] = models_.data + if self._targets_mistral(): + actions = self._list_mistral_actions(models) + self._list_actions_cache = actions + return actions for model in models: name = model.id if _is_known_unsupported(name): @@ -710,5 +782,74 @@ async def list_actions(self) -> list[Action]: self._list_actions_cache = actions return actions + def _list_mistral_actions(self, models: list[OpenAIModelEntry]) -> list[Action]: + """Actions for the entries of Mistral's ``/models``, by their ``capabilities``.""" + actions: list[Action] = [] + for model in models: + name = model.id + if 'embed' in name: + actions.append(self._create_embedder_action(name)) + continue + capabilities = listed_capabilities(model) + if not mistral_serves_chat(name, capabilities): + continue + if capabilities is not None and name not in SUPPORTED_MISTRAL_MODELS: + self._listed_supports[name] = mistral_model_supports(name, capabilities) + actions.append(self._create_model_action(name)) + return actions + + +class Mistral(OpenAI): + """Mistral's models through its OpenAI-compatible API, under ``mistral/``. + + The same as ``OpenAI(provider='mistral')``: ``mistral/`` names, as in + the JS and Dart plugins, Mistral's catalog, the key from ``api_key=`` or + ``MISTRAL_API_KEY``, and ``https://api.mistral.ai/v1`` unless ``base_url`` + names another host, such as a gateway in front of Mistral. + + Example: + ```python + ai = Genkit(plugins=[OpenAI(), Mistral()]) + res = await ai.generate(model=Mistral.model('mistral-small-latest'), prompt='Name a bakery.') + ``` + """ + + name = MISTRAL_NAMESPACE + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str | None = None, + client_options: Mapping[str, Any] | None = None, + ) -> None: + """Initializes the Mistral plugin. + + Args: + api_key: Mistral API key. Defaults to ``MISTRAL_API_KEY``. + base_url: API base URL up to and including ``/v1``. Defaults to + ``https://api.mistral.ai/v1``. + client_options: Other ``AsyncOpenAI`` settings, as for ``OpenAI``. + """ + super().__init__(api_key=api_key, base_url=base_url, client_options=client_options, provider='mistral') + + @classmethod + def model(cls, name: str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]: + """Typed ref for a Mistral chat model, e.g. ``Mistral.model('mistral-small-latest')``.""" + if not isinstance(name, str): + raise GenkitError(status='INVALID_ARGUMENT', message='Mistral.model: model name must be a string.') + local = name.removeprefix(f'{MISTRAL_NAMESPACE}/') + if not local: + raise GenkitError(status='INVALID_ARGUMENT', message='Mistral.model: model name is required.') + return ModelRef(name=f'{MISTRAL_NAMESPACE}/{local}', config_schema=OpenAIConfig, config=config) + + @classmethod + def gpt(cls, name: KnownGpt | str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]: + """Not for Mistral: refs from it name OpenAI's models. Use :meth:`model`.""" + raise GenkitError( + status='INVALID_ARGUMENT', + message=f"Mistral.gpt names OpenAI's models; use Mistral.model({name!r}) for mistral/{name}.", + ) + -__all__ = ['OpenAI'] +__all__ = ['Mistral', 'OpenAI'] diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 741973ed6..072d8da34 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -23,11 +23,12 @@ import httpx import pytest -from genkit_openai import OpenAI +from genkit_openai import Mistral, OpenAI, OpenAIConfig from genkit_openai._models._mistral import MISTRAL_CHAT_FIELDS, mistral_chat_body from pydantic import BaseModel from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role +from genkit.plugin_api import Action, ActionKind MISTRAL_URL = 'https://api.mistral.ai/v1' CODESTRAL_URL = 'https://codestral.mistral.ai/v1' @@ -193,9 +194,13 @@ def __init__(self) -> None: # Replaces the reply's content, or the streamed deltas, when set. self.content: Any = None self.deltas: list[Any] | None = None + # GET /models answers with these entries. + self.models: list[dict[str, Any]] = [] def handler(self, request: httpx.Request) -> httpx.Response: self.requests.append(request) + if request.method == 'GET' and request.url.path.endswith('/models'): + return httpx.Response(200, json={'object': 'list', 'data': self.models}) body = json.loads(request.content) embeddings = request.url.path.endswith('/embeddings') if request.url.host in _MISTRAL_HOSTS: @@ -250,8 +255,8 @@ def openai(server: _Server) -> Genkit: @pytest.mark.asyncio async def test_mistral_generate_goes_to_mistral_with_the_plugin_key(mistral: Genkit, server: _Server) -> None: - """`ai.generate(model='openai/mistral-small-latest')` posts to Mistral's chat endpoint with the plugin's key.""" - response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut') + """`ai.generate(model='mistral/mistral-small-latest')` posts to Mistral's chat endpoint with the plugin's key.""" + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut') assert response.text == 'bonjour' [request] = server.requests @@ -263,7 +268,7 @@ async def test_mistral_generate_goes_to_mistral_with_the_plugin_key(mistral: Gen @pytest.mark.asyncio async def test_mistral_stream_sends_no_stream_options_and_reads_usage(mistral: Genkit, server: _Server) -> None: """A streamed call to Mistral sends no `stream_options`, and usage still comes back from the last chunk.""" - stream = mistral.generate_stream(model='openai/mistral-small-latest', prompt='salut') + stream = mistral.generate_stream(model='mistral/mistral-small-latest', prompt='salut') chunks = [chunk.text async for chunk in stream.stream] response = await stream.response @@ -280,7 +285,7 @@ async def test_mistral_stream_sends_no_stream_options_and_reads_usage(mistral: G async def test_mistral_stream_drops_stream_options_from_config(mistral: Genkit, server: _Server) -> None: """`config={'stream_options': {...}}` is not sent to Mistral, which has no such field.""" stream = mistral.generate_stream( - model='openai/mistral-small-latest', + model='mistral/mistral-small-latest', prompt='salut', config={'stream_options': {'include_usage': True}}, ) @@ -302,7 +307,7 @@ async def test_mistral_max_output_tokens_goes_out_as_max_tokens( mistral: Genkit, server: _Server, config: dict[str, Any] ) -> None: """`max_output_tokens` reaches Mistral as `max_tokens`, even with `reasoning_effort` set.""" - await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) [body] = server.bodies() caps_sent = {k: body[k] for k in ('max_tokens', 'max_completion_tokens') if k in body} @@ -314,7 +319,7 @@ async def test_mistral_max_output_tokens_goes_out_as_max_tokens( async def test_mistral_seed_goes_out_as_random_seed(mistral: Genkit, server: _Server) -> None: """`config={'seed': 7}` reaches Mistral as `random_seed`, beside the other settings.""" await mistral.generate( - model='openai/mistral-small-latest', + model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7, 'temperature': 0.2, 'extra': {'min_tokens': 5}}, ) @@ -330,7 +335,7 @@ async def test_mistral_seed_goes_out_as_random_seed(mistral: Genkit, server: _Se async def test_mistral_random_seed_in_extra_wins_over_seed(mistral: Genkit, server: _Server) -> None: """`extra={'random_seed': 9}` replaces `seed=7`, as any `extra` key replaces a setting of the same name.""" await mistral.generate( - model='openai/mistral-small-latest', + model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7, 'extra': {'random_seed': 9}}, ) @@ -344,7 +349,7 @@ async def test_mistral_random_seed_in_extra_wins_over_seed(mistral: Genkit, serv async def test_mistral_tenant_key_call_is_rewritten_too(mistral: Genkit, server: _Server) -> None: """A call with a `context.secrets` key still goes to Mistral with Mistral's field names.""" stream = mistral.generate_stream( - model='openai/mistral-small-latest', + model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7}, context={'secrets': {'api_key': 'tenant-key'}}, @@ -363,7 +368,7 @@ async def test_mistral_tenant_key_call_is_rewritten_too(mistral: Genkit, server: async def test_mistral_embed_dimensions_goes_out_as_output_dimension(mistral: Genkit, server: _Server) -> None: """`config={'dimensions': 256}` reaches Mistral's embeddings endpoint as `output_dimension`.""" response = await mistral.embed( - embedder='openai/codestral-embed', content='def f(): ...', config={'dimensions': 256} + embedder='mistral/codestral-embed', content='def f(): ...', config={'dimensions': 256} ) assert response[0].embedding == [0.5, 0.25] @@ -378,7 +383,7 @@ async def test_mistral_embed_dimensions_goes_out_as_output_dimension(mistral: Ge async def test_mistral_embed_float_encoding_still_goes_out(mistral: Genkit, server: _Server) -> None: """`encodingFormat='float'` with `dimensions` sends both, `dimensions` under Mistral's name.""" await mistral.embed( - embedder='openai/codestral-embed', + embedder='mistral/codestral-embed', content='def f(): ...', config={'dimensions': 256, 'encodingFormat': 'float'}, ) @@ -409,7 +414,7 @@ async def test_codestral_host_gets_mistral_field_names(server: _Server) -> None: """OpenAI(base_url='https://codestral.mistral.ai/v1') sends Mistral's names too.""" ai = _ai(server, CODESTRAL_URL) - await ai.generate(model='openai/codestral-latest', prompt='def add(a, b):', config={'seed': 7}) + await ai.generate(model='mistral/codestral-latest', prompt='def add(a, b):', config={'seed': 7}) [request] = server.requests assert str(request.url) == f'{CODESTRAL_URL}/chat/completions' @@ -426,7 +431,7 @@ async def test_openai_base_url_env_pointing_at_mistral_gets_mistral_field_names( monkeypatch.setenv('OPENAI_BASE_URL', MISTRAL_URL) ai = _ai(server, None) - stream = ai.generate_stream(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + stream = ai.generate_stream(model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7}) await stream.response [request] = server.requests @@ -440,7 +445,7 @@ async def test_openai_base_url_env_pointing_at_mistral_gets_mistral_field_names( async def test_mistral_generate_drops_stream_options_from_config(mistral: Genkit, server: _Server) -> None: """`config={'stream_options': {...}}` on a non-streamed call is not sent to Mistral either.""" await mistral.generate( - model='openai/mistral-small-latest', prompt='salut', config={'stream_options': {'include_usage': True}} + model='mistral/mistral-small-latest', prompt='salut', config={'stream_options': {'include_usage': True}} ) [body] = server.bodies() @@ -450,7 +455,7 @@ async def test_mistral_generate_drops_stream_options_from_config(mistral: Genkit @pytest.mark.asyncio async def test_mistral_refuses_top_k(mistral: Genkit, server: _Server) -> None: """`config={'top_k': 5}` fails the turn before the request goes out: Mistral's models reject `top_k`.""" - response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'top_k': 5}) + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config={'top_k': 5}) assert response.finish_reason == FinishReason.FAILED assert 'top_k' in str(response.error) @@ -464,7 +469,7 @@ async def test_mistral_refuses_top_k(mistral: Genkit, server: _Server) -> None: async def test_mistral_reasoning_reply_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: """With `reasoning_effort` set, the reply's `thinking` chunk is a reasoning part and its `text` chunk the text.""" response = await mistral.generate( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) assert response.text == 'bonjour' @@ -478,7 +483,7 @@ async def test_mistral_reasoning_reply_splits_reasoning_from_text(mistral: Genki async def test_mistral_reasoning_stream_splits_reasoning_from_text(mistral: Genkit, server: _Server) -> None: """Streamed thinking chunks arrive as reasoning parts, through all three delta shapes Mistral sends.""" stream = mistral.generate_stream( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) chunks = [chunk async for chunk in stream.stream] response = await stream.response @@ -496,15 +501,15 @@ async def test_mistral_replays_reasoning_as_a_thinking_chunk(mistral: Genkit, se """The next turn sends the reply's reasoning back as one leading `thinking` chunk, signature included.""" if streamed: stream = mistral.generate_stream( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) first = await stream.response else: first = await mistral.generate( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) - second = await mistral.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + second = await mistral.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') assert second.finish_reason == FinishReason.STOP body = server.bodies()[-1] @@ -535,7 +540,7 @@ async def test_mistral_model_length_finish_is_length(mistral: Genkit, server: _S """Mistral's `model_length` finish reason comes back as LENGTH.""" server.finish_reason = 'model_length' - response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut') + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut') assert response.finish_reason == FinishReason.LENGTH @@ -546,7 +551,7 @@ async def test_mistral_regional_hosts_get_mistral_field_names(server: _Server, h """The EU and US endpoints get the same rewrite as the global one.""" ai = _ai(server, f'https://{host}/v1') - stream = ai.generate_stream(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + stream = ai.generate_stream(model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7}) await stream.response [request] = server.requests @@ -565,7 +570,7 @@ async def lookup_menu(dish: str) -> str: return f'{dish}: in stock' response = await mistral.generate( - model='openai/mistral-small-latest', + model='mistral/mistral-small-latest', prompt='Is the baguette in stock?', tools=['lookup_menu'], tool_choice='auto', @@ -585,7 +590,7 @@ class _Loaf(BaseModel): @pytest.mark.asyncio async def test_mistral_output_schema_goes_out_as_json_schema(mistral: Genkit, server: _Server) -> None: """`output_schema=` reaches Mistral as a `json_schema` response format.""" - await mistral.generate(model='openai/mistral-small-latest', prompt='Describe a loaf.', output_schema=_Loaf) + await mistral.generate(model='mistral/mistral-small-latest', prompt='Describe a loaf.', output_schema=_Loaf) [body] = server.bodies() assert body['response_format']['type'] == 'json_schema' @@ -596,7 +601,7 @@ async def test_mistral_output_schema_goes_out_as_json_schema(mistral: Genkit, se async def test_mistral_image_input_goes_out_as_image_url(mistral: Genkit, server: _Server) -> None: """An image part reaches Mistral as an `image_url` content block.""" await mistral.generate( - model='openai/pixtral-large-latest', + model='mistral/pixtral-large-latest', prompt=[Part.from_text('What bread is this?'), Part.from_media('https://example.com/loaf.png', 'image/png')], ) @@ -627,10 +632,10 @@ async def test_mistral_drops_openai_only_settings(mistral: Genkit, server: _Serv config = {field: _OPENAI_ONLY_SETTINGS[field]} if streamed: response = await mistral.generate_stream( - model='openai/mistral-small-latest', prompt='salut', config=config + model='mistral/mistral-small-latest', prompt='salut', config=config ).response else: - response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) assert response.finish_reason == FinishReason.STOP [body] = server.bodies() @@ -653,7 +658,7 @@ async def test_mistral_sends_the_settings_it_declares(mistral: Genkit, server: _ 'presence_penalty': 0.2, } - await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) [body] = server.bodies() assert {k: body[k] for k in config} == config @@ -696,7 +701,7 @@ def test_mistral_chat_fields_match_the_fake_servers_schema() -> None: @pytest.mark.asyncio async def test_mistral_embed_without_options_sends_only_mistral_fields(mistral: Genkit, server: _Server) -> None: """An embed call with no options sends `model`, `input`, and the SDK's default `encoding_format`.""" - response = await mistral.embed(embedder='openai/mistral-embed', content='croissant') + response = await mistral.embed(embedder='mistral/mistral-embed', content='croissant') assert response[0].embedding == [0.5, 0.25] [body] = server.bodies() @@ -755,7 +760,7 @@ async def test_mistral_replays_only_mistral_reasoning_from_a_mixed_history(mistr Message(role=Role.MODEL, content=[_mistral_reasoning(REASONING), Part.from_text('Four.')]), ] - response = await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And five?') + response = await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And five?') assert response.finish_reason == FinishReason.STOP [body] = server.bodies() @@ -772,12 +777,12 @@ async def test_mistral_replays_only_mistral_reasoning_from_a_mixed_history(mistr async def test_mistral_reasoning_replays_after_a_json_round_trip(mistral: Genkit, server: _Server) -> None: """A history saved as JSON and loaded back still replays Mistral's reasoning, signature included.""" first = await mistral.generate( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) saved = json.dumps([m.model_dump(mode='json', by_alias=True, exclude_none=True) for m in first.messages]) history = [Message.model_validate(m) for m in json.loads(saved)] - await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And three?') + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And three?') [assistant] = _assistant_messages(server.bodies()[-1]) assert assistant['content'][0] == { @@ -807,7 +812,7 @@ async def test_mistral_replays_reasoning_onto_a_tool_call_message_with_no_conten ), ] - response = await mistral.generate(model='openai/mistral-small-latest', messages=history) + response = await mistral.generate(model='mistral/mistral-small-latest', messages=history) assert response.finish_reason == FinishReason.STOP [body] = server.bodies() @@ -826,7 +831,7 @@ async def test_mistral_replays_a_reasoning_only_turn(mistral: Genkit, server: _S Message(role=Role.MODEL, content=[_mistral_reasoning(REASONING, signature=None)]), ] - await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='Well?') + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='Well?') [assistant] = _assistant_messages(server.bodies()[0]) assert assistant['content'] == [{'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}]}] @@ -858,10 +863,10 @@ async def test_mistral_renames_openai_fields_in_extra(mistral: Genkit, server: _ """`extra` with `seed`, `max_completion_tokens` or `stream_options` goes out under Mistral's names, not as a 422.""" config = {'extra': {'seed': 1, 'max_completion_tokens': 50, 'stream_options': {'include_usage': True}}} if streamed: - stream = mistral.generate_stream(model='openai/mistral-small-latest', prompt='salut', config=config) + stream = mistral.generate_stream(model='mistral/mistral-small-latest', prompt='salut', config=config) response = await stream.response else: - response = await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config=config) + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) assert response.finish_reason == FinishReason.STOP [body] = server.bodies() @@ -886,11 +891,11 @@ async def test_provider_mistral_sends_mistral_names_through_a_gateway(server: _S ai = _ai(server, GATEWAY_URL, provider='mistral') stream = ai.generate_stream( - model='openai/mistral-small-latest', prompt='Bread for two?', config={'seed': 7, **_REASONING_CONFIG} + model='mistral/mistral-small-latest', prompt='Bread for two?', config={'seed': 7, **_REASONING_CONFIG} ) first = await stream.response - await ai.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') - await ai.embed(embedder='openai/mistral-embed', content='croissant', config={'dimensions': 256}) + await ai.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') + await ai.embed(embedder='mistral/mistral-embed', content='croissant', config={'dimensions': 256}) streamed, replay, embed = server.requests assert {r.url.host for r in server.requests} == {'llm-gateway.example.com'} @@ -935,8 +940,8 @@ async def test_mistral_without_api_key_uses_mistral_api_key_env( monkeypatch.setenv('MISTRAL_API_KEY', 'mistral-env') ai = _ai(server, base_url, api_key=None, provider=provider) - await ai.generate(model='openai/mistral-small-latest', prompt='salut') - await ai.embed(embedder='openai/mistral-embed', content='croissant') + await ai.generate(model='mistral/mistral-small-latest', prompt='salut') + await ai.embed(embedder='mistral/mistral-embed', content='croissant') assert [r.headers['authorization'] for r in server.requests] == ['Bearer mistral-env'] * 2 @@ -949,7 +954,7 @@ async def test_mistral_explicit_api_key_beats_mistral_api_key_env( monkeypatch.setenv('MISTRAL_API_KEY', 'mistral-env') ai = _ai(server, MISTRAL_URL) - await ai.generate(model='openai/mistral-small-latest', prompt='salut') + await ai.generate(model='mistral/mistral-small-latest', prompt='salut') assert server.requests[0].headers['authorization'] == f'Bearer {PLUGIN_KEY}' @@ -963,7 +968,7 @@ async def test_mistral_without_any_key_does_not_send_openai_api_key( monkeypatch.delenv('MISTRAL_API_KEY', raising=False) ai = _ai(server, MISTRAL_URL, api_key=None) - response = await ai.generate(model='openai/mistral-small-latest', prompt='salut') + response = await ai.generate(model='mistral/mistral-small-latest', prompt='salut') assert response.finish_reason == FinishReason.FAILED assert response.error is not None @@ -996,7 +1001,7 @@ async def test_mistral_replays_each_reasoning_part_as_its_own_thinking_chunk(mis ), ] - await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And three?') + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And three?') [assistant] = _assistant_messages(server.bodies()[0]) assert assistant['content'] == [ @@ -1015,7 +1020,7 @@ async def test_mistral_sends_no_thinking_chunk_when_reasoning_parts_are_empty(mi Message(role=Role.MODEL, content=[_mistral_reasoning('', signature=None), Part.from_text('Two loaves.')]), ] - await mistral.generate(model='openai/mistral-small-latest', messages=history, prompt='And three?') + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And three?') [assistant] = _assistant_messages(server.bodies()[0]) assert assistant['content'] == 'Two loaves.' @@ -1032,8 +1037,8 @@ async def test_mistral_reply_with_two_thinking_chunks_gives_two_reasoning_parts( {'type': 'text', 'text': 'Two loaves.'}, ] - first = await mistral.generate(model='openai/mistral-small-latest', prompt='Bread for two?') - await mistral.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + first = await mistral.generate(model='mistral/mistral-small-latest', prompt='Bread for two?') + await mistral.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') assert first.message is not None assert [(p.reasoning, p.metadata) for p in first.message.content if p.reasoning is not None] == [ @@ -1048,7 +1053,7 @@ async def test_mistral_reply_with_two_thinking_chunks_gives_two_reasoning_parts( async def test_mistral_stream_joins_a_thinking_chunks_fragments_into_one_part(mistral: Genkit, server: _Server) -> None: """A streamed thinking chunk's fragments end up as one reasoning part, with the signature, in the final message.""" stream = mistral.generate_stream( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) response = await stream.response @@ -1066,7 +1071,7 @@ async def test_provider_mistral_without_base_url_goes_to_mistral( monkeypatch.setenv('OPENAI_BASE_URL', 'https://api.openai.com/v1') ai = _ai(server, None, provider='mistral') - await ai.generate(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + await ai.generate(model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7}) [request] = server.requests assert str(request.url) == f'{MISTRAL_URL}/chat/completions' @@ -1087,7 +1092,7 @@ async def test_provider_mistral_keeps_base_url_from_client_options(server: _Serv ] ) - await ai.generate(model='openai/mistral-small-latest', prompt='salut') + await ai.generate(model='mistral/mistral-small-latest', prompt='salut') assert server.requests[0].url.host == 'llm-gateway.example.com' @@ -1101,7 +1106,7 @@ async def test_mistral_missing_key_error_leaves_out_openai_api_key_when_unset( monkeypatch.delenv('MISTRAL_API_KEY', raising=False) ai = _ai(server, MISTRAL_URL, api_key=None) - response = await ai.generate(model='openai/mistral-small-latest', prompt='salut') + response = await ai.generate(model='mistral/mistral-small-latest', prompt='salut') assert response.error is not None assert response.error.status == 'FAILED_PRECONDITION' @@ -1135,10 +1140,10 @@ async def test_mistral_stream_keeps_two_signed_thinking_chunks_apart(mistral: Ge ] stream = mistral.generate_stream( - model='openai/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG ) first = await stream.response - await mistral.generate(model='openai/mistral-small-latest', messages=first.messages, prompt='And three?') + await mistral.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') assert first.message is not None assert [(p.reasoning, p.metadata) for p in first.message.content if p.reasoning is not None] == [ @@ -1156,7 +1161,7 @@ async def test_mistral_stream_keeps_two_signed_thinking_chunks_apart(mistral: Ge @pytest.mark.asyncio async def test_mistral_takes_reasoning_effort_max(mistral: Genkit, server: _Server) -> None: """`reasoning_effort='max'`, in Mistral's ReasoningEffort, goes out to Mistral as given.""" - await mistral.generate(model='openai/mistral-small-latest', prompt='salut', config={'reasoning_effort': 'max'}) + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config={'reasoning_effort': 'max'}) assert server.bodies()[0]['reasoning_effort'] == 'max' @@ -1195,7 +1200,7 @@ async def test_mistral_refuses_non_image_media( ) -> None: """Non-image media fails before the request instead of reaching Mistral as an image_url.""" response = await mistral.generate( - model='openai/mistral-small-latest', + model='mistral/mistral-small-latest', prompt=[Part.from_text('Summarize this.'), Part.from_media(url, content_type)], ) @@ -1217,7 +1222,7 @@ async def test_mistral_refuses_non_image_media( async def test_mistral_sends_image_media(mistral: Genkit, server: _Server, url: str, content_type: str | None) -> None: """Images, and remote URLs whose type isn't known, still go out as image_url.""" await mistral.generate( - model='openai/pixtral-large-latest', + model='mistral/pixtral-large-latest', prompt=[Part.from_text('What bread is this?'), Part.from_media(url, content_type)], ) @@ -1268,9 +1273,9 @@ async def test_mistral_keeps_thinking_and_text_in_the_order_they_came(mistral: G ('text', ' Water.'), ] - full = await mistral.generate(model='openai/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG) + full = await mistral.generate(model='mistral/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG) streamed = await mistral.generate_stream( - model='openai/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG + model='mistral/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG ).response assert _order(full.message) == expected @@ -1280,3 +1285,191 @@ async def test_mistral_keeps_thinking_and_text_in_the_order_they_came(mistral: G {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}, {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}, ] + + +# Namespace and catalog + + +def _plugin(server: _Server, plugin_class: type[OpenAI] = OpenAI, **kwargs: Any) -> OpenAI: # noqa: ANN401 + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return plugin_class(api_key=PLUGIN_KEY, client_options={'http_client': http_client, 'max_retries': 0}, **kwargs) + + +@pytest.mark.parametrize( + 'kwargs', + [{'provider': 'mistral'}, {'base_url': MISTRAL_URL}, {'base_url': CODESTRAL_URL}], + ids=['provider', 'base_url', 'codestral'], +) +def test_mistral_target_is_named_mistral(server: _Server, kwargs: dict[str, Any]) -> None: + """Any Mistral target is the `mistral` plugin; a plain OpenAI() stays `openai`.""" + assert _plugin(server, **kwargs).name == 'mistral' + assert _plugin(server).name == 'openai' + assert _plugin(server, Mistral).name == 'mistral' + + +@pytest.mark.asyncio +async def test_mistral_init_registers_mistrals_catalog_not_openais(server: _Server) -> None: + """init() on a Mistral target registers Mistral's models and embedders, under mistral/.""" + actions = await _plugin(server, Mistral).init() + + names = {(a.kind, a.name) for a in actions} + assert (ActionKind.MODEL, 'mistral/mistral-small-latest') in names + assert (ActionKind.MODEL, 'mistral/mistral-large-latest') in names + assert (ActionKind.MODEL, 'mistral/codestral-latest') in names + assert (ActionKind.EMBEDDER, 'mistral/mistral-embed') in names + assert (ActionKind.EMBEDDER, 'mistral/codestral-embed') in names + assert all(a.name.startswith('mistral/') for a in actions) + assert not any('gpt' in a.name or 'dall-e' in a.name or 'tts' in a.name for a in actions) + embed = next(a for a in actions if a.name == 'mistral/mistral-embed') + assert embed.metadata is not None + assert cast(dict[str, Any], embed.metadata['embedder'])['dimensions'] == 1024 + codestral = next(a for a in actions if a.name == 'mistral/codestral-latest') + assert codestral.metadata is not None + assert cast(dict[str, Any], codestral.metadata['model'])['supports']['media'] is False + + +@pytest.mark.asyncio +async def test_openai_and_mistral_side_by_side(server: _Server) -> None: + """OpenAI() and OpenAI(provider='mistral') register together, each call going to its own host and names.""" + ai = Genkit(plugins=[_plugin(server), _plugin(server, provider='mistral')]) + + await ai.generate(model='openai/gpt-4o', prompt='hi', config={'seed': 1}) + await ai.generate(model='mistral/mistral-small-latest', prompt='salut', config={'seed': 1}) + + openai_request, mistral_request = server.requests + assert openai_request.url.host == 'api.openai.com' + assert json.loads(openai_request.content)['seed'] == 1 + assert mistral_request.url.host == 'api.mistral.ai' + assert json.loads(mistral_request.content)['random_seed'] == 1 + + +@pytest.mark.asyncio +async def test_openai_and_mistral_list_without_clashing(server: _Server) -> None: + """Both catalogs list, each under its own namespace, with no OpenAI model under mistral/.""" + ai = Genkit(plugins=[_plugin(server), _plugin(server, Mistral)]) + + catalog = await ai._registry.list_actions() + + assert '/model/openai/gpt-4o' in catalog + assert '/embedder/openai/text-embedding-3-small' in catalog + assert '/model/mistral/mistral-small-latest' in catalog + assert '/embedder/mistral/mistral-embed' in catalog + assert not [key for key in catalog if key.startswith('/model/mistral/gpt')] + assert '/model/openai/mistral-small-latest' not in catalog + + +def test_mistral_model_ref() -> None: + """Mistral.model names mistral/, once, and binds OpenAIConfig.""" + ref = Mistral.model('mistral-small-latest', config=OpenAIConfig(temperature=0.2)) + + assert ref.name == 'mistral/mistral-small-latest' + assert Mistral.model('mistral/mistral-small-latest').name == 'mistral/mistral-small-latest' + assert ref.config_schema is OpenAIConfig + with pytest.raises(GenkitError): + Mistral.gpt('gpt-4o') + assert OpenAI.gpt('gpt-4o').name == 'openai/gpt-4o' + + +@pytest.mark.asyncio +async def test_mistral_resolves_any_id_as_chat(server: _Server) -> None: + """On Mistral an id with `tts` in it is a chat model, not OpenAI's speech endpoint.""" + plugin = _plugin(server, Mistral) + + action = await plugin.resolve(ActionKind.MODEL, 'voxtral-mini-tts-latest') + + assert action is not None + assert action.name == 'mistral/voxtral-mini-tts-latest' + assert action.metadata is not None + assert 'media' not in cast(dict[str, Any], action.metadata['model'])['supports'].get('output', []) + + +# Listing + + +def _entry(model_id: str, **capabilities: bool) -> dict[str, Any]: + return { + 'id': model_id, + 'object': 'model', + 'created': 0, + 'owned_by': 'mistralai', + 'capabilities': capabilities, + } + + +_LISTING = [ + _entry('mistral-small-latest', completion_chat=True, function_calling=True, vision=True), + _entry('codestral-2508', completion_chat=True, function_calling=True), + _entry('pixtral-next', completion_chat=True, vision=True), + _entry('voxtral-small-latest', completion_chat=True, function_calling=True, audio=True), + _entry('mistral-embed'), + _entry('codestral-embed-2505'), + _entry('voxtral-mini-tts-latest', function_calling=True, audio_speech=True), + _entry('voxtral-mini-transcribe-3', audio_transcription=True), + _entry('mistral-ocr-latest', function_calling=True, vision=True, ocr=True), + _entry('mistral-moderation-2603', classification=True, moderation=True), +] + + +def _supports(action: Action) -> dict[str, Any]: + assert action.metadata is not None + return cast(dict[str, Any], action.metadata['model'])['supports'] + + +@pytest.mark.asyncio +async def test_mistral_lists_models_by_capabilities(server: _Server) -> None: + """Chat from completion_chat, embedders by id; OCR, moderation, speech and transcription are left out.""" + server.models = _LISTING + plugin = _plugin(server, Mistral) + + actions = await plugin.list_actions() + + assert {(a.kind, a.name) for a in actions} == { + (ActionKind.MODEL, 'mistral/mistral-small-latest'), + (ActionKind.MODEL, 'mistral/codestral-2508'), + (ActionKind.MODEL, 'mistral/pixtral-next'), + (ActionKind.MODEL, 'mistral/voxtral-small-latest'), + (ActionKind.EMBEDDER, 'mistral/mistral-embed'), + (ActionKind.EMBEDDER, 'mistral/codestral-embed-2505'), + } + by_name = {a.name: a for a in actions} + assert _supports(by_name['mistral/codestral-2508'])['tools'] is True + assert _supports(by_name['mistral/codestral-2508'])['media'] is False + assert _supports(by_name['mistral/pixtral-next'])['tools'] is False + assert _supports(by_name['mistral/pixtral-next'])['media'] is True + assert _supports(by_name['mistral/pixtral-next'])['output'] == ['text'] + # A catalog model keeps its catalog info. + assert _supports(by_name['mistral/mistral-small-latest'])['output'] == ['json', 'text'] + # A listed model resolves with the info it was listed with. + resolved = await plugin.resolve(ActionKind.MODEL, 'codestral-2508') + assert resolved is not None + assert _supports(resolved)['tools'] is True + + +@pytest.mark.asyncio +async def test_mistral_listing_without_capabilities_skips_only_ocr(server: _Server) -> None: + """An entry with no capabilities is a chat model unless its id names OCR, as in Dart.""" + server.models = [ + {'id': 'mistral-next', 'object': 'model', 'created': 0, 'owned_by': 'mistralai'}, + {'id': 'mistral-ocr-next', 'object': 'model', 'created': 0, 'owned_by': 'mistralai'}, + ] + + actions = await _plugin(server, Mistral).list_actions() + + assert [a.name for a in actions] == ['mistral/mistral-next'] + assert _supports(actions[0])['tools'] is False + + +@pytest.mark.asyncio +async def test_openai_listing_still_classifies_by_name(server: _Server) -> None: + """A plain OpenAI() target keeps the name rules: a tts id is a speech model there.""" + server.models = [_entry('gpt-4o'), _entry('tts-1'), _entry('text-embedding-3-small')] + + actions = await _plugin(server).list_actions() + + assert {(a.kind, a.name) for a in actions} == { + (ActionKind.MODEL, 'openai/gpt-4o'), + (ActionKind.MODEL, 'openai/tts-1'), + (ActionKind.EMBEDDER, 'openai/text-embedding-3-small'), + } + tts = next(a for a in actions if a.name == 'openai/tts-1') + assert _supports(tts)['output'] == ['media'] From 04cd7db23bcf27806efa5360b6db6c6eabe3e977 Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 18 Nov 2026 10:54:26 +0000 Subject: [PATCH 21/22] fix(py/openai): refuse logprobs on Mistral Mistral's schema declares logprobs and top_logprobs, but every model answers 'Logprobs are not enabled for this model' with a 400. As in JS, logprobs=True or any top_logprobs now fails with INVALID_ARGUMENT before the request, like top_k, and logprobs=False is left out of the body. --- packages/genkit-openai/README.md | 12 ++--- .../src/genkit_openai/_models/_mistral.py | 20 +++++++- packages/genkit-openai/tests/mistral_test.py | 51 +++++++++++++++++-- 3 files changed, 71 insertions(+), 12 deletions(-) diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index e66e87048..484889ef1 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -114,7 +114,9 @@ that differ: even with `reasoning_effort` set. - `seed` goes out as `random_seed`. - `top_k` is refused before the request goes out: Mistral's models reject - `top_k` sampling. + `top_k` sampling. So are `logprobs=True` and any `top_logprobs`: Mistral's + models answer "Logprobs are not enabled for this model". `logprobs=False` + is left out of the request. - `reasoning_effort` also takes `'max'`, which Mistral's API declares and OpenAI's doesn't; other targets refuse it before the request goes out. Which values a model accepts varies: Mistral Small takes `none` and `high`, @@ -130,11 +132,9 @@ that differ: with a warning in the log: `verbosity`, `safety_identifier`, `store`, `logit_bias`, `prompt_cache_retention`, `web_search_options`, `modalities` and `audio`. Mistral would fail the call with a 422 naming them. - `logprobs`, `top_logprobs`, `service_tier`, `prompt_cache_key`, `metadata`, - `prediction` and `parallel_tool_calls` are Mistral fields too and go out as - given, though Mistral decides per model what it accepts (its current models - answer `logprobs` with "Logprobs are not enabled for this model", and - `service_tier` takes only `auto` or `standard_only`). + `service_tier`, `prompt_cache_key`, `metadata`, `prediction` and + `parallel_tool_calls` are Mistral fields too and go out as given + (`service_tier` takes only `auto` or `standard_only`). - `extra` gets the same renames: `seed` and `max_completion_tokens` there go out as `random_seed` and `max_tokens`, and `stream_options` is dropped. Nothing else in `extra` is dropped. diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index d8199174e..fb9510062 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -230,7 +230,9 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict settings such as ``verbosity``, ``safety_identifier``, ``store``, ``logit_bias``, ``prompt_cache_retention``, ``web_search_options``, ``modalities`` and ``audio`` would otherwise fail the call with a 422. - ``logprobs`` and ``top_logprobs`` are Mistral fields and go out. + - ``logprobs=True`` and any ``top_logprobs`` are refused, as in JS: + Mistral's schema declares them, but its models answer "Logprobs are not + enabled for this model". ``logprobs=False`` is left out. The SDK has no ``random_seed`` kwarg, so it rides in ``extra_body``; the same key in the caller's ``extra`` wins, as every ``extra`` key does. @@ -247,14 +249,28 @@ def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict A copy with Mistral's field names. Raises: - GenkitError: ``INVALID_ARGUMENT`` when ``top_k`` is set. + GenkitError: ``INVALID_ARGUMENT`` when ``top_k``, ``logprobs=True`` + or ``top_logprobs`` is set. """ if top_k is not None: raise GenkitError( status='INVALID_ARGUMENT', message="Mistral doesn't support top_k: its models reject top_k sampling. Remove top_k from the config.", ) + # top_logprobs=0 is still a request for logprobs; only logprobs=False isn't. + asked = [('logprobs', body.get('logprobs') is True), ('top_logprobs', body.get('top_logprobs') is not None)] + for field, set_ in asked: + if set_: + raise GenkitError( + status='INVALID_ARGUMENT', + message=( + f"Mistral doesn't support {field}: its models answer 'Logprobs are not enabled for this model'. " + f'Remove {field} from the config.' + ), + ) out = dict(body) + out.pop('logprobs', None) + out.pop('top_logprobs', None) out.pop('stream_options', None) if 'max_completion_tokens' in out: out['max_tokens'] = out.pop('max_completion_tokens') diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 072d8da34..9c7ce0114 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -462,6 +462,51 @@ async def test_mistral_refuses_top_k(mistral: Genkit, server: _Server) -> None: assert server.bodies() == [] +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('config', 'field'), + [ + ({'logprobs': True}, 'logprobs'), + ({'top_logprobs': 2}, 'top_logprobs'), + ({'top_logprobs': 0}, 'top_logprobs'), + ({'logprobs': True, 'top_logprobs': 2}, 'logprobs'), + ], +) +async def test_mistral_refuses_logprobs(mistral: Genkit, server: _Server, config: dict[str, Any], field: str) -> None: + """`logprobs=True` or any `top_logprobs` fails before the request: Mistral's models don't enable logprobs.""" + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + assert response.finish_reason == FinishReason.FAILED + assert field in str(response.error) + assert 'INVALID_ARGUMENT' in str(response.error) + assert server.bodies() == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +async def test_mistral_leaves_out_logprobs_false(mistral: Genkit, server: _Server, streamed: bool) -> None: + """`logprobs=False` asks for nothing, so it isn't sent.""" + config = {'logprobs': False} + if streamed: + await mistral.generate_stream(model='mistral/mistral-small-latest', prompt='salut', config=config).response + else: + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + [body] = server.bodies() + assert 'logprobs' not in body + assert 'top_logprobs' not in body + + +@pytest.mark.asyncio +async def test_openai_host_keeps_logprobs(openai: Genkit, server: _Server) -> None: + """OpenAI still gets logprobs and top_logprobs.""" + await openai.generate(model='openai/gpt-4o', prompt='hi', config={'logprobs': True, 'top_logprobs': 2}) + + [body] = server.bodies() + assert body['logprobs'] is True + assert body['top_logprobs'] == 2 + + _REASONING_CONFIG = {'reasoning_effort': 'high'} @@ -646,8 +691,6 @@ async def test_mistral_drops_openai_only_settings(mistral: Genkit, server: _Serv async def test_mistral_sends_the_settings_it_declares(mistral: Genkit, server: _Server) -> None: """Settings Mistral declares under the same name go out as given.""" config = { - 'logprobs': True, - 'top_logprobs': 2, 'service_tier': 'auto', 'prompt_cache_key': 'bakery', 'metadata': {'shop': 'paris'}, @@ -681,14 +724,14 @@ def test_mistral_chat_body_keeps_only_declared_fields_and_extra() -> None: 'messages': [], 'verbosity': 'low', 'safety_identifier': 'user-1', - 'logprobs': True, + 'n': 1, 'extra_body': {'user': 'u', 'min_tokens': 3}, }) assert out == { 'model': 'mistral-small-latest', 'messages': [], - 'logprobs': True, + 'n': 1, 'extra_body': {'user': 'u', 'min_tokens': 3}, } From bdca0b718ea37ce2a3b297c3e2bdd239763b55db Mon Sep 17 00:00:00 2001 From: Adesina H Date: Fri, 20 Nov 2026 11:46:40 +0000 Subject: [PATCH 22/22] fix(py/openai): keep json_object for Mistral ids outside the catalog An uncatalogued Mistral id, including one found via /models, got output=['text'], so generate(output_format='json') with no schema went out as response_format text. List json in the unknown-model supports so it sends json_object, as OpenAIModel does for unlisted ids. --- .../src/genkit_openai/_models/_mistral.py | 10 ++++--- packages/genkit-openai/tests/mistral_test.py | 26 ++++++++++++++++++- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py index fb9510062..a7c991157 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -124,14 +124,16 @@ ) # A model outside the catalog with no /models capabilities to go by: text in, -# text out, as JS's and Dart's unknown-model info. +# text out, as JS's and Dart's unknown-model info. ``output`` lists ``json`` so +# a schema-less JSON request still goes out as ``json_object``, as it did before +# the Mistral target (``OpenAIModel`` keeps it for unlisted ids, for fine-tunes). MISTRAL_UNKNOWN_MODEL_SUPPORTS = ModelSupports( multiturn=True, media=False, tools=False, tool_choice=False, system_role=True, - output=['text'], + output=['json', 'text'], ) # The chat models a Mistral target registers at init, the set JS's @@ -162,8 +164,8 @@ def mistral_model_supports(name: str, capabilities: Mapping[str, object] | None The catalog's entry when ``name`` is in it; else read from the ``/models`` entry's ``capabilities`` (``function_calling`` for tools, ``vision`` for - media), with text-only output since capabilities don't say whether the - model takes a JSON schema; else :data:`MISTRAL_UNKNOWN_MODEL_SUPPORTS`. + media), with ``json`` and ``text`` output (capabilities don't say whether the + model takes a JSON schema, so ``constrained`` stays unset); else :data:`MISTRAL_UNKNOWN_MODEL_SUPPORTS`. """ if (known := SUPPORTED_MISTRAL_MODELS.get(name)) is not None and known.supports is not None: return known.supports diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py index 9c7ce0114..c7b90874f 100644 --- a/packages/genkit-openai/tests/mistral_test.py +++ b/packages/genkit-openai/tests/mistral_test.py @@ -642,6 +642,30 @@ async def test_mistral_output_schema_goes_out_as_json_schema(mistral: Genkit, se assert set(body['response_format']['json_schema']['schema']['properties']) == {'name', 'grams'} +@pytest.mark.asyncio +async def test_mistral_unknown_id_json_without_schema_is_json_object(mistral: Genkit, server: _Server) -> None: + """An id outside the catalog keeps `json_object` for schema-less JSON, not `text`.""" + await mistral.generate(model='mistral/devstral-medium-latest', prompt='Reply in JSON.', output_format='json') + + [body] = server.bodies() + assert body['response_format'] == {'type': 'json_object'} + + +@pytest.mark.asyncio +async def test_mistral_listed_unknown_id_json_without_schema_is_json_object(server: _Server) -> None: + """An id found only through /models keeps `json_object` for schema-less JSON.""" + server.models = [_entry('devstral-medium-latest', completion_chat=True, function_calling=True)] + plugin = _plugin(server, Mistral) + [action] = [a for a in await plugin.list_actions() if a.kind == ActionKind.MODEL] + assert _supports(action)['output'] == ['json', 'text'] + ai = Genkit(plugins=[plugin]) + + await ai.generate(model='mistral/devstral-medium-latest', prompt='Reply in JSON.', output_format='json') + + [body] = [json.loads(r.content) for r in server.requests if r.method == 'POST'] + assert body['response_format'] == {'type': 'json_object'} + + @pytest.mark.asyncio async def test_mistral_image_input_goes_out_as_image_url(mistral: Genkit, server: _Server) -> None: """An image part reaches Mistral as an `image_url` content block.""" @@ -1479,7 +1503,7 @@ async def test_mistral_lists_models_by_capabilities(server: _Server) -> None: assert _supports(by_name['mistral/codestral-2508'])['media'] is False assert _supports(by_name['mistral/pixtral-next'])['tools'] is False assert _supports(by_name['mistral/pixtral-next'])['media'] is True - assert _supports(by_name['mistral/pixtral-next'])['output'] == ['text'] + assert _supports(by_name['mistral/pixtral-next'])['output'] == ['json', 'text'] # A catalog model keeps its catalog info. assert _supports(by_name['mistral/mistral-small-latest'])['output'] == ['json', 'text'] # A listed model resolves with the info it was listed with.