From a1510f85f5636a12200c459a04ad440a0fa7914c Mon Sep 17 00:00:00 2001 From: Adesina H Date: Wed, 11 Nov 2026 19:57:19 +0000 Subject: [PATCH 1/9] 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 2/9] 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 3/9] 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 4/9] 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 5/9] 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 6/9] 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 7/9] 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 8/9] 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 9/9] 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.