Skip to content

# `mistral_common.protocol.instruct.tool_calls`

## `ToolChoice = ToolChoiceEnum | NamedToolChoice` `module-attribute`

Tool choice are either a `ToolChoiceEnum` or a `NamedToolChoice`.

## `Function(**data)`

Bases: `FunctionName`

Function definition for tools.

Attributes:

Name | Type | Description
--- | --- | ---
`name` | `str` | The name of the function.
`description` | `str` | A description of what the function does.
`parameters` | `dict[str, Any]` | The parameters the functions accepts, described as a JSON Schema object.
`strict` | `bool` | Whether to enforce strict function calling.

Examples:

    >>> function = Function(
    ...     name="get_current_weather",
    ...     description="Get the current weather in a given location",
    ...     parameters={
    ...         "type": "object",
    ...         "properties": {
    ...             "location": {
    ...                 "type": "string",
    ...                 "description": "The city and state, e.g. San Francisco, CA",
    ...             },
    ...             "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
    ...         },
    ...         "required": ["location"],
    ...     },
    ... )

Source code in `pydantic/main.py`

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

    def __init__(self, /, **data: Any) -> None:
        """Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        """
        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
        __tracebackhide__ = True
        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
        if self is not validated_self:
            warnings.warn(
                'A custom validator is returning a value other than `self`.\n'
                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
                stacklevel=2,
            )

### `from_openai(openai_function)` `classmethod`

Convert an OpenAI function definition to a Mistral `Function`.

Filters out unknown fields and defaults missing `parameters` and `description`.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`openai_function` | `dict[str, Any]` | The OpenAI function definition. | required

Returns:

Type | Description
--- | ---
`Function` | The Mistral function.

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

    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71

    @classmethod
    def from_openai(cls, openai_function: dict[str, Any]) -> "Function":
        r"""Convert an OpenAI function definition to a Mistral `Function`.

        Filters out unknown fields and defaults missing `parameters` and `description`.

        Args:
            openai_function: The OpenAI function definition.

        Returns:
            The Mistral function.
        """
        filtered = cls._filter_cls_fields(openai_function)
        if filtered.get("parameters") is None:
            filtered["parameters"] = {}
        if filtered.get("description") is None:
            filtered["description"] = ""
        return cls.model_validate(filtered)

## `FunctionCall(**data)`

Bases: `MistralBase`

Function call.

Attributes:

Name | Type | Description
--- | --- | ---
`name` | `str` | The name of the function to call.
`arguments` | `str` | The arguments to pass to the function.

Examples:

    >>> function_call = FunctionCall(
    ...     name="get_current_weather",
    ...     arguments={"location": "San Francisco, CA", "unit": "celsius"},
    ... )

Source code in `pydantic/main.py`

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

    def __init__(self, /, **data: Any) -> None:
        """Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        """
        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
        __tracebackhide__ = True
        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
        if self is not validated_self:
            warnings.warn(
                'A custom validator is returning a value other than `self`.\n'
                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
                stacklevel=2,
            )

### `validate_arguments(v)`

Convert arguments to a JSON string if they are a dictionary.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`v` | `str | dict[str, Any] | None` | The arguments to validate. | required

Returns:

Type | Description
--- | ---
`str` | The arguments as a JSON string.

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

    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211

    @field_validator("arguments", mode="before")
    def validate_arguments(cls, v: str | dict[str, Any] | None) -> str:
        r"""Convert arguments to a JSON string if they are a dictionary.

        Args:
            v: The arguments to validate.

        Returns:
            The arguments as a JSON string.
        """
        if isinstance(v, dict):
            return json.dumps(v)
        elif v is None:
            return "{}"
        return v

## `FunctionName(**data)`

Bases: `MistralBase`

A function identified by name.

Attributes:

Name | Type | Description
--- | --- | ---
`name` | `str` | The name of the function.

Examples:

    >>> function_name = FunctionName(name="get_current_weather")

Source code in `pydantic/main.py`

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

    def __init__(self, /, **data: Any) -> None:
        """Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        """
        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
        __tracebackhide__ = True
        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
        if self is not validated_self:
            warnings.warn(
                'A custom validator is returning a value other than `self`.\n'
                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
                stacklevel=2,
            )

## `NamedToolChoice(**data)`

Bases: `MistralBase`

Forces the model to call a specific function.

Attributes:

Name | Type | Description
--- | --- | ---
`type` | `ToolTypes` | The type of the tool.
`function` | `FunctionName` | The function the model should call.

Examples:

    >>> named = NamedToolChoice(function=FunctionName(name="get_weather"))
    >>> isinstance(named, ToolChoice)
    True

Source code in `pydantic/main.py`

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

    def __init__(self, /, **data: Any) -> None:
        """Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        """
        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
        __tracebackhide__ = True
        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
        if self is not validated_self:
            warnings.warn(
                'A custom validator is returning a value other than `self`.\n'
                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
                stacklevel=2,
            )

## `Tool(**data)`

Bases: `MistralBase`

Tool definition.

Attributes:

Name | Type | Description
--- | --- | ---
`type` | `ToolTypes` | The type of the tool.
`function` | `Function` | The function definition.

Examples:

    >>> tool = Tool(
    ...     function=Function(
    ...         name="get_current_weather",
    ...         description="Get the current weather in a given location",
    ...         parameters={
    ...             "type": "object",
    ...             "properties": {
    ...                 "location": {
    ...                     "type": "string",
    ...                     "description": "The city and state, e.g. San Francisco, CA",
    ...                 },
    ...                 "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
    ...             },
    ...             "required": ["location"],
    ...         },
    ...     ),
    ... )

Source code in `pydantic/main.py`

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

    def __init__(self, /, **data: Any) -> None:
        """Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        """
        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
        __tracebackhide__ = True
        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
        if self is not validated_self:
            warnings.warn(
                'A custom validator is returning a value other than `self`.\n'
                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
                stacklevel=2,
            )

### `from_openai(openai_tool)` `classmethod`

Convert an OpenAI tool definition to a Mistral `Tool`.

Delegates function parsing to `Function.from_openai`.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`openai_tool` | `dict[str, Any]` | The OpenAI tool definition. | required

Returns:

Type | Description
--- | ---
`Tool` | The Mistral tool.

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

    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177

    @classmethod
    def from_openai(cls, openai_tool: dict[str, Any]) -> "Tool":
        r"""Convert an OpenAI tool definition to a Mistral `Tool`.

        Delegates function parsing to `Function.from_openai`.

        Args:
            openai_tool: The OpenAI tool definition.

        Returns:
            The Mistral tool.
        """
        openai_tool = openai_tool.copy()
        if function := openai_tool.get("function"):
            openai_tool["function"] = Function.from_openai(function)
        return cls.model_validate_ignore_extra(openai_tool)

## `ToolCall(**data)`

Bases: `MistralBase`

Tool call.

Attributes:

Name | Type | Description
--- | --- | ---
`id` | `str` | The ID of the tool call. Required for V3+ tokenization
`type` | `ToolTypes` | The type of the tool call.
`function` | `FunctionCall` | The function call.

Examples:

    >>> tool_call = ToolCall(
    ...     id="call_abc123",
    ...     function=FunctionCall(
    ...         name="get_current_weather",
    ...         arguments={"location": "San Francisco, CA", "unit": "celsius"},
    ...     ),
    ... )

Source code in `pydantic/main.py`

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

    def __init__(self, /, **data: Any) -> None:
        """Create a new model by parsing and validating input data from keyword arguments.

        Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
        validated to form a valid model.

        `self` is explicitly positional-only to allow `self` as a field name.
        """
        # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
        __tracebackhide__ = True
        validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
        if self is not validated_self:
            warnings.warn(
                'A custom validator is returning a value other than `self`.\n'
                "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
                'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
                stacklevel=2,
            )

## `ToolChoiceEnum`

Bases: `str`, `Enum`

Enum of tool choice types.

Attributes:

Name | Type | Description
--- | --- | ---
`auto` |  | Automatically choose the tool.
`none` |  | Do not use any tools.
`any` |  | Deprecated in favor of `required`.
`required` |  | Require the model to call at least one tool.

Examples:

    >>> tool_choice = ToolChoiceEnum.auto
    >>> isinstance(tool_choice, ToolChoice)
    True

## `ToolTypes`

Bases: `str`, `Enum`

Enum of tool types.

Attributes:

Name | Type | Description
--- | --- | ---
`function` |  | A function tool.

Examples:

    >>> tool_type = ToolTypes.function