Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions packages/genkit-openai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,57 @@ OpenAI(
)
```

## Mistral

Point `base_url` at Mistral's API and pass a Mistral key. Models keep the
`openai/` prefix:

```python
import os

from genkit import Genkit
from genkit_openai import OpenAI

ai = Genkit(
plugins=[OpenAI(api_key=os.environ['MISTRAL_API_KEY'], base_url='https://api.mistral.ai/v1')]
)

res = await ai.generate(
model='openai/mistral-small-latest',
prompt='Suggest 2 names for a French bakery.',
config={'temperature': 0.3, 'seed': 42, 'max_output_tokens': 200},
)

embeddings = await ai.embed(embedder='openai/mistral-embed', content='croissant')
```

Pass `api_key=` explicitly. Without it the plugin falls back to
`OPENAI_API_KEY` and sends that key to Mistral. The EU and US endpoints,
`https://api.eu.mistral.ai/v1` and `https://api.us.mistral.ai/v1`, work the
same way.

Mistral rejects any request field it doesn't declare, so with a Mistral host
the plugin sends Mistral's names for the settings that differ:

- `max_output_tokens` goes out as `max_tokens`, never `max_completion_tokens`,
even with `reasoning_effort` set.
- `seed` goes out as `random_seed`.
- `top_k` goes out as is. Mistral takes it; OpenAI never gets it.
- Streaming sends no `stream_options`; Mistral reports usage on the last chunk.
- An embedder's `dimensions` goes out as `output_dimension`.

With `reasoning_effort` set, replies carry their reasoning in `thinking`
chunks. Those come back as reasoning parts, ahead of the text, streamed or not,
and go back to Mistral as a `thinking` chunk on the next turn, as Mistral asks.

Other OpenAI-only settings, such as `verbosity` or `store`, are sent as given
and Mistral fails the call naming them. Mistral-only fields like `min_tokens`
go in `extra`. A gateway in front of Mistral on any other host gets the OpenAI
field names.

The plugin doesn't know Mistral's embedders, so their info reports the default
1536 dimensions; `mistral-embed` returns 1024.

## Config

`config` takes the settings `OpenAIConfig` declares. Any other key raises
Expand Down
83 changes: 83 additions & 0 deletions packages/genkit-openai/src/genkit_openai/_models/_mistral.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0

"""Request rewrites for Mistral's OpenAI-compatible API.

``OpenAI(base_url='https://api.mistral.ai/v1')`` talks to Mistral. Its chat and
embeddings endpoints take the OpenAI shape with a few fields renamed or
missing, and reject any field they don't declare, so a body built for OpenAI
fails with a 422. The plugin rewrites the few fields that differ; everything
else goes out unchanged.

The target is read from the client's base URL, not the model id as DeepSeek's
JSON handling is. Mistral's ids share no prefix (``mistral-``, ``magistral-``,
``codestral-``, ``pixtral-``, ...), and the same ids are served through other
OpenAI-compatible hosts that take OpenAI's names: Vertex Model Garden reuses
``OpenAIModel`` for ``mistralai/...`` models with a Vertex client, so it never
matches here.

Source: https://docs.mistral.ai/openapi.yaml (``ChatCompletionRequest``,
``EmbeddingRequest``).
"""

from typing import Any

from openai import AsyncOpenAI

# Mistral's API hosts: global, EU and US, the servers in the mistralai SDK's
# sdkconfiguration.py. codestral.mistral.ai, for Codestral-only keys, is not in
# that list or the OpenAPI servers; it is kept since nothing else lives there.
MISTRAL_HOSTS = frozenset({'api.mistral.ai', 'api.eu.mistral.ai', 'api.us.mistral.ai', 'codestral.mistral.ai'})


def is_mistral(client: AsyncOpenAI) -> bool:
"""Whether ``client`` sends its requests to one of Mistral's API hosts."""
return client.base_url.host in MISTRAL_HOSTS


def mistral_chat_body(body: dict[str, Any], *, top_k: int | None = None) -> dict[str, Any]:
"""Rewrite ``chat.completions.create()`` kwargs into a body Mistral accepts.

- ``stream_options`` is dropped. Mistral has no such field; it reports
usage on the last streamed chunk without being asked.
- ``max_completion_tokens`` goes out as ``max_tokens``, Mistral's only
reply cap, including when ``reasoning_effort`` is set.
- ``seed`` goes out as ``random_seed``.
- ``top_k``, which OpenAI has no field for, goes out as is.

The SDK has no ``random_seed`` or ``top_k`` kwarg, so both ride in
``extra_body``; the same key in the caller's ``extra`` wins, as every
``extra`` key does.

Args:
body: The kwargs the plugin built for OpenAI. Not modified.
top_k: Genkit's ``top_k`` setting, which the OpenAI kwargs leave out.

Returns:
A copy with Mistral's field names.
"""
out = dict(body)
out.pop('stream_options', None)
if 'max_completion_tokens' in out:
out['max_tokens'] = out.pop('max_completion_tokens')
renamed: dict[str, Any] = {}
if 'seed' in out:
renamed['random_seed'] = out.pop('seed')
if top_k is not None:
renamed['top_k'] = top_k
if renamed:
out['extra_body'] = {**renamed, **(out.get('extra_body') or {})}
return out
41 changes: 29 additions & 12 deletions packages/genkit-openai/src/genkit_openai/_models/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from collections.abc import Callable
from typing import Any, cast

from genkit_openai._models._mistral import is_mistral, mistral_chat_body
from genkit_openai._models._utils import (
OPENAI_CALL_ERRORS,
DictMessageAdapter,
Expand All @@ -28,6 +29,7 @@
check_extra_body,
extract_response_metadata,
reraise_openai_error,
split_reply_content,
strip_markdown_fences,
)
from genkit_openai._typing import OpenAIConfig
Expand Down Expand Up @@ -93,7 +95,8 @@ def _openai_create_kwargs(*, config: OpenAIConfig, model: str | None = None) ->
the JSON body, so a colliding key wins. ``max_output_tokens`` goes out as
``max_completion_tokens`` for reasoning models (or when
``reasoning_effort`` is set), since the OpenAI API rejects the deprecated
``max_tokens`` there, and as ``max_tokens`` otherwise.
``max_tokens`` there, and as ``max_tokens`` otherwise. ``_mistral.py``
renames the fields Mistral spells differently after this runs.
"""
body: dict[str, Any] = {}
for name in type(config).model_fields:
Expand Down Expand Up @@ -210,6 +213,8 @@ def _failure_message(extras: dict[str, Any] | None) -> str | None:
'insufficient_system_resource': FinishReason.OTHER,
'length': FinishReason.LENGTH,
'model_context_window_exceeded': FinishReason.LENGTH,
# Mistral: the model's own length limit, as opposed to max_tokens.
'model_length': FinishReason.LENGTH,
'network_error': FinishReason.OTHER,
'sensitive': FinishReason.BLOCKED,
'stop': FinishReason.STOP,
Expand Down Expand Up @@ -261,6 +266,7 @@ def __init__(self, model: str, client: AsyncOpenAI, *, supports: ModelSupports |
self._model = model
self._openai_client = client
self._supports = supports
self._mistral = is_mistral(client)

@property
def name(self) -> str:
Expand All @@ -282,7 +288,7 @@ def _get_messages(self, messages: list[Message]) -> list[dict]:
"""
openai_messages = []
for message in messages:
openai_messages.extend(MessageConverter.to_openai(message=message))
openai_messages.extend(MessageConverter.to_openai(message=message, replay_thinking=self._mistral))
return openai_messages

async def _get_tools_definition(self, tools: list[ToolDefinition]) -> list[dict]:
Expand Down Expand Up @@ -469,14 +475,18 @@ async def _get_openai_request_config(self, request: ModelRequest) -> dict:
if response_format:
# pyrefly: ignore[bad-typed-dict-key] - response_format dict is valid for OpenAI API
openai_config['response_format'] = response_format
top_k: int | None = None
if request.config:
config = (
request.config if isinstance(request.config, OpenAIConfig) else self._normalize_config(request.config)
)
top_k = config.top_k
if config.version:
openai_config['model'] = config.version
effective_model = config.model or config.version or self._model
openai_config.update(_openai_create_kwargs(config=config, model=effective_model))
if self._mistral:
openai_config = mistral_chat_body(openai_config, top_k=top_k)
return openai_config

async def _generate(self, request: ModelRequest) -> ModelResponse:
Expand Down Expand Up @@ -526,7 +536,10 @@ async def _generate(self, request: ModelRequest) -> ModelResponse:
finish_message=finish_message,
usage=_usage_from_completion(response.usage),
custom=metadata or None,
raw=response.to_dict(),
# raw is the provider's reply as sent. A list content (Mistral's
# thinking chunks) doesn't fit the SDK's str field, which is not
# worth a serializer warning on every call.
raw=response.to_dict(warnings=False),
)
return self._clean_json_response(result, request)

Expand All @@ -544,10 +557,12 @@ async def _generate_stream(
"""
openai_config = await self._get_openai_request_config(request=request)
openai_config['stream'] = True
openai_config['stream_options'] = {
**(openai_config.get('stream_options') or {}),
'include_usage': True,
}
# Mistral has no stream_options and sends usage unasked.
if not self._mistral:
openai_config['stream_options'] = {
**(openai_config.get('stream_options') or {}),
'include_usage': True,
}

stream = await self._openai_client.chat.completions.create(**openai_config)

Expand Down Expand Up @@ -589,9 +604,13 @@ async def _generate_stream(
reasoning_parts.append(reasoning_part)
parts.append(reasoning_part)

# Text content
if delta.content:
text_part = MessageConverter.text_part_to_genkit(delta.content)
# Text content; Mistral's reasoning models stream reasoning in it too.
thinking, text = split_reply_content(delta.content)
if thinking is not None:
reasoning_parts.append(thinking)
parts.append(thinking)
if text:
text_part = MessageConverter.text_part_to_genkit(text)
text_parts.append(text_part)
parts.append(text_part)

Expand Down Expand Up @@ -674,8 +693,6 @@ def _normalize_config(config: object) -> OpenAIConfig:

if isinstance(config, dict):
config_dict = cast(dict[str, Any], config)
if config_dict.get('top_k'):
del config_dict['top_k']
return OpenAIConfig(**config_dict)

raise ValueError(f'Expected request.config to be a dict or OpenAIConfig, got {type(config).__name__}.')
Loading
Loading