Skip to content

mistral.types

Types for working with Mistral prompts.

AssistantMessage

Bases: TypedDict

A message with the assistant role.

Attributes:

Name Type Description
role Required[Literal['assistant']]

The role of the message's author, in this case assistant.

content Required[str]

The contents of the message.

Source code in mirascope/base/types.py
class AssistantMessage(TypedDict, total=False):
    """A message with the `assistant` role.

    Attributes:
        role: The role of the message's author, in this case `assistant`.
        content: The contents of the message.
    """

    role: Required[Literal["assistant"]]
    content: Required[str]

BaseAsyncStream

Bases: Generic[BaseCallResponseChunkT, UserMessageParamT, AssistantMessageParamT, BaseToolT], ABC

A base class for async streaming responses from LLMs.

Source code in mirascope/base/types.py
class BaseAsyncStream(
    Generic[
        BaseCallResponseChunkT,
        UserMessageParamT,
        AssistantMessageParamT,
        BaseToolT,
    ],
    ABC,
):
    """A base class for async streaming responses from LLMs."""

    stream: AsyncGenerator[BaseCallResponseChunkT, None]
    message_param_type: type[AssistantMessageParamT]

    cost: Optional[float] = None
    user_message_param: Optional[UserMessageParamT] = None
    message_param: AssistantMessageParamT

    def __init__(
        self,
        stream: AsyncGenerator[BaseCallResponseChunkT, None],
        message_param_type: type[AssistantMessageParamT],
    ):
        """Initializes an instance of `BaseAsyncStream`."""
        self.stream = stream
        self.message_param_type = message_param_type

    def __aiter__(
        self,
    ) -> AsyncGenerator[tuple[BaseCallResponseChunkT, Optional[BaseToolT]], None]:
        """Iterates over the stream and stores useful information."""

        async def generator():
            content = ""
            async for chunk in self.stream:
                content += chunk.content
                if chunk.cost is not None:
                    self.cost = chunk.cost
                yield chunk, None
                self.user_message_param = chunk.user_message_param
            kwargs = {"role": "assistant"}
            if "message" in self.message_param_type.__annotations__:
                kwargs["message"] = content
            else:
                kwargs["content"] = content
            self.message_param = self.message_param_type(**kwargs)

        return generator()

BaseCallParams

Bases: BaseModel, Generic[BaseToolT]

The parameters with which to make a call.

Source code in mirascope/base/types.py
class BaseCallParams(BaseModel, Generic[BaseToolT]):
    """The parameters with which to make a call."""

    model: str
    tools: Optional[list[Union[Callable, Type[BaseToolT]]]] = None

    model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)

    def kwargs(
        self,
        tool_type: Optional[Type[BaseToolT]] = None,
        exclude: Optional[set[str]] = None,
    ) -> dict[str, Any]:
        """Returns all parameters for the call as a keyword arguments dictionary."""
        extra_exclude = {"tools"}
        exclude = extra_exclude if exclude is None else exclude.union(extra_exclude)
        kwargs = {
            key: value
            for key, value in self.model_dump(exclude=exclude).items()
            if value is not None
        }
        if not self.tools or tool_type is None:
            return kwargs
        kwargs["tools"] = [
            tool if isclass(tool) else convert_function_to_tool(tool, tool_type)
            for tool in self.tools
        ]
        return kwargs

kwargs(tool_type=None, exclude=None)

Returns all parameters for the call as a keyword arguments dictionary.

Source code in mirascope/base/types.py
def kwargs(
    self,
    tool_type: Optional[Type[BaseToolT]] = None,
    exclude: Optional[set[str]] = None,
) -> dict[str, Any]:
    """Returns all parameters for the call as a keyword arguments dictionary."""
    extra_exclude = {"tools"}
    exclude = extra_exclude if exclude is None else exclude.union(extra_exclude)
    kwargs = {
        key: value
        for key, value in self.model_dump(exclude=exclude).items()
        if value is not None
    }
    if not self.tools or tool_type is None:
        return kwargs
    kwargs["tools"] = [
        tool if isclass(tool) else convert_function_to_tool(tool, tool_type)
        for tool in self.tools
    ]
    return kwargs

BaseCallResponse

Bases: BaseModel, Generic[ResponseT, BaseToolT], ABC

A base abstract interface for LLM call responses.

Attributes:

Name Type Description
response ResponseT

The original response from whichever model response this wraps.

Source code in mirascope/base/types.py
class BaseCallResponse(BaseModel, Generic[ResponseT, BaseToolT], ABC):
    """A base abstract interface for LLM call responses.

    Attributes:
        response: The original response from whichever model response this wraps.
    """

    response: ResponseT
    user_message_param: Optional[Any] = None
    tool_types: Optional[list[Type[BaseToolT]]] = None
    start_time: float  # The start time of the completion in ms
    end_time: float  # The end time of the completion in ms
    cost: Optional[float] = None  # The cost of the completion in dollars

    model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)

    @property
    @abstractmethod
    def message_param(self) -> Any:
        """Returns the assistant's response as a message parameter."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def tools(self) -> Optional[list[BaseToolT]]:
        """Returns the tools for the 0th choice message."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def tool(self) -> Optional[BaseToolT]:
        """Returns the 0th tool for the 0th choice message."""
        ...  # pragma: no cover

    @classmethod
    @abstractmethod
    def tool_message_params(
        cls, tools_and_outputs: list[tuple[BaseToolT, Any]]
    ) -> list[Any]:
        """Returns the tool message parameters for tool call results."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def content(self) -> str:
        """Should return the string content of the response.

        If there are multiple choices in a response, this method should select the 0th
        choice and return it's string content.

        If there is no string content (e.g. when using tools), this method must return
        the empty string.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def finish_reasons(self) -> Union[None, list[str]]:
        """Should return the finish reasons of the response.

        If there is no finish reason, this method must return None.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def model(self) -> Optional[str]:
        """Should return the name of the response model."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def id(self) -> Optional[str]:
        """Should return the id of the response."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def usage(self) -> Any:
        """Should return the usage of the response.

        If there is no usage, this method must return None.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def input_tokens(self) -> Optional[Union[int, float]]:
        """Should return the number of input tokens.

        If there is no input_tokens, this method must return None.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def output_tokens(self) -> Optional[Union[int, float]]:
        """Should return the number of output tokens.

        If there is no output_tokens, this method must return None.
        """
        ...  # pragma: no cover

content: str abstractmethod property

Should return the string content of the response.

If there are multiple choices in a response, this method should select the 0th choice and return it's string content.

If there is no string content (e.g. when using tools), this method must return the empty string.

finish_reasons: Union[None, list[str]] abstractmethod property

Should return the finish reasons of the response.

If there is no finish reason, this method must return None.

id: Optional[str] abstractmethod property

Should return the id of the response.

input_tokens: Optional[Union[int, float]] abstractmethod property

Should return the number of input tokens.

If there is no input_tokens, this method must return None.

message_param: Any abstractmethod property

Returns the assistant's response as a message parameter.

model: Optional[str] abstractmethod property

Should return the name of the response model.

output_tokens: Optional[Union[int, float]] abstractmethod property

Should return the number of output tokens.

If there is no output_tokens, this method must return None.

tool: Optional[BaseToolT] abstractmethod property

Returns the 0th tool for the 0th choice message.

tools: Optional[list[BaseToolT]] abstractmethod property

Returns the tools for the 0th choice message.

usage: Any abstractmethod property

Should return the usage of the response.

If there is no usage, this method must return None.

tool_message_params(tools_and_outputs) abstractmethod classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/base/types.py
@classmethod
@abstractmethod
def tool_message_params(
    cls, tools_and_outputs: list[tuple[BaseToolT, Any]]
) -> list[Any]:
    """Returns the tool message parameters for tool call results."""
    ...  # pragma: no cover

BaseCallResponseChunk

Bases: BaseModel, Generic[ChunkT, BaseToolT], ABC

A base abstract interface for LLM streaming response chunks.

Attributes:

Name Type Description
response

The original response chunk from whichever model response this wraps.

Source code in mirascope/base/types.py
class BaseCallResponseChunk(BaseModel, Generic[ChunkT, BaseToolT], ABC):
    """A base abstract interface for LLM streaming response chunks.

    Attributes:
        response: The original response chunk from whichever model response this wraps.
    """

    chunk: ChunkT
    user_message_param: Optional[Any] = None
    tool_types: Optional[list[Type[BaseToolT]]] = None
    cost: Optional[float] = None  # The cost of the completion in dollars
    model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)

    @property
    @abstractmethod
    def content(self) -> str:
        """Should return the string content of the response chunk.

        If there are multiple choices in a chunk, this method should select the 0th
        choice and return it's string content.

        If there is no string content (e.g. when using tools), this method must return
        the empty string.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def model(self) -> Optional[str]:
        """Should return the name of the response model."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def id(self) -> Optional[str]:
        """Should return the id of the response."""
        ...  # pragma: no cover

    @property
    @abstractmethod
    def finish_reasons(self) -> Union[None, list[str]]:
        """Should return the finish reasons of the response.

        If there is no finish reason, this method must return None.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def usage(self) -> Any:
        """Should return the usage of the response.

        If there is no usage, this method must return None.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def input_tokens(self) -> Optional[Union[int, float]]:
        """Should return the number of input tokens.

        If there is no input_tokens, this method must return None.
        """
        ...  # pragma: no cover

    @property
    @abstractmethod
    def output_tokens(self) -> Optional[Union[int, float]]:
        """Should return the number of output tokens.

        If there is no output_tokens, this method must return None.
        """
        ...  # pragma: no cover

content: str abstractmethod property

Should return the string content of the response chunk.

If there are multiple choices in a chunk, this method should select the 0th choice and return it's string content.

If there is no string content (e.g. when using tools), this method must return the empty string.

finish_reasons: Union[None, list[str]] abstractmethod property

Should return the finish reasons of the response.

If there is no finish reason, this method must return None.

id: Optional[str] abstractmethod property

Should return the id of the response.

input_tokens: Optional[Union[int, float]] abstractmethod property

Should return the number of input tokens.

If there is no input_tokens, this method must return None.

model: Optional[str] abstractmethod property

Should return the name of the response model.

output_tokens: Optional[Union[int, float]] abstractmethod property

Should return the number of output tokens.

If there is no output_tokens, this method must return None.

usage: Any abstractmethod property

Should return the usage of the response.

If there is no usage, this method must return None.

BaseStream

Bases: Generic[BaseCallResponseChunkT, UserMessageParamT, AssistantMessageParamT, BaseToolT], ABC

A base class for streaming responses from LLMs.

Source code in mirascope/base/types.py
class BaseStream(
    Generic[
        BaseCallResponseChunkT,
        UserMessageParamT,
        AssistantMessageParamT,
        BaseToolT,
    ],
    ABC,
):
    """A base class for streaming responses from LLMs."""

    stream: Generator[BaseCallResponseChunkT, None, None]
    message_param_type: type[AssistantMessageParamT]

    cost: Optional[float] = None
    user_message_param: Optional[UserMessageParamT] = None
    message_param: AssistantMessageParamT

    def __init__(
        self,
        stream: Generator[BaseCallResponseChunkT, None, None],
        message_param_type: type[AssistantMessageParamT],
    ):
        """Initializes an instance of `BaseStream`."""
        self.stream = stream
        self.message_param_type = message_param_type

    def __iter__(
        self,
    ) -> Generator[tuple[BaseCallResponseChunkT, Optional[BaseToolT]], None, None]:
        """Iterator over the stream and stores useful information."""
        content = ""
        for chunk in self.stream:
            content += chunk.content
            if chunk.cost is not None:
                self.cost = chunk.cost
            yield chunk, None
            self.user_message_param = chunk.user_message_param
        kwargs = {"role": "assistant"}
        if "message" in self.message_param_type.__annotations__:
            kwargs["message"] = content
        else:
            kwargs["content"] = content
        self.message_param = self.message_param_type(**kwargs)

MistralAsyncStream

Bases: BaseAsyncStream[MistralCallResponseChunk, UserMessage, AssistantMessage, MistralTool]

A class for streaming responses from Mistral's API.

Source code in mirascope/mistral/types.py
class MistralAsyncStream(
    BaseAsyncStream[
        MistralCallResponseChunk,
        UserMessage,
        AssistantMessage,
        MistralTool,
    ]
):
    """A class for streaming responses from Mistral's API."""

    def __init__(self, stream: AsyncGenerator[MistralCallResponseChunk, None]):
        """Initializes an instance of `MistralAsyncStream`."""
        super().__init__(stream, AssistantMessage)

MistralCallParams

Bases: BaseCallParams[MistralTool]

The parameters to use when calling the Mistral API.

Source code in mirascope/mistral/types.py
class MistralCallParams(BaseCallParams[MistralTool]):
    """The parameters to use when calling the Mistral API."""

    model: str = "open-mixtral-8x7b"
    endpoint: Optional[str] = None
    temperature: Optional[float] = None
    max_tokens: Optional[int] = None
    top_p: Optional[float] = None
    random_seed: Optional[int] = None
    safe_mode: Optional[bool] = None
    safe_prompt: Optional[bool] = None
    tool_choice: Optional[ToolChoice] = None
    model_config = ConfigDict(arbitrary_types_allowed=True)

MistralCallResponse

Bases: BaseCallResponse[ChatCompletionResponse, MistralTool]

Convenience wrapper for Mistral's chat model completions.

When using Mirascope's convenience wrappers to interact with Mistral models via MistralCall, responses using MistralCall.call() will return a MistralCallResponse, whereby the implemented properties allow for simpler syntax and a convenient developer experience.

Example:

from mirascope.mistral import MistralCall

class BookRecommender(MistralCall):
    prompt_template = "Please recommend a {genre} book"

    genre: str

response = Bookrecommender(genre="fantasy").call()
print(response.content)
#> The Name of the Wind

print(response.message)
#> ChatMessage(content='The Name of the Wind', role='assistant',
#  function_call=None, tool_calls=None)

print(response.choices)
#> [Choice(finish_reason='stop', index=0, logprobs=None,
#  message=ChatMessage(content='The Name of the Wind', role='assistant',
#  function_call=None, tool_calls=None))]
Source code in mirascope/mistral/types.py
class MistralCallResponse(BaseCallResponse[ChatCompletionResponse, MistralTool]):
    """Convenience wrapper for Mistral's chat model completions.

    When using Mirascope's convenience wrappers to interact with Mistral models via
    `MistralCall`, responses using `MistralCall.call()` will return a
    `MistralCallResponse`, whereby the implemented properties allow for simpler syntax
    and a convenient developer experience.

    Example:

    ```python
    from mirascope.mistral import MistralCall

    class BookRecommender(MistralCall):
        prompt_template = "Please recommend a {genre} book"

        genre: str

    response = Bookrecommender(genre="fantasy").call()
    print(response.content)
    #> The Name of the Wind

    print(response.message)
    #> ChatMessage(content='The Name of the Wind', role='assistant',
    #  function_call=None, tool_calls=None)

    print(response.choices)
    #> [Choice(finish_reason='stop', index=0, logprobs=None,
    #  message=ChatMessage(content='The Name of the Wind', role='assistant',
    #  function_call=None, tool_calls=None))]
    ```

    """

    user_message_param: Optional[Message] = None

    @property
    def message_param(self) -> Message:
        """Returns the assistants's response as a message parameter."""
        return self.message.model_dump()  # type: ignore

    @property
    def choices(self) -> list[ChatCompletionResponseChoice]:
        """Returns the array of chat completion choices."""
        return self.response.choices

    @property
    def choice(self) -> ChatCompletionResponseChoice:
        """Returns the 0th choice."""
        return self.choices[0]

    @property
    def message(self) -> ChatMessage:
        """Returns the message of the chat completion for the 0th choice."""
        return self.choice.message

    @property
    def content(self) -> str:
        """The content of the chat completion for the 0th choice."""
        content = self.message.content
        # We haven't seen the `list[str]` response type in practice, so for now we
        # return the first item in the list
        return content if isinstance(content, str) else content[0]

    @property
    def model(self) -> str:
        """Returns the name of the response model."""
        return self.response.model

    @property
    def id(self) -> str:
        """Returns the id of the response."""
        return self.response.id

    @property
    def finish_reasons(self) -> list[str]:
        """Returns the finish reasons of the response."""
        return [
            choice.finish_reason if choice.finish_reason else ""
            for choice in self.choices
        ]

    @property
    def tool_calls(self) -> Optional[list[ToolCall]]:
        """Returns the tool calls for the 0th choice message."""
        return self.message.tool_calls

    @property
    def tools(self) -> Optional[list[MistralTool]]:
        """Returns the tools for the 0th choice message.

        Raises:
            ValidationError: if the tool call doesn't match the tool's schema.
        """
        if not self.tool_types or not self.tool_calls or len(self.tool_calls) == 0:
            return None

        if self.choice.finish_reason in ["length", "error"]:
            raise RuntimeError(
                f"Finish reason was {self.choice.finish_reason}, indicating the model "
                "ran out of token or failed (and could not complete the tool call if "
                "trying to)."
            )

        extracted_tools = []
        for tool_call in self.tool_calls:
            for tool_type in self.tool_types:
                if tool_call.function.name == tool_type.name():
                    extracted_tools.append(tool_type.from_tool_call(tool_call))
                    break

        return extracted_tools

    @property
    def tool(self) -> Optional[MistralTool]:
        """Returns the 0th tool for the 0th choice message.

        Raises:
            ValidationError: if the tool call doesn't match the tool's schema.
        """
        tools = self.tools
        if tools:
            return tools[0]
        return None

    @classmethod
    def tool_message_params(
        cls, tools_and_outputs: list[tuple[MistralTool, str]]
    ) -> list[ToolMessage]:
        """Returns the tool message parameters for tool call results."""
        return [
            {
                "role": "tool",
                "content": output,
                "tool_call_id": tool.tool_call.id,
                "name": tool.name(),
            }  # type: ignore
            for tool, output in tools_and_outputs
        ]

    @property
    def usage(self) -> UsageInfo:
        """Returns the usage of the chat completion."""
        return self.response.usage

    @property
    def input_tokens(self) -> int:
        """Returns the number of input tokens."""
        return self.usage.prompt_tokens

    @property
    def output_tokens(self) -> Optional[int]:
        """Returns the number of output tokens."""
        return self.usage.completion_tokens

    def dump(self) -> dict[str, Any]:
        """Dumps the response to a dictionary."""
        return {
            "start_time": self.start_time,
            "end_time": self.end_time,
            "output": self.response.model_dump(),
            "cost": self.cost,
        }

choice: ChatCompletionResponseChoice property

Returns the 0th choice.

choices: list[ChatCompletionResponseChoice] property

Returns the array of chat completion choices.

content: str property

The content of the chat completion for the 0th choice.

finish_reasons: list[str] property

Returns the finish reasons of the response.

id: str property

Returns the id of the response.

input_tokens: int property

Returns the number of input tokens.

message: ChatMessage property

Returns the message of the chat completion for the 0th choice.

message_param: Message property

Returns the assistants's response as a message parameter.

model: str property

Returns the name of the response model.

output_tokens: Optional[int] property

Returns the number of output tokens.

tool: Optional[MistralTool] property

Returns the 0th tool for the 0th choice message.

Raises:

Type Description
ValidationError

if the tool call doesn't match the tool's schema.

tool_calls: Optional[list[ToolCall]] property

Returns the tool calls for the 0th choice message.

tools: Optional[list[MistralTool]] property

Returns the tools for the 0th choice message.

Raises:

Type Description
ValidationError

if the tool call doesn't match the tool's schema.

usage: UsageInfo property

Returns the usage of the chat completion.

dump()

Dumps the response to a dictionary.

Source code in mirascope/mistral/types.py
def dump(self) -> dict[str, Any]:
    """Dumps the response to a dictionary."""
    return {
        "start_time": self.start_time,
        "end_time": self.end_time,
        "output": self.response.model_dump(),
        "cost": self.cost,
    }

tool_message_params(tools_and_outputs) classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/mistral/types.py
@classmethod
def tool_message_params(
    cls, tools_and_outputs: list[tuple[MistralTool, str]]
) -> list[ToolMessage]:
    """Returns the tool message parameters for tool call results."""
    return [
        {
            "role": "tool",
            "content": output,
            "tool_call_id": tool.tool_call.id,
            "name": tool.name(),
        }  # type: ignore
        for tool, output in tools_and_outputs
    ]

MistralCallResponseChunk

Bases: BaseCallResponseChunk[ChatCompletionStreamResponse, MistralTool]

Convenience wrapper around chat completion streaming chunks.

When using Mirascope's convenience wrappers to interact with Mistral models via MistralCall.stream, responses will return an MistralCallResponseChunk, whereby the implemented properties allow for simpler syntax and a convenient developer experience.

Example:

from mirascope.mistral import MistralCall


class Math(MistralCall):
    prompt_template = "What is 1 + 2?"


content = ""
for chunk in Math().stream():
    content += chunk.content
    print(content)
#> 1
#  1 +
#  1 + 2
#  1 + 2 equals
#  1 + 2 equals
#  1 + 2 equals 3
#  1 + 2 equals 3.
Source code in mirascope/mistral/types.py
class MistralCallResponseChunk(
    BaseCallResponseChunk[ChatCompletionStreamResponse, MistralTool]
):
    """Convenience wrapper around chat completion streaming chunks.

    When using Mirascope's convenience wrappers to interact with Mistral models via
    `MistralCall.stream`, responses will return an `MistralCallResponseChunk`, whereby
    the implemented properties allow for simpler syntax and a convenient developer
    experience.

    Example:

    ```python
    from mirascope.mistral import MistralCall


    class Math(MistralCall):
        prompt_template = "What is 1 + 2?"


    content = ""
    for chunk in Math().stream():
        content += chunk.content
        print(content)
    #> 1
    #  1 +
    #  1 + 2
    #  1 + 2 equals
    #  1 + 2 equals
    #  1 + 2 equals 3
    #  1 + 2 equals 3.
    ```
    """

    user_message_param: Optional[Message] = None

    @property
    def choices(self) -> list[ChatCompletionResponseStreamChoice]:
        """Returns the array of chat completion choices."""
        return self.chunk.choices

    @property
    def choice(self) -> ChatCompletionResponseStreamChoice:
        """Returns the 0th choice."""
        return self.choices[0]

    @property
    def delta(self) -> DeltaMessage:
        """Returns the delta of the 0th choice."""
        return self.choice.delta

    @property
    def content(self) -> str:
        """Returns the content of the delta."""
        return self.delta.content if self.delta.content is not None else ""

    @property
    def model(self) -> str:
        """Returns the name of the response model."""
        return self.chunk.model

    @property
    def id(self) -> str:
        """Returns the id of the response."""
        return self.chunk.id

    @property
    def finish_reasons(self) -> list[str]:
        """Returns the finish reasons of the response."""
        return [
            choice.finish_reason if choice.finish_reason else ""
            for choice in self.choices
        ]

    @property
    def tool_calls(self) -> Optional[list[ToolCall]]:
        """Returns the partial tool calls for the 0th choice message."""
        return self.delta.tool_calls

    @property
    def usage(self) -> Optional[UsageInfo]:
        """Returns the usage of the chat completion."""
        return self.chunk.usage

    @property
    def input_tokens(self) -> Optional[int]:
        """Returns the number of input tokens."""
        if self.usage:
            return self.usage.prompt_tokens
        return None

    @property
    def output_tokens(self) -> Optional[int]:
        """Returns the number of output tokens."""
        if self.usage:
            return self.usage.completion_tokens
        return None

choice: ChatCompletionResponseStreamChoice property

Returns the 0th choice.

choices: list[ChatCompletionResponseStreamChoice] property

Returns the array of chat completion choices.

content: str property

Returns the content of the delta.

delta: DeltaMessage property

Returns the delta of the 0th choice.

finish_reasons: list[str] property

Returns the finish reasons of the response.

id: str property

Returns the id of the response.

input_tokens: Optional[int] property

Returns the number of input tokens.

model: str property

Returns the name of the response model.

output_tokens: Optional[int] property

Returns the number of output tokens.

tool_calls: Optional[list[ToolCall]] property

Returns the partial tool calls for the 0th choice message.

usage: Optional[UsageInfo] property

Returns the usage of the chat completion.

MistralStream

Bases: BaseStream[MistralCallResponseChunk, UserMessage, AssistantMessage, MistralTool]

A class for streaming responses from Mistral's API.

Source code in mirascope/mistral/types.py
class MistralStream(
    BaseStream[
        MistralCallResponseChunk,
        UserMessage,
        AssistantMessage,
        MistralTool,
    ]
):
    """A class for streaming responses from Mistral's API."""

    def __init__(self, stream: Generator[MistralCallResponseChunk, None, None]):
        """Initializes an instance of `MistralStream`."""
        super().__init__(stream, AssistantMessage)

MistralTool

Bases: BaseTool[ToolCall]

A base class for easy use of tools with the Mistral client.

MistralTool internally handles the logic that allows you to use tools with simple calls such as MistralCallResponse.tool or MistralTool.fn, as seen in the examples below.

Example:

```python import os

from mirascope.mistral import MistralCall, MistralCallParams

def animal_matcher(fav_food: str, fav_color: str) -> str: """Tells you your most likely favorite animal from personality traits.

Args:
    fav_food: your favorite food.
    fav_color: your favorite color.

Returns:
    The animal most likely to be your favorite based on traits.
"""
return "Your favorite animal is the best one, a frog."

class AnimalMatcher(MistralCall): prompt_template = """\ Tell me my favorite animal if my favorite food is {food} and my favorite color is {color}. """

food: str
color: str

api_key = os.getenv("MISTRAL_API_KEY")
call_params = MistralCallParams(
    model="mistral-large-latest", tools=[animal_matcher]
)

prompt = AnimalMatcher(food="pizza", color="green") response = prompt.call()

if tools := response.tools: for tool in tools: print(tool.fn(**tool.args))

> Your favorite animal is the best one, a frog.

Source code in mirascope/mistral/tools.py
class MistralTool(BaseTool[ToolCall]):
    '''A base class for easy use of tools with the Mistral client.

    `MistralTool` internally handles the logic that allows you to use tools with simple
    calls such as `MistralCallResponse.tool` or `MistralTool.fn`, as seen in the 
    examples below.

    Example:

    ```python
    import os

    from mirascope.mistral import MistralCall, MistralCallParams


    def animal_matcher(fav_food: str, fav_color: str) -> str:
        """Tells you your most likely favorite animal from personality traits.

        Args:
            fav_food: your favorite food.
            fav_color: your favorite color.

        Returns:
            The animal most likely to be your favorite based on traits.
        """
        return "Your favorite animal is the best one, a frog."


    class AnimalMatcher(MistralCall):
        prompt_template = """\\
            Tell me my favorite animal if my favorite food is {food} and my
            favorite color is {color}.
        """

        food: str
        color: str

        api_key = os.getenv("MISTRAL_API_KEY")
        call_params = MistralCallParams(
            model="mistral-large-latest", tools=[animal_matcher]
        )


    prompt = AnimalMatcher(food="pizza", color="green")
    response = prompt.call()

    if tools := response.tools:
        for tool in tools:
            print(tool.fn(**tool.args))
    #> Your favorite animal is the best one, a frog.
    '''

    @classmethod
    def tool_schema(cls) -> dict[str, Any]:
        """Constructs a tool schema for use with the Mistral Chat client.

        A Mirascope `MistralTool` is deconstructed into a JSON schema, and relevant keys
        are renamed to match the Mistral API schema used to make functional/tool calls
        in Mistral API.

        Returns:
            The constructed tool schema.
        """
        fn = super().tool_schema()
        return {"type": "function", "function": fn}

    @classmethod
    def from_tool_call(cls, tool_call: ToolCall) -> MistralTool:
        """Extracts an instance of the tool constructed from a tool call response.

        Given `ToolCall` from a Mistral chat completion response, takes its function
        arguments and creates a `MistralTool` instance from it.

        Args:
            tool_call: The Mistral `ToolCall` to extract the tool from.

        Returns:
            An instance of the tool constructed from the tool call.

        Raises:
            ValueError: if the tool call doesn't match the tool schema.
        """
        try:
            model_json = json.loads(tool_call.function.arguments)
        except json.JSONDecodeError as e:
            raise ValueError() from e

        model_json["tool_call"] = tool_call
        return cls.model_validate(model_json)

    @classmethod
    def from_model(cls, model: Type[BaseModel]) -> Type[MistralTool]:
        """Constructs a `MistralTool` type from a `BaseModel` type."""
        return convert_base_model_to_tool(model, MistralTool)

    @classmethod
    def from_fn(cls, fn: Callable) -> Type[MistralTool]:
        """Constructs a `MistralTool` type from a function."""
        return convert_function_to_tool(fn, MistralTool)

    @classmethod
    def from_base_type(cls, base_type: Type[BaseType]) -> Type[MistralTool]:
        """Constructs a `MistralTool` type from a `BaseType` type."""
        return convert_base_type_to_tool(base_type, MistralTool)

from_base_type(base_type) classmethod

Constructs a MistralTool type from a BaseType type.

Source code in mirascope/mistral/tools.py
@classmethod
def from_base_type(cls, base_type: Type[BaseType]) -> Type[MistralTool]:
    """Constructs a `MistralTool` type from a `BaseType` type."""
    return convert_base_type_to_tool(base_type, MistralTool)

from_fn(fn) classmethod

Constructs a MistralTool type from a function.

Source code in mirascope/mistral/tools.py
@classmethod
def from_fn(cls, fn: Callable) -> Type[MistralTool]:
    """Constructs a `MistralTool` type from a function."""
    return convert_function_to_tool(fn, MistralTool)

from_model(model) classmethod

Constructs a MistralTool type from a BaseModel type.

Source code in mirascope/mistral/tools.py
@classmethod
def from_model(cls, model: Type[BaseModel]) -> Type[MistralTool]:
    """Constructs a `MistralTool` type from a `BaseModel` type."""
    return convert_base_model_to_tool(model, MistralTool)

from_tool_call(tool_call) classmethod

Extracts an instance of the tool constructed from a tool call response.

Given ToolCall from a Mistral chat completion response, takes its function arguments and creates a MistralTool instance from it.

Parameters:

Name Type Description Default
tool_call ToolCall

The Mistral ToolCall to extract the tool from.

required

Returns:

Type Description
MistralTool

An instance of the tool constructed from the tool call.

Raises:

Type Description
ValueError

if the tool call doesn't match the tool schema.

Source code in mirascope/mistral/tools.py
@classmethod
def from_tool_call(cls, tool_call: ToolCall) -> MistralTool:
    """Extracts an instance of the tool constructed from a tool call response.

    Given `ToolCall` from a Mistral chat completion response, takes its function
    arguments and creates a `MistralTool` instance from it.

    Args:
        tool_call: The Mistral `ToolCall` to extract the tool from.

    Returns:
        An instance of the tool constructed from the tool call.

    Raises:
        ValueError: if the tool call doesn't match the tool schema.
    """
    try:
        model_json = json.loads(tool_call.function.arguments)
    except json.JSONDecodeError as e:
        raise ValueError() from e

    model_json["tool_call"] = tool_call
    return cls.model_validate(model_json)

tool_schema() classmethod

Constructs a tool schema for use with the Mistral Chat client.

A Mirascope MistralTool is deconstructed into a JSON schema, and relevant keys are renamed to match the Mistral API schema used to make functional/tool calls in Mistral API.

Returns:

Type Description
dict[str, Any]

The constructed tool schema.

Source code in mirascope/mistral/tools.py
@classmethod
def tool_schema(cls) -> dict[str, Any]:
    """Constructs a tool schema for use with the Mistral Chat client.

    A Mirascope `MistralTool` is deconstructed into a JSON schema, and relevant keys
    are renamed to match the Mistral API schema used to make functional/tool calls
    in Mistral API.

    Returns:
        The constructed tool schema.
    """
    fn = super().tool_schema()
    return {"type": "function", "function": fn}

ToolMessage

Bases: TypedDict

A message with the tool role.

Attributes:

Name Type Description
role Required[Literal['tool']]

The role of the message's author, in this case tool.

content Required[str]

The contents of the message.

Source code in mirascope/base/types.py
class ToolMessage(TypedDict, total=False):
    """A message with the `tool` role.

    Attributes:
        role: The role of the message's author, in this case `tool`.
        content: The contents of the message.
    """

    role: Required[Literal["tool"]]
    content: Required[str]

UserMessage

Bases: TypedDict

A message with the user role.

Attributes:

Name Type Description
role Required[Literal['user']]

The role of the message's author, in this case user.

content Required[str]

The contents of the message.

Source code in mirascope/base/types.py
class UserMessage(TypedDict, total=False):
    """A message with the `user` role.

    Attributes:
        role: The role of the message's author, in this case `user`.
        content: The contents of the message.
    """

    role: Required[Literal["user"]]
    content: Required[str]