Skip to content

cohere.calls

A module for calling Cohere's chat models.

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

CohereCall

Bases: BaseCall[CohereCallResponse, CohereCallResponseChunk, CohereTool, ChatMessage]

A base class for calling Cohere's chat models.

Example:

from mirascope.cohere import CohereCall


class BookRecommender(CohereCall):
    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/cohere/calls.py
class CohereCall(
    BaseCall[CohereCallResponse, CohereCallResponseChunk, CohereTool, ChatMessage]
):
    """A base class for calling Cohere's chat models.

    Example:

    ```python
    from mirascope.cohere import CohereCall


    class BookRecommender(CohereCall):
        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[CohereCallParams] = CohereCallParams()
    _provider: ClassVar[str] = "cohere"

    def messages(self) -> list[ChatMessage]:
        """Returns the template as a formatted list of messages."""
        return [
            ChatMessage(role=message["role"].upper(), message=message["content"])  # type: ignore
            for message in self._parse_messages(
                [MessageRole.SYSTEM, MessageRole.USER, MessageRole.CHATBOT]
            )
        ]

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

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

        Returns:
            A `CohereCallResponse` instance.
        """
        message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
        co = get_wrapped_client(
            Client(api_key=self.api_key, base_url=self.base_url), self
        )

        chat = get_wrapped_call(
            co.chat, self, response_type=CohereCallResponse, tool_types=tool_types
        )
        start_time = datetime.datetime.now().timestamp() * 1000
        response = chat(message=message, **kwargs)
        cost = None
        if response.meta and response.meta.billed_units:
            cost = cohere_api_calculate_cost(
                response.meta.billed_units, self.call_params.model
            )
        return CohereCallResponse(
            response=response,
            user_message_param=ChatMessage(message=message, role="user"),  # type: ignore
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=cost,
        )

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

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

        Returns:
            An `CohereCallResponse` instance.
        """
        message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
        co = get_wrapped_async_client(
            AsyncClient(api_key=self.api_key, base_url=self.base_url), self
        )
        chat = get_wrapped_call(
            co.chat,
            self,
            is_async=True,
            response_type=CohereCallResponse,
            tool_types=tool_types,
        )
        start_time = datetime.datetime.now().timestamp() * 1000
        response = await chat(message=message, **kwargs)
        cost = None
        if response.meta and response.meta.billed_units:
            cost = cohere_api_calculate_cost(
                response.meta.billed_units, self.call_params.model
            )
        return CohereCallResponse(
            response=response,
            user_message_param=ChatMessage(message=message, role="user"),  # type: ignore
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=cost,
        )

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

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

        Yields:
            A `CohereCallResponseChunk` for each chunk of the response.
        """
        message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
        co = get_wrapped_client(
            Client(api_key=self.api_key, base_url=self.base_url), self
        )
        chat_stream = get_wrapped_call(
            co.chat_stream,
            self,
            response_chunk_type=CohereCallResponseChunk,
            tool_types=tool_types,
        )
        user_message_param = ChatMessage(message=message, role="user")  # type: ignore
        for event in chat_stream(message=message, **kwargs):
            yield CohereCallResponseChunk(
                chunk=event,
                user_message_param=user_message_param,
                tool_types=tool_types,
            )

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

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

        Yields:
            A `CohereCallResponseChunk` for each chunk of the response.
        """
        message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
        co = get_wrapped_async_client(
            AsyncClient(api_key=self.api_key, base_url=self.base_url), self
        )
        chat_stream = get_wrapped_call(
            co.chat_stream,
            self,
            is_async=True,
            response_chunk_type=CohereCallResponseChunk,
            tool_types=tool_types,
        )
        user_message_param = ChatMessage(message=message, role="user")  # type: ignore
        async for event in chat_stream(message=message, **kwargs):
            yield CohereCallResponseChunk(
                chunk=event,
                user_message_param=user_message_param,
                tool_types=tool_types,
            )

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

    def _setup_cohere_kwargs(
        self, kwargs: dict[str, Any]
    ) -> tuple[str, dict[str, Any], Optional[list[Type[CohereTool]]]]:
        """Overrides the `BaseCall._setup` for Cohere specific setup."""
        kwargs, tool_types = self._setup(kwargs, CohereTool)
        messages = self.messages()
        preamble = ""
        if "preamble" in kwargs and kwargs["preamble"] is not None:
            preamble += kwargs.pop("preamble")
        if messages[0].role == "SYSTEM":  # type: ignore
            preamble += messages.pop(0).message
        if preamble:
            kwargs["preamble"] = preamble
        if len(messages) > 1:
            kwargs["chat_history"] = messages[:-1]
        if hasattr(self, "documents"):
            kwargs["documents"] = self.documents
        return messages[-1].message, kwargs, tool_types

call(retries=0, **kwargs)

Makes a call to the model using this CohereCall 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
CohereCallResponse

A CohereCallResponse instance.

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

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

    Returns:
        A `CohereCallResponse` instance.
    """
    message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
    co = get_wrapped_client(
        Client(api_key=self.api_key, base_url=self.base_url), self
    )

    chat = get_wrapped_call(
        co.chat, self, response_type=CohereCallResponse, tool_types=tool_types
    )
    start_time = datetime.datetime.now().timestamp() * 1000
    response = chat(message=message, **kwargs)
    cost = None
    if response.meta and response.meta.billed_units:
        cost = cohere_api_calculate_cost(
            response.meta.billed_units, self.call_params.model
        )
    return CohereCallResponse(
        response=response,
        user_message_param=ChatMessage(message=message, role="user"),  # type: ignore
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=cost,
    )

call_async(retries=0, **kwargs) async

Makes an asynchronous call to the model using this CohereCall.

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
CohereCallResponse

An CohereCallResponse instance.

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

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

    Returns:
        An `CohereCallResponse` instance.
    """
    message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
    co = get_wrapped_async_client(
        AsyncClient(api_key=self.api_key, base_url=self.base_url), self
    )
    chat = get_wrapped_call(
        co.chat,
        self,
        is_async=True,
        response_type=CohereCallResponse,
        tool_types=tool_types,
    )
    start_time = datetime.datetime.now().timestamp() * 1000
    response = await chat(message=message, **kwargs)
    cost = None
    if response.meta and response.meta.billed_units:
        cost = cohere_api_calculate_cost(
            response.meta.billed_units, self.call_params.model
        )
    return CohereCallResponse(
        response=response,
        user_message_param=ChatMessage(message=message, role="user"),  # type: ignore
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=cost,
    )

messages()

Returns the template as a formatted list of messages.

Source code in mirascope/cohere/calls.py
def messages(self) -> list[ChatMessage]:
    """Returns the template as a formatted list of messages."""
    return [
        ChatMessage(role=message["role"].upper(), message=message["content"])  # type: ignore
        for message in self._parse_messages(
            [MessageRole.SYSTEM, MessageRole.USER, MessageRole.CHATBOT]
        )
    ]

stream(retries=0, **kwargs)

Streams the response for a call using this CohereCall.

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.

{}

Yields:

Type Description
CohereCallResponseChunk

A CohereCallResponseChunk for each chunk of the response.

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

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

    Yields:
        A `CohereCallResponseChunk` for each chunk of the response.
    """
    message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
    co = get_wrapped_client(
        Client(api_key=self.api_key, base_url=self.base_url), self
    )
    chat_stream = get_wrapped_call(
        co.chat_stream,
        self,
        response_chunk_type=CohereCallResponseChunk,
        tool_types=tool_types,
    )
    user_message_param = ChatMessage(message=message, role="user")  # type: ignore
    for event in chat_stream(message=message, **kwargs):
        yield CohereCallResponseChunk(
            chunk=event,
            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 CohereCall.

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.

{}

Yields:

Type Description
AsyncGenerator[CohereCallResponseChunk, None]

A CohereCallResponseChunk for each chunk of the response.

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

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

    Yields:
        A `CohereCallResponseChunk` for each chunk of the response.
    """
    message, kwargs, tool_types = self._setup_cohere_kwargs(kwargs)
    co = get_wrapped_async_client(
        AsyncClient(api_key=self.api_key, base_url=self.base_url), self
    )
    chat_stream = get_wrapped_call(
        co.chat_stream,
        self,
        is_async=True,
        response_chunk_type=CohereCallResponseChunk,
        tool_types=tool_types,
    )
    user_message_param = ChatMessage(message=message, role="user")  # type: ignore
    async for event in chat_stream(message=message, **kwargs):
        yield CohereCallResponseChunk(
            chunk=event,
            user_message_param=user_message_param,
            tool_types=tool_types,
        )

CohereCallParams

Bases: BaseCallParams[CohereTool]

The parameters to use when calling the Cohere chat API.

Source code in mirascope/cohere/types.py
class CohereCallParams(BaseCallParams[CohereTool]):
    """The parameters to use when calling the Cohere chat API."""

    model: str = "command-r-plus"
    preamble: Optional[str] = None
    chat_history: Optional[Sequence[ChatMessage]] = None
    conversation_id: Optional[str] = None
    prompt_truncation: Optional[ChatRequestPromptTruncation] = None
    connectors: Optional[Sequence[ChatConnector]] = None
    search_queries_only: Optional[bool] = None
    documents: Optional[Sequence[ChatDocument]] = None
    temperature: Optional[float] = None
    max_tokens: Optional[int] = None
    max_input_tokens: Optional[int] = None
    k: Optional[int] = None
    p: Optional[float] = None
    seed: Optional[float] = None
    stop_sequences: Optional[Sequence[str]] = None
    frequency_penalty: Optional[float] = None
    presence_penalty: Optional[float] = None
    raw_prompting: Optional[bool] = None
    tool_results: Optional[Sequence[ToolResult]] = None
    request_options: Optional[RequestOptions] = None

    model_config = ConfigDict(arbitrary_types_allowed=True)

    def kwargs(
        self,
        tool_type: Optional[Type[CohereTool]] = CohereTool,
        exclude: Optional[set[str]] = None,
    ) -> dict[str, Any]:
        """Returns the keyword argument call parameters."""
        extra_exclude = {"wrapper", "wrapper_async"}
        exclude = extra_exclude if exclude is None else exclude.union(extra_exclude)
        return super().kwargs(tool_type, exclude)

kwargs(tool_type=CohereTool, exclude=None)

Returns the keyword argument call parameters.

Source code in mirascope/cohere/types.py
def kwargs(
    self,
    tool_type: Optional[Type[CohereTool]] = CohereTool,
    exclude: Optional[set[str]] = None,
) -> dict[str, Any]:
    """Returns the keyword argument call parameters."""
    extra_exclude = {"wrapper", "wrapper_async"}
    exclude = extra_exclude if exclude is None else exclude.union(extra_exclude)
    return super().kwargs(tool_type, exclude)

CohereCallResponse

Bases: BaseCallResponse[NonStreamedChatResponse, CohereTool]

A convenience wrapper around the Cohere NonStreamedChatResponse response.

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

Example:

from mirascope.cohere import CohereCall


class BookRecommender(CohereCall):
    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)
#> ...

print(response.choices)
#> ...
Source code in mirascope/cohere/types.py
class CohereCallResponse(BaseCallResponse[NonStreamedChatResponse, CohereTool]):
    """A convenience wrapper around the Cohere `NonStreamedChatResponse` response.

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

    Example:

    ```python
    from mirascope.cohere import CohereCall


    class BookRecommender(CohereCall):
        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)
    #> ...

    print(response.choices)
    #> ...
    ```
    """

    # We need to skip validation since it's a pydantic_v1 model and breaks validation.
    response: SkipValidation[NonStreamedChatResponse]
    user_message_param: SkipValidation[Optional[ChatMessage]] = None

    @property
    def message_param(self) -> ChatMessage:
        """Returns the assistant's response as a message parameter."""
        return ChatMessage(
            message=self.response.text,
            tool_calls=self.response.tool_calls,
            role="assistant",  # type: ignore
        )

    @property
    def content(self) -> str:
        """Returns the content of the chat completion for the 0th choice."""
        return self.response.text

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

        Cohere does not return model, so we return None
        """
        return None

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

    @property
    def finish_reasons(self) -> Optional[list[str]]:
        """Returns the finish reasons of the response."""
        return [str(self.response.finish_reason)]

    @property
    def search_queries(self) -> Optional[list[ChatSearchQuery]]:
        """Returns the search queries for the 0th choice message."""
        return self.response.search_queries

    @property
    def search_results(self) -> Optional[list[ChatSearchResult]]:
        """Returns the search results for the 0th choice message."""
        return self.response.search_results

    @property
    def documents(self) -> Optional[list[ChatDocument]]:
        """Returns the documents for the 0th choice message."""
        return self.response.documents

    @property
    def citations(self) -> Optional[list[ChatCitation]]:
        """Returns the citations for the 0th choice message."""
        return self.response.citations

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

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

        Raises:
            ValidationError: if a tool call doesn't match the tool's schema.
        """
        if not self.tool_types or not self.tool_calls:
            return None

        if self.response.finish_reason == "MAX_TOKENS":
            raise RuntimeError(
                "Generation stopped with MAX_TOKENS finish reason. This means that the "
                "response hit the token limit before completion."
            )

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

        return extracted_tools

    @property
    def tool(self) -> Optional[CohereTool]:
        """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(
        self, tools_and_outputs: list[tuple[CohereTool, list[dict[str, Any]]]]
    ) -> list[ToolResult]:
        """Returns the tool message parameters for tool call results."""
        return [
            {"call": tool.tool_call, "outputs": output}  # type: ignore
            for tool, output in tools_and_outputs
        ]

    @property
    def usage(self) -> Optional[ApiMetaBilledUnits]:
        """Returns the usage of the response."""
        if self.response.meta:
            return self.response.meta.billed_units
        return None

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

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

    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.dict(),
            "cost": self.cost,
        }

citations: Optional[list[ChatCitation]] property

Returns the citations for the 0th choice message.

content: str property

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

documents: Optional[list[ChatDocument]] property

Returns the documents for the 0th choice message.

finish_reasons: Optional[list[str]] property

Returns the finish reasons of the response.

id: Optional[str] property

Returns the id of the response.

input_tokens: Optional[float] property

Returns the number of input tokens.

message_param: ChatMessage property

Returns the assistant's response as a message parameter.

model: Optional[str] property

Returns the name of the response model.

Cohere does not return model, so we return None

output_tokens: Optional[float] property

Returns the number of output tokens.

search_queries: Optional[list[ChatSearchQuery]] property

Returns the search queries for the 0th choice message.

search_results: Optional[list[ChatSearchResult]] property

Returns the search results for the 0th choice message.

tool: Optional[CohereTool] 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[CohereTool]] property

Returns the tools for the 0th choice message.

Raises:

Type Description
ValidationError

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

usage: Optional[ApiMetaBilledUnits] property

Returns the usage of the response.

dump()

Dumps the response to a dictionary.

Source code in mirascope/cohere/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.dict(),
        "cost": self.cost,
    }

tool_message_params(tools_and_outputs) classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/cohere/types.py
@classmethod
def tool_message_params(
    self, tools_and_outputs: list[tuple[CohereTool, list[dict[str, Any]]]]
) -> list[ToolResult]:
    """Returns the tool message parameters for tool call results."""
    return [
        {"call": tool.tool_call, "outputs": output}  # type: ignore
        for tool, output in tools_and_outputs
    ]

CohereCallResponseChunk

Bases: BaseCallResponseChunk[StreamedChatResponse, CohereTool]

Convenience wrapper around chat completion streaming chunks.

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

Example:

from mirascope.cohere import CohereCall


class Math(CohereCall):
    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/cohere/types.py
class CohereCallResponseChunk(BaseCallResponseChunk[StreamedChatResponse, CohereTool]):
    """Convenience wrapper around chat completion streaming chunks.

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

    Example:

    ```python
    from mirascope.cohere import CohereCall


    class Math(CohereCall):
        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.
    ```
    """

    chunk: SkipValidation[StreamedChatResponse]
    user_message_param: SkipValidation[Optional[ChatMessage]] = None

    @property
    def event_type(
        self,
    ) -> Literal[
        "stream-start",
        "search-queries-generation",
        "search-results",
        "text-generation",
        "citation-generation",
        "tool-calls-generation",
        "stream-end",
        "tool-calls-chunk",
    ]:
        """Returns the type of the chunk."""
        return self.chunk.event_type

    @property
    def content(self) -> str:
        """Returns the content for the 0th choice delta."""
        if isinstance(self.chunk, StreamedChatResponse_TextGeneration):
            return self.chunk.text
        return ""

    @property
    def search_queries(self) -> Optional[list[ChatSearchQuery]]:
        """Returns the search queries for search-query event type else None."""
        if isinstance(self.chunk, StreamedChatResponse_SearchQueriesGeneration):
            return self.chunk.search_queries  # type: ignore
        return None

    @property
    def search_results(self) -> Optional[list[ChatSearchResult]]:
        """Returns the search results for search-results event type else None."""
        if isinstance(self.chunk, StreamedChatResponse_SearchResults):
            return self.chunk.search_results
        return None

    @property
    def documents(self) -> Optional[list[ChatDocument]]:
        """Returns the documents for search-results event type else None."""
        if isinstance(self.chunk, StreamedChatResponse_SearchResults):
            return self.chunk.documents
        return None

    @property
    def citations(self) -> Optional[list[ChatCitation]]:
        """Returns the citations for citation-generation event type else None."""
        if isinstance(self.chunk, StreamedChatResponse_CitationGeneration):
            return self.chunk.citations
        return None

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

        Cohere does not return model, so we return None
        """
        return None

    @property
    def id(self) -> Optional[str]:
        """Returns the id of the response."""
        if isinstance(self.chunk, StreamedChatResponse_StreamStart):
            return self.chunk.generation_id
        return None

    @property
    def finish_reasons(self) -> Optional[list[str]]:
        """Returns the finish reasons of the response."""
        if isinstance(self.chunk, StreamedChatResponse_StreamEnd):
            return [str(self.chunk.finish_reason)]
        return None

    @property
    def response(self) -> Optional[NonStreamedChatResponse]:
        """Returns the full response for the stream-end event type else None."""
        if isinstance(self.chunk, StreamedChatResponse_StreamEnd):
            return self.chunk.response
        return None

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

    @property
    def usage(self) -> Optional[ApiMetaBilledUnits]:
        """Returns the usage of the response."""
        if isinstance(self.chunk, StreamedChatResponse_StreamEnd):
            if self.chunk.response.meta:
                return self.chunk.response.meta.billed_units
        return None

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

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

citations: Optional[list[ChatCitation]] property

Returns the citations for citation-generation event type else None.

content: str property

Returns the content for the 0th choice delta.

documents: Optional[list[ChatDocument]] property

Returns the documents for search-results event type else None.

event_type: Literal['stream-start', 'search-queries-generation', 'search-results', 'text-generation', 'citation-generation', 'tool-calls-generation', 'stream-end', 'tool-calls-chunk'] property

Returns the type of the chunk.

finish_reasons: Optional[list[str]] property

Returns the finish reasons of the response.

id: Optional[str] property

Returns the id of the response.

input_tokens: Optional[float] property

Returns the number of input tokens.

model: Optional[str] property

Returns the name of the response model.

Cohere does not return model, so we return None

output_tokens: Optional[float] property

Returns the number of output tokens.

response: Optional[NonStreamedChatResponse] property

Returns the full response for the stream-end event type else None.

search_queries: Optional[list[ChatSearchQuery]] property

Returns the search queries for search-query event type else None.

search_results: Optional[list[ChatSearchResult]] property

Returns the search results for search-results event type else None.

tool_calls: Optional[list[ToolCall]] property

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

usage: Optional[ApiMetaBilledUnits] property

Returns the usage of the response.

CohereTool

Bases: BaseTool[ToolCall]

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

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

Example:

from mirascope.cohere import CohereCall, CohereCallParams


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(CohereCall):
    prompt_template = """
    Tell me my favorite animal if my favorite food is {food} and my
    favorite color is {color}.
    """

    food: str
    color: str

    call_params = CohereCallParams(tools=[animal_matcher])


response = AnimalMatcher(food="pizza", color="red").call
tool = response.tool
print(tool.fn(**tool.args))
#> Your favorite animal is the best one, a frog.
Source code in mirascope/cohere/tools.py
class CohereTool(BaseTool[ToolCall]):
    '''A base class for easy use of tools with the Cohere chat client.

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

    Example:

    ```python
    from mirascope.cohere import CohereCall, CohereCallParams


    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(CohereCall):
        prompt_template = """
        Tell me my favorite animal if my favorite food is {food} and my
        favorite color is {color}.
        """

        food: str
        color: str

        call_params = CohereCallParams(tools=[animal_matcher])


    response = AnimalMatcher(food="pizza", color="red").call
    tool = response.tool
    print(tool.fn(**tool.args))
    #> Your favorite animal is the best one, a frog.
    ```
    '''

    tool_call: SkipJsonSchema[SkipValidation[ToolCall]]

    @classmethod
    def tool_schema(cls) -> Tool:
        """Constructs a tool schema for use with the Cohere chat client.

        A Mirascope `CohereTool` is deconstructed into a JSON schema, and relevant keys
        are renamed to match the Cohere tool schema used to make function/tool calls in
        the Cohere chat API.

        Returns:
            The constructed tool schema.
        """
        tool_schema = super().tool_schema()
        parameter_definitions = None
        if "parameters" in tool_schema:
            if "$defs" in tool_schema["parameters"]:
                raise ValueError(
                    "Unfortunately Cohere's chat API cannot handle nested structures "
                    "with $defs."
                )
            parameter_definitions = {
                prop: ToolParameterDefinitionsValue(
                    description=prop_schema["description"]
                    if "description" in prop_schema
                    else None,
                    type=prop_schema["type"],
                    required="required" in tool_schema["parameters"]
                    and prop in tool_schema["parameters"]["required"],
                )
                for prop, prop_schema in tool_schema["parameters"]["properties"].items()
            }
        return Tool(
            name=tool_schema["name"],
            description=tool_schema["description"],
            parameter_definitions=parameter_definitions,
        )

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

        Given `ToolCall` from an Cohere chat completion response, takes its function
        arguments and creates an `CohereTool` instance from it.

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

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

        Raises:
            ValidationError: if the tool call doesn't match the tool schema.
        """
        model_json = tool_call.parameters
        model_json["tool_call"] = tool_call  # type: ignore
        return cls.model_validate(model_json)

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

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

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

from_base_type(base_type) classmethod

Constructs a CohereTool type from a BaseType type.

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

from_fn(fn) classmethod

Constructs a CohereTool type from a function.

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

from_model(model) classmethod

Constructs a CohereTool type from a BaseModel type.

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

from_tool_call(tool_call) classmethod

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

Given ToolCall from an Cohere chat completion response, takes its function arguments and creates an CohereTool instance from it.

Parameters:

Name Type Description Default
tool_call ToolCall

The ... to extract the tool from.

required

Returns:

Type Description
CohereTool

An instance of the tool constructed from the tool call.

Raises:

Type Description
ValidationError

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

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

    Given `ToolCall` from an Cohere chat completion response, takes its function
    arguments and creates an `CohereTool` instance from it.

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

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

    Raises:
        ValidationError: if the tool call doesn't match the tool schema.
    """
    model_json = tool_call.parameters
    model_json["tool_call"] = tool_call  # type: ignore
    return cls.model_validate(model_json)

tool_schema() classmethod

Constructs a tool schema for use with the Cohere chat client.

A Mirascope CohereTool is deconstructed into a JSON schema, and relevant keys are renamed to match the Cohere tool schema used to make function/tool calls in the Cohere chat API.

Returns:

Type Description
Tool

The constructed tool schema.

Source code in mirascope/cohere/tools.py
@classmethod
def tool_schema(cls) -> Tool:
    """Constructs a tool schema for use with the Cohere chat client.

    A Mirascope `CohereTool` is deconstructed into a JSON schema, and relevant keys
    are renamed to match the Cohere tool schema used to make function/tool calls in
    the Cohere chat API.

    Returns:
        The constructed tool schema.
    """
    tool_schema = super().tool_schema()
    parameter_definitions = None
    if "parameters" in tool_schema:
        if "$defs" in tool_schema["parameters"]:
            raise ValueError(
                "Unfortunately Cohere's chat API cannot handle nested structures "
                "with $defs."
            )
        parameter_definitions = {
            prop: ToolParameterDefinitionsValue(
                description=prop_schema["description"]
                if "description" in prop_schema
                else None,
                type=prop_schema["type"],
                required="required" in tool_schema["parameters"]
                and prop in tool_schema["parameters"]["required"],
            )
            for prop, prop_schema in tool_schema["parameters"]["properties"].items()
        }
    return Tool(
        name=tool_schema["name"],
        description=tool_schema["description"],
        parameter_definitions=parameter_definitions,
    )

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"

cohere_api_calculate_cost(usage, model='command-r')

Calculate the cost of a completion using the Cohere API.

https://cohere.com/pricing

Model Input Output command-r $0.5 / 1M tokens $1.5 / 1M tokens command-r-plus $3 / 1M tokens $15 / 1M tokens

Source code in mirascope/cohere/utils.py
def cohere_api_calculate_cost(
    usage: ApiMetaBilledUnits, model="command-r"
) -> Optional[float]:
    """Calculate the cost of a completion using the Cohere API.

    https://cohere.com/pricing

    Model              Input               Output
    command-r          $0.5 / 1M tokens	   $1.5 / 1M tokens
    command-r-plus     $3 / 1M tokens	   $15 / 1M tokens
    """
    pricing = {
        "command-r": {
            "prompt": 0.000_000_5,
            "completion": 0.000_001_5,
        },
        "command-r-plus": {
            "prompt": 0.000_003,
            "completion": 0.000_015,
        },
    }

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

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

    return total_cost

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

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)