diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index d562d3a3b..62b34150e 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -55,6 +55,57 @@ 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') +``` + +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, +`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 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. +- `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`. + +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 `min_tokens` +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 `config` takes the settings `OpenAIConfig` declares. Any other key raises 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..263fde9dd --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -0,0 +1,83 @@ +# 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 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``). +""" + +from typing import Any + +from openai import AsyncOpenAI + +# 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: + """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], *, 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``. + - ``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. + """ + out = dict(body) + 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: + 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 243486df6..e48bf7046 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, @@ -28,6 +29,7 @@ check_extra_body, extract_response_metadata, reraise_openai_error, + split_reply_content, strip_markdown_fences, ) from genkit_openai._typing import OpenAIConfig @@ -93,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: @@ -210,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, @@ -261,6 +266,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: @@ -282,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]: @@ -469,14 +475,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: @@ -526,7 +536,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) @@ -544,10 +557,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, - } + # 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) @@ -589,9 +604,13 @@ 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 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) parts.append(text_part) @@ -674,8 +693,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..d75cfd9f1 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,87 @@ def _extract_media(request: ModelRequest) -> tuple[str, str]: return url, content_type +# 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 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: + 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 None, content + if not isinstance(content, list): + return None, '' + reasoning: list[str] = [] + signature: str | None = None + 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): + 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'])) + 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: """Adapter for dictionary-based chat message objects with OpenAI-compatible fields.""" @@ -549,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. @@ -561,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. @@ -571,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 @@ -628,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. @@ -650,8 +754,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 is not None: + content.append(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 db0fdcf48..d59fa5b3b 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, @@ -593,33 +594,21 @@ async def embed_fn(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedRespons 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(ctx.context) - try: - if 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``. diff --git a/packages/genkit-openai/tests/mistral_test.py b/packages/genkit-openai/tests/mistral_test.py new file mode 100644 index 000000000..7ab98afab --- /dev/null +++ b/packages/genkit-openai/tests/mistral_test.py @@ -0,0 +1,625 @@ +# 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_openai._models._mistral import mistral_chat_body +from pydantic import BaseModel + +from genkit import FinishReason, Genkit, Message, Part, Role + +MISTRAL_URL = 'https://api.mistral.ai/v1' +CODESTRAL_URL = 'https://codestral.mistral.ai/v1' +PLUGIN_KEY = 'mistral-key' + +# 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', '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'}) + +SIGNATURE = 'sig-abc' +REASONING = 'Two loaves, one each.' + + +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(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': 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(body: dict[str, Any]) -> 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'): + 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': 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 + 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}, + } + + +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 and, on Mistral's hosts, enforces its schema.""" + + 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) + body = json.loads(request.content) + 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) + _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), 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] + + +@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/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} + 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': {'min_tokens': 5}}, + ) + + [body] = server.bodies() + assert body['random_seed'] == 7 + assert 'seed' not in body + assert body['temperature'] == 0.2 + assert body['min_tokens'] == 5 + + +@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 + + +@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 + + +_REASONING_CONFIG = {'reasoning_effort': 'high'} + + +@pytest.mark.asyncio +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 + [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_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] == ['', '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 ''.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 +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': {'min_tokens': 5}, + } + 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, 'min_tokens': 5}, + }