Skip to content

mistral_common.tokens.tokenizers.base

InstructTokenizer(tokenizer, image_encoder, audio_encoder)

Bases: Generic[InstructRequestType, FIMRequestType, TokenizedType]

Base class for instruct tokenizers.

Combines a text tokenizer with optional image and audio encoders, and defines the encode/decode API for instruct, transcription, speech, and FIM requests.

Attributes:

Name Type Description
tokenizer Tokenizer

The text tokenizer to use.

image_encoder ImageEncoder | None

The image encoder to use, or None if image support is not configured.

audio_encoder AudioEncoder | None

The audio encoder to use, or None if audio support is not configured.

Parameters:

Name Type Description Default
tokenizer Tokenizer

The text tokenizer to use.

required
image_encoder ImageEncoder | None

The image encoder to use, or None if image support is not configured for this tokenizer.

required
audio_encoder AudioEncoder | None

The audio encoder to use, or None if audio support is not configured for this tokenizer.

required
Source code in src/mistral_common/tokens/tokenizers/base.py
def __init__(
    self, tokenizer: Tokenizer, image_encoder: ImageEncoder | None, audio_encoder: AudioEncoder | None
) -> None:
    r"""Initialize the instruct tokenizer.

    Args:
        tokenizer: The text tokenizer to use.
        image_encoder: The image encoder to use, or `None` if image support
            is not configured for this tokenizer.
        audio_encoder: The audio encoder to use, or `None` if audio support
            is not configured for this tokenizer.
    """

version property

The version of the tokenizer.

Returns:

Type Description
TokenizerVersion

The TokenizerVersion of the underlying text tokenizer.

decode(tokens, special_token_policy) abstractmethod

Decode the token IDs to a string.

Parameters:

Name Type Description Default
tokens list[int]

The token IDs to decode.

required
special_token_policy SpecialTokenPolicy

The policy to use for special tokens (IGNORE, KEEP, or RAISE).

required

Returns:

Type Description
str

The decoded string.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def decode(self, tokens: list[int], special_token_policy: SpecialTokenPolicy) -> str:
    r"""Decode the token IDs to a string.

    Args:
        tokens: The token IDs to decode.
        special_token_policy: The policy to use for special tokens
            (IGNORE, KEEP, or RAISE).

    Returns:
        The decoded string.
    """

encode_fim(request) abstractmethod

Encode a FIM request into a Tokenized object.

Wraps the prompt and suffix with FIM markers ([PREFIX], [SUFFIX], [MIDDLE]) so the model completes the middle section.

Parameters:

Name Type Description Default
request FIMRequestType

The FIM request to encode.

required

Returns:

Type Description
TokenizedType

The tokenized FIM request.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_fim(self, request: FIMRequestType) -> TokenizedType:
    r"""Encode a FIM request into a Tokenized object.

    Wraps the prompt and suffix with FIM markers ([PREFIX], [SUFFIX],
    [MIDDLE]) so the model completes the middle section.

    Args:
        request: The FIM request to encode.

    Returns:
        The tokenized FIM request.
    """

encode_instruct(request) abstractmethod

Encode an instruct request into a Tokenized object.

Parameters:

Name Type Description Default
request InstructRequestType

The instruct request to encode.

required

Returns:

Type Description
TokenizedType

The tokenized instruct request.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_instruct(self, request: InstructRequestType) -> TokenizedType:
    r"""Encode an instruct request into a Tokenized object.

    Args:
        request: The instruct request to encode.

    Returns:
        The tokenized instruct request.
    """

encode_speech_request(request) abstractmethod

Encodes a speech synthesis request into a tokenized format.

This method processes a speech request containing text input and optional reference audio or voice preset, and returns the tokenized output.

Parameters:

Name Type Description Default
request SpeechRequest

The speech request object containing the text and voice/audio data.

required

Returns:

Type Description
Tokenized

The tokenized representation of the speech request.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_speech_request(self, request: SpeechRequest) -> TokenizedType:
    r"""Encodes a speech synthesis request into a tokenized format.

    This method processes a speech request containing text input and
    optional reference audio or voice preset, and returns the tokenized output.

    Args:
        request: The speech request object containing the text and voice/audio data.

    Returns:
        Tokenized: The tokenized representation of the speech request.
    """

encode_system_message(message) abstractmethod

Encode a system message.

Parameters:

Name Type Description Default
message SystemMessage

The system message to encode.

required

Returns:

Type Description
A tuple of (tokens, audios

the encoded token IDs and the loaded

list[Audio]

audio for this message.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_system_message(self, message: SystemMessage) -> tuple[list[int], list[Audio]]:
    r"""Encode a system message.

    Args:
        message: The system message to encode.

    Returns:
        A tuple of (tokens, audios): the encoded token IDs and the loaded
        audio for this message.
    """
    ...

encode_transcription(request) abstractmethod

Encodes an audio transcription request into a tokenized format.

This method processes a transcription request containing audio data, encodes the user message, and returns the tokenized output.

Parameters:

Name Type Description Default
request TranscriptionRequest

The transcription request object containing the audio data to be encoded.

required

Returns:

Type Description
Tokenized

The tokenized representation of the audio data, including processed audio and tokens

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_transcription(self, request: TranscriptionRequest) -> TokenizedType:
    r"""
    Encodes an audio transcription request into a tokenized format.

    This method processes a transcription request containing audio data,
    encodes the user message, and returns the tokenized output.

    Args:
        request: The transcription request object containing
            the audio data to be encoded.

    Returns:
        Tokenized: The tokenized representation of the audio data, including processed audio and tokens
    """

encode_user_content(content, is_last, system_prompt=None, force_img_first=False) abstractmethod

Encode user content.

Parameters:

Name Type Description Default
content str | list[ContentChunk]

The user content to encode. A plain string or a list of content chunks (text, image, audio).

required
is_last bool

True if this is the last content of the conversation.

required
system_prompt str | None

The system prompt, or None. Its placement depends on the tokenizer version.

None
force_img_first bool

If True, image tokens are placed before text tokens.

False

Returns:

Type Description
A tuple of (tokens, images, audios

the encoded token IDs, the

list[ndarray]

loaded images, and the loaded audio for this content.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_user_content(
    self,
    content: str | list[ContentChunk],
    is_last: bool,
    system_prompt: str | None = None,
    force_img_first: bool = False,
) -> tuple[list[int], list[np.ndarray], list[Audio]]:
    r"""Encode user content.

    Args:
        content: The user content to encode. A plain string or a list of
            content chunks (text, image, audio).
        is_last: `True` if this is the last content of the conversation.
        system_prompt: The system prompt, or `None`. Its placement depends
            on the tokenizer version.
        force_img_first: If `True`, image tokens are placed before text
            tokens.

    Returns:
        A tuple of (tokens, images, audios): the encoded token IDs, the
        loaded images, and the loaded audio for this content.
    """
    ...

encode_user_message(message, available_tools, is_last, is_first, system_prompt=None, force_img_first=False, settings=ModelSettings.none()) abstractmethod

Encode a user message.

Parameters:

Name Type Description Default
message UserMessage

The user message to encode.

required
available_tools list[Tool] | None

The tools available to the assistant, or None. Depending on the tokenizer version, wrapped in an [AVAILABLE_TOOLS] section.

required
is_last bool

True if this is the last message of the conversation.

required
is_first bool

True if this is the first message of the conversation.

required
system_prompt str | None

The system prompt, or None. Its placement depends on the tokenizer version.

None
force_img_first bool

If True, image tokens are placed before text tokens within the message.

False
settings ModelSettings

The model settings to encode into the token stream.

none()

Returns:

Type Description
A tuple of (tokens, images, audios

the encoded token IDs, the

list[ndarray]

loaded images, and the loaded audio for this message.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode_user_message(
    self,
    message: UserMessage,
    available_tools: list[Tool] | None,
    is_last: bool,
    is_first: bool,
    system_prompt: str | None = None,
    force_img_first: bool = False,
    settings: ModelSettings = ModelSettings.none(),
) -> tuple[list[int], list[np.ndarray], list[Audio]]:
    r"""Encode a user message.

    Args:
        message: The user message to encode.
        available_tools: The tools available to the assistant, or `None`.
            Depending on the tokenizer version, wrapped in an
            [AVAILABLE_TOOLS] section.
        is_last: `True` if this is the last message of the conversation.
        is_first: `True` if this is the first message of the conversation.
        system_prompt: The system prompt, or `None`. Its placement depends on
            the tokenizer version.
        force_img_first: If `True`, image tokens are placed before text
            tokens within the message.
        settings: The model settings to encode into the token stream.

    Returns:
        A tuple of (tokens, images, audios): the encoded token IDs, the
        loaded images, and the loaded audio for this message.
    """
    ...

SpecialTokenPolicy

Bases: str, Enum

What to do with special tokens when encoding/decoding.

Attributes:

Name Type Description
IGNORE

Drop special tokens from the output.

KEEP

Include special token strings in the output.

RAISE

Raise an error if special tokens are found.

Note

Integer values 0, 1, 2 are still accepted for backward compatibility, mapping to IGNORE, KEEP, RAISE respectively.

SpecialTokens

Bases: str, Enum

Enum of special tokens used in the tokenizer.

Attributes:

Name Type Description
unk

The unknown token.

bos

The beginning of string token.

eos

The end of string token.

begin_inst

The beginning of instruction token.

end_inst

The end of instruction token.

begin_tools

The beginning of tools token.

end_tools

The end of tools token.

begin_tool_results

The beginning of tool results token.

end_tool_results

The end of tool results token.

tool_calls

The tool calls token.

img

The image token.

pad

The pad token.

img_break

The image break token.

img_end

The image end token.

prefix

The prefix token for FIM.

middle

The middle token for FIM.

suffix

The suffix token for FIM.

begin_system

The beginning of system prompt token.

end_system

The end of system prompt token.

begin_tool_content

The beginning of tool content token.

args

The args token.

call_id

The call id token.

audio

The audio token.

begin_audio

The beginning of audio token.

transcribe

The transcribe token.

begin_think

The beginning of think token.

end_think

The end of think token.

streaming_pad

The streaming pad token.

streaming_word

The streaming word token.

text_to_audio

The text to audio token.

audio_to_text

The audio to text token.

begin_model_settings

The beginning of model settings token.

end_model_settings

The end of model settings token.

Examples:

>>> unk = SpecialTokens.unk

Tokenized(**data)

Bases: MistralBase

A tokenized InstructRequest.

Attributes:

Name Type Description
tokens list[int]

The token IDs of the encoded request.

prefix_ids list[int] | None

The token IDs of the prefix section, set for FIM requests. None for non-FIM requests.

images list[ndarray]

Loaded images referenced by the tokens, as arrays ready for the model. Empty if the request has no images.

audios list[Audio]

Loaded audio referenced by the tokens, as processed Audio objects. Empty if the request has no audio.

Examples:

>>> tokenized = Tokenized(tokens=[1, 2, 3], prefix_ids=[1], images=[], audios=[])
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,
        )

text property

The text representation of the tokens, decoded with special tokens kept.

Deprecated: Use tokenizer.decode(tokens=tokenized.tokens, special_token_policy=SpecialTokenPolicy.KEEP) instead. Will be removed in 1.13.0.

Returns:

Type Description
str | None

The decoded string, or None if it was not set by the tokenizer that produced this Tokenized.

Tokenizer

Bases: ABC

Abstract text tokenizer interface.

Defines the encode/decode and vocabulary introspection API shared by the tekken and sentencepiece implementations.

bos_id abstractmethod property

id of the Beginning of String token.

eos_id abstractmethod property

id of the End of String token.

file_path abstractmethod property

The file path of the tokenizer.

model_settings_builder abstractmethod property

The model settings builder, or None if unsupported by this version.

n_words abstractmethod property

Vocabulary size of the tokenizer.

num_special_tokens abstractmethod property

The number of special tokens of the tokenizer.

pad_id abstractmethod property

id of the Pad token.

special_ids abstractmethod property

Ids of the special tokens.

unk_id abstractmethod property

id of the Unk token.

version abstractmethod property

Get the version of the tokenizer.

decode(tokens, special_token_policy=SpecialTokenPolicy.IGNORE) abstractmethod

Decode the token ids to a string.

Parameters:

Name Type Description Default
tokens list[int]

The token ids to decode.

required
special_token_policy SpecialTokenPolicy

The policy to use for special tokens.

IGNORE

Returns:

Type Description
str

The decoded string.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def decode(self, tokens: list[int], special_token_policy: SpecialTokenPolicy = SpecialTokenPolicy.IGNORE) -> str:
    r"""Decode the token ids to a string.

    Args:
        tokens: The token ids to decode.
        special_token_policy: The policy to use for special tokens.

    Returns:
        The decoded string.
    """

encode(s, bos, eos) abstractmethod

Convert a string to a list of token IDs.

Parameters:

Name Type Description Default
s str

The string to encode.

required
bos bool

If True, prepend the beginning-of-sentence token ID.

required
eos bool

If True, append the end-of-sentence token ID.

required

Returns:

Type Description
list[int]

The encoded token IDs.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def encode(self, s: str, bos: bool, eos: bool) -> list[int]:
    r"""Convert a string to a list of token IDs.

    Args:
        s: The string to encode.
        bos: If `True`, prepend the beginning-of-sentence token ID.
        eos: If `True`, append the end-of-sentence token ID.

    Returns:
        The encoded token IDs.
    """

get_special_token(s) abstractmethod

Get the id of a control token.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def get_special_token(self, s: str) -> int:
    r"""Get the id of a control token."""

id_to_piece(token_id) abstractmethod

Convert a token id to the token str.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def id_to_piece(self, token_id: int) -> str:
    r"""Convert a token id to the token str."""

is_special(token) abstractmethod

Check if token id or token str is a special token.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def is_special(self, token: int | np.integer | str) -> bool:
    r"""Check if token id or token str is a special token."""

vocab() abstractmethod

All tokens in the vocabulary as strings.

Source code in src/mistral_common/tokens/tokenizers/base.py
@abstractmethod
def vocab(self) -> list[str]:
    r"""All tokens in the vocabulary as strings."""

TokenizerVersion

Bases: str, Enum

Enum of tokenizer versions, ordered and comparable.

Allows distinguishing between tokenizer generations and maintaining backward compatibility. Instances compare by numeric version (e.g., TokenizerVersion.v13 > TokenizerVersion.v7).

Attributes:

Name Type Description
v1

First version of the tokenizer.

v2

Adds special control tokens [INST], [/INST].

v3

Adds improved function calling.

v7

Adds improved system prompt and function calling.

v11

Adds improved function calling.

v13

Removes call id tokenization and improves prompt caching.

v15

Adds model settings support (e.g., reasoning effort).

Examples:

>>> version = TokenizerVersion.v1
>>> TokenizerVersion.v15.supports_model_settings
True

supports_model_settings property

Whether this version supports model settings.

Returns:

Type Description
bool

True for v15 and later, False for earlier versions.

version_num property

Numeric part of the version string.

Returns:

Type Description
int

The integer version, e.g. 13 for TokenizerVersion.v13.

UserMessagePosition

Bases: str, Enum

Where to encode available tools in the token stream.

Attributes:

Name Type Description
first

Encode the available tools section before the message.

last

Encode the available tools section after the message.