Skip to content

mistral_common.protocol.instruct.chunk

AudioChunk(**data)

Bases: BaseContentChunk

Audio content provided inline as base64 or raw bytes.

Attributes:

Name Type Description
input_audio str | bytes

The audio data as a base64-encoded string (optionally with a data:audio/;base64, prefix) or raw bytes. The format is detected at serialization time.

Examples:

>>> audio_chunk = AudioChunk(input_audio="base64_encoded_audio_data")
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_audio(audio) classmethod

Create an AudioChunk instance from an Audio object.

Parameters:

Name Type Description Default
audio Audio

An Audio object containing audio data.

required

Returns:

Type Description
AudioChunk

An AudioChunk instance initialized with the audio data.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_audio(cls, audio: "Audio") -> "AudioChunk":
    r"""Create an AudioChunk instance from an Audio object.

    Args:
        audio: An Audio object containing audio data.

    Returns:
        An AudioChunk instance initialized with the audio data.
    """
    return cls(input_audio=audio.to_base64(audio.format, False))

from_openai(openai_chunk) classmethod

Convert the OpenAI chunk to the Mistral format.

Parameters:

Name Type Description Default
openai_chunk dict[str, Any]

A dictionary representing the audio chunk in the OpenAI format.

required

Returns:

Type Description
AudioChunk

An AudioChunk instance initialized with the data from the OpenAI chunk.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "AudioChunk":
    r"""Convert the OpenAI chunk to the Mistral format.

    Args:
        openai_chunk: A dictionary representing the audio chunk in the OpenAI format.

    Returns:
        An AudioChunk instance initialized with the data from the OpenAI chunk.
    """
    return cls.model_validate_ignore_extra(openai_chunk)

should_not_be_empty(v) classmethod

Validate that the audio data is not empty.

Source code in src/mistral_common/protocol/instruct/chunk.py
@field_validator("input_audio")
@classmethod
def should_not_be_empty(cls, v: str | bytes) -> str | bytes:
    r"""Validate that the audio data is not empty."""
    if isinstance(v, str) and not v.strip():
        raise ValueError("`input_audio` should not be empty.")
    if isinstance(v, bytes) and not v:
        raise ValueError("`input_audio` should not be empty.")
    return v

to_openai()

Convert the chunk to the OpenAI format.

Returns:

Type Description
dict[str, Any]

A dictionary representing the audio chunk in the OpenAI format.

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

    Returns:
        A dictionary representing the audio chunk in the OpenAI format.
    """
    if isinstance(self.input_audio, bytes):
        content = base64.b64encode(self.input_audio).decode("utf-8")
    else:
        content = _strip_audio_data_url_prefix(self.input_audio)
    fmt = _detect_audio_format(self.input_audio)
    return {
        "type": self.type,
        "input_audio": {
            "data": content,
            "format": fmt,
        },
    }

AudioURL(**data)

Bases: MistralBase

Audio URL reference.

Attributes:

Name Type Description
url str

The URL of the audio file.

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

AudioURLChunk(**data)

Bases: BaseContentChunk

Audio content referenced by URL, path, file URI or base64.

The URL kind is resolved lazily by get_url_type; the audio itself is loaded at tokenization time.

Attributes:

Name Type Description
audio_url str | AudioURL

The audio reference. Either an AudioURL instance or a plain string (URL, file path, file URI, or base64).

Examples:

>>> audio_url_chunk = AudioURLChunk(audio_url="https://example.com/audio.mp3")
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,
        )

url property

The audio URL string.

Returns:

Type Description
str

The URL regardless of whether audio_url is an AudioURL or a plain string.

from_openai(openai_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "AudioURLChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate_ignore_extra(openai_chunk)

get_url_type()

Detect the kind of the referenced audio URL.

Note

URLs should be either: - a valid URL (http:// or https://) - a valid file path (e.g. /path/to/file) - a valid file URI (e.g. file:///path/to/file) - a base64 encoded audio. It is assumed to be base64 encoded if it is not a valid URL or file path.

Returns:

Type Description
AudioURLType

The detected AudioURLType for this chunk's URL.

Source code in src/mistral_common/protocol/instruct/chunk.py
def get_url_type(self) -> AudioURLType:
    r"""Detect the kind of the referenced audio URL.

    Note:
        URLs should be either:
        - a valid URL (http:// or https://)
        - a valid file path (e.g. /path/to/file)
        - a valid file URI (e.g. file:///path/to/file)
        - a base64 encoded audio. It is assumed to be base64 encoded if it is not a valid URL or file path.

    Returns:
        The detected AudioURLType for this chunk's URL.
    """
    url_scheme = urlparse(self.url).scheme
    if url_scheme in {"http", "https"}:
        return AudioURLType.url
    elif url_scheme == "data":
        return AudioURLType.base64
    elif url_scheme == "file":
        return AudioURLType.file_uri

    try:
        url_path = Path(self.url)
        exist_path = url_path.exists()
    except OSError:  # File name too long
        exist_path = False

    if exist_path:
        return AudioURLType.file

    return AudioURLType.base64

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/chunk.py
def to_openai(self) -> dict[str, Any]:
    r"""Converts the chunk to the OpenAI format."""
    if isinstance(self.audio_url, AudioURL):
        return self.model_dump()
    else:
        return {"type": self.type, "audio_url": {"url": self.audio_url}}

AudioURLType

Bases: str, Enum

Enum for the kinds of audio URL references.

Attributes:

Name Type Description
url

An http(s) URL.

base64

A base64-encoded audio string. May be prefixed with data:audio/<format>;base64,.

file

A local file path (e.g., /path/to/file).

file_uri

A file URI (e.g., file:///path/to/file).

BaseContentChunk(**data)

Bases: MistralBase

Base class for all content chunks.

Content chunks represent a piece of multimodal content (text, image, audio, thinking) inside a message. A message's content can be a string or a list of these chunks.

Attributes:

Name Type Description
type Literal[text, image, image_url, input_audio, audio_url, thinking]

The chunk type, used as the pydantic discriminator.

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_chunk) classmethod

Create a chunk instance from OpenAI format.

Must be implemented by concrete subclasses.

Parameters:

Name Type Description Default
openai_chunk dict[str, Any]

Dictionary matching OpenAI's content chunk schema.

required

Returns:

Type Description
BaseContentChunk

Chunk instance of the appropriate subclass.

Raises:

Type Description
NotImplementedError

Always, as this is an abstract method.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "BaseContentChunk":
    r"""Create a chunk instance from OpenAI format.

    Must be implemented by concrete subclasses.

    Args:
        openai_chunk: Dictionary matching OpenAI's content chunk schema.

    Returns:
        Chunk instance of the appropriate subclass.

    Raises:
        NotImplementedError: Always, as this is an abstract method.
    """
    raise NotImplementedError(f"from_openai method not implemented for {cls.__name__}")

to_openai()

Convert this chunk to the OpenAI format.

Must be implemented by concrete subclasses.

Returns:

Type Description
dict[str, Any]

Dictionary matching OpenAI's content chunk schema.

Raises:

Type Description
NotImplementedError

Always, as this is an abstract method.

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

    Must be implemented by concrete subclasses.

    Returns:
        Dictionary matching OpenAI's content chunk schema.

    Raises:
        NotImplementedError: Always, as this is an abstract method.
    """
    raise NotImplementedError(f"to_openai method not implemented for {type(self).__name__}")

ChunkTypes

Bases: str, Enum

Enum of the types of content chunks that can be sent to the model.

Attributes:

Name Type Description
text

A plain text chunk.

image

An image provided as raw data (PIL image, base64, URL or path).

image_url

An image referenced by URL or base64 data URL.

input_audio

Audio provided inline as base64 or raw bytes.

audio_url

Audio referenced by URL, file path, file URI or base64.

thinking

A reasoning/thinking chunk from the assistant.

Examples:

>>> from mistral_common.protocol.instruct.chunk import ChunkTypes
>>> chunk_type = ChunkTypes.text

ImageChunk(**data)

Bases: BaseContentChunk

Image content provided as raw data.

The image is processed (resized, serialized) at tokenization time by the image encoder.

Attributes:

Name Type Description
image SerializableImage

The image to send to the model. Accepts a PIL image, a URL (http/https), a base64-encoded string (optionally with a data:...;base64, prefix), or a local file path.

Examples:

>>> from PIL import Image
>>> image_chunk = ImageChunk(image=Image.new('RGB', (200, 200), color='blue'))
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_chunk) classmethod

Create an ImageChunk from an OpenAI image_url chunk.

Parameters:

Name Type Description Default
openai_chunk dict[str, Any]

Dictionary with "type" set to image_url and an image_url -> "url" entry (URL or base64 data URL).

required

Returns:

Type Description
ImageChunk

An ImageChunk with the base64 prefix stripped if present.

Raises:

Type Description
AssertionError

If the chunk type is not image_url or the image_url entry is malformed.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "ImageChunk":
    r"""Create an ImageChunk from an OpenAI `image_url` chunk.

    Args:
        openai_chunk: Dictionary with "type" set to `image_url` and an
            `image_url` -> "url" entry (URL or base64 data URL).

    Returns:
        An ImageChunk with the base64 prefix stripped if present.

    Raises:
        AssertionError: If the chunk type is not `image_url` or the
            `image_url` entry is malformed.
    """
    assert openai_chunk.get("type") == "image_url", openai_chunk

    image_url_dict = openai_chunk["image_url"]
    assert isinstance(image_url_dict, dict) and "url" in image_url_dict, image_url_dict

    url = image_url_dict["url"]
    if re.match(r"^data:image/\w+;base64,", url):  # Remove the prefix if it exists
        url = url.split(",")[1]

    return cls.model_validate({"image": url})

to_openai()

Convert this chunk to the OpenAI image_url format.

Returns:

Type Description
dict[str, Any]

Dictionary with "type" set to image_url and the image as a

dict[str, Any]

base64 data URL under image_url -> "url".

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

    Returns:
        Dictionary with "type" set to `image_url` and the image as a
        base64 data URL under `image_url` -> "url".
    """
    base64_image = self.model_dump(include={"image"}, context={"add_format_prefix": True})["image"]
    return {"type": "image_url", "image_url": {"url": base64_image}}

ImageURL(**data)

Bases: MistralBase

Image URL with optional detail level.

Attributes:

Name Type Description
url str

The URL of the image, or a base64-encoded image (optionally with a data:...;base64, prefix).

detail str | None

Optional detail level hint for image processing (e.g., "high", "low", "auto"). If None, the default is used.

Examples:

>>> image_url = ImageURL(url="https://example.com/image.png")
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,
        )

ImageURLChunk(**data)

Bases: BaseContentChunk

Image content referenced by URL or base64 data URL.

Unlike ImageChunk, the image is not loaded at request construction time; the URL is resolved at tokenization time.

Attributes:

Name Type Description
image_url ImageURL | str

The image reference. Either an ImageURL instance (allowing a detail hint) or a plain URL/base64 string.

Examples:

>>> image_url_chunk = ImageURLChunk(image_url="data:image/png;base64,iVBORw0")
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_chunk) classmethod

Create an ImageURLChunk from an OpenAI chunk.

Parameters:

Name Type Description Default
openai_chunk dict[str, Any]

Dictionary with an image_url entry (dict or string).

required

Returns:

Type Description
ImageURLChunk

An ImageURLChunk with the image_url parsed from the OpenAI format.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "ImageURLChunk":
    r"""Create an ImageURLChunk from an OpenAI chunk.

    Args:
        openai_chunk: Dictionary with an `image_url` entry (dict or string).

    Returns:
        An ImageURLChunk with the `image_url` parsed from the OpenAI format.
    """
    return cls.model_validate({"image_url": openai_chunk["image_url"]})

get_url()

Return the underlying image URL string.

Returns:

Type Description
str

The URL regardless of whether image_url is an ImageURL or a plain string.

Source code in src/mistral_common/protocol/instruct/chunk.py
def get_url(self) -> str:
    r"""Return the underlying image URL string.

    Returns:
        The URL regardless of whether `image_url` is an ImageURL or a plain string.
    """
    if isinstance(self.image_url, ImageURL):
        return self.image_url.url
    return self.image_url

to_openai()

Convert this chunk to the OpenAI format.

Returns:

Type Description
dict[str, Any]

Dictionary with "type" set to image_url and the URL (plus

dict[str, Any]

optional "detail") under image_url.

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

    Returns:
        Dictionary with "type" set to `image_url` and the URL (plus
        optional "detail") under `image_url`.
    """
    image_url_dict = {"url": self.get_url()}
    if isinstance(self.image_url, ImageURL) and self.image_url.detail is not None:
        image_url_dict["detail"] = self.image_url.detail

    out_dict: dict[str, Any] = {
        "type": "image_url",
        "image_url": image_url_dict,
    }
    return out_dict

RawAudio(**data)

Bases: MistralBase

Audio data with an explicit format.

Deprecated: Use str | bytes directly. Will be removed in 1.13.0.

Attributes:

Name Type Description
data str | bytes

The audio data as raw bytes or a base64-encoded string.

format str

The audio format (e.g., "wav", "mp3"). Must not be empty.

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_audio(audio) classmethod

Create a RawAudio instance from an Audio object.

Parameters:

Name Type Description Default
audio Audio

An Audio object containing audio data, format, and duration.

required

Returns:

Type Description
RawAudio

A RawAudio instance initialized with the audio data.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_audio(cls, audio: "Audio") -> "RawAudio":
    r"""Create a RawAudio instance from an Audio object.

    Args:
        audio: An Audio object containing audio data, format, and duration.

    Returns:
        A RawAudio instance initialized with the audio data.
    """
    format = audio.format
    data = audio.to_base64(format, False)
    return cls(data=data, format=format)

model_post_init(__context)

Emit a one-shot deprecation warning for RawAudio.

Source code in src/mistral_common/protocol/instruct/chunk.py
def model_post_init(self, __context: Any) -> None:
    r"""Emit a one-shot deprecation warning for `RawAudio`."""
    warn_once(
        "RawAudio",
        "RawAudio is deprecated. Use str | bytes directly for audio data. Will be removed in 1.13.0.",
        DeprecationWarning,
        stacklevel=2,
    )

should_not_be_empty(v)

Reject empty format strings.

Returns:

Type Description
str

The unchanged format string if non-empty.

Raises:

Type Description
ValueError

If format is empty or whitespace.

Source code in src/mistral_common/protocol/instruct/chunk.py
@field_validator("format")
def should_not_be_empty(cls, v: str) -> str:
    r"""Reject empty format strings.

    Returns:
        The unchanged format string if non-empty.

    Raises:
        ValueError: If `format` is empty or whitespace.
    """
    if not v.strip():
        raise ValueError("`format` should not be empty")

    return v

TextChunk(**data)

Bases: BaseContentChunk

Text chunk.

Attributes:

Name Type Description
text str

The text to be sent to the model.

Examples:

>>> text_chunk = TextChunk(text="Hello, how can I help you?")
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_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "TextChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate_ignore_extra(openai_chunk)

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/chunk.py
def to_openai(self) -> dict[str, Any]:
    r"""Converts the chunk to the OpenAI format."""
    return self.model_dump()

ThinkChunk(**data)

Bases: BaseContentChunk

Reasoning/thinking content from the assistant.

ThinkChunks represent chain-of-thought text the model produces before the final answer. In AssistantMessage content they must appear before any other chunk.

Attributes:

Name Type Description
thinking str

The thinking text content.

closed bool

If True (default), the thinking section is complete. If False, the thinking is ongoing (e.g., mid-stream during generation).

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_chunk) classmethod

Converts the OpenAI chunk to the Mistral format.

Source code in src/mistral_common/protocol/instruct/chunk.py
@classmethod
def from_openai(cls, openai_chunk: dict[str, Any]) -> "ThinkChunk":
    r"""Converts the OpenAI chunk to the Mistral format."""
    return cls.model_validate_ignore_extra(openai_chunk)

to_openai()

Converts the chunk to the OpenAI format.

Source code in src/mistral_common/protocol/instruct/chunk.py
def to_openai(self) -> dict[str, Any]:
    r"""Converts the chunk to the OpenAI format."""
    return self.model_dump()