Skip to content

# `mistral_common.protocol.instruct.normalize`

## `InstructRequestNormalizer(user_message_class, assistant_message_class, tool_message_class, system_message_class, instruct_request_class, model_settings_builder)`

Bases: `Generic[UserMessageType, AssistantMessageType, ToolMessageType, SystemMessageType, InstructRequestType]`

Takes a ChatCompletionRequest and normalizes it into an InstructRequest.

The normalization process does several things such as: - Aggregate consecutive messages of the same role - Aggregate system prompts - Normalize json content - Normalize tool calls

Examples:

    >>> normalizer = InstructRequestNormalizer.normalizer()

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`user_message_class` | `type[UserMessageType]` | The class for user messages. | required
`assistant_message_class` | `type[AssistantMessageType]` | The class for assistant messages. | required
`tool_message_class` | `type[ToolMessageType]` | The class for tool messages. | required
`system_message_class` | `type[SystemMessageType]` | The class for system messages. | required
`instruct_request_class` | `type[InstructRequestType]` | The class for instruct requests. | required
`model_settings_builder` | `ModelSettingsBuilder | None` | The builder for model settings, or None if unsupported. | required

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

    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142

    def __init__(
        self,
        user_message_class: type[UserMessageType],
        assistant_message_class: type[AssistantMessageType],
        tool_message_class: type[ToolMessageType],
        system_message_class: type[SystemMessageType],
        instruct_request_class: type[InstructRequestType],
        model_settings_builder: ModelSettingsBuilder | None,
    ):
        r"""Initializes the normalizer with the appropriate message classes.

        Args:
           user_message_class: The class for user messages.
           assistant_message_class: The class for assistant messages.
           tool_message_class: The class for tool messages.
           system_message_class: The class for system messages.
           instruct_request_class: The class for instruct requests.
           model_settings_builder: The builder for model settings, or None if unsupported.
        """
        self._user_message_class = user_message_class
        self._assistant_message_class = assistant_message_class
        self._tool_message_class = tool_message_class
        self._instruct_request_class = instruct_request_class
        # this is unused but makes creation nicer
        self._system_message_class = system_message_class
        self._model_settings_builder = model_settings_builder

### `build_settings(request)`

Build model settings from a chat completion request.

For pre-v15 normalizers, model settings are all `None`.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `ChatCompletionRequest` | The chat completion request. | required

Returns:

Type | Description
--- | ---
`ModelSettings` | Returns `ModelSettings.none()`.

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

    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183

    def build_settings(self, request: ChatCompletionRequest) -> ModelSettings:
        r"""Build model settings from a chat completion request.

        For pre-v15 normalizers, model settings are all `None`.

        Args:
            request: The chat completion request.

        Returns:
            Returns `ModelSettings.none()`.
        """
        if self._model_settings_builder is not None:
            raise InvalidRequestException(
                f"model_settings_builder should be None for {type(self).__name__}, got {self._model_settings_builder}"
            )
        return ModelSettings.none()

### `from_chat_completion_request(request)`

Converts a chat completion request to an instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `ChatCompletionRequest[UATS]` | The chat completion request to convert. | required

Returns:

Type | Description
--- | ---
`InstructRequestType` | The converted instruct request.

Examples:

    >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage
    >>> request = ChatCompletionRequest(
    ...     messages=[
    ...         UserMessage(content="Hello"),
    ...         AssistantMessage(content="Hi"),
    ...     ],
    ... )
    >>> normalizer = InstructRequestNormalizer.normalizer()
    >>> instruct_request = normalizer.from_chat_completion_request(request)

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

    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385

    def from_chat_completion_request(self, request: ChatCompletionRequest[UATS]) -> InstructRequestType:
        r"""Converts a chat completion request to an instruct request.

        Args:
            request: The chat completion request to convert.

        Returns:
            The converted instruct request.

        Examples:
            >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage
            >>> request = ChatCompletionRequest(
            ...     messages=[
            ...         UserMessage(content="Hello"),
            ...         AssistantMessage(content="Hi"),
            ...     ],
            ... )
            >>> normalizer = InstructRequestNormalizer.normalizer()
            >>> instruct_request = normalizer.from_chat_completion_request(request)
        """
        system_prompt = self._aggregate_system_prompts(request.messages)
        messages = self._aggregate_messages(request.messages)

        settings = self.build_settings(request)
        if settings != ModelSettings.none():
            raise InvalidRequestException(f"Model settings are not supported for {type(self).__name__}, got {settings}")

        return self._instruct_request_class(
            messages=messages,
            system_prompt=system_prompt,
            available_tools=request.tools,
            continue_final_message=request.continue_final_message,
            settings=settings,
        )

### `normalizer(model_settings_builder=None)` `staticmethod`

Returns a normalizer for the default instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model_settings_builder` | `ModelSettingsBuilder | None` | Must be None for this normalizer version. | `None`

Returns:

Type | Description
--- | ---
`InstructRequestNormalizer` | A normalizer for the default instruct request.

Raises:

Type | Description
--- | ---
`ValueError` | If model_settings_builder is not None.

Examples:

    >>> normalizer = InstructRequestNormalizer.normalizer()

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

    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166

    @staticmethod
    def normalizer(model_settings_builder: ModelSettingsBuilder | None = None) -> "InstructRequestNormalizer":
        r"""Returns a normalizer for the default instruct request.

        Args:
            model_settings_builder: Must be None for this normalizer version.

        Returns:
            A normalizer for the default instruct request.

        Raises:
            ValueError: If model_settings_builder is not None.

        Examples:
            >>> normalizer = InstructRequestNormalizer.normalizer()
        """
        if model_settings_builder is not None:
            raise ValueError(
                f"model_settings_builder must be None for InstructRequestNormalizer, got {model_settings_builder}"
            )
        return InstructRequestNormalizer(
            UserMessage, AssistantMessage, ToolMessage, SystemMessage, InstructRequest[UATS, Tool], None
        )

## `InstructRequestNormalizerV13(user_message_class, assistant_message_class, tool_message_class, system_message_class, instruct_request_class, model_settings_builder)`

Bases: `InstructRequestNormalizerV7`

Normalizer for the v13 tokenizer.

It reorders tool messages based on the tool call order.

Examples:

    >>> normalizer = InstructRequestNormalizerV13.normalizer()

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

    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142

    def __init__(
        self,
        user_message_class: type[UserMessageType],
        assistant_message_class: type[AssistantMessageType],
        tool_message_class: type[ToolMessageType],
        system_message_class: type[SystemMessageType],
        instruct_request_class: type[InstructRequestType],
        model_settings_builder: ModelSettingsBuilder | None,
    ):
        r"""Initializes the normalizer with the appropriate message classes.

        Args:
           user_message_class: The class for user messages.
           assistant_message_class: The class for assistant messages.
           tool_message_class: The class for tool messages.
           system_message_class: The class for system messages.
           instruct_request_class: The class for instruct requests.
           model_settings_builder: The builder for model settings, or None if unsupported.
        """
        self._user_message_class = user_message_class
        self._assistant_message_class = assistant_message_class
        self._tool_message_class = tool_message_class
        self._instruct_request_class = instruct_request_class
        # this is unused but makes creation nicer
        self._system_message_class = system_message_class
        self._model_settings_builder = model_settings_builder

### `normalizer(model_settings_builder=None)` `staticmethod`

Returns a normalizer for the default instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model_settings_builder` | `ModelSettingsBuilder | None` | Must be None for this normalizer version. | `None`

Returns:

Type | Description
--- | ---
`InstructRequestNormalizerV13` | A normalizer for the V13 instruct request.

Raises:

Type | Description
--- | ---
`ValueError` | If model_settings_builder is not None.

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

    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525

    @staticmethod
    def normalizer(model_settings_builder: ModelSettingsBuilder | None = None) -> "InstructRequestNormalizerV13":
        r"""Returns a normalizer for the default instruct request.

        Args:
            model_settings_builder: Must be None for this normalizer version.

        Returns:
            A normalizer for the V13 instruct request.

        Raises:
            ValueError: If model_settings_builder is not None.
        """
        if model_settings_builder is not None:
            raise ValueError(
                f"model_settings_builder must be None for InstructRequestNormalizerV13, got {model_settings_builder}"
            )
        return InstructRequestNormalizerV13(
            UserMessage, AssistantMessage, ToolMessage, SystemMessage, InstructRequest[UATS, Tool], None
        )

## `InstructRequestNormalizerV15(user_message_class, assistant_message_class, tool_message_class, system_message_class, instruct_request_class, model_settings_builder)`

Bases: `InstructRequestNormalizerV13`

Normalizer for the v15 tokenizer.

It reorders tool messages based on the tool call order and builds model settings.

Examples:

    >>> normalizer = InstructRequestNormalizerV15.normalizer()

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

    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142

    def __init__(
        self,
        user_message_class: type[UserMessageType],
        assistant_message_class: type[AssistantMessageType],
        tool_message_class: type[ToolMessageType],
        system_message_class: type[SystemMessageType],
        instruct_request_class: type[InstructRequestType],
        model_settings_builder: ModelSettingsBuilder | None,
    ):
        r"""Initializes the normalizer with the appropriate message classes.

        Args:
           user_message_class: The class for user messages.
           assistant_message_class: The class for assistant messages.
           tool_message_class: The class for tool messages.
           system_message_class: The class for system messages.
           instruct_request_class: The class for instruct requests.
           model_settings_builder: The builder for model settings, or None if unsupported.
        """
        self._user_message_class = user_message_class
        self._assistant_message_class = assistant_message_class
        self._tool_message_class = tool_message_class
        self._instruct_request_class = instruct_request_class
        # this is unused but makes creation nicer
        self._system_message_class = system_message_class
        self._model_settings_builder = model_settings_builder

### `build_settings(request)`

Build model settings using the configured model settings builder.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `ChatCompletionRequest` | The chat completion request. | required

Returns:

Type | Description
--- | ---
`ModelSettings` | The built model settings.

Raises:

Type | Description
--- | ---
`InvalidRequestException` | If no model settings builder is configured.

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

    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601

    def build_settings(self, request: ChatCompletionRequest) -> ModelSettings:
        r"""Build model settings using the configured model settings builder.

        Args:
            request: The chat completion request.

        Returns:
            The built model settings.

        Raises:
            InvalidRequestException: If no model settings builder is configured.
        """
        if self._model_settings_builder is None:
            raise InvalidRequestException(f"model_settings_builder must not be None for {type(self).__name__}")
        return self._model_settings_builder.build_settings(request)

### `from_chat_completion_request(request)`

Converts a chat completion request to an instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `ChatCompletionRequest[UATS]` | The chat completion request to convert. | required

Returns:

Type | Description
--- | ---
`InstructRequestType` | The converted instruct request.

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

    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620

    def from_chat_completion_request(self, request: ChatCompletionRequest[UATS]) -> InstructRequestType:  # type: ignore[type-var, misc]
        r"""Converts a chat completion request to an instruct request.

        Args:
            request: The chat completion request to convert.

        Returns:
            The converted instruct request.
        """
        messages = self._aggregate_messages(request.messages)
        settings = self.build_settings(request)
        return self._instruct_request_class(  # type: ignore[no-any-return]
            messages=messages,
            system_prompt=None,
            available_tools=request.tools,
            continue_final_message=request.continue_final_message,
            settings=settings,
        )

### `normalizer(model_settings_builder=None)` `staticmethod`

Returns a normalizer for the V15 instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model_settings_builder` | `ModelSettingsBuilder | None` | The builder for model settings. | `None`

Returns:

Type | Description
--- | ---
`InstructRequestNormalizerV15` | A normalizer for the V15 instruct request.

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

    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585

    @staticmethod
    def normalizer(model_settings_builder: ModelSettingsBuilder | None = None) -> "InstructRequestNormalizerV15":
        r"""Returns a normalizer for the V15 instruct request.

        Args:
            model_settings_builder: The builder for model settings.

        Returns:
            A normalizer for the V15 instruct request.
        """
        return InstructRequestNormalizerV15(
            UserMessage,
            AssistantMessage,
            ToolMessage,
            SystemMessage,
            InstructRequest,
            model_settings_builder,
        )

## `InstructRequestNormalizerV7(user_message_class, assistant_message_class, tool_message_class, system_message_class, instruct_request_class, model_settings_builder)`

Bases: `InstructRequestNormalizer`

Normalizer for the v7 tokenizer.

Examples:

    >>> normalizer = InstructRequestNormalizerV7.normalizer()

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

    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142

    def __init__(
        self,
        user_message_class: type[UserMessageType],
        assistant_message_class: type[AssistantMessageType],
        tool_message_class: type[ToolMessageType],
        system_message_class: type[SystemMessageType],
        instruct_request_class: type[InstructRequestType],
        model_settings_builder: ModelSettingsBuilder | None,
    ):
        r"""Initializes the normalizer with the appropriate message classes.

        Args:
           user_message_class: The class for user messages.
           assistant_message_class: The class for assistant messages.
           tool_message_class: The class for tool messages.
           system_message_class: The class for system messages.
           instruct_request_class: The class for instruct requests.
           model_settings_builder: The builder for model settings, or None if unsupported.
        """
        self._user_message_class = user_message_class
        self._assistant_message_class = assistant_message_class
        self._tool_message_class = tool_message_class
        self._instruct_request_class = instruct_request_class
        # this is unused but makes creation nicer
        self._system_message_class = system_message_class
        self._model_settings_builder = model_settings_builder

### `from_chat_completion_request(request)`

Converts a chat completion request to an instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`request` | `ChatCompletionRequest[UATS]` | The chat completion request to convert. | required

Returns:

Type | Description
--- | ---
`InstructRequestType` | The converted instruct request.

Examples:

    >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage
    >>> request = ChatCompletionRequest(
    ...     messages=[
    ...         UserMessage(content="Hello"),
    ...         AssistantMessage(content="Hi"),
    ...     ],
    ... )
    >>> normalizer = InstructRequestNormalizerV7.normalizer()
    >>> instruct_request = normalizer.from_chat_completion_request(request)

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

    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494

    def from_chat_completion_request(self, request: ChatCompletionRequest[UATS]) -> InstructRequestType:  # type: ignore[type-var, misc]
        r"""Converts a chat completion request to an instruct request.

        Args:
            request: The chat completion request to convert.

        Returns:
            The converted instruct request.

        Examples:
            >>> from mistral_common.protocol.instruct.messages import UserMessage, AssistantMessage
            >>> request = ChatCompletionRequest(
            ...     messages=[
            ...         UserMessage(content="Hello"),
            ...         AssistantMessage(content="Hi"),
            ...     ],
            ... )
            >>> normalizer = InstructRequestNormalizerV7.normalizer()
            >>> instruct_request = normalizer.from_chat_completion_request(request)
        """
        messages = self._aggregate_messages(request.messages)
        settings = self.build_settings(request)
        if settings != ModelSettings.none():
            raise InvalidRequestException(f"Model settings are not supported for {type(self).__name__}, got {settings}")
        return self._instruct_request_class(  # type: ignore[no-any-return]
            messages=messages,
            system_prompt=None,
            available_tools=request.tools,
            continue_final_message=request.continue_final_message,
            settings=settings,
        )

### `normalizer(model_settings_builder=None)` `staticmethod`

Returns a normalizer for the default instruct request.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model_settings_builder` | `ModelSettingsBuilder | None` | Must be None for this normalizer version. | `None`

Returns:

Type | Description
--- | ---
`InstructRequestNormalizerV7` | A normalizer for the V7 instruct request.

Raises:

Type | Description
--- | ---
`ValueError` | If model_settings_builder is not None.

Examples:

    >>> normalizer = InstructRequestNormalizerV7.normalizer()

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

    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420

    @staticmethod
    def normalizer(model_settings_builder: ModelSettingsBuilder | None = None) -> "InstructRequestNormalizerV7":
        r"""Returns a normalizer for the default instruct request.

        Args:
            model_settings_builder: Must be None for this normalizer version.

        Returns:
            A normalizer for the V7 instruct request.

        Raises:
            ValueError: If model_settings_builder is not None.

        Examples:
            >>> normalizer = InstructRequestNormalizerV7.normalizer()
        """
        if model_settings_builder is not None:
            raise ValueError(
                f"model_settings_builder must be None for InstructRequestNormalizerV7, got {model_settings_builder}"
            )
        return InstructRequestNormalizerV7(
            UserMessage, AssistantMessage, ToolMessage, SystemMessage, InstructRequest[UATS, Tool], None
        )

## `get_normalizer(version, model_settings_builder=None)`

Gets the appropriate normalizer for the given tokenizer version.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`version` | `TokenizerVersion` | The tokenizer version to get the normalizer for. | required
`model_settings_builder` | `ModelSettingsBuilder | None` | The builder for model settings, or None if unsupported. | `None`

Returns:

Type | Description
--- | ---
`InstructRequestNormalizer` | The appropriate normalizer for the given tokenizer version.

Examples:

    >>> normalizer = get_normalizer(TokenizerVersion.v1)

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

    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662

    def get_normalizer(
        version: TokenizerVersion, model_settings_builder: ModelSettingsBuilder | None = None
    ) -> InstructRequestNormalizer:
        r"""Gets the appropriate normalizer for the given tokenizer version.

        Args:
            version: The tokenizer version to get the normalizer for.
            model_settings_builder: The builder for model settings, or None if unsupported.

        Returns:
            The appropriate normalizer for the given tokenizer version.

        Examples:
            >>> normalizer = get_normalizer(TokenizerVersion.v1)
        """
        match version:
            case TokenizerVersion.v1 | TokenizerVersion.v2 | TokenizerVersion.v3:
                normalizer_cls = InstructRequestNormalizer
            case TokenizerVersion.v7:
                normalizer_cls = InstructRequestNormalizerV7
            case TokenizerVersion.v11 | TokenizerVersion.v13:
                normalizer_cls = InstructRequestNormalizerV13
            case TokenizerVersion.v15:
                normalizer_cls = InstructRequestNormalizerV15
            case _:
                assert_never(version)

        return normalizer_cls.normalizer(model_settings_builder=model_settings_builder)

## `normalizer_for_tokenizer_version(version, model_settings_builder=None)`

Deprecated in favor to `get_normalizer`, will be removed in 1.12.0.

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

    623
    624
    625
    626
    627
    628
    629
    630
    631
    632

    def normalizer_for_tokenizer_version(
        version: TokenizerVersion, model_settings_builder: ModelSettingsBuilder | None = None
    ) -> InstructRequestNormalizer:
        r"""Deprecated in favor to `get_normalizer`, will be removed in 1.12.0."""
        warnings.warn(
            "`normalizer_for_tokenizer_version` is deprecated and will be removed in 1.12.0. "
            "Please call `get_normalizer` instead.",
            FutureWarning,
        )
        return get_normalizer(version=version, model_settings_builder=model_settings_builder)