Skip to content

mistral.calls

A module for prompting Mistral API.

BaseCall

Bases: BasePrompt, Generic[BaseCallResponseT, BaseCallResponseChunkT, BaseToolT, MessageParamT], ABC

The base class abstract interface for calling LLMs.

Source code in mirascope/base/calls.py
class BaseCall(
    BasePrompt,
    Generic[BaseCallResponseT, BaseCallResponseChunkT, BaseToolT, MessageParamT],
    ABC,
):
    """The base class abstract interface for calling LLMs."""

    api_key: ClassVar[Optional[str]] = None
    base_url: ClassVar[Optional[str]] = None
    call_params: ClassVar[BaseCallParams] = BaseCallParams[BaseToolT](
        model="gpt-3.5-turbo-0125"
    )
    configuration: ClassVar[BaseConfig] = BaseConfig(llm_ops=[], client_wrappers=[])
    _provider: ClassVar[str] = "base"

    @abstractmethod
    def call(
        self, retries: Union[int, Retrying] = 0, **kwargs: Any
    ) -> BaseCallResponseT:
        """A call to an LLM.

        An implementation of this function must return a response that extends
        `BaseCallResponse`. This ensures a consistent API and convenience across e.g.
        different model providers.
        """
        ...  # pragma: no cover

    @abstractmethod
    async def call_async(
        self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
    ) -> BaseCallResponseT:
        """An asynchronous call to an LLM.

        An implementation of this function must return a response that extends
        `BaseCallResponse`. This ensures a consistent API and convenience across e.g.
        different model providers.
        """
        ...  # pragma: no cover

    @abstractmethod
    def stream(
        self, retries: Union[int, Retrying] = 0, **kwargs: Any
    ) -> Generator[BaseCallResponseChunkT, None, None]:
        """A call to an LLM that streams the response in chunks.

        An implementation of this function must yield response chunks that extend
        `BaseCallResponseChunk`. This ensures a consistent API and convenience across
        e.g. different model providers.
        """
        ...  # pragma: no cover

    @abstractmethod
    async def stream_async(
        self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
    ) -> AsyncGenerator[BaseCallResponseChunkT, None]:
        """A asynchronous call to an LLM that streams the response in chunks.

        An implementation of this function must yield response chunks that extend
        `BaseCallResponseChunk`. This ensures a consistent API and convenience across
        e.g. different model providers."""
        yield ...  # type: ignore # pragma: no cover

    @classmethod
    def from_prompt(
        cls, prompt_type: type[BasePromptT], call_params: BaseCallParams
    ) -> type[BasePromptT]:
        """Returns a call_type generated dynamically from this base call.

        Args:
            prompt_type: The prompt class to use for the call. Properties and class
                variables of this class will be used to create the new call class. Must
                be a class that can be instantiated.
            call_params: The call params to use for the call.

        Returns:
            A new call class with new call_type.
        """

        fields: dict[str, Any] = {
            name: (field.annotation, field.default)
            for name, field in prompt_type.model_fields.items()
        }

        class_vars = {
            name: value
            for name, value in prompt_type.__dict__.items()
            if name not in prompt_type.model_fields
        }
        new_call = create_model(prompt_type.__name__, __base__=cls, **fields)

        for var_name, var_value in class_vars.items():
            setattr(new_call, var_name, var_value)
        setattr(new_call, "call_params", call_params)

        return cast(type[BasePromptT], new_call)

    ############################## PRIVATE METHODS ###################################

    def _setup(
        self,
        kwargs: dict[str, Any],
        base_tool_type: Optional[Type[BaseToolT]] = None,
    ) -> tuple[dict[str, Any], Optional[list[Type[BaseToolT]]]]:
        """Returns the call params kwargs and tool types.

        The tools in the call params first get converted into BaseToolT types. We then
        need both the converted tools for the response (so it can construct actual tool
        instances if present in the response) as well as the actual schemas injected
        through kwargs. This function handles that setup.
        """
        call_params = self.call_params.model_copy(update=kwargs)
        kwargs = call_params.kwargs(tool_type=base_tool_type)
        tool_types = None
        if "tools" in kwargs and base_tool_type is not None:
            tool_types = kwargs.pop("tools")
            kwargs["tools"] = [tool_type.tool_schema() for tool_type in tool_types]
        return kwargs, tool_types

    def _get_possible_user_message(
        self, messages: list[Any]
    ) -> Optional[MessageParamT]:
        """Returns the most recent message if it's a user message, otherwise `None`."""
        return messages[-1] if messages[-1]["role"] == "user" else None

call(retries=0, **kwargs) abstractmethod

A call to an LLM.

An implementation of this function must return a response that extends BaseCallResponse. This ensures a consistent API and convenience across e.g. different model providers.

Source code in mirascope/base/calls.py
@abstractmethod
def call(
    self, retries: Union[int, Retrying] = 0, **kwargs: Any
) -> BaseCallResponseT:
    """A call to an LLM.

    An implementation of this function must return a response that extends
    `BaseCallResponse`. This ensures a consistent API and convenience across e.g.
    different model providers.
    """
    ...  # pragma: no cover

call_async(retries=0, **kwargs) abstractmethod async

An asynchronous call to an LLM.

An implementation of this function must return a response that extends BaseCallResponse. This ensures a consistent API and convenience across e.g. different model providers.

Source code in mirascope/base/calls.py
@abstractmethod
async def call_async(
    self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
) -> BaseCallResponseT:
    """An asynchronous call to an LLM.

    An implementation of this function must return a response that extends
    `BaseCallResponse`. This ensures a consistent API and convenience across e.g.
    different model providers.
    """
    ...  # pragma: no cover

from_prompt(prompt_type, call_params) classmethod

Returns a call_type generated dynamically from this base call.

Parameters:

Name Type Description Default
prompt_type type[BasePromptT]

The prompt class to use for the call. Properties and class variables of this class will be used to create the new call class. Must be a class that can be instantiated.

required
call_params BaseCallParams

The call params to use for the call.

required

Returns:

Type Description
type[BasePromptT]

A new call class with new call_type.

Source code in mirascope/base/calls.py
@classmethod
def from_prompt(
    cls, prompt_type: type[BasePromptT], call_params: BaseCallParams
) -> type[BasePromptT]:
    """Returns a call_type generated dynamically from this base call.

    Args:
        prompt_type: The prompt class to use for the call. Properties and class
            variables of this class will be used to create the new call class. Must
            be a class that can be instantiated.
        call_params: The call params to use for the call.

    Returns:
        A new call class with new call_type.
    """

    fields: dict[str, Any] = {
        name: (field.annotation, field.default)
        for name, field in prompt_type.model_fields.items()
    }

    class_vars = {
        name: value
        for name, value in prompt_type.__dict__.items()
        if name not in prompt_type.model_fields
    }
    new_call = create_model(prompt_type.__name__, __base__=cls, **fields)

    for var_name, var_value in class_vars.items():
        setattr(new_call, var_name, var_value)
    setattr(new_call, "call_params", call_params)

    return cast(type[BasePromptT], new_call)

stream(retries=0, **kwargs) abstractmethod

A call to an LLM that streams the response in chunks.

An implementation of this function must yield response chunks that extend BaseCallResponseChunk. This ensures a consistent API and convenience across e.g. different model providers.

Source code in mirascope/base/calls.py
@abstractmethod
def stream(
    self, retries: Union[int, Retrying] = 0, **kwargs: Any
) -> Generator[BaseCallResponseChunkT, None, None]:
    """A call to an LLM that streams the response in chunks.

    An implementation of this function must yield response chunks that extend
    `BaseCallResponseChunk`. This ensures a consistent API and convenience across
    e.g. different model providers.
    """
    ...  # pragma: no cover

stream_async(retries=0, **kwargs) abstractmethod async

A asynchronous call to an LLM that streams the response in chunks.

An implementation of this function must yield response chunks that extend BaseCallResponseChunk. This ensures a consistent API and convenience across e.g. different model providers.

Source code in mirascope/base/calls.py
@abstractmethod
async def stream_async(
    self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
) -> AsyncGenerator[BaseCallResponseChunkT, None]:
    """A asynchronous call to an LLM that streams the response in chunks.

    An implementation of this function must yield response chunks that extend
    `BaseCallResponseChunk`. This ensures a consistent API and convenience across
    e.g. different model providers."""
    yield ...  # type: ignore # pragma: no cover

MessageRole

Bases: _Enum

Roles that the BasePrompt messages parser can parse from the template.

SYSTEM: A system message. USER: A user message. ASSISTANT: A message response from the assistant or chat client. MODEL: A message response from the assistant or chat client. Model is used by Google's Gemini instead of assistant, which doesn't have system messages. CHATBOT: A message response from the chat client. Chatbot is used by Cohere instead of assistant. TOOL: A message representing the output of calling a tool.

Source code in mirascope/enums.py
class MessageRole(_Enum):
    """Roles that the `BasePrompt` messages parser can parse from the template.

    SYSTEM: A system message.
    USER: A user message.
    ASSISTANT: A message response from the assistant or chat client.
    MODEL: A message response from the assistant or chat client. Model is used by
        Google's Gemini instead of assistant, which doesn't have system messages.
    CHATBOT: A message response from the chat client. Chatbot is used by Cohere instead
        of assistant.
    TOOL: A message representing the output of calling a tool.
    """

    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"
    MODEL = "model"
    CHATBOT = "chatbot"
    TOOL = "tool"

MistralCall

Bases: BaseCall[MistralCallResponse, MistralCallResponseChunk, MistralTool, UserMessage]

A class for" prompting Mistral's chat API.

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)
#> There are many great books to read, it ultimately depends...
Source code in mirascope/mistral/calls.py
class MistralCall(
    BaseCall[MistralCallResponse, MistralCallResponseChunk, MistralTool, UserMessage]
):
    """A class for" prompting Mistral's chat API.

    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)
    #> There are many great books to read, it ultimately depends...
    ```
    """

    call_params: ClassVar[MistralCallParams] = MistralCallParams()
    _provider: ClassVar[str] = "mistral"

    def messages(self) -> list[Message]:
        """Returns the template as a formatted list of messages."""
        return self._parse_messages(
            [MessageRole.SYSTEM, MessageRole.USER, MessageRole.ASSISTANT]
        )

    @retry
    def call(
        self, retries: Union[int, Retrying] = 0, **kwargs: Any
    ) -> MistralCallResponse:
        """Makes a call to the model using this `MistralCall` instance.

        Args:
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Returns:
            A `MistralCallResponse` instance.

        Raises:
            MistralException: raises any Mistral errors, see:
                https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
        """
        kwargs, tool_types = self._setup(kwargs, MistralTool)
        client = get_wrapped_client(
            MistralClient(
                api_key=self.api_key,
                endpoint=self.base_url if self.base_url else ENDPOINT,
            ),
            self,
        )
        chat = get_wrapped_call(
            client.chat,
            self,
            response_type=MistralCallResponse,
            tool_types=tool_types,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        start_time = datetime.datetime.now().timestamp() * 1000
        completion = chat(messages=messages, **kwargs)
        return MistralCallResponse(
            response=completion,
            user_message_param=user_message_param,
            tool_types=tool_types,
            start_time=start_time,
            cost=mistral_api_calculate_cost(completion.usage, completion.model),
            end_time=datetime.datetime.now().timestamp() * 1000,
        )

    @retry
    async def call_async(
        self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
    ) -> MistralCallResponse:
        """Makes an asynchronous call to the model using this `MistralCall` instance.

        Args:
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Returns:
            A `MistralCallResponse` instance.

        Raises:
            MistralException: raises any Mistral errors, see:
                https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
        """
        kwargs, tool_types = self._setup(kwargs, MistralTool)
        client = get_wrapped_async_client(
            MistralAsyncClient(
                api_key=self.api_key,
                endpoint=self.base_url if self.base_url else ENDPOINT,
            ),
            self,
        )
        chat = get_wrapped_call(
            client.chat,
            self,
            is_async=True,
            response_type=MistralCallResponse,
            tool_types=tool_types,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        start_time = datetime.datetime.now().timestamp() * 1000
        completion = await chat(messages=messages, **kwargs)
        return MistralCallResponse(
            response=completion,
            user_message_param=user_message_param,
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=mistral_api_calculate_cost(completion.usage, completion.model),
        )

    @retry
    def stream(
        self, retries: Union[int, Retrying] = 0, **kwargs: Any
    ) -> Generator[MistralCallResponseChunk, None, None]:
        """Streams the response for a call using this `MistralCall` instance.

        Args:
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Returns:
            A `MistralCallResponseChunk` for each chunk of the response.

        Raises:
            MistralException: raises any Mistral errors, see:
                https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
        """
        kwargs, tool_types = self._setup(kwargs, MistralTool)
        client = get_wrapped_client(
            MistralClient(
                api_key=self.api_key,
                endpoint=self.base_url if self.base_url else ENDPOINT,
            ),
            self,
        )
        chat_stream = get_wrapped_call(
            client.chat_stream,
            self,
            response_chunk_type=MistralCallResponseChunk,
            tool_types=tool_types,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        for chunk in chat_stream(messages=messages, **kwargs):
            yield MistralCallResponseChunk(
                chunk=chunk,
                user_message_param=user_message_param,
                tool_types=tool_types,
            )

    @retry
    async def stream_async(
        self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
    ) -> AsyncGenerator[MistralCallResponseChunk, None]:
        """Streams the response for an asynchronous call using this `MistralCall`.

        Args:
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Returns:
            A `MistralCallResponseChunk` for each chunk of the response.

        Raises:
            MistralException: raises any Mistral errors, see:
                https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
        """
        kwargs, tool_types = self._setup(kwargs, MistralTool)
        client = get_wrapped_async_client(
            MistralAsyncClient(
                api_key=self.api_key,
                endpoint=self.base_url if self.base_url else ENDPOINT,
            ),
            self,
        )
        chat_stream = get_wrapped_call(
            client.chat_stream,
            self,
            is_async=True,
            response_chunk_type=MistralCallResponseChunk,
            tool_types=tool_types,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        async for chunk in chat_stream(messages=messages, **kwargs):
            yield MistralCallResponseChunk(
                chunk=chunk,
                user_message_param=user_message_param,
                tool_types=tool_types,
            )

call(retries=0, **kwargs)

Makes a call to the model using this MistralCall instance.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments parameters to pass to the call. These will override any existing arguments in call_params.

{}

Returns:

Type Description
MistralCallResponse

A MistralCallResponse instance.

Raises:

Type Description
MistralException

raises any Mistral errors, see: https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py

Source code in mirascope/mistral/calls.py
@retry
def call(
    self, retries: Union[int, Retrying] = 0, **kwargs: Any
) -> MistralCallResponse:
    """Makes a call to the model using this `MistralCall` instance.

    Args:
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Returns:
        A `MistralCallResponse` instance.

    Raises:
        MistralException: raises any Mistral errors, see:
            https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
    """
    kwargs, tool_types = self._setup(kwargs, MistralTool)
    client = get_wrapped_client(
        MistralClient(
            api_key=self.api_key,
            endpoint=self.base_url if self.base_url else ENDPOINT,
        ),
        self,
    )
    chat = get_wrapped_call(
        client.chat,
        self,
        response_type=MistralCallResponse,
        tool_types=tool_types,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    start_time = datetime.datetime.now().timestamp() * 1000
    completion = chat(messages=messages, **kwargs)
    return MistralCallResponse(
        response=completion,
        user_message_param=user_message_param,
        tool_types=tool_types,
        start_time=start_time,
        cost=mistral_api_calculate_cost(completion.usage, completion.model),
        end_time=datetime.datetime.now().timestamp() * 1000,
    )

call_async(retries=0, **kwargs) async

Makes an asynchronous call to the model using this MistralCall instance.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments parameters to pass to the call. These will override any existing arguments in call_params.

{}

Returns:

Type Description
MistralCallResponse

A MistralCallResponse instance.

Raises:

Type Description
MistralException

raises any Mistral errors, see: https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py

Source code in mirascope/mistral/calls.py
@retry
async def call_async(
    self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
) -> MistralCallResponse:
    """Makes an asynchronous call to the model using this `MistralCall` instance.

    Args:
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Returns:
        A `MistralCallResponse` instance.

    Raises:
        MistralException: raises any Mistral errors, see:
            https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
    """
    kwargs, tool_types = self._setup(kwargs, MistralTool)
    client = get_wrapped_async_client(
        MistralAsyncClient(
            api_key=self.api_key,
            endpoint=self.base_url if self.base_url else ENDPOINT,
        ),
        self,
    )
    chat = get_wrapped_call(
        client.chat,
        self,
        is_async=True,
        response_type=MistralCallResponse,
        tool_types=tool_types,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    start_time = datetime.datetime.now().timestamp() * 1000
    completion = await chat(messages=messages, **kwargs)
    return MistralCallResponse(
        response=completion,
        user_message_param=user_message_param,
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=mistral_api_calculate_cost(completion.usage, completion.model),
    )

messages()

Returns the template as a formatted list of messages.

Source code in mirascope/mistral/calls.py
def messages(self) -> list[Message]:
    """Returns the template as a formatted list of messages."""
    return self._parse_messages(
        [MessageRole.SYSTEM, MessageRole.USER, MessageRole.ASSISTANT]
    )

stream(retries=0, **kwargs)

Streams the response for a call using this MistralCall instance.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments parameters to pass to the call. These will override any existing arguments in call_params.

{}

Returns:

Type Description
Generator[MistralCallResponseChunk, None, None]

A MistralCallResponseChunk for each chunk of the response.

Raises:

Type Description
MistralException

raises any Mistral errors, see: https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py

Source code in mirascope/mistral/calls.py
@retry
def stream(
    self, retries: Union[int, Retrying] = 0, **kwargs: Any
) -> Generator[MistralCallResponseChunk, None, None]:
    """Streams the response for a call using this `MistralCall` instance.

    Args:
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Returns:
        A `MistralCallResponseChunk` for each chunk of the response.

    Raises:
        MistralException: raises any Mistral errors, see:
            https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
    """
    kwargs, tool_types = self._setup(kwargs, MistralTool)
    client = get_wrapped_client(
        MistralClient(
            api_key=self.api_key,
            endpoint=self.base_url if self.base_url else ENDPOINT,
        ),
        self,
    )
    chat_stream = get_wrapped_call(
        client.chat_stream,
        self,
        response_chunk_type=MistralCallResponseChunk,
        tool_types=tool_types,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    for chunk in chat_stream(messages=messages, **kwargs):
        yield MistralCallResponseChunk(
            chunk=chunk,
            user_message_param=user_message_param,
            tool_types=tool_types,
        )

stream_async(retries=0, **kwargs) async

Streams the response for an asynchronous call using this MistralCall.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments parameters to pass to the call. These will override any existing arguments in call_params.

{}

Returns:

Type Description
AsyncGenerator[MistralCallResponseChunk, None]

A MistralCallResponseChunk for each chunk of the response.

Raises:

Type Description
MistralException

raises any Mistral errors, see: https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py

Source code in mirascope/mistral/calls.py
@retry
async def stream_async(
    self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
) -> AsyncGenerator[MistralCallResponseChunk, None]:
    """Streams the response for an asynchronous call using this `MistralCall`.

    Args:
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Returns:
        A `MistralCallResponseChunk` for each chunk of the response.

    Raises:
        MistralException: raises any Mistral errors, see:
            https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
    """
    kwargs, tool_types = self._setup(kwargs, MistralTool)
    client = get_wrapped_async_client(
        MistralAsyncClient(
            api_key=self.api_key,
            endpoint=self.base_url if self.base_url else ENDPOINT,
        ),
        self,
    )
    chat_stream = get_wrapped_call(
        client.chat_stream,
        self,
        is_async=True,
        response_chunk_type=MistralCallResponseChunk,
        tool_types=tool_types,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    async for chunk in chat_stream(messages=messages, **kwargs):
        yield MistralCallResponseChunk(
            chunk=chunk,
            user_message_param=user_message_param,
            tool_types=tool_types,
        )

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.

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}

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]

get_wrapped_async_client(client, self)

Get a wrapped async client.

Source code in mirascope/base/ops_utils.py
def get_wrapped_async_client(client: T, self: Union[BaseCall, BaseEmbedder]) -> T:
    """Get a wrapped async client."""
    if self.configuration.client_wrappers:
        for op in self.configuration.client_wrappers:
            if op == "langfuse":  # pragma: no cover
                from langfuse.openai import AsyncOpenAI as LangfuseAsyncOpenAI

                client = LangfuseAsyncOpenAI(
                    api_key=self.api_key, base_url=self.base_url
                )
            elif op == "logfire":  # pragma: no cover
                import logfire

                if self._provider == "openai":
                    logfire.instrument_openai(client)  # type: ignore
                elif self._provider == "anthropic":
                    logfire.instrument_anthropic(client)  # type: ignore
            elif callable(op):
                client = op(client)
    return client

get_wrapped_call(call, self, **kwargs)

Wrap a call to add the llm_ops parameter if it exists.

Source code in mirascope/base/ops_utils.py
def get_wrapped_call(call: C, self: Union[BaseCall, BaseEmbedder], **kwargs) -> C:
    """Wrap a call to add the `llm_ops` parameter if it exists."""
    if self.configuration.llm_ops:
        wrapped_call = call
        for op in self.configuration.llm_ops:
            if op == "weave":  # pragma: no cover
                import weave

                wrapped_call = weave.op()(wrapped_call)
            elif callable(op):
                wrapped_call = op(
                    wrapped_call,
                    self._provider,
                    **kwargs,
                )
        return wrapped_call
    return call

get_wrapped_client(client, self)

Get a wrapped client.

Source code in mirascope/base/ops_utils.py
def get_wrapped_client(client: T, self: Union[BaseCall, BaseEmbedder]) -> T:
    """Get a wrapped client."""
    if self.configuration.client_wrappers:
        for op in self.configuration.client_wrappers:  # pragma: no cover
            if op == "langfuse":
                from langfuse.openai import OpenAI as LangfuseOpenAI

                client = LangfuseOpenAI(api_key=self.api_key, base_url=self.base_url)
            elif op == "logfire":  # pragma: no cover
                import logfire

                if self._provider == "openai":
                    logfire.instrument_openai(client)  # type: ignore
                elif self._provider == "anthropic":
                    logfire.instrument_anthropic(client)  # type: ignore
            elif callable(op):
                client = op(client)
    return client

mistral_api_calculate_cost(usage, model='open-mistral-7b')

Calculate the cost of a completion using the Mistral API.

https://mistral.ai/technology/#pricing

Model Input Output open-mistral-7b $0.25/1M tokens $0.25/1M tokens open-mixtral-8x7b $0.7/1M tokens $0.7/1M tokens open-mixtral-8x22b $2/1M tokens $6/1M tokens mistral-small $2/1M tokens $6/1M tokens mistral-medium $2.7/1M tokens $8.1/1M tokens mistral-large $8/1M tokens $24/1M tokens

Source code in mirascope/mistral/utils.py
def mistral_api_calculate_cost(
    usage: UsageInfo, model="open-mistral-7b"
) -> Optional[float]:
    """Calculate the cost of a completion using the Mistral API.

    https://mistral.ai/technology/#pricing

    Model                     Input               Output
    open-mistral-7b	          $0.25/1M tokens	  $0.25/1M tokens
    open-mixtral-8x7b	      $0.7/1M tokens	  $0.7/1M tokens
    open-mixtral-8x22b	      $2/1M tokens	      $6/1M tokens
    mistral-small		      $2/1M tokens	      $6/1M tokens
    mistral-medium		      $2.7/1M tokens	  $8.1/1M tokens
    mistral-large		      $8/1M tokens	      $24/1M tokens
    """
    pricing = {
        "open-mistral-7b": {"prompt": 0.000_000_25, "completion": 0.000_000_25},
        "open-mixtral-8x7b": {"prompt": 0.000_000_7, "completion": 0.000_000_7},
        "open-mixtral-8x22b": {"prompt": 0.000_002, "completion": 0.000_006},
        "mistral-small": {"prompt": 0.000_002, "completion": 0.000_006},
        "mistral-medium": {"prompt": 0.000_002_7, "completion": 0.000_008_1},
        "mistral-large": {"prompt": 0.000_008, "completion": 0.000_024},
    }

    try:
        model_pricing = pricing[model]
    except KeyError:
        return None

    completion_tokens = usage.completion_tokens or 0
    prompt_cost = usage.prompt_tokens * model_pricing["prompt"]
    completion_cost = completion_tokens * model_pricing["completion"]
    total_cost = prompt_cost + completion_cost

    return total_cost

retry(fn)

Decorator for retrying a function.

Source code in mirascope/base/utils.py
def retry(fn: F) -> F:
    """Decorator for retrying a function."""

    @wraps(fn)
    def wrapper(*args, **kwargs):
        """Wrapper for retrying a function."""
        retries = kwargs.pop("retries", 0)
        if isinstance(retries, int):
            if retries > 0:
                retries = Retrying(stop=stop_after_attempt(retries))
            else:
                return fn(*args, **kwargs)
        try:
            for attempt in retries:
                with attempt:
                    result = fn(*args, **kwargs)
                if (
                    attempt.retry_state.outcome
                    and not attempt.retry_state.outcome.failed
                ):
                    attempt.retry_state.set_result(result)
            return result
        except RetryError:
            raise

    @wraps(fn)
    async def wrapper_async(*args, **kwargs):
        """Wrapper for retrying an async function."""
        retries = kwargs.pop("retries", 0)
        if isinstance(retries, int):
            if retries > 0:
                retries = AsyncRetrying(stop=stop_after_attempt(retries))
            else:
                return await fn(*args, **kwargs)
        try:
            async for attempt in retries:
                with attempt:
                    result = await fn(*args, **kwargs)
                if (
                    attempt.retry_state.outcome
                    and not attempt.retry_state.outcome.failed
                ):
                    attempt.retry_state.set_result(result)
            return result
        except RetryError:
            raise

    @wraps(fn)
    def wrapper_generator(*args, **kwargs):
        """Wrapper for retrying a generator function."""
        retries = kwargs.pop("retries", 0)
        if isinstance(retries, int):
            if retries > 0:
                retries = Retrying(stop=stop_after_attempt(retries))
            else:
                for value in fn(*args, **kwargs):
                    yield value
                return
        try:
            for attempt in retries:
                with attempt:
                    for value in fn(*args, **kwargs):
                        yield value
        except RetryError:
            raise

    @wraps(fn)
    async def wrapper_generator_async(*args, **kwargs):
        """Wrapper for retrying an async generator function."""
        retries = kwargs.pop("retries", 0)
        if isinstance(retries, int):
            if retries > 0:
                retries = AsyncRetrying(stop=stop_after_attempt(retries))
            else:
                async for value in fn(*args, **kwargs):
                    yield value
                return
        try:
            async for attempt in retries:
                with attempt:
                    async for value in fn(*args, **kwargs):
                        yield value
        except RetryError:
            raise

    if inspect.iscoroutinefunction(fn):
        return cast(F, wrapper_async)
    elif inspect.isgeneratorfunction(fn):
        return cast(F, wrapper_generator)
    elif inspect.isasyncgenfunction(fn):
        return cast(F, wrapper_generator_async)
    else:
        return cast(F, wrapper)