Skip to content

mistral_common.protocol.instruct.request

ChatCompletionRequest(**data)

Bases: BaseCompletionRequest, Generic[ChatMessageType]

Request for a chat completion.

Main entry point for creating instruct model requests. Contains all configuration for a single chat completion including messages, tools, and model settings.

Attributes:

Name Type Description
model str | None

Name of the model to use. Required in serving mode; optional in other modes. If None, the default model will be used.

messages list[ChatMessageType]

List of chat messages (user, assistant, system, tool). Must not be empty.

response_format ResponseFormat

Format of the response (text or JSON). Defaults to text.

tools list[Tool] | None

List of available tools for the model to use. If None, no tools are available.

tool_choice ToolChoice

Strategy for tool selection. Options: auto (model decides), none (no tools), any/required (deprecated, use required). Default: auto.

parallel_tool_calls bool

Whether the model may call multiple tools in one response. Defaults to True.

truncate_for_context_length bool

If True, automatically truncate messages to fit within the model's context length. Default: False.

reasoning_effort ReasoningEffort | None

Controls reasoning effort (one of "none", "minimal", "low", "medium", "high", "xhigh", or "max"). Requires tokenizer >= v15. If None, uses model default.

Examples:

>>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage
>>> from mistral_common.protocol.instruct.tool_calls import ToolTypes, Function
>>> request = ChatCompletionRequest(
...     messages=[
...         UserMessage(content="Hello!"),
...         AssistantMessage(content="Hi! How can I help you?"),
...     ],
...     response_format=ResponseFormat(type=ResponseFormats.text),
...     tools=[Tool(type=ToolTypes.function, function=Function(name="get_weather", parameters={}))],
...     tool_choice=ToolChoiceEnum.auto,
...     truncate_for_context_length=True,
... )
Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

from_openai(messages, tools=None, continue_final_message=False, **kwargs) classmethod

Create a ChatCompletionRequest from OpenAI ChatCompletion request format.

Parameters:

Name Type Description Default
messages list[dict[str, str | list[dict[str, str | dict[str, Any]]]]]

List of message dicts in OpenAI format. Each dict must have a "role" key and optionally "content" or other role-specific fields.

required
tools list[dict[str, Any]] | None

List of tool dicts in OpenAI format, or None. Each tool dict must have "type" and "function" keys for function tools.

None
continue_final_message bool

If True and the last message is an assistant, sets AssistantMessage.prefix=True on it.

False
**kwargs Any

Additional request parameters. Supports both OpenAI names (e.g., "seed") and mistral-common names (e.g., random_seed). Cannot specify both "seed" and random_seed. A None value for temperature, top_p, tool_choice, response_format or parallel_tool_calls selects the default.

{}

Returns:

Type Description
ChatCompletionRequest

A ChatCompletionRequest instance with messages and tools converted

ChatCompletionRequest

from OpenAI format.

Raises:

Type Description
ValueError

If both "seed" and random_seed are specified in kwargs, or if max_tokens and "max_completion_tokens" are both set to different values.

Source code in src/mistral_common/protocol/instruct/request.py
@classmethod
def from_openai(
    cls,
    messages: list[dict[str, str | list[dict[str, str | dict[str, Any]]]]],
    tools: list[dict[str, Any]] | None = None,
    continue_final_message: bool = False,
    **kwargs: Any,
) -> "ChatCompletionRequest":
    r"""Create a ChatCompletionRequest from OpenAI ChatCompletion request format.

    Args:
        messages: List of message dicts in OpenAI format. Each dict must have
            a "role" key and optionally "content" or other role-specific fields.
        tools: List of tool dicts in OpenAI format, or `None`. Each tool dict must
            have "type" and "function" keys for function tools.
        continue_final_message: If `True` and the last message is an assistant,
            sets `AssistantMessage.prefix=True` on it.
        **kwargs: Additional request parameters. Supports both OpenAI names
            (e.g., "seed") and mistral-common names (e.g., `random_seed`).
            Cannot specify both "seed" and `random_seed`. A `None` value for
            `temperature`, `top_p`, `tool_choice`, `response_format` or
            `parallel_tool_calls` selects the default.

    Returns:
        A ChatCompletionRequest instance with messages and tools converted
        from OpenAI format.

    Raises:
        ValueError: If both "seed" and `random_seed` are specified in kwargs, or if
            `max_tokens` and "max_completion_tokens" are both set to different values.
    """
    if "seed" in kwargs and "random_seed" in kwargs:
        raise ValueError("Cannot specify both `seed` and `random_seed`.")

    random_seed = kwargs.pop("seed", None)
    if random_seed is None:
        random_seed = kwargs.pop("random_seed", None)

    # OpenAI deprecates `max_tokens` in favor of `max_completion_tokens`.
    max_completion_tokens = kwargs.pop("max_completion_tokens", None)
    if max_completion_tokens is not None:
        max_tokens = kwargs.get("max_tokens")
        if max_tokens is not None and max_tokens != max_completion_tokens:
            raise ValueError(
                f"Cannot specify different values for `max_tokens` ({max_tokens}) "
                f"and `max_completion_tokens` ({max_completion_tokens})."
            )
        kwargs["max_tokens"] = max_completion_tokens

    # OpenAI clients send `parallel_tool_calls: null` to mean the default.
    if "parallel_tool_calls" in kwargs and kwargs["parallel_tool_calls"] is None:
        kwargs["parallel_tool_calls"] = True

    # OpenAI clients send `temperature: null`, `top_p: null`, `tool_choice: null` and
    # `response_format: null` to mean the default.
    null_means_default = ["temperature", "top_p", "tool_choice", "response_format"]
    kwargs = {k: v for k, v in kwargs.items() if not (v is None and k in null_means_default)}

    # OpenAI clients send `strict: null` in a JSON schema response format to mean the default.
    response_format = kwargs.get("response_format")
    if isinstance(response_format, dict) and isinstance(response_format.get("json_schema"), dict):
        json_schema = {k: v for k, v in response_format["json_schema"].items() if not (k == "strict" and v is None)}
        kwargs["response_format"] = {**response_format, "json_schema": json_schema}

    converted_messages: list[ChatMessage] = convert_openai_messages(messages)
    converted_messages = _map_continue_final_message(
        messages=converted_messages,
        continue_final_message=TypeAdapter(bool).validate_python(continue_final_message),
    )

    converted_tools = convert_openai_tools(tools) if tools is not None else None

    return cls.model_validate(
        {
            "messages": converted_messages,
            "tools": converted_tools,
            "random_seed": random_seed,
            **kwargs,
        },
        extra="ignore",
    )

to_openai(reasoning_field_format=None, **kwargs)

Convert this request to OpenAI ChatCompletion API format.

Note

Interleaved thinking (a ThinkChunk after other content in an assistant message) is not supported: only leading ThinkChunks can be converted.

Parameters:

Name Type Description Default
reasoning_field_format ReasoningFieldFormat | None

Format for converting thinking/thinking chunks in assistant messages to OpenAI's reasoning field. If None, uses reasoning. See AssistantMessage.to_openai for available formats.

None
**kwargs Any

Additional OpenAI-specific parameters to include in the output (e.g., stream, temperature, top_p). Must not conflict with existing fields.

{}

Returns:

Type Description
dict[str, Any]

Dictionary matching the OpenAI ChatCompletion request schema.

Raises:

Type Description
InvalidAssistantMessageException

If an assistant message has interleaved thinking.

ValueError

If kwargs contains duplicate or conflicting keys.

NotImplementedError

If truncate_for_context_length is True (not implemented).

Examples:

>>> from mistral_common.protocol.instruct.messages import UserMessage
>>> from mistral_common.protocol.instruct.tool_calls import Tool, Function
>>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], temperature=0.15)
>>> request.to_openai(stream=True)
{'temperature': 0.15, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'stream': True}
>>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], tools=[
...     Tool(function=Function(
...         name="get_current_weather",
...         description="Get the current weather in a given location",
...         parameters={
...             "type": "object",
...             "properties": {
...                 "location": {
...                     "type": "string",
...                     "description": "The city and state, e.g. San Francisco, CA",
...                 },
...                 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
...             },
...             "required": ["location"],
...         },
...     ),
... )])
>>> request.to_openai()
{'temperature': 0.7, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'tools': [{'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}, 'strict': False}}], 'parallel_tool_calls': True, 'tool_choice': 'auto'}
Source code in src/mistral_common/protocol/instruct/request.py
def to_openai(
    self,
    reasoning_field_format: ReasoningFieldFormat | None = None,
    **kwargs: Any,
) -> dict[str, Any]:
    r"""Convert this request to OpenAI ChatCompletion API format.

    Note:
        Interleaved thinking (a ThinkChunk after other content in an assistant message)
        is not supported: only leading ThinkChunks can be converted.

    Args:
        reasoning_field_format: Format for converting thinking/thinking chunks in
            assistant messages to OpenAI's reasoning field. If `None`, uses `reasoning`.
            See `AssistantMessage.to_openai` for available formats.
        **kwargs: Additional OpenAI-specific parameters to include in the output
            (e.g., stream, temperature, `top_p`). Must not conflict with existing fields.

    Returns:
        Dictionary matching the OpenAI ChatCompletion request schema.

    Raises:
        InvalidAssistantMessageException: If an assistant message has interleaved thinking.
        ValueError: If kwargs contains duplicate or conflicting keys.
        NotImplementedError: If `truncate_for_context_length` is `True` (not implemented).

    Examples:
        >>> from mistral_common.protocol.instruct.messages import UserMessage
        >>> from mistral_common.protocol.instruct.tool_calls import Tool, Function
        >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], temperature=0.15)
        >>> request.to_openai(stream=True)
        {'temperature': 0.15, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'stream': True}
        >>> request = ChatCompletionRequest(messages=[UserMessage(content="Hello, how are you?")], tools=[
        ...     Tool(function=Function(
        ...         name="get_current_weather",
        ...         description="Get the current weather in a given location",
        ...         parameters={
        ...             "type": "object",
        ...             "properties": {
        ...                 "location": {
        ...                     "type": "string",
        ...                     "description": "The city and state, e.g. San Francisco, CA",
        ...                 },
        ...                 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        ...             },
        ...             "required": ["location"],
        ...         },
        ...     ),
        ... )])
        >>> request.to_openai()
        {'temperature': 0.7, 'top_p': 1.0, 'response_format': {'type': 'text'}, 'continue_final_message': False, 'messages': [{'role': 'user', 'content': 'Hello, how are you?'}], 'tools': [{'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}, 'strict': False}}], 'parallel_tool_calls': True, 'tool_choice': 'auto'}
    """  # noqa: E501

    # Handle messages and tools separately.
    openai_request: dict[str, Any] = self.model_dump(
        exclude={"messages", "tools", "truncate_for_context_length", "tool_choice", "parallel_tool_calls"},
        exclude_none=True,
        by_alias=True,
    )

    # Rename random_seed to seed.
    seed = openai_request.pop("random_seed", None)
    if seed is not None:
        openai_request["seed"] = seed

    reasoning_effort = openai_request.pop("reasoning_effort", None)
    openai_request["continue_final_message"] = bool(
        self.messages and isinstance(self.messages[-1], AssistantMessage) and self.messages[-1].prefix
    )
    if reasoning_effort is not None:
        openai_request["reasoning_effort"] = reasoning_effort

    if self.truncate_for_context_length:
        raise NotImplementedError("Truncating for context length is not implemented for OpenAI requests.")

    for kwarg in kwargs:
        if kwarg in openai_request:
            raise ValueError(f"Duplicate keyword argument: {kwarg}")
        elif kwarg in ChatCompletionRequest.model_fields:
            raise ValueError(f"Keyword argument {kwarg} is already set in the request.")

    openai_messages = []
    for message in self.messages:
        if isinstance(message, AssistantMessage):
            openai_messages.append(message.to_openai(reasoning_field_format=reasoning_field_format))
        else:
            openai_messages.append(message.to_openai())

    openai_request["messages"] = openai_messages
    if self.tools is not None:
        openai_request["tools"] = [tool.to_openai() for tool in self.tools]
    # OpenAI rejects `parallel_tool_calls` and `tool_choice` when no tools are given.
    if self.tools:
        openai_request["parallel_tool_calls"] = self.parallel_tool_calls

        openai_tool_choice: str | dict[str, Any]
        match self.tool_choice:
            case ToolChoiceEnum.auto | ToolChoiceEnum.none:
                openai_tool_choice = self.tool_choice
            case ToolChoiceEnum.required | ToolChoiceEnum.any:
                openai_tool_choice = ToolChoiceEnum.required.value
            case _:
                openai_tool_choice = self.tool_choice.model_dump()

        openai_request["tool_choice"] = openai_tool_choice

    openai_request.update(kwargs)

    return openai_request

InstructRequest(**data)

Bases: MistralBase, Generic[ChatMessageType, ToolType]

Internal representation of a validated instruct request ready for tokenization.

This class represents the fully normalized and validated request that will be passed to the tokenizer. It separates system prompts from regular messages and handles tool configuration.

Note

This class is intended for internal use only. External users should use ChatCompletionRequest to build requests and convert to/from OpenAI format.

Attributes:

Name Type Description
messages list[ChatMessageType]

List of chat messages (user and assistant only; system is separate).

system_prompt str | None

System prompt string, or None if no system prompt.

available_tools list[ToolType] | None

List of tools available to the assistant. If None, no tools are available. Tools are separate from messages here.

truncate_at_max_tokens int | None

Maximum token count for truncation. If None, no truncation is performed. If set, messages will be truncated from the beginning to fit within this limit.

settings ModelSettings

Model configuration settings. Defaults to all None values.

Examples:

>>> from mistral_common.protocol.instruct.messages import UserMessage, SystemMessage
>>> request = InstructRequest(
...     messages=[UserMessage(content="Hello, how are you?")],
...     system_prompt="You are a helpful assistant."
... )
Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

JsonSchema(**data)

Bases: MistralBase

A named JSON schema for structured responses.

Attributes:

Name Type Description
name str

The schema name.

description str | None

An optional description of the schema.

custom_schema dict[str, Any]

The JSON schema (aliased schema).

strict bool

Whether grammar generation uses the custom schema. When False, grammar generation falls back to any valid JSON; model settings always retain the custom schema. The value is also preserved for OpenAI compatibility.

Examples:

>>> schema = JsonSchema(name="obj", schema={"type": "object"})
Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

validate_custom_schema(value) classmethod

Validate the schema against JSON Schema Draft 7.

Source code in src/mistral_common/protocol/instruct/request.py
@field_validator("custom_schema")
@classmethod
def validate_custom_schema(cls, value: dict[str, Any]) -> dict[str, Any]:
    r"""Validate the schema against JSON Schema Draft 7."""
    validate_json_schema_by_draft7(value=value)
    return value

ModelSettings(**data)

Bases: MistralBase

Model configuration settings for instruct requests.

Encapsulates model-specific settings that influence inference behavior. Currently supports reasoning effort and response format configuration.

Attributes:

Name Type Description
reasoning_effort ReasoningEffort | None

Controls reasoning effort. If None, the model uses its default reasoning behavior. Requires tokenizer >= v15.

json_schema dict[str, Any] | None

The JSON schema to enforce on the response, derived from the request's response format. If None, no schema is enforced. Requires tokenizer >= v15.

Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

none() staticmethod

Create a ModelSettings instance with all fields set to None.

Returns:

Type Description
ModelSettings

An instance with all fields set to None.

Source code in src/mistral_common/protocol/instruct/request.py
@staticmethod
def none() -> "ModelSettings":
    r"""Create a ModelSettings instance with all fields set to `None`.

    Returns:
        An instance with all fields set to `None`.
    """
    return ModelSettings()

ReasoningEffort

Bases: StrEnum

Controls the amount of reasoning effort the model applies during generation.

Attributes:

Name Type Description
none

No reasoning effort; model generates responses directly.

minimal

Minimal reasoning effort, with only a small amount of additional computation.

low

Low reasoning effort; the model spends little compute on reasoning.

medium

Medium reasoning effort, between low and high.

high

High reasoning effort for complex tasks; model spends more compute on reasoning before generating the final response.

xhigh

Extra-high reasoning effort, above high, for the most demanding tasks.

max

Maximum reasoning effort the model supports.

Note

Supported for tokenizer >= v15 only. Earlier versions will raise an error.

ResponseFormat(**data)

Bases: MistralBase

Configuration for the response format.

Attributes:

Name Type Description
type ResponseFormats

The response format type. Use ResponseFormats.text for plain text, ResponseFormats.json_object for JSON output, or ResponseFormats.json_schema for a custom JSON schema.

json_schema JsonSchema | None

The JSON schema when type is json_schema.

Examples:

>>> response_format = ResponseFormat(type=ResponseFormats.text)
Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

get_schema(purpose)

Resolve the response schema for grammar generation or model settings.

Parameters:

Name Type Description Default
purpose SchemaRenderingMode

Whether the schema is used to constrain a grammar or encode model settings.

required

Returns:

Type Description
dict[str, Any] | None

The schema selected for this purpose, or None for text.

Source code in src/mistral_common/protocol/instruct/request.py
def get_schema(self, purpose: SchemaRenderingMode) -> dict[str, Any] | None:
    r"""Resolve the response schema for grammar generation or model settings.

    Args:
        purpose: Whether the schema is used to constrain a grammar or encode
            model settings.

    Returns:
        The schema selected for this purpose, or None for `text`.
    """
    if self.type == ResponseFormats.json_schema:
        assert self.json_schema is not None
        if purpose == SchemaRenderingMode.grammar and not self.json_schema.strict:
            return _JSON_OBJECT_OR_ARRAY_SCHEMA
        return self.json_schema.custom_schema
    if self.type == ResponseFormats.json_object:
        return _JSON_OBJECT_OR_ARRAY_SCHEMA
    return None

validate_schema_presence()

Require a schema when the response format selects json_schema.

Source code in src/mistral_common/protocol/instruct/request.py
@model_validator(mode="after")
def validate_schema_presence(self) -> "ResponseFormat":
    r"""Require a schema when the response format selects `json_schema`."""
    if self.type == ResponseFormats.json_schema and self.json_schema is None:
        raise ValueError("Response format `json_schema` must define the schema")
    return self

ResponseFormats

Bases: StrEnum

Enum of the different formats for an instruct response.

Attributes:

Name Type Description
text

Response will be plain text.

json_object

Response will be a valid JSON object.

json_schema

Response will follow a custom JSON schema.

Examples:

>>> response_format = ResponseFormats.text

SchemaRenderingMode

Bases: StrEnum

Select how a response-format schema is applied.

Attributes:

Name Type Description
grammar

The schema constrains decoding; non-strict schemas fall back to any valid JSON.

model_settings

The schema is encoded in model settings unchanged.