Skip to content

# `mistral_common.protocol.instruct.messages`

## `AssistantMessage(**data)`

Bases: `BaseMessage`

Assistant message.

Attributes:

Name | Type | Description
--- | --- | ---
`role` | `Literal[assistant]` | The role of the message.
`content` | `str | list[ContentChunk] | None` | The content of the message.
`tool_calls` | `list[ToolCall] | None` | The tool calls of the message.
`prefix` | `bool` | Whether the message is a prefix.

Examples:

    >>> message = AssistantMessage(content="Hello, how can I help you?")

Source code in `pydantic/main.py`

    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270

    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(openai_message)` `classmethod`

Converts the OpenAI message to the Mistral format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338

    @classmethod
    def from_openai(cls, openai_message: dict[str, Any]) -> "AssistantMessage":
        r"""Converts the OpenAI message to the Mistral format."""
        openai_tool_calls = openai_message.get("tool_calls", None)
        if openai_tool_calls is None:
            tools_calls: list[ToolCall] | None = None
        elif isinstance(openai_tool_calls, list):
            tools_calls = []
            for openai_tool_call in openai_tool_calls or []:
                tools_calls.append(ToolCall.from_openai(openai_tool_call))
        else:
            raise ValueError(f"tool_calls must be a list, got {type(openai_tool_calls)}")
        content = cls._content_from_openai(openai_message.get("content"))

        reasoning_content: str | None = openai_message.get("reasoning_content")
        reasoning: str | None = openai_message.get("reasoning")

        match reasoning_content, reasoning:
            case None, None:
                openai_thinking = None
            case None, _:
                openai_thinking = reasoning
            case _, None:
                openai_thinking = reasoning_content
            case _, _:
                if reasoning_content != reasoning:
                    raise ValueError("`reasoning_content` and `reasoning` should be equal.")
                openai_thinking = reasoning

        if openai_thinking is not None:
            has_thinking_chunks = isinstance(content, list) and any(isinstance(chunk, ThinkChunk) for chunk in content)
            if has_thinking_chunks:
                raise InvalidAssistantMessageException(
                    "Message cannot have both thinking chunks in content and a top-level"
                    " `reasoning` or `reasoning_content` field."
                )

            reasoning_chunk = ThinkChunk(thinking=openai_thinking, closed=True)
            if isinstance(content, str):
                content = [reasoning_chunk, TextChunk(text=content)]
            elif content is None:
                content = [reasoning_chunk]
            else:
                content.insert(0, reasoning_chunk)

        return cls.model_validate(
            {
                "role": openai_message["role"],
                "content": content,
                "tool_calls": tools_calls,
            }
        )

### `to_openai(reasoning_field_format=None)`

Converts the message to the OpenAI format.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`reasoning_field_format` | `ReasoningFieldFormat | None` | Format for converting thinking chunks. When `None`, defaults to `ReasoningFieldFormat.thinking_chunks` (chunks kept inline) but emits a `FutureWarning` if the content contains `ThinkChunk`. | `None`

Source code in `src/mistral_common/protocol/instruct/messages.py`

    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285

    def to_openai(
        self,
        reasoning_field_format: ReasoningFieldFormat | None = None,
    ) -> dict[str, Any]:
        r"""Converts the message to the OpenAI format.

        Args:
            reasoning_field_format: Format for converting thinking chunks. When `None`, defaults to
                `ReasoningFieldFormat.thinking_chunks` (chunks kept inline) but emits a `FutureWarning` if
                the content contains `ThinkChunk`.
        """
        out_dict: dict[str, Any] = {
            "role": self.role,
        }
        if self.tool_calls is not None:
            out_dict["tool_calls"] = [tool_call.to_openai() for tool_call in self.tool_calls]

        if self.content is None:
            return out_dict

        if isinstance(self.content, str):
            out_dict["content"] = self.content
            return out_dict

        last_think_idx: int = -1
        for i, chunk in enumerate(self.content):
            if isinstance(chunk, ThinkChunk):
                if (i - last_think_idx) > 1:
                    raise InvalidAssistantMessageException(
                        "ThinkChunks must be leading: all ThinkChunks must appear before any other content chunk."
                    )
                last_think_idx = i

        if reasoning_field_format is None and last_think_idx >= 0:
            warnings.warn(
                "`convert_thinking_format` defaults to 'thinking_chunks' but will change to 'reasoning' "
                "in 1.13.0. Pass `reasoning_field_format` explicitly to silence this warning.",
                FutureWarning,
                stacklevel=2,
            )

        match reasoning_field_format:
            case None | ReasoningFieldFormat.thinking_chunks:
                out_dict["content"] = self._content_to_openai(self.content)
            case ReasoningFieldFormat.reasoning | ReasoningFieldFormat.reasoning_content:
                think_chunks, content_chunks = self.content[: last_think_idx + 1], self.content[last_think_idx + 1 :]
                if not _are_think_chunks(think_chunks) or not _are_text_chunks(content_chunks):
                    raise RuntimeError("Impossible, only think or content chunks should have been present.")
                if len(think_chunks) > 0:
                    out_dict[reasoning_field_format.value] = "\n".join(tc.thinking for tc in think_chunks)

                if len(content_chunks) == 1:
                    out_dict["content"] = content_chunks[0].text
                elif content_chunks:
                    out_dict["content"] = self._content_to_openai(content_chunks)
            case _:
                raise ValueError(f"{reasoning_field_format=} is not supported.")

        return out_dict

## `BaseMessage(**data)`

Bases: `MistralBase`

Base class for all messages.

Attributes:

Name | Type | Description
--- | --- | ---
`role` | `Literal[system, user, assistant, tool]` | The role of the message.

Source code in `pydantic/main.py`

    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270

    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(openai_message)` `classmethod`

Converts the OpenAI message to the Mistral format.

Should be implemented by subclasses.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    141
    142
    143
    144
    145
    146
    147

    @classmethod
    def from_openai(cls, openai_message: dict[str, Any]) -> "BaseMessage":
        r"""Converts the OpenAI message to the Mistral format.

        Should be implemented by subclasses.
        """
        raise NotImplementedError(f"from_openai method not implemented for {cls.__name__}.")

### `to_openai()`

Converts the message to the OpenAI format.

Should be implemented by subclasses.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    134
    135
    136
    137
    138
    139

    def to_openai(self) -> dict[str, Any]:
        r"""Converts the message to the OpenAI format.

        Should be implemented by subclasses.
        """
        raise NotImplementedError(f"to_openai method not implemented for {type(self).__name__}")

## `FinetuningAssistantMessage(**data)`

Bases: `AssistantMessage`

Assistant message for finetuning.

Attributes:

Name | Type | Description
--- | --- | ---
`weight` | `float | None` | The weight of the message to train on.

Examples:

    >>> message = FinetuningAssistantMessage(content="Hello, how can I help you?", weight=0.5)

Source code in `pydantic/main.py`

    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270

    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,
            )

## `ReasoningFieldFormat`

Bases: `str`, `Enum`

How to serialize leading `ThinkChunk` in `AssistantMessage.to_openai()`.

Attributes:

Name | Type | Description
--- | --- | ---
`thinking_chunks` |  | Use think chunks (Mistral convention).
`reasoning` |  | Flat `reasoning` string (vLLM convention).
`reasoning_content` |  | Flat `reasoning_content` string (SGLang convention).

## `Roles`

Bases: `str`, `Enum`

Enum for the roles of the messages.

Attributes:

Name | Type | Description
--- | --- | ---
`system` |  | The system role.
`user` |  | The user role.
`assistant` |  | The assistant role.
`tool` |  | The tool role.

Examples:

    >>> role = Roles.user

## `SystemMessage(**data)`

Bases: `BaseMessage`

System message.

Attributes:

Name | Type | Description
--- | --- | ---
`content` | `str | list[ContentChunk]` | The content of the message.

Examples:

    >>> message = SystemMessage(content="You are a helpful assistant.")

Source code in `pydantic/main.py`

    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270

    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(openai_message)` `classmethod`

Converts the OpenAI message to the Mistral format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    200
    201
    202
    203
    204
    205

    @classmethod
    def from_openai(cls, openai_message: dict[str, Any]) -> "SystemMessage":
        r"""Converts the OpenAI message to the Mistral format."""
        return cls.model_validate(
            {"role": openai_message["role"], "content": cls._content_from_openai(openai_message["content"])}
        )

### `to_openai()`

Converts the message to the OpenAI format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    196
    197
    198

    def to_openai(self) -> dict[str, Any]:
        r"""Converts the message to the OpenAI format."""
        return {"role": self.role, "content": self._content_to_openai(self.content)}

## `ToolMessage(**data)`

Bases: `BaseMessage`

Tool message.

Attributes:

Name | Type | Description
--- | --- | ---
`content` | `str | list[ContentChunk]` | The content of the message.
`tool_call_id` | `str | None` | The tool call id of the message.
`name` | `str | None` | The name of the tool. (Deprecated in V3 tokenization)

Examples:

    >>> message = ToolMessage(content="Hello, how can I help you?", tool_call_id="123")

Source code in `pydantic/main.py`

    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270

    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(openai_message)` `classmethod`

Converts the OpenAI message to the Mistral format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403

    @classmethod
    def from_openai(cls, openai_message: dict[str, Any]) -> "ToolMessage":
        r"""Converts the OpenAI message to the Mistral format."""
        content = cls._content_from_openai(openai_message["content"])
        tool_message = cls.model_validate(
            {
                "role": openai_message["role"],
                "tool_call_id": openai_message["tool_call_id"],
                "content": content,
                "name": openai_message.get("name"),
            }
        )
        return tool_message

### `to_openai()`

Converts the message to the OpenAI format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    382
    383
    384
    385
    386
    387
    388
    389

    def to_openai(self) -> dict[str, Any]:
        r"""Converts the message to the OpenAI format."""
        assert self.tool_call_id is not None, "tool_call_id must be provided for tool messages."
        return {
            "role": self.role,
            "tool_call_id": self.tool_call_id,
            "content": self._content_to_openai(self.content),
        }

## `UserMessage(**data)`

Bases: `BaseMessage`

User message.

Attributes:

Name | Type | Description
--- | --- | ---
`content` | `str | list[ContentChunk]` | The content of the message.

Examples:

    >>> message = UserMessage(content="Can you help me to write a poem?")

Source code in `pydantic/main.py`

    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270

    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(openai_message)` `classmethod`

Converts the OpenAI message to the Mistral format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    174
    175
    176
    177
    178
    179

    @classmethod
    def from_openai(cls, openai_message: dict[str, Any]) -> "UserMessage":
        r"""Converts the OpenAI message to the Mistral format."""
        return cls.model_validate(
            {"role": openai_message["role"], "content": cls._content_from_openai(openai_message["content"])}
        )

### `to_openai()`

Converts the message to the OpenAI format.

Source code in `src/mistral_common/protocol/instruct/messages.py`

    170
    171
    172

    def to_openai(self) -> dict[str, Any]:
        r"""Converts the message to the OpenAI format."""
        return {"role": self.role, "content": self._content_to_openai(self.content)}