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

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__}")

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

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

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]}