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 Optional[Union[str, List[Union[TextChunk, ThinkChunk]]]]

The content of the message.

tool_calls Optional[List[ToolCall]]

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 .venv/lib/python3.13/site-packages/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(openai_message) classmethod

Converts the OpenAI message to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(
    cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]
) -> "AssistantMessage":
    r"""Converts the OpenAI message to the Mistral format."""
    openai_tool_calls = openai_message.get("tool_calls", None)
    tools_calls = (
        [
            ToolCall.from_openai(openai_tool_call)  # type: ignore[arg-type]
            for openai_tool_call in openai_tool_calls
        ]
        if openai_tool_calls is not None
        else None
    )
    openai_content = openai_message.get("content", None)
    content: Optional[Union[str, List[ContentChunk]]] = None
    if openai_content is None or isinstance(openai_content, str):
        content = openai_content
    elif isinstance(openai_content, list):
        content = [_convert_openai_content_chunks(chunk) for chunk in openai_content]
    else:
        raise ValueError(f"Unknown content type: {type(openai_content)}")

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

to_openai()

Converts the message to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]:
    r"""Converts the message to the OpenAI format."""
    out_dict: dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]] = {
        "role": self.role,
    }
    if self.content is None:
        pass
    elif isinstance(self.content, str):
        out_dict["content"] = self.content
    else:
        out_dict["content"] = [chunk.to_openai() for chunk in self.content]
    if self.tool_calls is not None:
        out_dict["tool_calls"] = [tool_call.to_openai() for tool_call in self.tool_calls]

    return out_dict

AudioChunk(**data)

Bases: BaseContentChunk

Audio chunk containing raw audio data.

This class represents a chunk of audio data that can be used as input.

Attributes:

Name Type Description
type Literal[input_audio]

The type of the chunk, which is always ChunkTypes.input_audio.

input_audio RawAudio

The RawAudio object containing the audio data.

Examples:

>>> audio_chunk = AudioChunk(input_audio=RawAudio(data="base64_encoded_audio_data", format="mp3"))
Source code in .venv/lib/python3.13/site-packages/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_audio(audio) classmethod

Creates an AudioChunk instance from an Audio object.

Parameters:

Name Type Description Default
audio Audio

An Audio object containing audio data.

required

Returns:

Type Description
AudioChunk

An AudioChunk instance initialized with the audio data.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_audio(cls, audio: Audio) -> "AudioChunk":
    r"""Creates an AudioChunk instance from an Audio object.

    Args:
        audio: An Audio object containing audio data.

    Returns:
        An AudioChunk instance initialized with the audio data.
    """
    return cls(input_audio=RawAudio.from_audio(audio))

from_openai(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Parameters:

Name Type Description Default
openai_chunk Dict[str, Union[str, Dict[str, str]]]

A dictionary representing the audio chunk in the OpenAI format.

required

Returns:

Type Description
AudioChunk

An AudioChunk instance initialized with the data from the OpenAI chunk.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "AudioChunk":
    r"""Converts the OpenAI chunk to the Mistral format.

    Args:
        openai_chunk: A dictionary representing the audio chunk in the OpenAI format.

    Returns:
        An AudioChunk instance initialized with the data from the OpenAI chunk.
    """
    return cls.model_validate(openai_chunk)

to_openai()

Converts the chunk to the OpenAI format.

Returns:

Type Description
Dict[str, Union[str, Dict[str, str]]]

A dictionary representing the audio chunk in the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format.

    Returns:
        A dictionary representing the audio chunk in the OpenAI format.
    """
    content = (
        self.input_audio.data.decode("utf-8") if isinstance(self.input_audio.data, bytes) else self.input_audio.data
    )
    return {
        "type": self.type,
        "input_audio": RawAudio(data=content, format=self.input_audio.format).model_dump(),
    }

AudioURL(**data)

Bases: MistralBase

Audio URL.

Attributes:

Name Type Description
url str

The URL of the audio file.

Source code in .venv/lib/python3.13/site-packages/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,
        )

AudioURLChunk(**data)

Bases: BaseContentChunk

Audio URL chunk.

Attributes:

Name Type Description
type Literal[audio_url]

The type of the chunk, which is always ChunkTypes.audio_url.

audio_url Union[str, AudioURL]

The URL of the audio file.

Source code in .venv/lib/python3.13/site-packages/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(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "AudioURLChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate(openai_chunk)

get_url_type()

Returns the type of the audio URL.

Note

URLs should be either: - a valid URL (http:// or https://) - a valid file path (e.g. /path/to/file) - a valid file URI (e.g. file:///path/to/file) - a base64 encoded audio. It is assumed to be base64 encoded if it is not a valid URL or file path.

Returns:

Type Description
AudioURLType

The type of the audio URL.

Source code in src/mistral_common/protocol/instruct/messages.py
def get_url_type(self) -> AudioURLType:
    r"""Returns the type of the audio URL.

    Note:
        URLs should be either:
        - a valid URL (http:// or https://)
        - a valid file path (e.g. /path/to/file)
        - a valid file URI (e.g. file:///path/to/file)
        - a base64 encoded audio. It is assumed to be base64 encoded if it is not a valid URL or file path.

    Returns:
        The type of the audio URL.
    """
    url_scheme = urlparse(self.url).scheme
    if url_scheme in {"http", "https"}:
        return AudioURLType.url
    elif url_scheme == "data":
        return AudioURLType.base64
    elif url_scheme == "file":
        return AudioURLType.file_uri

    try:
        url_path = Path(self.url)
        exist_path = url_path.exists()
    except OSError:  # File name too long
        exist_path = False

    if exist_path:
        return AudioURLType.file

    return AudioURLType.base64

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format."""
    if isinstance(self.audio_url, AudioURL):
        return self.model_dump()
    else:
        return {"type": self.type, "audio_url": {"url": self.audio_url}}

AudioURLType

Bases: str, Enum

Enum for the types of audio URLs.

Attributes:

Name Type Description
url

A URL.

base64

A base64 encoded audio. Can be prefixed with data:audio/<format>;base64,.

file

A file path.

file_uri

A file URI (eg. file:///path/to/file).

BaseContentChunk(**data)

Bases: MistralBase

Base class for all content chunks.

Content chunks are used to send different types of content to the model.

Attributes:

Name Type Description
type Literal[text, image, image_url, input_audio, audio_url, thinking]

The type of the chunk.

Source code in .venv/lib/python3.13/site-packages/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(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Should be implemented by subclasses.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "BaseContentChunk":
    r"""Converts the OpenAI chunk to the Mistral format.

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

to_openai()

Converts the chunk to the OpenAI format.

Should be implemented by subclasses.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format.

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

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 .venv/lib/python3.13/site-packages/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(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
@classmethod
def from_openai(
    cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, 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
def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, 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__}")

ChunkTypes

Bases: str, Enum

Enum for the types of chunks that can be sent to the model.

Attributes:

Name Type Description
text

A text chunk.

image

An image chunk.

image_url

An image url chunk.

input_audio

An input audio chunk.

audio_url

An audio url chunk.

Examples:

>>> from mistral_common.protocol.instruct.messages import ChunkTypes
>>> chunk_type = ChunkTypes.text

FinetuningAssistantMessage(**data)

Bases: AssistantMessage

Assistant message for finetuning.

Attributes:

Name Type Description
weight Optional[float]

The weight of the message to train on.

Examples:

>>> message = FinetuningAssistantMessage(content="Hello, how can I help you?", weight=0.5)
Source code in .venv/lib/python3.13/site-packages/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,
        )

ImageChunk(**data)

Bases: BaseContentChunk

Image chunk.

Attributes:

Name Type Description
image SerializableImage

The image to be sent to the model.

Examples:

>>> from PIL import Image
>>> image_chunk = ImageChunk(image=Image.new('RGB', (200, 200), color='blue'))
Source code in .venv/lib/python3.13/site-packages/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(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "ImageChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    assert openai_chunk.get("type") == "image_url", openai_chunk

    image_url_dict = openai_chunk["image_url"]
    assert isinstance(image_url_dict, dict) and "url" in image_url_dict, image_url_dict

    if re.match(r"^data:image/\w+;base64,", image_url_dict["url"]):  # Remove the prefix if it exists
        image_url_dict["url"] = image_url_dict["url"].split(",")[1]

    return cls.model_validate({"image": image_url_dict["url"]})

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format."""
    base64_image = self.model_dump(include={"image"}, context={"add_format_prefix": True})["image"]
    return {"type": "image_url", "image_url": {"url": base64_image}}

ImageURL(**data)

Bases: MistralBase

Image URL or a base64 encoded image.

Attributes:

Name Type Description
url str

The URL of the image.

detail Optional[str]

The detail of the image.

Examples:

>>> image_url = ImageURL(url="https://example.com/image.png")
Source code in .venv/lib/python3.13/site-packages/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,
        )

ImageURLChunk(**data)

Bases: BaseContentChunk

Image URL chunk.

Attributes:

Name Type Description
image_url Union[ImageURL, str]

The URL of the image or a base64 encoded image to be sent to the model.

Examples:

>>> image_url_chunk = ImageURLChunk(image_url="data:image/png;base64,iVBORw0")
Source code in .venv/lib/python3.13/site-packages/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(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "ImageURLChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate({"image_url": openai_chunk["image_url"]})

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format."""
    image_url_dict = {"url": self.get_url()}
    if isinstance(self.image_url, ImageURL) and self.image_url.detail is not None:
        image_url_dict["detail"] = self.image_url.detail

    out_dict: Dict[str, Union[str, Dict[str, str]]] = {
        "type": "image_url",
        "image_url": image_url_dict,
    }
    return out_dict

RawAudio(**data)

Bases: MistralBase

Base64 encoded audio data.

This class represents raw audio data encoded in base64 format.

Attributes:

Name Type Description
data Union[str, bytes]

The base64 encoded audio data, which can be a string or bytes.

format str

The format of the audio data.

Examples:

>>> audio = RawAudio(data="base64_encoded_audio_data", format="mp3")
Source code in .venv/lib/python3.13/site-packages/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_audio(audio) classmethod

Creates a RawAudio instance from an Audio object.

Parameters:

Name Type Description Default
audio Audio

An Audio object containing audio data, format, and duration.

required

Returns:

Type Description
RawAudio

An AudioChunk instance initialized with the audio data.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_audio(cls, audio: Audio) -> "RawAudio":
    """Creates a RawAudio instance from an Audio object.

    Args:
        audio: An Audio object containing audio data, format, and duration.

    Returns:
        An AudioChunk instance initialized with the audio data.
    """
    format = audio.format
    data = audio.to_base64(format, False)

    return cls(data=data, format=format)

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 Union[str, List[Union[TextChunk, ThinkChunk]]]

The content of the message.

Examples:

>>> message = SystemMessage(content="You are a helpful assistant.")
Source code in .venv/lib/python3.13/site-packages/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(openai_message) classmethod

Converts the OpenAI message to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(
    cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]
) -> "SystemMessage":
    r"""Converts the OpenAI message to the Mistral format."""
    return cls.model_validate(openai_message)

to_openai()

Converts the message to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]:
    r"""Converts the message to the OpenAI format."""
    return self.model_dump()

TextChunk(**data)

Bases: BaseContentChunk

Text chunk.

Attributes:

Name Type Description
text str

The text to be sent to the model.

Examples:

>>> text_chunk = TextChunk(text="Hello, how can I help you?")
Source code in .venv/lib/python3.13/site-packages/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(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "TextChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate(openai_chunk)

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format."""
    return self.model_dump()

ThinkChunk(**data)

Bases: BaseContentChunk

Thinking chunk.

Attributes:

Name Type Description
type Literal[thinking]

The type of the chunk, which is always ChunkTypes.thinking.

thinking str

The list of text chunks of the thinking.

closed bool

Whether the thinking chunk is closed or not.

Source code in .venv/lib/python3.13/site-packages/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(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, openai_chunk: Dict[str, Union[str, Dict[str, str]]]) -> "ThinkChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate(openai_chunk)

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, Dict[str, str]]]:
    r"""Converts the chunk to the OpenAI format."""
    return self.model_dump()

ToolMessage(**data)

Bases: BaseMessage

Tool message.

Attributes:

Name Type Description
content str

The content of the message.

tool_call_id Optional[str]

The tool call id of the message.

name Optional[str]

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 .venv/lib/python3.13/site-packages/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) classmethod

Converts the OpenAI message to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(cls, messages: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]) -> "ToolMessage":
    r"""Converts the OpenAI message to the Mistral format."""
    tool_message = cls.model_validate(messages)
    assert tool_message.tool_call_id is not None, "tool_call_id must be provided for tool messages."
    return tool_message

to_openai()

Converts the message to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, 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 self.model_dump(exclude={"name"})

UserMessage(**data)

Bases: BaseMessage

User message.

Attributes:

Name Type Description
content Union[str, List[UserContentChunk]]

The content of the message.

Examples:

>>> message = UserMessage(content="Can you help me to write a poem?")
Source code in .venv/lib/python3.13/site-packages/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(openai_message) classmethod

Converts the OpenAI message to the Mistral format.

Source code in src/mistral_common/protocol/instruct/messages.py
@classmethod
def from_openai(
    cls, openai_message: Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]
) -> "UserMessage":
    r"""Converts the OpenAI message to the Mistral format."""
    if isinstance(openai_message["content"], str):
        return cls.model_validate(openai_message)
    return cls.model_validate(
        {
            "role": openai_message["role"],
            "content": [_convert_openai_content_chunks(chunk) for chunk in openai_message["content"]],
        },
    )

to_openai()

Converts the message to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/messages.py
def to_openai(self) -> Dict[str, Union[str, List[Dict[str, Union[str, Dict[str, Any]]]]]]:
    r"""Converts the message to the OpenAI format."""
    if isinstance(self.content, str):
        return {"role": self.role, "content": self.content}
    return {"role": self.role, "content": [chunk.to_openai() for chunk in self.content]}