Skip to content

mistral_common.protocol.instruct.tool_calls

ToolChoice = ToolChoiceEnum | NamedToolChoice module-attribute

Tool choice can be either a ToolChoiceEnum value or a NamedToolChoice instance.

Function(**data)

Bases: FunctionName

Complete function definition for a tool.

Defines a callable function with its schema and metadata. Used within Tool definitions to specify what functions are available.

Attributes:

Name Type Description
name str

Function name. Used by the model to identify which function to call.

description str

Human-readable description of the function's purpose. Displayed to help users understand when to use this function.

parameters dict[str, Any]

JSON Schema object defining the function's parameters. Used for validation and to generate the function call arguments. Must have "type": "object" and define "properties" and optionally "required".

strict bool

If True, the function's parameters schema is enforced: the model's arguments must conform to it. If False (default), the parameters schema is not enforced and the model may emit any JSON object as arguments.

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
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.

Handles conversion from OpenAI's format, filtering out unknown fields and providing defaults for missing required fields.

Parameters:

Name Type Description Default
openai_function dict[str, Any]

Dictionary matching OpenAI's function schema. Must contain at least a "name" key.

required

Returns:

Type Description
Function

Function instance with parameters and description defaulted to

Function

empty dict and empty string respectively if not provided.

Source code in src/mistral_common/protocol/instruct/tool_calls.py
@classmethod
def from_openai(cls, openai_function: dict[str, Any]) -> "Function":
    r"""Convert an OpenAI function definition to a Mistral Function.

    Handles conversion from OpenAI's format, filtering out unknown fields
    and providing defaults for missing required fields.

    Args:
        openai_function: Dictionary matching OpenAI's function schema.
            Must contain at least a "name" key.

    Returns:
        Function instance with parameters and description defaulted to
        empty dict and empty string respectively if not provided.
    """
    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

Represents a function call made by the model.

Contains the function name and its arguments as they would be passed to the actual function.

Attributes:

Name Type Description
name str

The name of the function being called.

arguments str

JSON string of the arguments to pass to the function. Stored as a string but parsed from/to dict for convenience.

Examples:

>>> function_call = FunctionCall(
...     name="get_current_weather",
...     arguments={"location": "San Francisco, CA", "unit": "celsius"},
... )
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,
        )

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 value. Can be a dict (converted to JSON string), str (used as-is), or None (converted to "{}").

required

Returns:

Type Description
str

The arguments as a JSON string.

Source code in src/mistral_common/protocol/instruct/tool_calls.py
@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 value. Can be a dict (converted to JSON string),
            str (used as-is), or `None` (converted to "{}").

    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

Identifier for a function by its name.

Used to reference a function without its full definition.

Attributes:

Name Type Description
name str

The function name string. Must be a valid identifier.

Examples:

>>> function_name = FunctionName(name="get_current_weather")
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,
        )

NamedToolChoice(**data)

Bases: MistralBase

Forces the model to call a specific function.

Use this to constrain the model to use a particular function rather than letting it choose from available tools.

Attributes:

Name Type Description
type ToolTypes

The tool type. Must be ToolTypes.function.

function FunctionName

The FunctionName identifying which specific function to call. The model will only use this function, regardless of what tools are available.

Examples:

>>> named = NamedToolChoice(function=FunctionName(name="get_weather"))
>>> isinstance(named, ToolChoice)
True
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,
        )

Tool(**data)

Bases: MistralBase

Definition of a tool available to the model.

A tool combines a function definition with metadata about how it should be presented and used.

Attributes:

Name Type Description
type ToolTypes

The tool type. Must be ToolTypes.function.

function Function

The Function definition specifying the callable function, its parameters, and description.

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

Create a Tool from an OpenAI tool definition.

Converts OpenAI's tool format to Mistral's format, delegating function parsing to Function.from_openai.

Parameters:

Name Type Description Default
openai_tool dict[str, Any]

Dictionary matching OpenAI's tool schema. Must have "type" and optionally "function" keys.

required

Returns:

Type Description
Tool

Tool instance with the function converted from OpenAI format.

Source code in src/mistral_common/protocol/instruct/tool_calls.py
@classmethod
def from_openai(cls, openai_tool: dict[str, Any]) -> "Tool":
    r"""Create a Tool from an OpenAI tool definition.

    Converts OpenAI's tool format to Mistral's format, delegating function
    parsing to Function.`from_openai`.

    Args:
        openai_tool: Dictionary matching OpenAI's tool schema. Must have
            "type" and optionally "function" keys.

    Returns:
        Tool instance with the function converted from OpenAI format.
    """
    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)

to_openai()

Convert this tool to OpenAI format.

Returns:

Type Description
dict[str, Any]

Dictionary matching OpenAI's tool schema.

Source code in src/mistral_common/protocol/instruct/tool_calls.py
def to_openai(self) -> dict[str, Any]:
    r"""Convert this tool to OpenAI format.

    Returns:
        Dictionary matching OpenAI's tool schema.
    """
    return self.model_dump()

ToolCall(**data)

Bases: MistralBase

Represents a tool call made by the model during generation.

A tool call wraps a FunctionCall with metadata including a unique ID.

Attributes:

Name Type Description
id str

Unique identifier for this tool call. Must be a non-empty string for tokenizer version >= v13. Defaults to "null" for backwards compatibility.

type ToolTypes

The tool type. Must be ToolTypes.function.

function FunctionCall

The FunctionCall containing the function name and arguments.

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

Create a ToolCall from an OpenAI tool call definition.

Parameters:

Name Type Description Default
tool_call dict[str, Any]

Dictionary matching OpenAI's tool call schema.

required

Returns:

Type Description
ToolCall

ToolCall instance with fields parsed from the OpenAI format.

Source code in src/mistral_common/protocol/instruct/tool_calls.py
@classmethod
def from_openai(cls, tool_call: dict[str, Any]) -> "ToolCall":
    r"""Create a ToolCall from an OpenAI tool call definition.

    Args:
        tool_call: Dictionary matching OpenAI's tool call schema.

    Returns:
        ToolCall instance with fields parsed from the OpenAI format.
    """
    return cls.model_validate_ignore_extra(tool_call)

to_openai()

Convert this tool call to OpenAI format.

Returns:

Type Description
dict[str, Any]

Dictionary matching OpenAI's tool call schema.

Source code in src/mistral_common/protocol/instruct/tool_calls.py
def to_openai(self) -> dict[str, Any]:
    r"""Convert this tool call to OpenAI format.

    Returns:
        Dictionary matching OpenAI's tool call schema.
    """
    return self.model_dump()

ToolChoiceEnum

Bases: str, Enum

Enum controlling how the model selects tools.

Attributes:

Name Type Description
auto

Model automatically decides whether to call tools.

none

Model will not call any tools.

any

Deprecated; use required instead.

required

Model must call at least one available tool.

Examples:

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

ToolTypes

Bases: str, Enum

Enum of supported tool types.

Attributes:

Name Type Description
function

A function tool that can be called with arguments.

Examples:

>>> tool_type = ToolTypes.function