diff --git a/packages/genkit-openai/README.md b/packages/genkit-openai/README.md index d562d3a3..484889ef 100644 --- a/packages/genkit-openai/README.md +++ b/packages/genkit-openai/README.md @@ -55,6 +55,102 @@ OpenAI( ) ``` +## Mistral + +`Mistral()` registers Mistral's models and embedders under `mistral/`, as the +JS and Dart SDKs do, so it can sit beside `OpenAI()`: + +```python +from genkit import Genkit +from genkit_openai import Mistral, OpenAI + +# The Mistral key comes from MISTRAL_API_KEY, the OpenAI one from OPENAI_API_KEY. +ai = Genkit(plugins=[OpenAI(), Mistral()]) + +res = await ai.generate( + model=Mistral.model('mistral-small-latest'), # or 'mistral/mistral-small-latest' + prompt='Suggest 2 names for a French bakery.', + config={'temperature': 0.3, 'seed': 42, 'max_output_tokens': 200}, +) + +embeddings = await ai.embed(embedder='mistral/mistral-embed', content='croissant') +``` + +`Mistral()` is `OpenAI(provider='mistral')`. `OpenAI(base_url=...)` with one of +Mistral's hosts (`OPENAI_BASE_URL` too) is the same plugin, also named +`mistral`. Its key comes from `api_key=` or `MISTRAL_API_KEY`, never +`OPENAI_API_KEY`. The EU and US endpoints, `https://api.eu.mistral.ai/v1` and +`https://api.us.mistral.ai/v1`, work the same way. + +At startup it registers Mistral's own catalog, not OpenAI's: +`mistral-large-latest`, `mistral-large-4`, `mistral-small-latest`, +`ministral-14b-latest`, `ministral-8b-latest`, `ministral-3b-latest`, +`codestral-latest` and `mistral-medium-latest` (deprecated by Mistral), and +the `mistral-embed` (1024 dimensions) and `codestral-embed` (1536) embedders. +The Dev UI's model list comes from Mistral's `/models`, read by each entry's +`capabilities`: ids with `embed` are embedders, entries with `completion_chat` +are chat models, and OCR, moderation, transcription and speech models are left +out. A model outside the catalog takes tool and image support from +`function_calling` and `vision`. Any other id still resolves as a chat model +when named, e.g. `mistral/magistral-medium-latest`. + +A gateway in front of Mistral on another host needs `Mistral(base_url=...)` +(or `provider='mistral'`); without it the plugin can't tell the API behind it +is Mistral's and sends OpenAI's field names, which Mistral rejects. Pass the +gateway's own key as `api_key=`, or the plugin reads `MISTRAL_API_KEY`: + +```python +Mistral(base_url='https://llm-gateway.example.com/v1', api_key=gateway_key) +``` + +`Mistral()` with no `base_url` goes to `https://api.mistral.ai/v1`; +`OPENAI_BASE_URL` isn't read then. + +Mistral rejects any request field it doesn't declare, so with a Mistral host +(or `provider='mistral'`) the plugin sends Mistral's names for the settings +that differ: + +- `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` is refused before the request goes out: Mistral's models reject + `top_k` sampling. So are `logprobs=True` and any `top_logprobs`: Mistral's + models answer "Logprobs are not enabled for this model". `logprobs=False` + is left out of the request. +- `reasoning_effort` also takes `'max'`, which Mistral's API declares and + OpenAI's doesn't; other targets refuse it before the request goes out. + Which values a model accepts varies: Mistral Small takes `none` and `high`, + Mistral Large `low`, `medium` and `high`. +- Streaming sends no `stream_options`; Mistral reports usage on the last chunk + without it. +- An embedder's `dimensions` goes out as `output_dimension`. +- Media other than images, such as a PDF, is refused before the request goes + out: every media part goes out as `image_url`. The type comes from the part's + `content_type`, else a `data:` URL's header; a remote URL with neither is + sent as an image. +- OpenAI-only settings Mistral doesn't declare are left out of the request, + with a warning in the log: `verbosity`, `safety_identifier`, `store`, + `logit_bias`, `prompt_cache_retention`, `web_search_options`, `modalities` + and `audio`. Mistral would fail the call with a 422 naming them. + `service_tier`, `prompt_cache_key`, `metadata`, `prediction` and + `parallel_tool_calls` are Mistral fields too and go out as given + (`service_tier` takes only `auto` or `standard_only`). +- `extra` gets the same renames: `seed` and `max_completion_tokens` there go + out as `random_seed` and `max_tokens`, and `stream_options` is dropped. + Nothing else in `extra` is dropped. + +With `reasoning_effort` set, replies carry their reasoning in `thinking` +chunks. Each comes back as its own reasoning part, in the order it came among +the text, with its own signature in `metadata['thoughtSignature']`; a streamed +reply's final message keeps the same order and joins each chunk's fragments +back into one part, ending a part at the fragment that carries a signature. On the next turn each part goes back to Mistral as its own +`thinking` chunk, in order, as Mistral asks, so a signature stays with the text +it signs. Only reasoning that came from Mistral goes back: each such part is +marked `metadata['reasoningSource'] == 'mistral'`, which survives saving the +history as JSON. Reasoning another model left in a mixed history is dropped. + +Mistral-only fields like `min_tokens` go in `extra`. + ## Config `config` takes the settings `OpenAIConfig` declares. Any other key raises diff --git a/packages/genkit-openai/src/genkit_openai/__init__.py b/packages/genkit-openai/src/genkit_openai/__init__.py index 2d2964d8..e15180d4 100644 --- a/packages/genkit-openai/src/genkit_openai/__init__.py +++ b/packages/genkit-openai/src/genkit_openai/__init__.py @@ -20,6 +20,8 @@ Registers OpenAI chat, image, text-to-speech, transcription, and embedding models under ``openai/``, using the official OpenAI Python SDK. ``base_url=`` points it at any OpenAI-compatible server, such as Azure OpenAI or Together AI. +``Mistral()`` (or ``OpenAI(provider='mistral')``) registers Mistral's chat +models and embedders under ``mistral/``. Example: ```python @@ -48,7 +50,8 @@ async def main() -> None: ``` Credentials: - The plugin key comes from ``api_key=`` or ``OPENAI_API_KEY``. A + The plugin key comes from ``api_key=`` or ``OPENAI_API_KEY`` + (``MISTRAL_API_KEY`` when the target is Mistral). A ``generate()`` or ``embed()`` call can bring its own key as ``context={'secrets': {'api_key': ...}}``; a plugin with no key of its own serves only those calls. @@ -57,7 +60,7 @@ async def main() -> None: - OpenAI documentation: https://platform.openai.com/docs/ """ -from ._openai_plugin import OpenAI +from ._openai_plugin import Mistral, OpenAI from ._typing import OpenAIConfig -__all__ = ['OpenAI', 'OpenAIConfig'] +__all__ = ['Mistral', 'OpenAI', 'OpenAIConfig'] diff --git a/packages/genkit-openai/src/genkit_openai/_models/_mistral.py b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py new file mode 100644 index 00000000..a7c99115 --- /dev/null +++ b/packages/genkit-openai/src/genkit_openai/_models/_mistral.py @@ -0,0 +1,317 @@ +# 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. + +``Mistral()`` (``OpenAI(provider='mistral')``, or ``OpenAI`` with a Mistral +``base_url``) talks to Mistral. Its chat and embeddings endpoints take the +OpenAI shape with a few fields renamed or missing, and reject any field they +don't declare, so a body built for OpenAI fails with a 422. The plugin +renames the fields that differ and leaves out the OpenAI-only ones. This +module also holds the catalog and ``/models`` reading a Mistral target uses. + +The target is read from the client's base URL, not the model id as DeepSeek's +JSON handling is, or set with ``OpenAI(provider='mistral')`` for a gateway in +front of Mistral on another host. Mistral's ids share no prefix (``mistral-``, ``magistral-``, +``codestral-``, ``pixtral-``, ...), and the same ids are served through other +OpenAI-compatible hosts that take OpenAI's names: Vertex Model Garden reuses +``OpenAIModel`` for ``mistralai/...`` models with a Vertex client, so it never +matches here. + +Source: https://docs.mistral.ai/openapi.yaml (``ChatCompletionRequest``, +``EmbeddingRequest``). +""" + +from collections.abc import Mapping +from typing import Any, cast + +import httpx +from genkit_openai._models._utils import parse_data_uri_content_type +from openai import AsyncOpenAI + +from genkit import GenkitError, Message, get_logger +from genkit.model import ConstrainedSupport, ModelInfo, ModelStage, ModelSupports + +logger = get_logger(__name__) + +# 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'}) + + +# Where OpenAI(provider='mistral') sends calls when no base_url is given, as +# JS's and Dart's mistral() do. +MISTRAL_BASE_URL = 'https://api.mistral.ai/v1' + +# The key Mistral's own SDKs, and Genkit's JS and Dart plugins, read. +MISTRAL_API_KEY_ENV = 'MISTRAL_API_KEY' + +# The plugin namespace for a Mistral target, as in JS and Dart: mistral/. +MISTRAL_NAMESPACE = 'mistral' + +# The top-level fields Mistral's ChatCompletionRequest declares +# (https://docs.mistral.ai/openapi.yaml). Its schema is closed: anything else +# is a 422 "Extra inputs are not permitted". ``extra_body`` is the SDK's +# passthrough, not a wire field, and is kept. +MISTRAL_CHAT_FIELDS = frozenset({ + 'model', + 'messages', + 'temperature', + 'top_p', + 'max_tokens', + 'stream', + 'stop', + 'random_seed', + 'metadata', + 'response_format', + 'tools', + 'tool_choice', + 'presence_penalty', + 'frequency_penalty', + 'min_tokens', + 'repetition_penalty', + 'top_k', + 'logprobs', + 'top_logprobs', + 'prompt_logprobs', + 'top_prompt_logprobs', + 'n', + 'prediction', + 'parallel_tool_calls', + 'reasoning_effort', + 'prompt_mode', + 'guardrails', + 'prompt_cache_key', + 'service_tier', + 'safe_prompt', +}) + +# Chat models with vision, tools and structured output (JS's +# MISTRAL_MODEL_INFO, Dart's multimodalSupports). +_MISTRAL_MULTIMODAL_SUPPORTS = ModelSupports( + multiturn=True, + media=True, + tools=True, + tool_choice=True, + system_role=True, + output=['json', 'text'], + constrained=ConstrainedSupport.ALL, +) + +# Codestral: the same without image input. +_MISTRAL_TEXT_SUPPORTS = ModelSupports( + multiturn=True, + media=False, + tools=True, + tool_choice=True, + system_role=True, + output=['json', 'text'], + constrained=ConstrainedSupport.ALL, +) + +# A model outside the catalog with no /models capabilities to go by: text in, +# text out, as JS's and Dart's unknown-model info. ``output`` lists ``json`` so +# a schema-less JSON request still goes out as ``json_object``, as it did before +# the Mistral target (``OpenAIModel`` keeps it for unlisted ids, for fine-tunes). +MISTRAL_UNKNOWN_MODEL_SUPPORTS = ModelSupports( + multiturn=True, + media=False, + tools=False, + tool_choice=False, + system_role=True, + output=['json', 'text'], +) + +# The chat models a Mistral target registers at init, the set JS's +# SUPPORTED_MISTRAL_MODELS and Dart's KnownMistralModel register. +SUPPORTED_MISTRAL_MODELS: dict[str, ModelInfo] = { + 'mistral-large-latest': ModelInfo(label='Mistral Large', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'mistral-large-4': ModelInfo(label='Mistral Large 4', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'mistral-small-latest': ModelInfo(label='Mistral Small', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'ministral-14b-latest': ModelInfo(label='Ministral 14B', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'ministral-8b-latest': ModelInfo(label='Ministral 8B', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'ministral-3b-latest': ModelInfo(label='Ministral 3B', supports=_MISTRAL_MULTIMODAL_SUPPORTS), + 'codestral-latest': ModelInfo(label='Codestral', supports=_MISTRAL_TEXT_SUPPORTS), + # Mistral Medium 3.5, which Mistral has deprecated (retiring 2027-04-30). + 'mistral-medium-latest': ModelInfo( + label='Mistral Medium', supports=_MISTRAL_MULTIMODAL_SUPPORTS, stage=ModelStage.LEGACY + ), +} + +# The embedders a Mistral target registers at init. +SUPPORTED_MISTRAL_EMBEDDERS: dict[str, dict[str, Any]] = { + 'mistral-embed': {'label': 'Mistral Embed', 'dimensions': 1024, 'supports': {'input': ['text']}}, + 'codestral-embed': {'label': 'Codestral Embed', 'dimensions': 1536, 'supports': {'input': ['text']}}, +} + + +def mistral_model_supports(name: str, capabilities: Mapping[str, object] | None = None) -> ModelSupports: + """What a Mistral chat model supports. + + The catalog's entry when ``name`` is in it; else read from the ``/models`` + entry's ``capabilities`` (``function_calling`` for tools, ``vision`` for + media), with ``json`` and ``text`` output (capabilities don't say whether the + model takes a JSON schema, so ``constrained`` stays unset); else :data:`MISTRAL_UNKNOWN_MODEL_SUPPORTS`. + """ + if (known := SUPPORTED_MISTRAL_MODELS.get(name)) is not None and known.supports is not None: + return known.supports + if capabilities is None: + return MISTRAL_UNKNOWN_MODEL_SUPPORTS + tools = capabilities.get('function_calling') is True + return MISTRAL_UNKNOWN_MODEL_SUPPORTS.model_copy( + update={'tools': tools, 'tool_choice': tools, 'media': capabilities.get('vision') is True} + ) + + +def listed_capabilities(entry: object) -> Mapping[str, object] | None: + """The ``capabilities`` object of a Mistral ``/models`` entry, or None when it has none. + + It is a Mistral field, not part of OpenAI's ``Model``; the SDK keeps it in + ``model_extra``. + """ + extra = getattr(entry, 'model_extra', None) or {} + capabilities = extra.get('capabilities') if isinstance(extra, Mapping) else None + return cast(Mapping[str, object], capabilities) if isinstance(capabilities, Mapping) else None + + +def mistral_serves_chat(model_id: str, capabilities: Mapping[str, object] | None) -> bool: + """Whether a ``/models`` entry is a chat model, from ``capabilities.completion_chat``. + + That leaves out OCR, moderation, transcription and speech models. An + entry with no ``capabilities`` counts as chat unless its id names OCR, + which ``/v1/ocr`` serves, as Dart's plugin does. + """ + if capabilities is None: + return 'ocr' not in model_id.lower() + return capabilities.get('completion_chat') is True + + +def is_mistral_url(url: str | httpx.URL) -> bool: + """Whether ``url`` is on one of Mistral's API hosts.""" + return httpx.URL(str(url)).host in MISTRAL_HOSTS + + +def is_mistral(client: AsyncOpenAI) -> bool: + """Whether ``client`` sends its requests to one of Mistral's API hosts.""" + return is_mistral_url(client.base_url) + + +def _rename(body: dict[str, Any], old: str, new: str) -> None: + """Move ``body[old]`` to ``body[new]``, unless ``new`` is already set there.""" + if old in body: + value = body.pop(old) + body.setdefault(new, value) + + +def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict[str, Any]: + """Rewrite ``chat.completions.create()`` kwargs into a body Mistral accepts. + + - ``stream_options`` is dropped. Mistral reports usage on the last + streamed chunk without being asked, so it isn't needed. + - ``max_completion_tokens`` goes out as ``max_tokens``, Mistral's only + reply cap, including when ``reasoning_effort`` is set. + - ``seed`` goes out as ``random_seed``. + - ``top_k`` is refused. Mistral's schema declares it, but its models + answer "top_k sampling is not enabled for this model". + - Any other field Mistral's schema doesn't declare is dropped, as Dart's + ``mistralChatBody`` drops ``user`` and ``verbosity``: OpenAI-only + settings such as ``verbosity``, ``safety_identifier``, ``store``, + ``logit_bias``, ``prompt_cache_retention``, ``web_search_options``, + ``modalities`` and ``audio`` would otherwise fail the call with a 422. + - ``logprobs=True`` and any ``top_logprobs`` are refused, as in JS: + Mistral's schema declares them, but its models answer "Logprobs are not + enabled for this model". ``logprobs=False`` is left out. + + The SDK has no ``random_seed`` kwarg, so it rides in ``extra_body``; the + same key in the caller's ``extra`` wins, as every ``extra`` key does. + ``extra`` gets the same renames: its ``seed``, ``max_completion_tokens`` + and ``stream_options`` would otherwise reach Mistral as given and fail + with a 422. Where ``extra`` has both names, Mistral's wins. Nothing else + in ``extra`` is dropped: it is sent as the caller wrote it. + + Args: + body: The kwargs the plugin built for OpenAI. Not modified. + top_k: Genkit's ``top_k`` setting, which the OpenAI kwargs leave out. + + Returns: + A copy with Mistral's field names. + + Raises: + GenkitError: ``INVALID_ARGUMENT`` when ``top_k``, ``logprobs=True`` + or ``top_logprobs`` is set. + """ + if top_k is not None: + raise GenkitError( + status='INVALID_ARGUMENT', + message="Mistral doesn't support top_k: its models reject top_k sampling. Remove top_k from the config.", + ) + # top_logprobs=0 is still a request for logprobs; only logprobs=False isn't. + asked = [('logprobs', body.get('logprobs') is True), ('top_logprobs', body.get('top_logprobs') is not None)] + for field, set_ in asked: + if set_: + raise GenkitError( + status='INVALID_ARGUMENT', + message=( + f"Mistral doesn't support {field}: its models answer 'Logprobs are not enabled for this model'. " + f'Remove {field} from the config.' + ), + ) + out = dict(body) + out.pop('logprobs', None) + out.pop('top_logprobs', None) + out.pop('stream_options', None) + if 'max_completion_tokens' in out: + out['max_tokens'] = out.pop('max_completion_tokens') + renamed: dict[str, Any] = {} + if 'seed' in out: + renamed['random_seed'] = out.pop('seed') + if dropped := sorted(k for k in out if k not in MISTRAL_CHAT_FIELDS and k != 'extra_body'): + logger.warning('Mistral does not define these OpenAI settings; not sending them', fields=dropped) + for key in dropped: + del out[key] + extra = dict(out.pop('extra_body', None) or {}) + extra.pop('stream_options', None) + _rename(extra, 'max_completion_tokens', 'max_tokens') + _rename(extra, 'seed', 'random_seed') + if renamed or extra: + out['extra_body'] = {**renamed, **extra} + return out + + +def refuse_non_image_media(messages: list[Message]) -> None: + """Refuse media Mistral's chat endpoint can't take as an image. + + Every media part goes out as an ``image_url`` chunk, so a PDF or audio + clip would reach Mistral as a broken image and fail there. The type is the + part's ``content_type``, else the one a ``data:`` URL declares; a remote + URL with neither is sent as is, since only the host knows what it serves. + + Raises: + GenkitError: ``INVALID_ARGUMENT`` naming the first non-image type. + """ + for message in messages: + for part in message.content: + media = part.media + if media is None: + continue + declared = media.content_type or parse_data_uri_content_type(media.url) + content_type = declared.split(';', 1)[0].strip().lower() + if content_type and not content_type.startswith('image/'): + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'Mistral only supports image media in chat requests, got {content_type}.', + ) diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index ec00050c..80b6d4d3 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, refuse_non_image_media from genkit_openai._models._utils import ( OPENAI_CALL_ERRORS, DictMessageAdapter, @@ -27,10 +28,12 @@ MessageConverter, check_extra_body, extract_response_metadata, + merge_streamed_reasoning, + reply_content, reraise_openai_error, strip_markdown_fences, ) -from genkit_openai._typing import OpenAIConfig +from genkit_openai._typing import OpenAIConfig, ReasoningEffort from openai import AsyncOpenAI from openai.lib._pydantic import _ensure_strict_json_schema from openai.types import CompletionUsage @@ -93,7 +96,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 +214,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, @@ -350,7 +356,14 @@ def _unwrap_tool_inputs(message: Message, wrapped: frozenset[str]) -> Message: class OpenAIModel: """Handles OpenAI API interactions for the Genkit plugin.""" - def __init__(self, model: str, client: AsyncOpenAI, *, supports: ModelSupports | None = None) -> None: + def __init__( + self, + model: str, + client: AsyncOpenAI, + *, + supports: ModelSupports | None = None, + mistral: bool | None = None, + ) -> None: """Initializes the OpenAIModel instance with the specified model and OpenAI client parameters. Args: @@ -360,10 +373,13 @@ def __init__(self, model: str, client: AsyncOpenAI, *, supports: ModelSupports | ``supports.output`` means the endpoint accepts schema-less JSON mode. ``None`` (or an entry that omits ``output``) still sends ``json_object`` so a fine-tune keeps working. + mistral: Send Mistral's field names (see ``_mistral.py``). + ``None`` decides from the client's host. """ self._model = model self._openai_client = client self._supports = supports + self._mistral = is_mistral(client) if mistral is None else mistral @property def name(self) -> str: @@ -383,9 +399,11 @@ def _get_messages(self, messages: list[Message]) -> list[dict]: Raises: ValueError: If no messages are provided in the request. """ + if self._mistral: + refuse_non_image_media(messages) openai_messages = [] for message in messages: - openai_messages.extend(MessageConverter.to_openai(message=message)) + 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]: @@ -577,14 +595,26 @@ 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.reasoning_effort == ReasoningEffort.MAX and not self._mistral: + raise GenkitError( + status='INVALID_ARGUMENT', + message=( + "reasoning_effort='max' is Mistral's; OpenAI's API stops at 'xhigh'. For another host " + "that takes it, pass extra={'reasoning_effort': 'max'}." + ), + ) if config.version: openai_config['model'] = config.version effective_model = config.model or config.version or self._model 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: @@ -634,7 +664,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) @@ -652,17 +685,23 @@ 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) tool_calls: dict[int, Any] = {} wrapped = _wrapped_tool_names(request.tools) - reasoning_parts: list[Part] = [] - text_parts: list[Part] = [] + # As a full reply is read (MessageConverter.to_genkit): reasoning from + # its own field (DeepSeek's reasoning_content) first, then the + # content's reasoning and text in the order they arrived (Mistral's + # thinking chunks can come between text chunks), then tool calls. + field_reasoning: list[Part] = [] + content_parts: list[Part] = [] metadata: dict[str, Any] = {} usage: CompletionUsage | None = None saw_choice = False @@ -695,14 +734,14 @@ async def _generate_stream( # Reasoning content (DeepSeek R1 / reasoner models). if reasoning_text := MessageAdapter(delta).reasoning_content: reasoning_part = Part.from_reasoning(reasoning_text) - reasoning_parts.append(reasoning_part) + field_reasoning.append(reasoning_part) parts.append(reasoning_part) - # Text content - if delta.content: - text_part = MessageConverter.text_part_to_genkit(delta.content) - text_parts.append(text_part) - parts.append(text_part) + # Text content; Mistral's reasoning models stream reasoning in it too. + for item in reply_content(delta.content): + part = MessageConverter.text_part_to_genkit(item) if isinstance(item, str) else item + content_parts.append(part) + parts.append(part) # Tool calls (partial function calls) if delta.tool_calls: @@ -747,7 +786,7 @@ async def _generate_stream( ) ) - accumulated_content: list[Part] = [*reasoning_parts, *text_parts] + accumulated_content: list[Part] = [*field_reasoning, *merge_streamed_reasoning(content_parts)] if tool_calls: message = _unwrap_tool_inputs( MessageConverter.to_genkit(DictMessageAdapter({'tool_calls': tool_calls.values(), 'role': Role.MODEL})), @@ -802,8 +841,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 2587b5a2..e1769445 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,149 @@ 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' + +# Marks a reasoning part read from a Mistral thinking chunk, so only those go +# back to Mistral: a history can hold reasoning from other models, whose text +# and signatures Mistral can't use. Part metadata, unlike the response that +# carried it, stays with the part through a JSON round trip of the history. +REASONING_SOURCE = 'reasoningSource' +MISTRAL_SOURCE = 'mistral' + + +def _mistral_reasoning(text: str, signature: str | None) -> Part: + metadata: dict[str, Any] = {REASONING_SOURCE: MISTRAL_SOURCE} + if signature is not None: + metadata[THOUGHT_SIGNATURE] = signature + return Part.from_reasoning(text, metadata=metadata) + + +def _is_mistral_reasoning(part: Part) -> bool: + return part.reasoning is not None and (part.metadata or {}).get(REASONING_SOURCE) == MISTRAL_SOURCE + + +def _signature(part: Part) -> str | None: + value = (part.metadata or {}).get(THOUGHT_SIGNATURE) + return value if isinstance(value, str) and value else None + + +def reply_content(content: object) -> list[Part | str]: + """The reasoning and the text in a reply's ``content``, in the order they came. + + OpenAI sends ``content`` as a string. Mistral sends a list of chunks + instead when it reasons (``reasoning_effort`` set), in full replies and in + streamed deltas alike: ``{'type': 'text', 'text': ...}`` for the answer and + ``{'type': 'thinking', 'thinking': [{'type': 'text', 'text': ...}], + 'signature': ...}`` for reasoning. Other chunk types carry no text and are + skipped. + + Args: + content: A message's or delta's ``content`` as the SDK parsed it. + + Returns: + In chunk order: one reasoning part per thinking chunk with text or a + signature, each marked ``metadata['reasoningSource'] = 'mistral'`` and + holding its own chunk's signature in ``metadata['thoughtSignature']``; + and the text, one string per run of adjacent text chunks. Empty text is + left out, so a plain empty string gives an empty list. + """ + if isinstance(content, str): + return [content] if content else [] + if not isinstance(content, list): + return [] + out: list[Part | str] = [] + for chunk in cast(list[object], content): + if not isinstance(chunk, Mapping): + continue + chunk = cast(Mapping[str, object], chunk) + if chunk.get('type') == 'text' and isinstance(chunk.get('text'), str): + text = cast(str, chunk['text']) + if not text: + continue + if out and isinstance(out[-1], str): + out[-1] += text + else: + out.append(text) + elif chunk.get('type') == 'thinking' and isinstance(chunk.get('thinking'), list): + signature = chunk.get('signature') + signature = signature if isinstance(signature, str) and signature else None + thought: list[str] = [] + for item in cast(list[object], chunk['thinking']): + if isinstance(item, Mapping): + item = cast(Mapping[str, object], item) + if item.get('type') == 'text' and isinstance(item.get('text'), str): + thought.append(cast(str, item['text'])) + if thought or signature is not None: + out.append(_mistral_reasoning(''.join(thought), signature)) + return out + + +def merge_streamed_reasoning(parts: list[Part]) -> list[Part]: + """Join a stream's Mistral reasoning fragments back into one part per thinking chunk. + + A streamed thinking chunk arrives in many deltas, each read as its own + reasoning part, and its signature, if any, rides on its last fragment. + Replayed one part per fragment, the signature would be paired with a + piece of the text it signs. Runs of adjacent Mistral reasoning parts are + joined into one, and a fragment carrying a signature closes its part: the + next fragment starts a new one, so two signed thinking chunks stay two + parts, each with its own signature, as in a non-streamed reply. Other + parts are kept as they are. + """ + merged: list[Part] = [] + run: list[Part] = [] + + def flush(signature: str | None = None) -> None: + if run: + merged.append(_mistral_reasoning(''.join(p.reasoning or '' for p in run), signature)) + run.clear() + + for part in parts: + if _is_mistral_reasoning(part): + run.append(part) + if (signature := _signature(part)) is not None: + flush(signature) + continue + flush() + merged.append(part) + flush() + return merged + + +def thinking_chunks(parts: list[Part]) -> list[dict[str, Any]]: + """Mistral ``thinking`` chunks replaying a model message's reasoning parts. + + Mistral asks for the whole assistant message, reasoning included, on later + turns; stripping it degrades the answer. Each reasoning part goes back as + its own chunk, in order, with its own signature, so a signature is never + paired with text it didn't sign. Only parts read from Mistral's thinking + chunks (marked ``reasoningSource: 'mistral'``) go back; reasoning another + model left in the history is dropped, as it is for OpenAI. A part with + neither text nor a signature has nothing to send and is skipped. + + Args: + parts: The message's parts. + + Returns: + The chunks, empty when the message has no Mistral reasoning. + """ + chunks: list[dict[str, Any]] = [] + for part in parts: + if not _is_mistral_reasoning(part): + continue + text = part.reasoning or '' + signature = _signature(part) + if not text and signature is None: + continue + chunk: dict[str, Any] = {'type': 'thinking', 'thinking': [{'type': 'text', 'text': text}]} + if signature is not None: + chunk['signature'] = signature + chunks.append(chunk) + return chunks + + class DictMessageAdapter: """Adapter for dictionary-based chat message objects with OpenAI-compatible fields.""" @@ -549,7 +692,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 +704,10 @@ def to_openai(cls, message: Message) -> list[dict]: Args: message: The internal `Message` instance. + replay_thinking: Send a model message's Mistral reasoning back as + leading ``thinking`` chunks in its content, one per reasoning + part. Off, reasoning is dropped, which is what OpenAI and + DeepSeek need. Returns: A list of OpenAI-compatible message dictionaries. @@ -571,9 +718,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,14 +774,36 @@ 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 thinking chunks, at the front of its first assistant message.""" + chunks = thinking_chunks(message.content) + if not chunks: + return + role = cls._get_openai_role(message.role) + target = next((m for m in result if m.get('role') == role), None) + if target is None: + result.insert(0, {'role': role, 'content': chunks}) + return + content = target.get('content') + if isinstance(content, str): + target['content'] = [*chunks, {'type': 'text', 'text': content}] + elif isinstance(content, list): + target['content'] = [*chunks, *content] + else: + target['content'] = chunks + @classmethod def to_genkit(cls, message: ChatCompletionMessageAdapter) -> Message: """Converts an OpenAI-style message into a Genkit `Message` object. - Emits a reasoning part, a text part, and one tool request part per - tool call, in that order, for whichever of them the message carries. + Emits a reasoning part, the content's reasoning and text parts in the + order they came, and one tool request part per tool call, in that + order, for whichever of them the message carries. Args: message: A ChatCompletionMessageAdapter instance. @@ -650,8 +818,8 @@ 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)) + for item in reply_content(message.content): + content.append(cls.text_part_to_genkit(item) if isinstance(item, str) else item) for tool_call in message.tool_calls or []: content.append(cls.tool_call_to_genkit(tool_call, args_parser=json.loads)) diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index 396fd345..cedf24d0 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -65,6 +65,18 @@ OpenAIGptImageConfig, OpenAIImageModel, ) +from genkit_openai._models._mistral import ( + MISTRAL_API_KEY_ENV, + MISTRAL_BASE_URL, + MISTRAL_NAMESPACE, + SUPPORTED_MISTRAL_EMBEDDERS, + SUPPORTED_MISTRAL_MODELS, + is_mistral, + is_mistral_url, + listed_capabilities, + mistral_model_supports, + mistral_serves_chat, +) from genkit_openai._models._model import OpenAIModel from genkit_openai._models._model_info import ( SUPPORTED_EMBEDDING_MODELS, @@ -108,11 +120,18 @@ def _client_kwargs( return options -def _missing_key_error() -> GenkitError: +def _missing_key_error(env: str) -> GenkitError: + # A Mistral target used to fall back to OPENAI_API_KEY; say why a key + # that is set there no longer counts. + ignored = ( + f"{env} is not set; OPENAI_API_KEY is set but isn't used for Mistral. " + if env == MISTRAL_API_KEY_ENV and os.environ.get('OPENAI_API_KEY') + else '' + ) return GenkitError( status='FAILED_PRECONDITION', message=( - 'OpenAI needs an API key: set OPENAI_API_KEY or pass OpenAI(api_key=...), ' + f'{ignored}OpenAI needs an API key: set {env} or pass OpenAI(api_key=...), ' "or send a per-request key as context={'secrets': {'api_key': ...}}." ), ) @@ -277,6 +296,8 @@ class OpenAI(Plugin): interaction with supported OpenAI models. """ + # The class default; an instance that targets Mistral is named 'mistral' + # (see __init__), so OpenAI and Mistral can be registered side by side. name = 'openai' @classmethod @@ -317,34 +338,91 @@ def __init__( api_key: str | None = None, base_url: str | None = None, client_options: Mapping[str, Any] | None = None, + provider: Literal['mistral'] | None = None, ) -> None: """Initializes the OpenAI plugin. Args: - api_key: OpenAI API key. Defaults to ``OPENAI_API_KEY``. + api_key: OpenAI API key. Defaults to ``OPENAI_API_KEY``, or + ``MISTRAL_API_KEY`` when the target is Mistral. base_url: OpenAI API base URL up to and including ``/v1``, e.g. ``https://openrouter.ai/api/v1``; the SDK appends ``/chat/completions``. Defaults to ``OPENAI_BASE_URL``, then the - public API. + public API; with ``provider='mistral'``, ``https://api.mistral.ai/v1`` + (``OPENAI_BASE_URL`` is not read then). client_options: Other ``AsyncOpenAI`` settings, such as ``organization``, ``project``, ``timeout``, ``max_retries``, ``default_headers``, or ``http_client``. + provider: ``'mistral'`` sends Mistral's field names whatever the + host, for a gateway in front of Mistral. Without it they go + out only when ``base_url`` is one of Mistral's own hosts. + Either way, a Mistral target is named ``mistral``: its + actions are ``mistral/``, it registers Mistral's catalog + instead of OpenAI's, and it can sit beside an ``OpenAI()``. + ``Mistral()`` is the same plugin. Raises: TypeError: If ``client_options`` has a key ``AsyncOpenAI`` doesn't take, or repeats ``api_key`` or ``base_url``. + ValueError: If ``provider`` is not ``'mistral'`` or None. """ + if provider not in (None, 'mistral'): + raise ValueError(f"OpenAI got provider={provider!r}; the only provider it knows is 'mistral'") + self._provider = provider options = _client_kwargs(api_key=api_key, base_url=base_url, client_options=client_options) + if provider == 'mistral' and options.get('base_url') is None: + # Else the SDK's default, api.openai.com, would get the Mistral key + # and Mistral's field names. + options['base_url'] = MISTRAL_BASE_URL self._options = options + # Mistral's models live under mistral/, as in JS and Dart, so an + # OpenAI plugin and a Mistral one don't clash. + self.name = MISTRAL_NAMESPACE if self._targets_mistral() else 'openai' self._plugin_api_key: str | None = options.get('api_key') plugin_headers: dict[str, str] = dict(options.get('default_headers') or {}) self._tenant_headers = {k: v for k, v in plugin_headers.items() if k.lower() not in _PLUGIN_ACCOUNT_HEADERS} self._pins_authorization = any(k.lower() == 'authorization' for k in plugin_headers) self._list_actions_cache: list[Action] | None = None + # Supports read from Mistral's /models capabilities, so a listed model + # resolves with the info it was listed with. + self._listed_supports: dict[str, ModelSupports] = {} + + def _action_name(self, name: str) -> str: + """``name`` in this plugin's namespace: ``openai/`` or ``mistral/``.""" + return f'{self.name}/{name}' + + def _mistral_supports(self, name: str) -> ModelSupports: + """Catalog supports for a Mistral model, else what /models listed, else the text-only default.""" + if name in SUPPORTED_MISTRAL_MODELS or name not in self._listed_supports: + return mistral_model_supports(name) + return self._listed_supports[name] + + def _targets_mistral(self) -> bool: + """Whether calls go to Mistral's API: ``provider='mistral'`` or a Mistral base URL.""" + if self._provider == 'mistral': + return True + # The SDK's own fallback when base_url isn't given. + base_url = self._options.get('base_url') or os.environ.get('OPENAI_BASE_URL') + return bool(base_url) and is_mistral_url(base_url) + + def _key_env(self) -> str: + """The variable the plugin key falls back to. Mistral's, so an OpenAI key never goes to Mistral.""" + return MISTRAL_API_KEY_ENV if self._targets_mistral() else 'OPENAI_API_KEY' + + def _uses_mistral_names(self, client: AsyncOpenAI) -> bool: + return self._provider == 'mistral' or is_mistral(client) @loop_local_client def _runtime_client(self) -> AsyncOpenAI: - return AsyncOpenAI(**self._options) + options: dict[str, Any] = self._options + if self._plugin_api_key is None and self._targets_mistral(): + # Otherwise the SDK reads OPENAI_API_KEY and sends it to Mistral, + # so an unset MISTRAL_API_KEY must not reach it as api_key=None. + key = os.environ.get(MISTRAL_API_KEY_ENV) + if not key: + raise _missing_key_error(MISTRAL_API_KEY_ENV) + options = {**options, 'api_key': key} + return AsyncOpenAI(**options) @loop_local_client def _tenant_only_client(self) -> AsyncOpenAI: @@ -354,16 +432,22 @@ def _tenant_only_client(self) -> AsyncOpenAI: return AsyncOpenAI(**params) def _has_plugin_key(self) -> bool: - return bool(self._plugin_api_key or os.environ.get('OPENAI_API_KEY')) + return bool(self._plugin_api_key or os.environ.get(self._key_env())) async def init(self) -> list[Action]: """Initialize plugin. Returns: - Actions for built-in OpenAI models, embedders, image, TTS, and STT. + Actions for built-in OpenAI models, embedders, image, TTS, and STT; + for a Mistral target, Mistral's chat models and embedders instead. """ actions = [] + if self._targets_mistral(): + actions.extend(self._create_model_action(name) for name in SUPPORTED_MISTRAL_MODELS) + actions.extend(self._create_embedder_action(name) for name in SUPPORTED_MISTRAL_EMBEDDERS) + return actions + # Add known chat models. for name in SUPPORTED_OPENAI_MODELS: actions.append(self._create_model_action(name)) @@ -398,6 +482,12 @@ def get_model_info(self, name: str) -> dict[str, Any] | None: is provided). The 'supports' key contains a dictionary representing the model's capabilities (e.g., tools, streaming). """ + if self._targets_mistral(): + known = SUPPORTED_MISTRAL_MODELS.get(name) + return { + 'label': known.label if known is not None else f'Mistral - {name}', + 'supports': self._mistral_supports(name).model_dump(by_alias=True, exclude_none=True), + } if model_supported := SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)): supports = ( model_supported.supports.model_dump(by_alias=True, exclude_none=True) @@ -421,14 +511,23 @@ async def resolve(self, action_type: ActionKind, name: str) -> Action | None: Uses name-based pattern matching (mirroring JS implementation) to route to the correct model type: image, TTS, STT, embedder, or chat. + A Mistral target serves only chat models and embedders, so an id is + never routed to OpenAI's image or audio endpoints there. Args: action_type: The kind of action to resolve. - name: The id without the ``openai/`` prefix. + name: The id without the plugin's ``openai/`` or ``mistral/`` prefix. Returns: Action object if found, None otherwise. """ + if self._targets_mistral(): + if action_type == ActionKind.EMBEDDER: + return self._create_embedder_action(name) + if action_type == ActionKind.MODEL: + return self._create_model_action(name) + return None + if action_type == ActionKind.EMBEDDER: if _classify_model(name) != _ModelType.EMBEDDER: return None @@ -461,7 +560,7 @@ def _client_for_context(self, context: dict[str, Any]) -> AsyncOpenAI: client = self._runtime_client() return self._with_tenant_key(client, key) if key else client if key is None: - raise _missing_key_error() + raise _missing_key_error(self._key_env()) return self._with_tenant_key(self._tenant_only_client(), key) def _with_tenant_key(self, client: AsyncOpenAI, key: str) -> AsyncOpenAI: @@ -506,13 +605,19 @@ def _create_model_action(self, name: str) -> Action: model_info = self.get_model_info(name) or {} async def _generate(request: ModelRequest[OpenAIConfig], ctx: ModelContext) -> ModelResponse: - catalog = SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)) - supports = catalog.supports if catalog is not None else get_default_openai_model_info(name).supports - openai_model = OpenAIModelHandler(OpenAIModel(name, self._client_for_call(request, ctx), supports=supports)) + if self._targets_mistral(): + supports = self._mistral_supports(name) + else: + catalog = SUPPORTED_OPENAI_MODELS.get(cast(KnownGpt, name)) + supports = catalog.supports if catalog is not None else get_default_openai_model_info(name).supports + client = self._client_for_call(request, ctx) + openai_model = OpenAIModelHandler( + OpenAIModel(name, client, supports=supports, mistral=self._uses_mistral_names(client)) + ) return await openai_model.generate(request, ctx) return Model( - open_ai_name(name), + self._action_name(name), _generate, config_schema=OpenAIConfig, metadata={'model': model_info}, @@ -543,7 +648,7 @@ async def _generate(request: ModelRequest, ctx: ModelContext) -> ModelResponse: return await model_instance.generate(request, ctx) return Model( - open_ai_name(name), + self._action_name(name), _generate, config_schema=config_schema, info=info, @@ -558,14 +663,20 @@ def _create_embedder_action(self, name: str) -> Action: Returns: Action object for the embedder. """ - embedder_info = SUPPORTED_EMBEDDING_MODELS.get( - name, - { - 'label': f'OpenAI Embedding - {name}', - 'dimensions': 1536, - 'supports': {'input': ['text']}, - }, - ) + if self._targets_mistral(): + # No dimensions for an embedder outside the catalog: Mistral's differ. + embedder_info = SUPPORTED_MISTRAL_EMBEDDERS.get( + name, {'label': f'Mistral Embedding - {name}', 'supports': {'input': ['text']}} + ) + else: + embedder_info = SUPPORTED_EMBEDDING_MODELS.get( + name, + { + 'label': f'OpenAI Embedding - {name}', + 'dimensions': 1536, + 'supports': {'input': ['text']}, + }, + ) async def embed_fn(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: """Embedder function that calls OpenAI embeddings API.""" @@ -594,33 +705,21 @@ async def embed_fn(request: EmbedRequest, ctx: EmbedContext) -> 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(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 self._uses_mistral_names(client): + # Mistral names it output_dimension and rejects dimensions. + # The SDK has no output_dimension kwarg, so it rides in extra_body. + create_kwargs['extra_body'] = {'output_dimension': dimensions} else: - 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) @@ -629,7 +728,7 @@ async def embed_fn(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: return EmbedResponse(embeddings=embeddings) return Embedder( - open_ai_name(name), + self._action_name(name), embed_fn, info=EmbedderInfo( label=embedder_info['label'], @@ -643,6 +742,11 @@ async def list_actions(self) -> list[Action]: Uses pattern matching on model names (mirroring the JS implementation) to categorize models as embedders, image generators, TTS, STT, or chat. + A Mistral target reads each entry's ``capabilities`` instead, as the JS + and Dart plugins do: ids with ``embed`` are embedders, entries with + ``completion_chat`` are chat models with tools and media from + ``function_calling`` and ``vision``, and the rest (OCR, moderation, + transcription, speech) are skipped. Returns: list[Action]: A list of Action objects. Empty for a @@ -660,6 +764,10 @@ async def list_actions(self) -> list[Action]: except APIError as e: reraise_openai_error(e) models: list[OpenAIModelEntry] = models_.data + if self._targets_mistral(): + actions = self._list_mistral_actions(models) + self._list_actions_cache = actions + return actions for model in models: name = model.id if _is_known_unsupported(name): @@ -675,5 +783,74 @@ async def list_actions(self) -> list[Action]: self._list_actions_cache = actions return actions + def _list_mistral_actions(self, models: list[OpenAIModelEntry]) -> list[Action]: + """Actions for the entries of Mistral's ``/models``, by their ``capabilities``.""" + actions: list[Action] = [] + for model in models: + name = model.id + if 'embed' in name: + actions.append(self._create_embedder_action(name)) + continue + capabilities = listed_capabilities(model) + if not mistral_serves_chat(name, capabilities): + continue + if capabilities is not None and name not in SUPPORTED_MISTRAL_MODELS: + self._listed_supports[name] = mistral_model_supports(name, capabilities) + actions.append(self._create_model_action(name)) + return actions + + +class Mistral(OpenAI): + """Mistral's models through its OpenAI-compatible API, under ``mistral/``. + + The same as ``OpenAI(provider='mistral')``: ``mistral/`` names, as in + the JS and Dart plugins, Mistral's catalog, the key from ``api_key=`` or + ``MISTRAL_API_KEY``, and ``https://api.mistral.ai/v1`` unless ``base_url`` + names another host, such as a gateway in front of Mistral. + + Example: + ```python + ai = Genkit(plugins=[OpenAI(), Mistral()]) + res = await ai.generate(model=Mistral.model('mistral-small-latest'), prompt='Name a bakery.') + ``` + """ + + name = MISTRAL_NAMESPACE + + def __init__( + self, + *, + api_key: str | None = None, + base_url: str | None = None, + client_options: Mapping[str, Any] | None = None, + ) -> None: + """Initializes the Mistral plugin. + + Args: + api_key: Mistral API key. Defaults to ``MISTRAL_API_KEY``. + base_url: API base URL up to and including ``/v1``. Defaults to + ``https://api.mistral.ai/v1``. + client_options: Other ``AsyncOpenAI`` settings, as for ``OpenAI``. + """ + super().__init__(api_key=api_key, base_url=base_url, client_options=client_options, provider='mistral') + + @classmethod + def model(cls, name: str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]: + """Typed ref for a Mistral chat model, e.g. ``Mistral.model('mistral-small-latest')``.""" + if not isinstance(name, str): + raise GenkitError(status='INVALID_ARGUMENT', message='Mistral.model: model name must be a string.') + local = name.removeprefix(f'{MISTRAL_NAMESPACE}/') + if not local: + raise GenkitError(status='INVALID_ARGUMENT', message='Mistral.model: model name is required.') + return ModelRef(name=f'{MISTRAL_NAMESPACE}/{local}', config_schema=OpenAIConfig, config=config) + + @classmethod + def gpt(cls, name: KnownGpt | str, *, config: OpenAIConfig | None = None) -> ModelRef[OpenAIConfig]: + """Not for Mistral: refs from it name OpenAI's models. Use :meth:`model`.""" + raise GenkitError( + status='INVALID_ARGUMENT', + message=f"Mistral.gpt names OpenAI's models; use Mistral.model({name!r}) for mistral/{name}.", + ) + -__all__ = ['OpenAI'] +__all__ = ['Mistral', 'OpenAI'] diff --git a/packages/genkit-openai/src/genkit_openai/_typing.py b/packages/genkit-openai/src/genkit_openai/_typing.py index 24c9e477..e70608f8 100644 --- a/packages/genkit-openai/src/genkit_openai/_typing.py +++ b/packages/genkit-openai/src/genkit_openai/_typing.py @@ -53,6 +53,9 @@ class ReasoningEffort(StrEnum): MEDIUM = 'medium' HIGH = 'high' XHIGH = 'xhigh' + # Mistral only (its ReasoningEffort has it; OpenAI's doesn't). Refused + # before the request for any other target. + MAX = 'max' class Verbosity(StrEnum): @@ -149,7 +152,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 +197,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 +206,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 00000000..c7b90874 --- /dev/null +++ b/packages/genkit-openai/tests/mistral_test.py @@ -0,0 +1,1542 @@ +# 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, Literal, cast + +import httpx +import pytest +from genkit_openai import Mistral, OpenAI, OpenAIConfig +from genkit_openai._models._mistral import MISTRAL_CHAT_FIELDS, mistral_chat_body +from pydantic import BaseModel + +from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role +from genkit.plugin_api import Action, ActionKind + +MISTRAL_URL = 'https://api.mistral.ai/v1' +CODESTRAL_URL = 'https://codestral.mistral.ai/v1' +# A gateway that forwards to Mistral, so the fake enforces Mistral's schema on it too. +GATEWAY_URL = 'https://llm-gateway.example.com/v1' +PLUGIN_KEY = 'mistral-key' + +# The fields Mistral's ChatCompletionRequest and EmbeddingRequest declare +# (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', + 'llm-gateway.example.com', +}) +# Chunk types a message's content list may hold, and the keys a thinking chunk +# may carry (ContentChunk and ThinkChunk in the mistralai SDK). +_CHUNK_TYPES = frozenset({ + '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, content: Any = None) -> dict[str, Any]: # noqa: ANN401 + # With reasoning_effort set, Mistral puts the reasoning in a thinking chunk + # ahead of the answer, in a content list. + if content is None and body.get('reasoning_effort'): + content = [_thinking(REASONING, signature=SIGNATURE), {'type': 'text', 'text': 'bonjour'}] + elif content is None: + content = 'bonjour' + return { + 'id': 'cmpl-1', + 'object': 'chat.completion', + '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], deltas: list[Any] | None = None) -> bytes: + # Mistral sends usage on the last chunk, beside finish_reason, without stream_options. + # With reasoning_effort set, deltas go: a list with a thinking chunk, a list + # with the closing thinking chunk and the first text chunk, then strings. + if deltas is None and not body.get('reasoning_effort'): + deltas = ['bon', 'jour'] + elif deltas is None: + deltas = [ + [_thinking('Two loaves,')], + [_thinking(' one each.', signature=SIGNATURE), {'type': 'text', 'text': 'bon'}], + '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' + # Replaces the reply's content, or the streamed deltas, when set. + self.content: Any = None + self.deltas: list[Any] | None = None + # GET /models answers with these entries. + self.models: list[dict[str, Any]] = [] + + def handler(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + if request.method == 'GET' and request.url.path.endswith('/models'): + return httpx.Response(200, json={'object': 'list', 'data': self.models}) + body = json.loads(request.content) + embeddings = request.url.path.endswith('/embeddings') + if request.url.host in _MISTRAL_HOSTS: + 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'): + stream = _stream_body(body, self.deltas) + return httpx.Response(200, content=stream, headers={'content-type': 'text/event-stream'}) + return httpx.Response(200, json=_completion(body, self.finish_reason, self.content)) + + def bodies(self) -> list[dict[str, Any]]: + return [json.loads(r.content) for r in self.requests] + + +@pytest.fixture +def server() -> _Server: + return _Server() + + +def _ai( + server: _Server, + base_url: str | None, + *, + api_key: str | None = PLUGIN_KEY, + provider: Literal['mistral'] | None = None, +) -> Genkit: + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return Genkit( + plugins=[ + OpenAI( + api_key=api_key, + base_url=base_url, + client_options={'http_client': http_client, 'max_retries': 0}, + provider=provider, + ) + ] + ) + + +@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='mistral/mistral-small-latest')` posts to Mistral's chat endpoint with the plugin's key.""" + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut') + + assert response.text == 'bonjour' + [request] = server.requests + 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='mistral/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='mistral/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='mistral/mistral-small-latest', prompt='salut', config=config) + + [body] = server.bodies() + caps_sent = {k: body[k] for k in ('max_tokens', 'max_completion_tokens') if k in body} + 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='mistral/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='mistral/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='mistral/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='mistral/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='mistral/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='mistral/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='mistral/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='mistral/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_refuses_top_k(mistral: Genkit, server: _Server) -> None: + """`config={'top_k': 5}` fails the turn before the request goes out: Mistral's models reject `top_k`.""" + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config={'top_k': 5}) + + assert response.finish_reason == FinishReason.FAILED + assert 'top_k' in str(response.error) + assert server.bodies() == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('config', 'field'), + [ + ({'logprobs': True}, 'logprobs'), + ({'top_logprobs': 2}, 'top_logprobs'), + ({'top_logprobs': 0}, 'top_logprobs'), + ({'logprobs': True, 'top_logprobs': 2}, 'logprobs'), + ], +) +async def test_mistral_refuses_logprobs(mistral: Genkit, server: _Server, config: dict[str, Any], field: str) -> None: + """`logprobs=True` or any `top_logprobs` fails before the request: Mistral's models don't enable logprobs.""" + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + assert response.finish_reason == FinishReason.FAILED + assert field in str(response.error) + assert 'INVALID_ARGUMENT' in str(response.error) + assert server.bodies() == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +async def test_mistral_leaves_out_logprobs_false(mistral: Genkit, server: _Server, streamed: bool) -> None: + """`logprobs=False` asks for nothing, so it isn't sent.""" + config = {'logprobs': False} + if streamed: + await mistral.generate_stream(model='mistral/mistral-small-latest', prompt='salut', config=config).response + else: + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + [body] = server.bodies() + assert 'logprobs' not in body + assert 'top_logprobs' not in body + + +@pytest.mark.asyncio +async def test_openai_host_keeps_logprobs(openai: Genkit, server: _Server) -> None: + """OpenAI still gets logprobs and top_logprobs.""" + await openai.generate(model='openai/gpt-4o', prompt='hi', config={'logprobs': True, 'top_logprobs': 2}) + + [body] = server.bodies() + assert body['logprobs'] is True + assert body['top_logprobs'] == 2 + + +_REASONING_CONFIG = {'reasoning_effort': 'high'} + + +@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='mistral/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 == {'reasoningSource': 'mistral', '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='mistral/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='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + first = await stream.response + else: + first = await mistral.generate( + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + + second = await mistral.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') + + assert second.finish_reason == FinishReason.STOP + body = server.bodies()[-1] + [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='mistral/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='mistral/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='mistral/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='mistral/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_unknown_id_json_without_schema_is_json_object(mistral: Genkit, server: _Server) -> None: + """An id outside the catalog keeps `json_object` for schema-less JSON, not `text`.""" + await mistral.generate(model='mistral/devstral-medium-latest', prompt='Reply in JSON.', output_format='json') + + [body] = server.bodies() + assert body['response_format'] == {'type': 'json_object'} + + +@pytest.mark.asyncio +async def test_mistral_listed_unknown_id_json_without_schema_is_json_object(server: _Server) -> None: + """An id found only through /models keeps `json_object` for schema-less JSON.""" + server.models = [_entry('devstral-medium-latest', completion_chat=True, function_calling=True)] + plugin = _plugin(server, Mistral) + [action] = [a for a in await plugin.list_actions() if a.kind == ActionKind.MODEL] + assert _supports(action)['output'] == ['json', 'text'] + ai = Genkit(plugins=[plugin]) + + await ai.generate(model='mistral/devstral-medium-latest', prompt='Reply in JSON.', output_format='json') + + [body] = [json.loads(r.content) for r in server.requests if r.method == 'POST'] + assert body['response_format'] == {'type': 'json_object'} + + +@pytest.mark.asyncio +async def test_mistral_image_input_goes_out_as_image_url(mistral: Genkit, server: _Server) -> None: + """An image part reaches Mistral as an `image_url` content block.""" + await mistral.generate( + model='mistral/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 + + +# OpenAI settings Mistral's chat schema doesn't declare; each was checked +# live against api.mistral.ai, which answers it with a 422. +_OPENAI_ONLY_SETTINGS = { + 'verbosity': 'low', + 'safety_identifier': 'user-1', + 'store': False, + 'logit_bias': {'1': 1}, + 'prompt_cache_retention': '24h', + 'web_search_options': {}, + 'modalities': ['text'], + 'audio': {'voice': 'alloy', 'format': 'mp3'}, +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.parametrize('field', sorted(_OPENAI_ONLY_SETTINGS)) +async def test_mistral_drops_openai_only_settings(mistral: Genkit, server: _Server, field: str, streamed: bool) -> None: + """An OpenAI-only setting such as `verbosity` is left out, so Mistral answers instead of failing with a 422.""" + config = {field: _OPENAI_ONLY_SETTINGS[field]} + if streamed: + response = await mistral.generate_stream( + model='mistral/mistral-small-latest', prompt='salut', config=config + ).response + else: + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + assert field not in body + + +@pytest.mark.asyncio +async def test_mistral_sends_the_settings_it_declares(mistral: Genkit, server: _Server) -> None: + """Settings Mistral declares under the same name go out as given.""" + config = { + 'service_tier': 'auto', + 'prompt_cache_key': 'bakery', + 'metadata': {'shop': 'paris'}, + 'prediction': {'type': 'content', 'content': 'bonjour'}, + 'parallel_tool_calls': False, + 'n': 1, + 'frequency_penalty': 0.1, + 'presence_penalty': 0.2, + } + + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + [body] = server.bodies() + assert {k: body[k] for k in config} == config + + +@pytest.mark.asyncio +async def test_openai_host_keeps_openai_only_settings(openai: Genkit, server: _Server) -> None: + """OpenAI's own settings still go out to OpenAI.""" + await openai.generate(model='openai/gpt-4o', prompt='hi', config={'verbosity': 'low', 'store': True}) + + [body] = server.bodies() + assert body['verbosity'] == 'low' + assert body['store'] is True + + +def test_mistral_chat_body_keeps_only_declared_fields_and_extra() -> None: + """`mistral_chat_body` drops top-level fields Mistral doesn't declare but sends `extra` as written.""" + out = mistral_chat_body({ + 'model': 'mistral-small-latest', + 'messages': [], + 'verbosity': 'low', + 'safety_identifier': 'user-1', + 'n': 1, + 'extra_body': {'user': 'u', 'min_tokens': 3}, + }) + + assert out == { + 'model': 'mistral-small-latest', + 'messages': [], + 'n': 1, + 'extra_body': {'user': 'u', 'min_tokens': 3}, + } + + +def test_mistral_chat_fields_match_the_fake_servers_schema() -> None: + """The plugin's allowlist is Mistral's ChatCompletionRequest, the schema the fake enforces.""" + assert MISTRAL_CHAT_FIELDS == _CHAT_FIELDS + + +@pytest.mark.asyncio +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='mistral/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) + + assert body == before + assert out == { + 'model': 'mistral-small-latest', + 'max_tokens': 50, + 'extra_body': {'random_seed': 7, 'min_tokens': 5}, + } + + +def _mistral_reasoning(text: str, signature: str | None = SIGNATURE) -> Part: + """A reasoning part as the plugin reads it from a Mistral thinking chunk.""" + metadata: dict[str, Any] = {'reasoningSource': 'mistral'} + if signature is not None: + metadata['thoughtSignature'] = signature + return Part.from_reasoning(text, metadata=metadata) + + +def _assistant_messages(body: dict[str, Any]) -> list[dict[str, Any]]: + return [m for m in body['messages'] if m['role'] == 'assistant'] + + +@pytest.mark.asyncio +async def test_mistral_replays_only_mistral_reasoning_from_a_mixed_history(mistral: Genkit, server: _Server) -> None: + """Reasoning another model left in the history, signed or not, is not sent to Mistral; Mistral's own is.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + # A Gemini or Claude turn: its reasoning carries a signature under the same key. + Message( + role=Role.MODEL, + content=[ + Part.from_reasoning('Gemini thinks.', metadata={'thoughtSignature': 'gemini-sig'}), + Part.from_text('Two loaves.'), + ], + ), + Message(role=Role.USER, content=[Part.from_text('And three?')]), + Message(role=Role.MODEL, content=[Part.from_reasoning('Unsigned, unmarked.'), Part.from_text('Three.')]), + Message(role=Role.USER, content=[Part.from_text('And four?')]), + Message(role=Role.MODEL, content=[_mistral_reasoning(REASONING), Part.from_text('Four.')]), + ] + + response = await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And five?') + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + gemini, unmarked, own = _assistant_messages(body) + assert gemini['content'] == 'Two loaves.' + assert unmarked['content'] == 'Three.' + assert own['content'] == [ + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}], 'signature': SIGNATURE}, + {'type': 'text', 'text': 'Four.'}, + ] + + +@pytest.mark.asyncio +async def test_mistral_reasoning_replays_after_a_json_round_trip(mistral: Genkit, server: _Server) -> None: + """A history saved as JSON and loaded back still replays Mistral's reasoning, signature included.""" + first = await mistral.generate( + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + saved = json.dumps([m.model_dump(mode='json', by_alias=True, exclude_none=True) for m in first.messages]) + history = [Message.model_validate(m) for m in json.loads(saved)] + + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And three?') + + [assistant] = _assistant_messages(server.bodies()[-1]) + assert assistant['content'][0] == { + 'type': 'thinking', + 'thinking': [{'type': 'text', 'text': REASONING}], + 'signature': SIGNATURE, + } + + +@pytest.mark.asyncio +async def test_mistral_replays_reasoning_onto_a_tool_call_message_with_no_content( + mistral: Genkit, server: _Server +) -> None: + """A turn with reasoning and only tool calls goes back as one assistant message: thinking chunk and calls.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Is the baguette in stock?')]), + Message( + role=Role.MODEL, + content=[ + _mistral_reasoning(REASONING), + Part.from_tool_request(name='lookup_menu', input={'dish': 'baguette'}, ref='call-1'), + ], + ), + Message( + role=Role.TOOL, + content=[Part.from_tool_response(name='lookup_menu', output='baguette: in stock', ref='call-1')], + ), + ] + + response = await mistral.generate(model='mistral/mistral-small-latest', messages=history) + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + [assistant] = _assistant_messages(body) + assert assistant['content'] == [ + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}], 'signature': SIGNATURE} + ] + assert [c['id'] for c in assistant['tool_calls']] == ['call-1'] + + +@pytest.mark.asyncio +async def test_mistral_replays_a_reasoning_only_turn(mistral: Genkit, server: _Server) -> None: + """A turn that is only reasoning goes back as an assistant message holding just the thinking chunk.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message(role=Role.MODEL, content=[_mistral_reasoning(REASONING, signature=None)]), + ] + + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='Well?') + + [assistant] = _assistant_messages(server.bodies()[0]) + assert assistant['content'] == [{'type': 'thinking', 'thinking': [{'type': 'text', 'text': REASONING}]}] + + +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.asyncio +async def test_openai_host_reads_list_content(openai: Genkit, server: _Server, streamed: bool) -> None: + """A non-Mistral host that answers with a list of text chunks gives back their text, with no reasoning part.""" + server.content = [{'type': 'text', 'text': 'bon'}, {'type': 'text', 'text': 'jour'}] + server.deltas = [[{'type': 'text', 'text': 'bon'}], 'jour'] + + if streamed: + stream = openai.generate_stream(model='openai/gpt-4o', prompt='hi') + chunks = [chunk.text async for chunk in stream.stream] + response = await stream.response + assert chunks == ['bon', 'jour'] + else: + response = await openai.generate(model='openai/gpt-4o', prompt='hi') + + assert response.text == 'bonjour' + assert response.message is not None + assert [p for p in response.message.content if p.reasoning is not None] == [] + + +@pytest.mark.parametrize('streamed', [False, True], ids=['generate', 'stream']) +@pytest.mark.asyncio +async def test_mistral_renames_openai_fields_in_extra(mistral: Genkit, server: _Server, streamed: bool) -> None: + """`extra` with `seed`, `max_completion_tokens` or `stream_options` goes out under Mistral's names, not as a 422.""" + config = {'extra': {'seed': 1, 'max_completion_tokens': 50, 'stream_options': {'include_usage': True}}} + if streamed: + stream = mistral.generate_stream(model='mistral/mistral-small-latest', prompt='salut', config=config) + response = await stream.response + else: + response = await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config=config) + + assert response.finish_reason == FinishReason.STOP + [body] = server.bodies() + assert body['random_seed'] == 1 + assert body['max_tokens'] == 50 + assert not {'seed', 'max_completion_tokens', 'stream_options'} & set(body) + + +def test_mistral_chat_body_prefers_mistral_names_in_extra() -> None: + """With both names in `extra`, Mistral's own one is kept; `extra` still beats the config's `seed`.""" + out = mistral_chat_body({ + 'seed': 7, + 'extra_body': {'seed': 1, 'random_seed': 2, 'max_completion_tokens': 50, 'max_tokens': 60}, + }) + + assert out == {'extra_body': {'random_seed': 2, 'max_tokens': 60}} + + +@pytest.mark.asyncio +async def test_provider_mistral_sends_mistral_names_through_a_gateway(server: _Server) -> None: + """`OpenAI(base_url=, provider='mistral')` sends Mistral's names to a host that isn't Mistral's.""" + ai = _ai(server, GATEWAY_URL, provider='mistral') + + stream = ai.generate_stream( + model='mistral/mistral-small-latest', prompt='Bread for two?', config={'seed': 7, **_REASONING_CONFIG} + ) + first = await stream.response + await ai.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') + await ai.embed(embedder='mistral/mistral-embed', content='croissant', config={'dimensions': 256}) + + streamed, replay, embed = server.requests + assert {r.url.host for r in server.requests} == {'llm-gateway.example.com'} + streamed_body = json.loads(streamed.content) + assert 'stream_options' not in streamed_body + assert streamed_body['random_seed'] == 7 + [assistant] = _assistant_messages(json.loads(replay.content)) + assert assistant['content'][0]['type'] == 'thinking' + assert json.loads(embed.content)['output_dimension'] == 256 + + +@pytest.mark.asyncio +async def test_gateway_without_provider_keeps_openai_names(server: _Server) -> None: + """Without `provider='mistral'` a gateway host gets OpenAI's names (and the fake Mistral behind it 422s).""" + ai = _ai(server, GATEWAY_URL) + + response = await ai.generate(model='openai/mistral-small-latest', prompt='salut', config={'seed': 7}) + + assert response.finish_reason == FinishReason.FAILED + assert server.bodies()[0]['seed'] == 7 + + +def test_unknown_provider_is_refused() -> None: + """`provider=` takes only `'mistral'`.""" + with pytest.raises(ValueError, match='mistral'): + OpenAI(api_key=PLUGIN_KEY, provider=cast(Any, 'cohere')) + + +@pytest.mark.parametrize( + ('base_url', 'provider'), + [ + pytest.param(MISTRAL_URL, None, id='mistral-host'), + pytest.param(GATEWAY_URL, 'mistral', id='provider'), + ], +) +@pytest.mark.asyncio +async def test_mistral_without_api_key_uses_mistral_api_key_env( + server: _Server, monkeypatch: pytest.MonkeyPatch, base_url: str, provider: Literal['mistral'] | None +) -> None: + """With no `api_key=`, a Mistral target sends MISTRAL_API_KEY, never OPENAI_API_KEY.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai') + monkeypatch.setenv('MISTRAL_API_KEY', 'mistral-env') + ai = _ai(server, base_url, api_key=None, provider=provider) + + await ai.generate(model='mistral/mistral-small-latest', prompt='salut') + await ai.embed(embedder='mistral/mistral-embed', content='croissant') + + assert [r.headers['authorization'] for r in server.requests] == ['Bearer mistral-env'] * 2 + + +@pytest.mark.asyncio +async def test_mistral_explicit_api_key_beats_mistral_api_key_env( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """`api_key=` wins over MISTRAL_API_KEY.""" + monkeypatch.setenv('MISTRAL_API_KEY', 'mistral-env') + ai = _ai(server, MISTRAL_URL) + + await ai.generate(model='mistral/mistral-small-latest', prompt='salut') + + assert server.requests[0].headers['authorization'] == f'Bearer {PLUGIN_KEY}' + + +@pytest.mark.asyncio +async def test_mistral_without_any_key_does_not_send_openai_api_key( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """With only OPENAI_API_KEY set, a Mistral call fails naming MISTRAL_API_KEY and sends nothing.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai') + monkeypatch.delenv('MISTRAL_API_KEY', raising=False) + ai = _ai(server, MISTRAL_URL, api_key=None) + + response = await ai.generate(model='mistral/mistral-small-latest', prompt='salut') + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'MISTRAL_API_KEY' in str(response.finish_message) + assert "OPENAI_API_KEY is set but isn't used for Mistral" in str(response.finish_message) + assert server.requests == [] + + +def _signed_thinking(text: str, signature: str) -> dict[str, Any]: + return {'type': 'thinking', 'thinking': [{'type': 'text', 'text': text}], 'signature': signature} + + +@pytest.mark.asyncio +async def test_mistral_replays_each_reasoning_part_as_its_own_thinking_chunk(mistral: Genkit, server: _Server) -> None: + """Each Mistral reasoning part goes back as its own chunk with its own signature; others are left out.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message( + role=Role.MODEL, + content=[ + _mistral_reasoning('First, count.', signature='sig-1'), + Part.from_reasoning('Gemini thinks.', metadata={'thoughtSignature': 'gemini-sig'}), + Part.from_reasoning('Unmarked.'), + _mistral_reasoning('', signature=None), + _mistral_reasoning('Unsigned middle.', signature=None), + _mistral_reasoning('Then, answer.', signature='sig-2'), + Part.from_text('Two loaves.'), + ], + ), + ] + + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And three?') + + [assistant] = _assistant_messages(server.bodies()[0]) + assert assistant['content'] == [ + _signed_thinking('First, count.', 'sig-1'), + {'type': 'thinking', 'thinking': [{'type': 'text', 'text': 'Unsigned middle.'}]}, + _signed_thinking('Then, answer.', 'sig-2'), + {'type': 'text', 'text': 'Two loaves.'}, + ] + + +@pytest.mark.asyncio +async def test_mistral_sends_no_thinking_chunk_when_reasoning_parts_are_empty(mistral: Genkit, server: _Server) -> None: + """Mistral reasoning parts with neither text nor a signature leave the turn as plain text.""" + history = [ + Message(role=Role.USER, content=[Part.from_text('Bread for two?')]), + Message(role=Role.MODEL, content=[_mistral_reasoning('', signature=None), Part.from_text('Two loaves.')]), + ] + + await mistral.generate(model='mistral/mistral-small-latest', messages=history, prompt='And three?') + + [assistant] = _assistant_messages(server.bodies()[0]) + assert assistant['content'] == 'Two loaves.' + + +@pytest.mark.asyncio +async def test_mistral_reply_with_two_thinking_chunks_gives_two_reasoning_parts( + mistral: Genkit, server: _Server +) -> None: + """Two thinking chunks in a reply come back as two reasoning parts, each with its own signature, and replay so.""" + server.content = [ + _signed_thinking('First, count.', 'sig-1'), + _signed_thinking('Then, answer.', 'sig-2'), + {'type': 'text', 'text': 'Two loaves.'}, + ] + + first = await mistral.generate(model='mistral/mistral-small-latest', prompt='Bread for two?') + await mistral.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') + + assert first.message is not None + assert [(p.reasoning, p.metadata) for p in first.message.content if p.reasoning is not None] == [ + ('First, count.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}), + ('Then, answer.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}), + ] + [assistant] = _assistant_messages(server.bodies()[-1]) + assert assistant['content'] == server.content + + +@pytest.mark.asyncio +async def test_mistral_stream_joins_a_thinking_chunks_fragments_into_one_part(mistral: Genkit, server: _Server) -> None: + """A streamed thinking chunk's fragments end up as one reasoning part, with the signature, in the final message.""" + stream = mistral.generate_stream( + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + response = await stream.response + + assert response.message is not None + assert [(p.reasoning, p.metadata) for p in response.message.content if p.reasoning is not None] == [ + (REASONING, {'reasoningSource': 'mistral', 'thoughtSignature': SIGNATURE}) + ] + + +@pytest.mark.asyncio +async def test_provider_mistral_without_base_url_goes_to_mistral( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """`OpenAI(provider='mistral')` with no base_url sends to api.mistral.ai, not the SDK's api.openai.com.""" + monkeypatch.setenv('OPENAI_BASE_URL', 'https://api.openai.com/v1') + ai = _ai(server, None, provider='mistral') + + await ai.generate(model='mistral/mistral-small-latest', prompt='salut', config={'seed': 7}) + + [request] = server.requests + assert str(request.url) == f'{MISTRAL_URL}/chat/completions' + assert json.loads(request.content)['random_seed'] == 7 + + +@pytest.mark.asyncio +async def test_provider_mistral_keeps_base_url_from_client_options(server: _Server) -> None: + """A base_url given in client_options still wins over the Mistral default.""" + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + ai = Genkit( + plugins=[ + OpenAI( + api_key=PLUGIN_KEY, + client_options={'http_client': http_client, 'max_retries': 0, 'base_url': GATEWAY_URL}, + provider='mistral', + ) + ] + ) + + await ai.generate(model='mistral/mistral-small-latest', prompt='salut') + + assert server.requests[0].url.host == 'llm-gateway.example.com' + + +@pytest.mark.asyncio +async def test_mistral_missing_key_error_leaves_out_openai_api_key_when_unset( + server: _Server, monkeypatch: pytest.MonkeyPatch +) -> None: + """With neither key set, the error names MISTRAL_API_KEY and says nothing about OPENAI_API_KEY.""" + monkeypatch.delenv('OPENAI_API_KEY', raising=False) + monkeypatch.delenv('MISTRAL_API_KEY', raising=False) + ai = _ai(server, MISTRAL_URL, api_key=None) + + response = await ai.generate(model='mistral/mistral-small-latest', prompt='salut') + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert 'MISTRAL_API_KEY' in str(response.finish_message) + assert 'OPENAI_API_KEY' not in str(response.finish_message) + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_mistral_runtime_client_raises_without_mistral_api_key(monkeypatch: pytest.MonkeyPatch) -> None: + """The Mistral client never falls through to the SDK's OPENAI_API_KEY default, even if called with no key.""" + monkeypatch.setenv('OPENAI_API_KEY', 'sk-openai') + monkeypatch.delenv('MISTRAL_API_KEY', raising=False) + plugin = OpenAI(base_url=MISTRAL_URL) + + with pytest.raises(GenkitError, match='MISTRAL_API_KEY') as excinfo: + plugin._runtime_client() # pyright: ignore[reportPrivateUsage] + + assert excinfo.value.status == 'FAILED_PRECONDITION' + + +@pytest.mark.asyncio +async def test_mistral_stream_keeps_two_signed_thinking_chunks_apart(mistral: Genkit, server: _Server) -> None: + """Two streamed signed thinking chunks end as two reasoning parts, each with its own text and signature.""" + server.deltas = [ + [_thinking('First,')], + [_thinking(' count.', signature='sig-1')], + [_thinking('Then,')], + [_thinking(' answer.', signature='sig-2'), {'type': 'text', 'text': 'Two'}], + ' loaves.', + ] + + stream = mistral.generate_stream( + model='mistral/mistral-small-latest', prompt='Bread for two?', config=_REASONING_CONFIG + ) + first = await stream.response + await mistral.generate(model='mistral/mistral-small-latest', messages=first.messages, prompt='And three?') + + assert first.message is not None + assert [(p.reasoning, p.metadata) for p in first.message.content if p.reasoning is not None] == [ + ('First, count.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}), + ('Then, answer.', {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}), + ] + [assistant] = _assistant_messages(server.bodies()[-1]) + assert assistant['content'] == [ + _signed_thinking('First, count.', 'sig-1'), + _signed_thinking('Then, answer.', 'sig-2'), + {'type': 'text', 'text': 'Two loaves.'}, + ] + + +@pytest.mark.asyncio +async def test_mistral_takes_reasoning_effort_max(mistral: Genkit, server: _Server) -> None: + """`reasoning_effort='max'`, in Mistral's ReasoningEffort, goes out to Mistral as given.""" + await mistral.generate(model='mistral/mistral-small-latest', prompt='salut', config={'reasoning_effort': 'max'}) + + assert server.bodies()[0]['reasoning_effort'] == 'max' + + +@pytest.mark.asyncio +async def test_openai_refuses_reasoning_effort_max(openai: Genkit, server: _Server) -> None: + """Other targets refuse `reasoning_effort='max'` before the request, pointing at `extra`.""" + response = await openai.generate(model='openai/gpt-5', prompt='salut', config={'reasoning_effort': 'max'}) + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert "extra={'reasoning_effort': 'max'}" in str(response.finish_message) + assert server.requests == [] + + +@pytest.mark.asyncio +async def test_openai_reasoning_effort_max_through_extra(openai: Genkit, server: _Server) -> None: + """A non-Mistral host that takes 'max' gets it through `extra`.""" + await openai.generate(model='openai/gpt-5', prompt='salut', config={'extra': {'reasoning_effort': 'max'}}) + + assert server.bodies()[0]['reasoning_effort'] == 'max' + + +@pytest.mark.parametrize( + ('url', 'content_type', 'expected'), + [ + pytest.param('data:application/pdf;base64,JVBERi0xLjQK', 'application/pdf', 'application/pdf', id='inline'), + pytest.param('data:application/pdf;base64,JVBERi0xLjQK', None, 'application/pdf', id='inline-untyped'), + pytest.param('https://example.com/menu.pdf', 'application/pdf', 'application/pdf', id='remote'), + pytest.param('https://example.com/song.mp3', 'audio/mpeg; charset=binary', 'audio/mpeg', id='params'), + ], +) +@pytest.mark.asyncio +async def test_mistral_refuses_non_image_media( + mistral: Genkit, server: _Server, url: str, content_type: str | None, expected: str +) -> None: + """Non-image media fails before the request instead of reaching Mistral as an image_url.""" + response = await mistral.generate( + model='mistral/mistral-small-latest', + prompt=[Part.from_text('Summarize this.'), Part.from_media(url, content_type)], + ) + + assert response.error is not None + assert response.error.status == 'INVALID_ARGUMENT' + assert expected in str(response.finish_message) + assert server.requests == [] + + +@pytest.mark.parametrize( + ('url', 'content_type'), + [ + pytest.param('data:image/png;base64,iVBORw0KGgo=', None, id='inline-untyped'), + pytest.param('https://example.com/loaf', None, id='remote-untyped'), + pytest.param('https://example.com/loaf.jpg', 'IMAGE/JPEG', id='remote-typed'), + ], +) +@pytest.mark.asyncio +async def test_mistral_sends_image_media(mistral: Genkit, server: _Server, url: str, content_type: str | None) -> None: + """Images, and remote URLs whose type isn't known, still go out as image_url.""" + await mistral.generate( + model='mistral/pixtral-large-latest', + prompt=[Part.from_text('What bread is this?'), Part.from_media(url, content_type)], + ) + + [body] = server.bodies() + assert {'type': 'image_url', 'image_url': {'url': url}} in body['messages'][-1]['content'] + + +@pytest.mark.asyncio +async def test_openai_host_still_sends_non_image_media(openai: Genkit, server: _Server) -> None: + """The guard is Mistral's: other hosts get the media part as before.""" + url = 'data:application/pdf;base64,JVBERi0xLjQK' + await openai.generate( + model='openai/gpt-4o', prompt=[Part.from_text('Summarize this.'), Part.from_media(url, 'application/pdf')] + ) + + assert len(server.requests) == 1 + + +# Reply order + + +_INTERLEAVED = [ + _thinking('First, flour.', signature='sig-1'), + {'type': 'text', 'text': 'Flour.'}, + _thinking('Then, water.', signature='sig-2'), + {'type': 'text', 'text': ' Water.'}, +] + + +def _order(message: Message | None) -> list[tuple[str, str]]: + assert message is not None + return [ + ('reasoning', p.reasoning) if p.reasoning is not None else ('text', p.text or '') + for p in message.content + if p.reasoning is not None or p.text is not None + ] + + +@pytest.mark.asyncio +async def test_mistral_keeps_thinking_and_text_in_the_order_they_came(mistral: Genkit, server: _Server) -> None: + """thinking, text, thinking, text stays in that order, streamed or not.""" + server.content = _INTERLEAVED + server.deltas = [[chunk] for chunk in _INTERLEAVED] + expected = [ + ('reasoning', 'First, flour.'), + ('text', 'Flour.'), + ('reasoning', 'Then, water.'), + ('text', ' Water.'), + ] + + full = await mistral.generate(model='mistral/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG) + streamed = await mistral.generate_stream( + model='mistral/mistral-small-latest', prompt='Bread?', config=_REASONING_CONFIG + ).response + + assert _order(full.message) == expected + assert _order(streamed.message) == expected + assert streamed.message is not None + assert [p.metadata for p in streamed.message.content if p.reasoning is not None] == [ + {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-1'}, + {'reasoningSource': 'mistral', 'thoughtSignature': 'sig-2'}, + ] + + +# Namespace and catalog + + +def _plugin(server: _Server, plugin_class: type[OpenAI] = OpenAI, **kwargs: Any) -> OpenAI: # noqa: ANN401 + http_client = httpx.AsyncClient(transport=httpx.MockTransport(server.handler)) + return plugin_class(api_key=PLUGIN_KEY, client_options={'http_client': http_client, 'max_retries': 0}, **kwargs) + + +@pytest.mark.parametrize( + 'kwargs', + [{'provider': 'mistral'}, {'base_url': MISTRAL_URL}, {'base_url': CODESTRAL_URL}], + ids=['provider', 'base_url', 'codestral'], +) +def test_mistral_target_is_named_mistral(server: _Server, kwargs: dict[str, Any]) -> None: + """Any Mistral target is the `mistral` plugin; a plain OpenAI() stays `openai`.""" + assert _plugin(server, **kwargs).name == 'mistral' + assert _plugin(server).name == 'openai' + assert _plugin(server, Mistral).name == 'mistral' + + +@pytest.mark.asyncio +async def test_mistral_init_registers_mistrals_catalog_not_openais(server: _Server) -> None: + """init() on a Mistral target registers Mistral's models and embedders, under mistral/.""" + actions = await _plugin(server, Mistral).init() + + names = {(a.kind, a.name) for a in actions} + assert (ActionKind.MODEL, 'mistral/mistral-small-latest') in names + assert (ActionKind.MODEL, 'mistral/mistral-large-latest') in names + assert (ActionKind.MODEL, 'mistral/codestral-latest') in names + assert (ActionKind.EMBEDDER, 'mistral/mistral-embed') in names + assert (ActionKind.EMBEDDER, 'mistral/codestral-embed') in names + assert all(a.name.startswith('mistral/') for a in actions) + assert not any('gpt' in a.name or 'dall-e' in a.name or 'tts' in a.name for a in actions) + embed = next(a for a in actions if a.name == 'mistral/mistral-embed') + assert embed.metadata is not None + assert cast(dict[str, Any], embed.metadata['embedder'])['dimensions'] == 1024 + codestral = next(a for a in actions if a.name == 'mistral/codestral-latest') + assert codestral.metadata is not None + assert cast(dict[str, Any], codestral.metadata['model'])['supports']['media'] is False + + +@pytest.mark.asyncio +async def test_openai_and_mistral_side_by_side(server: _Server) -> None: + """OpenAI() and OpenAI(provider='mistral') register together, each call going to its own host and names.""" + ai = Genkit(plugins=[_plugin(server), _plugin(server, provider='mistral')]) + + await ai.generate(model='openai/gpt-4o', prompt='hi', config={'seed': 1}) + await ai.generate(model='mistral/mistral-small-latest', prompt='salut', config={'seed': 1}) + + openai_request, mistral_request = server.requests + assert openai_request.url.host == 'api.openai.com' + assert json.loads(openai_request.content)['seed'] == 1 + assert mistral_request.url.host == 'api.mistral.ai' + assert json.loads(mistral_request.content)['random_seed'] == 1 + + +@pytest.mark.asyncio +async def test_openai_and_mistral_list_without_clashing(server: _Server) -> None: + """Both catalogs list, each under its own namespace, with no OpenAI model under mistral/.""" + ai = Genkit(plugins=[_plugin(server), _plugin(server, Mistral)]) + + catalog = await ai._registry.list_actions() + + assert '/model/openai/gpt-4o' in catalog + assert '/embedder/openai/text-embedding-3-small' in catalog + assert '/model/mistral/mistral-small-latest' in catalog + assert '/embedder/mistral/mistral-embed' in catalog + assert not [key for key in catalog if key.startswith('/model/mistral/gpt')] + assert '/model/openai/mistral-small-latest' not in catalog + + +def test_mistral_model_ref() -> None: + """Mistral.model names mistral/, once, and binds OpenAIConfig.""" + ref = Mistral.model('mistral-small-latest', config=OpenAIConfig(temperature=0.2)) + + assert ref.name == 'mistral/mistral-small-latest' + assert Mistral.model('mistral/mistral-small-latest').name == 'mistral/mistral-small-latest' + assert ref.config_schema is OpenAIConfig + with pytest.raises(GenkitError): + Mistral.gpt('gpt-4o') + assert OpenAI.gpt('gpt-4o').name == 'openai/gpt-4o' + + +@pytest.mark.asyncio +async def test_mistral_resolves_any_id_as_chat(server: _Server) -> None: + """On Mistral an id with `tts` in it is a chat model, not OpenAI's speech endpoint.""" + plugin = _plugin(server, Mistral) + + action = await plugin.resolve(ActionKind.MODEL, 'voxtral-mini-tts-latest') + + assert action is not None + assert action.name == 'mistral/voxtral-mini-tts-latest' + assert action.metadata is not None + assert 'media' not in cast(dict[str, Any], action.metadata['model'])['supports'].get('output', []) + + +# Listing + + +def _entry(model_id: str, **capabilities: bool) -> dict[str, Any]: + return { + 'id': model_id, + 'object': 'model', + 'created': 0, + 'owned_by': 'mistralai', + 'capabilities': capabilities, + } + + +_LISTING = [ + _entry('mistral-small-latest', completion_chat=True, function_calling=True, vision=True), + _entry('codestral-2508', completion_chat=True, function_calling=True), + _entry('pixtral-next', completion_chat=True, vision=True), + _entry('voxtral-small-latest', completion_chat=True, function_calling=True, audio=True), + _entry('mistral-embed'), + _entry('codestral-embed-2505'), + _entry('voxtral-mini-tts-latest', function_calling=True, audio_speech=True), + _entry('voxtral-mini-transcribe-3', audio_transcription=True), + _entry('mistral-ocr-latest', function_calling=True, vision=True, ocr=True), + _entry('mistral-moderation-2603', classification=True, moderation=True), +] + + +def _supports(action: Action) -> dict[str, Any]: + assert action.metadata is not None + return cast(dict[str, Any], action.metadata['model'])['supports'] + + +@pytest.mark.asyncio +async def test_mistral_lists_models_by_capabilities(server: _Server) -> None: + """Chat from completion_chat, embedders by id; OCR, moderation, speech and transcription are left out.""" + server.models = _LISTING + plugin = _plugin(server, Mistral) + + actions = await plugin.list_actions() + + assert {(a.kind, a.name) for a in actions} == { + (ActionKind.MODEL, 'mistral/mistral-small-latest'), + (ActionKind.MODEL, 'mistral/codestral-2508'), + (ActionKind.MODEL, 'mistral/pixtral-next'), + (ActionKind.MODEL, 'mistral/voxtral-small-latest'), + (ActionKind.EMBEDDER, 'mistral/mistral-embed'), + (ActionKind.EMBEDDER, 'mistral/codestral-embed-2505'), + } + by_name = {a.name: a for a in actions} + assert _supports(by_name['mistral/codestral-2508'])['tools'] is True + assert _supports(by_name['mistral/codestral-2508'])['media'] is False + assert _supports(by_name['mistral/pixtral-next'])['tools'] is False + assert _supports(by_name['mistral/pixtral-next'])['media'] is True + assert _supports(by_name['mistral/pixtral-next'])['output'] == ['json', 'text'] + # A catalog model keeps its catalog info. + assert _supports(by_name['mistral/mistral-small-latest'])['output'] == ['json', 'text'] + # A listed model resolves with the info it was listed with. + resolved = await plugin.resolve(ActionKind.MODEL, 'codestral-2508') + assert resolved is not None + assert _supports(resolved)['tools'] is True + + +@pytest.mark.asyncio +async def test_mistral_listing_without_capabilities_skips_only_ocr(server: _Server) -> None: + """An entry with no capabilities is a chat model unless its id names OCR, as in Dart.""" + server.models = [ + {'id': 'mistral-next', 'object': 'model', 'created': 0, 'owned_by': 'mistralai'}, + {'id': 'mistral-ocr-next', 'object': 'model', 'created': 0, 'owned_by': 'mistralai'}, + ] + + actions = await _plugin(server, Mistral).list_actions() + + assert [a.name for a in actions] == ['mistral/mistral-next'] + assert _supports(actions[0])['tools'] is False + + +@pytest.mark.asyncio +async def test_openai_listing_still_classifies_by_name(server: _Server) -> None: + """A plain OpenAI() target keeps the name rules: a tts id is a speech model there.""" + server.models = [_entry('gpt-4o'), _entry('tts-1'), _entry('text-embedding-3-small')] + + actions = await _plugin(server).list_actions() + + assert {(a.kind, a.name) for a in actions} == { + (ActionKind.MODEL, 'openai/gpt-4o'), + (ActionKind.MODEL, 'openai/tts-1'), + (ActionKind.EMBEDDER, 'openai/text-embedding-3-small'), + } + tts = next(a for a in actions if a.name == 'openai/tts-1') + assert _supports(tts)['output'] == ['media']