Skip to content

anthropic

A module for interacting with Anthropic models.

AnthropicAsyncStream

Bases: BaseAsyncStream[AnthropicCallResponseChunk, MessageParam, MessageParam, AnthropicTool]

A class for streaming responses from Anthropic's Claude API.

Source code in mirascope/anthropic/types.py
class AnthropicAsyncStream(
    BaseAsyncStream[
        AnthropicCallResponseChunk,
        MessageParam,
        MessageParam,
        AnthropicTool,
    ]
):
    """A class for streaming responses from Anthropic's Claude API."""

    def __init__(
        self,
        stream: AsyncGenerator[AnthropicCallResponseChunk, None],
        allow_partial: bool = False,
    ):
        """Initializes an instance of `AnthropicAsyncStream`."""
        AnthropicToolStream._check_version_for_partial(allow_partial)
        super().__init__(stream, MessageParam)
        self._allow_partial = allow_partial

    def __aiter__(
        self,
    ) -> AsyncGenerator[
        tuple[AnthropicCallResponseChunk, Optional[AnthropicTool]], None
    ]:
        """Async iterator over the stream and constructs tools as they are streamed."""
        stream = super().__aiter__()

        async def generator():
            current_tool_call = ToolUseBlock(id="", input={}, name="", type="tool_use")
            current_tool_type = None
            buffer, content = "", []
            async for chunk, _ in stream:
                (
                    buffer,
                    tool,
                    current_tool_call,
                    current_tool_type,
                    starting_new,
                ) = _handle_chunk(
                    buffer,
                    chunk,
                    current_tool_call,
                    current_tool_type,
                    self._allow_partial,
                )
                if tool is not None:
                    yield chunk, tool
                elif current_tool_type is None:
                    yield chunk, None
                if starting_new and self._allow_partial:
                    yield chunk, None
                if chunk.chunk.type == "content_block_stop":
                    content.append(chunk.chunk.content_block.model_dump())
            if content:
                self.message_param["content"] = content  # type: ignore

        return generator()

    @classmethod
    def tool_message_params(cls, tools_and_outputs: list[tuple[AnthropicTool, str]]):
        """Returns the tool message parameters for tool call results."""
        return AnthropicCallResponse.tool_message_params(tools_and_outputs)

tool_message_params(tools_and_outputs) classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/anthropic/types.py
@classmethod
def tool_message_params(cls, tools_and_outputs: list[tuple[AnthropicTool, str]]):
    """Returns the tool message parameters for tool call results."""
    return AnthropicCallResponse.tool_message_params(tools_and_outputs)

AnthropicCall

Bases: BaseCall[AnthropicCallResponse, AnthropicCallResponseChunk, AnthropicTool, MessageParam]

A base class for calling Anthropic's Claude models.

Example:

from mirascope.anthropic import AnthropicCall


class BookRecommender(AnthropicCall):
    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/anthropic/calls.py
class AnthropicCall(
    BaseCall[
        AnthropicCallResponse,
        AnthropicCallResponseChunk,
        AnthropicTool,
        MessageParam,
    ]
):
    """A base class for calling Anthropic's Claude models.

    Example:

    ```python
    from mirascope.anthropic import AnthropicCall


    class BookRecommender(AnthropicCall):
        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[AnthropicCallParams] = AnthropicCallParams()
    _provider: ClassVar[str] = "anthropic"

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

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

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

        Returns:
            A `AnthropicCallResponse` instance.
        """
        messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
        user_message_param = self._get_possible_user_message(messages)
        client = get_wrapped_client(
            Anthropic(api_key=self.api_key, base_url=self.base_url), self
        )
        create = get_wrapped_call(
            client.messages.create,
            self,
            response_type=AnthropicCallResponse,
            tool_types=tool_types,
        )
        start_time = datetime.datetime.now().timestamp() * 1000
        message = create(
            messages=messages,
            stream=False,
            **kwargs,
        )
        return AnthropicCallResponse(
            response=message,
            user_message_param=user_message_param,
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=anthropic_api_calculate_cost(message.usage, message.model),
            response_format=self.call_params.response_format,
        )

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

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

        Returns:
            A `AnthropicCallResponse` instance.
        """
        messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
        user_message_param = self._get_possible_user_message(messages)
        client = get_wrapped_async_client(
            AsyncAnthropic(api_key=self.api_key, base_url=self.base_url), self
        )
        create = get_wrapped_call(
            client.messages.create,
            self,
            is_async=True,
            response_type=AnthropicCallResponse,
            tool_types=tool_types,
        )
        start_time = datetime.datetime.now().timestamp() * 1000
        message = await create(
            messages=messages,
            stream=False,
            **kwargs,
        )
        return AnthropicCallResponse(
            response=message,
            user_message_param=user_message_param,
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=anthropic_api_calculate_cost(message.usage, message.model),
            response_format=self.call_params.response_format,
        )

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

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

        Yields:
            An `AnthropicCallResponseChunk` for each chunk of the response.
        """
        messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
        user_message_param = self._get_possible_user_message(messages)
        client = get_wrapped_client(
            Anthropic(api_key=self.api_key, base_url=self.base_url), self
        )
        stream_fn = get_wrapped_call(
            client.messages.stream,
            self,
            response_chunk_type=AnthropicCallResponseChunk,
            tool_types=tool_types,
        )
        stream = stream_fn(messages=messages, **kwargs)
        if isinstance(stream, AbstractContextManager):
            with stream as message_stream:
                for chunk in message_stream:
                    yield AnthropicCallResponseChunk(
                        chunk=chunk,
                        user_message_param=user_message_param,
                        tool_types=tool_types,
                        response_format=self.call_params.response_format,
                    )
        else:
            for chunk in stream:  # type: ignore
                yield AnthropicCallResponseChunk(
                    chunk=chunk,  # type: ignore
                    user_message_param=user_message_param,
                    tool_types=tool_types,
                    response_format=self.call_params.response_format,
                )

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

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

        Yields:
            An `AnthropicCallResponseChunk` for each chunk of the response.
        """
        messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
        user_message_param = self._get_possible_user_message(messages)
        client = get_wrapped_async_client(
            AsyncAnthropic(api_key=self.api_key, base_url=self.base_url), self
        )
        stream_fn = get_wrapped_call(
            client.messages.stream,
            self,
            is_async=True,
            response_chunk_type=AnthropicCallResponseChunk,
            tool_types=tool_types,
        )
        stream = stream_fn(messages=messages, **kwargs)
        if isinstance(stream, AbstractAsyncContextManager):
            async with stream as message_stream:
                async for chunk in message_stream:  # type: ignore
                    yield AnthropicCallResponseChunk(
                        chunk=chunk,
                        user_message_param=user_message_param,
                        tool_types=tool_types,
                        response_format=self.call_params.response_format,
                    )
        else:
            async for chunk in stream:  # type: ignore
                yield AnthropicCallResponseChunk(
                    chunk=chunk,
                    user_message_param=user_message_param,
                    tool_types=tool_types,
                    response_format=self.call_params.response_format,
                )

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

    def _setup_anthropic_kwargs(
        self,
        kwargs: dict[str, Any],
    ) -> tuple[
        list[MessageParam],
        dict[str, Any],
        Optional[list[Type[AnthropicTool]]],
    ]:
        """Overrides the `BaseCall._setup` for Anthropic specific setup."""
        kwargs, tool_types = self._setup(kwargs, AnthropicTool)
        messages = self.messages()
        system_message = ""
        if "system" in kwargs and kwargs["system"] is not None:
            system_message += f'{kwargs.pop("system")}'
        if messages[0]["role"] == "system":
            if system_message:
                system_message += "\n"
            system_message += messages.pop(0)["content"]
        if self.call_params.response_format == "json":
            if system_message:
                system_message += "\n\n"
            system_message += "Response format: JSON."
            messages.append(
                {
                    "role": "assistant",
                    "content": "Here is the JSON requested with only the fields "
                    "defined in the schema you provided:\n{",
                }
            )
            if "tools" in kwargs:
                tools = kwargs.pop("tools")
                messages[-1]["content"] = (
                    "For each JSON you output, output ONLY the fields defined by these "
                    "schemas. Include a `tool_name` field that EXACTLY MATCHES the "
                    "tool name found in the schema matching this tool:"
                    "\n{schemas}\n{json_msg}".format(
                        schemas="\n\n".join([str(tool) for tool in tools]),
                        json_msg=messages[-1]["content"],
                    )
                )
        if system_message:
            kwargs["system"] = system_message

        return messages, kwargs, tool_types

call(retries=0, **kwargs)

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

A AnthropicCallResponse instance.

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

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

    Returns:
        A `AnthropicCallResponse` instance.
    """
    messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
    user_message_param = self._get_possible_user_message(messages)
    client = get_wrapped_client(
        Anthropic(api_key=self.api_key, base_url=self.base_url), self
    )
    create = get_wrapped_call(
        client.messages.create,
        self,
        response_type=AnthropicCallResponse,
        tool_types=tool_types,
    )
    start_time = datetime.datetime.now().timestamp() * 1000
    message = create(
        messages=messages,
        stream=False,
        **kwargs,
    )
    return AnthropicCallResponse(
        response=message,
        user_message_param=user_message_param,
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=anthropic_api_calculate_cost(message.usage, message.model),
        response_format=self.call_params.response_format,
    )

call_async(retries=0, **kwargs) async

Makes an asynchronous call to the model using this AnthropicCall 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
AnthropicCallResponse

A AnthropicCallResponse instance.

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

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

    Returns:
        A `AnthropicCallResponse` instance.
    """
    messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
    user_message_param = self._get_possible_user_message(messages)
    client = get_wrapped_async_client(
        AsyncAnthropic(api_key=self.api_key, base_url=self.base_url), self
    )
    create = get_wrapped_call(
        client.messages.create,
        self,
        is_async=True,
        response_type=AnthropicCallResponse,
        tool_types=tool_types,
    )
    start_time = datetime.datetime.now().timestamp() * 1000
    message = await create(
        messages=messages,
        stream=False,
        **kwargs,
    )
    return AnthropicCallResponse(
        response=message,
        user_message_param=user_message_param,
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=anthropic_api_calculate_cost(message.usage, message.model),
        response_format=self.call_params.response_format,
    )

messages()

Returns the template as a formatted list of messages.

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

stream(retries=0, **kwargs)

Streams the response for a call using this AnthropicCall.

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
AnthropicCallResponseChunk

An AnthropicCallResponseChunk for each chunk of the response.

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

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

    Yields:
        An `AnthropicCallResponseChunk` for each chunk of the response.
    """
    messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
    user_message_param = self._get_possible_user_message(messages)
    client = get_wrapped_client(
        Anthropic(api_key=self.api_key, base_url=self.base_url), self
    )
    stream_fn = get_wrapped_call(
        client.messages.stream,
        self,
        response_chunk_type=AnthropicCallResponseChunk,
        tool_types=tool_types,
    )
    stream = stream_fn(messages=messages, **kwargs)
    if isinstance(stream, AbstractContextManager):
        with stream as message_stream:
            for chunk in message_stream:
                yield AnthropicCallResponseChunk(
                    chunk=chunk,
                    user_message_param=user_message_param,
                    tool_types=tool_types,
                    response_format=self.call_params.response_format,
                )
    else:
        for chunk in stream:  # type: ignore
            yield AnthropicCallResponseChunk(
                chunk=chunk,  # type: ignore
                user_message_param=user_message_param,
                tool_types=tool_types,
                response_format=self.call_params.response_format,
            )

stream_async(retries=0, **kwargs) async

Streams the response for an asynchronous call using this AnthropicCall.

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[AnthropicCallResponseChunk, None]

An AnthropicCallResponseChunk for each chunk of the response.

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

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

    Yields:
        An `AnthropicCallResponseChunk` for each chunk of the response.
    """
    messages, kwargs, tool_types = self._setup_anthropic_kwargs(kwargs)
    user_message_param = self._get_possible_user_message(messages)
    client = get_wrapped_async_client(
        AsyncAnthropic(api_key=self.api_key, base_url=self.base_url), self
    )
    stream_fn = get_wrapped_call(
        client.messages.stream,
        self,
        is_async=True,
        response_chunk_type=AnthropicCallResponseChunk,
        tool_types=tool_types,
    )
    stream = stream_fn(messages=messages, **kwargs)
    if isinstance(stream, AbstractAsyncContextManager):
        async with stream as message_stream:
            async for chunk in message_stream:  # type: ignore
                yield AnthropicCallResponseChunk(
                    chunk=chunk,
                    user_message_param=user_message_param,
                    tool_types=tool_types,
                    response_format=self.call_params.response_format,
                )
    else:
        async for chunk in stream:  # type: ignore
            yield AnthropicCallResponseChunk(
                chunk=chunk,
                user_message_param=user_message_param,
                tool_types=tool_types,
                response_format=self.call_params.response_format,
            )

AnthropicCallParams

Bases: BaseCallParams[AnthropicTool]

The parameters to use when calling d Claud API with a prompt.

Example:

from mirascope.anthropic import AnthropicCall, AnthropicCallParams


class BookRecommender(AnthropicCall):
    prompt_template = "Please recommend some books."

    call_params = AnthropicCallParams(
        model="anthropic-3-opus-20240229",
    )
Source code in mirascope/anthropic/types.py
class AnthropicCallParams(BaseCallParams[AnthropicTool]):
    """The parameters to use when calling d Claud API with a prompt.

    Example:

    ```python
    from mirascope.anthropic import AnthropicCall, AnthropicCallParams


    class BookRecommender(AnthropicCall):
        prompt_template = "Please recommend some books."

        call_params = AnthropicCallParams(
            model="anthropic-3-opus-20240229",
        )
    ```
    """

    max_tokens: int = 1000
    model: str = "claude-3-haiku-20240307"
    metadata: Optional[Metadata] = None
    stop_sequences: Optional[list[str]] = None
    system: Optional[str] = None
    temperature: Optional[float] = None
    top_k: Optional[int] = None
    top_p: Optional[float] = None
    extra_headers: Optional[Headers] = None
    extra_query: Optional[Query] = None
    extra_body: Optional[Body] = None
    timeout: Optional[Union[float, Timeout]] = 600

    response_format: Optional[Literal["json"]] = None

    model_config = ConfigDict(arbitrary_types_allowed=True)

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

kwargs(tool_type=None, exclude=None)

Returns the keyword argument call parameters.

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

AnthropicCallResponse

Bases: BaseCallResponse[Message, AnthropicTool]

Convenience wrapper around the Anthropic Claude API.

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

Example:

from mirascope.anthropic import AnthropicCall


class BookRecommender(AnthropicCall):
    prompt_template = "Please recommend some books."


print(BookRecommender().call())
Source code in mirascope/anthropic/types.py
class AnthropicCallResponse(BaseCallResponse[Message, AnthropicTool]):
    """Convenience wrapper around the Anthropic Claude API.

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

    Example:

    ```python
    from mirascope.anthropic import AnthropicCall


    class BookRecommender(AnthropicCall):
        prompt_template = "Please recommend some books."


    print(BookRecommender().call())
    ```
    """

    response_format: Optional[Literal["json"]] = None
    user_message_param: Optional[MessageParam] = None

    @property
    def message_param(self) -> MessageParam:
        """Returns the assistant's response as a message parameter."""
        return self.response.model_dump(include={"content", "role"})  # type: ignore

    @property
    def tools(self) -> Optional[list[AnthropicTool]]:
        """Returns the tools for the 0th choice message."""
        if not self.tool_types:
            return None

        if self.response_format == "json":
            # Note: we only handle single tool calls in JSON mode.
            tool_type = self.tool_types[0]
            return [
                tool_type.from_tool_call(
                    ToolUseBlock(
                        id="id",
                        input=json.loads(self.content),
                        name=tool_type.name(),
                        type="tool_use",
                    )
                )
            ]

        if self.response.stop_reason != "tool_use":
            raise RuntimeError(
                "Generation stopped with stop reason that is not `tool_use`. "
                "This is likely due to a limit on output tokens that is too low. "
                "Note that this could also indicate no tool is beind called, so we "
                "recommend that you check the output of the call to confirm. "
                f"Stop Reason: {self.response.stop_reason} "
            )

        extracted_tools = []
        for tool_call in self.response.content:
            if tool_call.type != "tool_use":
                continue
            for tool_type in self.tool_types:
                if tool_call.name == tool_type.name():
                    tool = tool_type.from_tool_call(tool_call)
                    extracted_tools.append(tool)
                    break

        return extracted_tools

    @property
    def tool(self) -> Optional[AnthropicTool]:
        """Returns the 0th tool for the 0th choice text block."""
        tools = self.tools
        if tools:
            return tools[0]
        return None

    @classmethod
    def tool_message_params(
        self, tools_and_outputs: list[tuple[AnthropicTool, str]]
    ) -> list[MessageParam]:
        """Returns the tool message parameters for tool call results."""
        return [
            {
                "role": "user",
                "content": [
                    ToolResultBlockParam(
                        tool_use_id=tool.tool_call.id,
                        type="tool_result",
                        content=[{"text": output, "type": "text"}],
                    )
                    for tool, output in tools_and_outputs
                ],
            }
        ]

    @property
    def content(self) -> str:
        """Returns the string text of the 0th text block."""
        block = self.response.content[0]
        return block.text if block.type == "text" else ""

    @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) -> Optional[list[str]]:
        """Returns the finish reason of the response."""
        return [str(self.response.stop_reason)]

    @property
    def usage(self) -> Usage:
        """Returns the usage of the message."""
        return self.response.usage

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

    @property
    def output_tokens(self) -> int:
        """Returns the number of output tokens."""
        return self.usage.output_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(),
        }

content: str property

Returns the string text of the 0th text block.

finish_reasons: Optional[list[str]] property

Returns the finish reason of the response.

id: str property

Returns the id of the response.

input_tokens: int property

Returns the number of input tokens.

message_param: MessageParam property

Returns the assistant's response as a message parameter.

model: str property

Returns the name of the response model.

output_tokens: int property

Returns the number of output tokens.

tool: Optional[AnthropicTool] property

Returns the 0th tool for the 0th choice text block.

tools: Optional[list[AnthropicTool]] property

Returns the tools for the 0th choice message.

usage: Usage property

Returns the usage of the message.

dump()

Dumps the response to a dictionary.

Source code in mirascope/anthropic/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(),
    }

tool_message_params(tools_and_outputs) classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/anthropic/types.py
@classmethod
def tool_message_params(
    self, tools_and_outputs: list[tuple[AnthropicTool, str]]
) -> list[MessageParam]:
    """Returns the tool message parameters for tool call results."""
    return [
        {
            "role": "user",
            "content": [
                ToolResultBlockParam(
                    tool_use_id=tool.tool_call.id,
                    type="tool_result",
                    content=[{"text": output, "type": "text"}],
                )
                for tool, output in tools_and_outputs
            ],
        }
    ]

AnthropicCallResponseChunk

Bases: BaseCallResponseChunk[MessageStreamEvent, AnthropicTool]

Convenience wrapper around the Anthropic API streaming chunks.

When using Mirascope's convenience wrappers to interact with Anthropic models via AnthropicCall, responses using AnthropicCall.stream() will yield AnthropicCallResponseChunk, whereby the implemented properties allow for simpler syntax and a convenient developer experience.

Example:

from mirascope.anthropic import AnthropicCall


class Math(AnthropicCall):
    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/anthropic/types.py
class AnthropicCallResponseChunk(
    BaseCallResponseChunk[MessageStreamEvent, AnthropicTool]
):
    """Convenience wrapper around the Anthropic API streaming chunks.

    When using Mirascope's convenience wrappers to interact with Anthropic models via
    `AnthropicCall`, responses using `AnthropicCall.stream()` will yield
    `AnthropicCallResponseChunk`, whereby the implemented properties allow for simpler
    syntax and a convenient developer experience.

    Example:

    ```python
    from mirascope.anthropic import AnthropicCall


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

    response_format: Optional[Literal["json"]] = None
    user_message_param: Optional[MessageParam] = None

    @property
    def type(
        self,
    ) -> Literal[
        "text",
        "input_json",
        "message_start",
        "message_delta",
        "message_stop",
        "content_block_start",
        "content_block_delta",
        "content_block_stop",
    ]:
        """Returns the type of the chunk."""
        return self.chunk.type

    @property
    def content(self) -> str:
        """Returns the string content of the 0th message."""
        if isinstance(self.chunk, ContentBlockStartEvent):
            return (
                self.chunk.content_block.text
                if isinstance(self.chunk.content_block, TextBlock)
                else ""
            )
        if isinstance(self.chunk, ContentBlockDeltaEvent):
            return (
                self.chunk.delta.text if isinstance(self.chunk.delta, TextDelta) else ""
            )
        return ""

    @property
    def model(self) -> Optional[str]:
        """Returns the name of the response model."""
        if isinstance(self.chunk, MessageStartEvent):
            return self.chunk.message.model
        return None

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

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

    @property
    def usage(self) -> Optional[Usage]:
        """Returns the usage of the message."""
        if isinstance(self.chunk, MessageStartEvent):
            return self.chunk.message.usage
        return None

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

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

content: str property

Returns the string content of the 0th message.

finish_reasons: Optional[list[str]] property

Returns the finish reason of the response.

id: Optional[str] property

Returns the id of the response.

input_tokens: Optional[int] property

Returns the number of input tokens.

model: Optional[str] property

Returns the name of the response model.

output_tokens: Optional[int] property

Returns the number of output tokens.

type: Literal['text', 'input_json', 'message_start', 'message_delta', 'message_stop', 'content_block_start', 'content_block_delta', 'content_block_stop'] property

Returns the type of the chunk.

usage: Optional[Usage] property

Returns the usage of the message.

AnthropicExtractor

Bases: BaseExtractor[AnthropicCall, AnthropicTool, Any, T], Generic[T]

A class for extracting structured information using Anthropic Claude models.

Example:

from typing import Literal, Type

from mirascope.anthropic import AnthropicExtractor
from pydantic import BaseModel


class TaskDetails(BaseModel):
    title: str
    priority: Literal["low", "normal", "high"]
    due_date: str


class TaskExtractor(AnthropicExtractor[TaskDetails]):
    extract_schema: Type[TaskDetails] = TaskDetails

    prompt_template = """
    Please extract the task details:
    {task}
    """

    task: str


task_description = "Submit quarterly report by next Friday. Task is high priority."
task = TaskExtractor(task=task_description).extract(retries=3)
assert isinstance(task, TaskDetails)
print(task)
#> title='Submit quarterly report' priority='high' due_date='next Friday'
Source code in mirascope/anthropic/extractors.py
class AnthropicExtractor(
    BaseExtractor[AnthropicCall, AnthropicTool, Any, T], Generic[T]
):
    '''A class for extracting structured information using Anthropic Claude models.

    Example:

    ```python
    from typing import Literal, Type

    from mirascope.anthropic import AnthropicExtractor
    from pydantic import BaseModel


    class TaskDetails(BaseModel):
        title: str
        priority: Literal["low", "normal", "high"]
        due_date: str


    class TaskExtractor(AnthropicExtractor[TaskDetails]):
        extract_schema: Type[TaskDetails] = TaskDetails

        prompt_template = """
        Please extract the task details:
        {task}
        """

        task: str


    task_description = "Submit quarterly report by next Friday. Task is high priority."
    task = TaskExtractor(task=task_description).extract(retries=3)
    assert isinstance(task, TaskDetails)
    print(task)
    #> title='Submit quarterly report' priority='high' due_date='next Friday'
    ```
    '''

    call_params: ClassVar[AnthropicCallParams] = AnthropicCallParams()
    _provider: ClassVar[str] = "anthropic"

    def extract(self, retries: Union[int, Retrying] = 0, **kwargs: Any) -> T:
        """Extracts `extract_schema` from the Anthropic call response.

        The `extract_schema` is converted into an `AnthropicTool`, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of Anthropics's tool/function calling functionality to extract
        information from a prompt according to the context provided by the `BaseModel`
        schema.

        Args:
            retries: The maximum number of times to retry the query on validation error.
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Returns:
            The `Schema` instance extracted from the completion.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """
        kwargs["system"] = EXTRACT_SYSTEM_MESSAGE
        return self._extract(AnthropicCall, AnthropicTool, retries, **kwargs)

    async def extract_async(
        self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
    ) -> T:
        """Asynchronously extracts `extract_schema` from the Anthropic call response.

        The `extract_schema` is converted into an `AnthropicTool`, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of Anthropic's tool/function calling functionality to extract
        information from a prompt according to the context provided by the `BaseModel`
        schema.

        Args:
            retries: The maximum number of times to retry the query on validation error.
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Returns:
            The `Schema` instance extracted from the completion.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """
        kwargs["system"] = EXTRACT_SYSTEM_MESSAGE
        return await self._extract_async(
            AnthropicCall, AnthropicTool, retries, **kwargs
        )

    def stream(
        self, retries: Union[int, Retrying] = 0, **kwargs: Any
    ) -> Generator[T, None, None]:
        """Streams partial instances of `extract_schema` as the schema is streamed.

        The `extract_schema` is converted into a `partial(AnthropicTool)`, which allows
        for any field (i.e.function argument) in the tool to be `None`. This allows us
        to stream partial results as we construct the tool from the streamed chunks.

        Args:
            retries: The maximum number of times to retry the query on validation error.
            **kwargs: Additional keyword argument parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Yields:
            The partial `extract_schema` instance from the current buffer.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """
        yield from self._stream(
            AnthropicCall, AnthropicTool, AnthropicToolStream, retries, **kwargs
        )

    async def stream_async(
        self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
    ) -> AsyncGenerator[T, None]:
        """Asynchronously streams partial instances of `extract_schema` as streamed.

        The `extract_schema` is converted into a `partial(AnthropicTool)`, which allows
        for any field (i.e.function argument) in the tool to be `None`. This allows us
        to stream partial results as we construct the tool from the streamed chunks.

        Args:
            retries: The maximum number of times to retry the query on validation error.
            **kwargs: Additional keyword arguments parameters to pass to the call. These
                will override any existing arguments in `call_params`.

        Yields:
            The partial `extract_schema` instance from the current buffer.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """
        async for partial_tool in self._stream_async(
            AnthropicCall, AnthropicTool, AnthropicToolStream, retries, **kwargs
        ):
            yield partial_tool

extract(retries=0, **kwargs)

Extracts extract_schema from the Anthropic call response.

The extract_schema is converted into an AnthropicTool, complete with a description of the tool, all of the fields, and their types. This allows us to take advantage of Anthropics's tool/function calling functionality to extract information from a prompt according to the context provided by the BaseModel schema.

Parameters:

Name Type Description Default
retries Union[int, Retrying]

The maximum number of times to retry the query on validation error.

0
**kwargs Any

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

{}

Returns:

Type Description
T

The Schema instance extracted from the completion.

Raises:

Type Description
AttributeError

if there is no tool in the call creation.

ValidationError

if the schema cannot be instantiated from the completion.

Source code in mirascope/anthropic/extractors.py
def extract(self, retries: Union[int, Retrying] = 0, **kwargs: Any) -> T:
    """Extracts `extract_schema` from the Anthropic call response.

    The `extract_schema` is converted into an `AnthropicTool`, complete with a
    description of the tool, all of the fields, and their types. This allows us to
    take advantage of Anthropics's tool/function calling functionality to extract
    information from a prompt according to the context provided by the `BaseModel`
    schema.

    Args:
        retries: The maximum number of times to retry the query on validation error.
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Returns:
        The `Schema` instance extracted from the completion.

    Raises:
        AttributeError: if there is no tool in the call creation.
        ValidationError: if the schema cannot be instantiated from the completion.
    """
    kwargs["system"] = EXTRACT_SYSTEM_MESSAGE
    return self._extract(AnthropicCall, AnthropicTool, retries, **kwargs)

extract_async(retries=0, **kwargs) async

Asynchronously extracts extract_schema from the Anthropic call response.

The extract_schema is converted into an AnthropicTool, complete with a description of the tool, all of the fields, and their types. This allows us to take advantage of Anthropic's tool/function calling functionality to extract information from a prompt according to the context provided by the BaseModel schema.

Parameters:

Name Type Description Default
retries Union[int, AsyncRetrying]

The maximum number of times to retry the query on validation error.

0
**kwargs Any

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

{}

Returns:

Type Description
T

The Schema instance extracted from the completion.

Raises:

Type Description
AttributeError

if there is no tool in the call creation.

ValidationError

if the schema cannot be instantiated from the completion.

Source code in mirascope/anthropic/extractors.py
async def extract_async(
    self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
) -> T:
    """Asynchronously extracts `extract_schema` from the Anthropic call response.

    The `extract_schema` is converted into an `AnthropicTool`, complete with a
    description of the tool, all of the fields, and their types. This allows us to
    take advantage of Anthropic's tool/function calling functionality to extract
    information from a prompt according to the context provided by the `BaseModel`
    schema.

    Args:
        retries: The maximum number of times to retry the query on validation error.
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Returns:
        The `Schema` instance extracted from the completion.

    Raises:
        AttributeError: if there is no tool in the call creation.
        ValidationError: if the schema cannot be instantiated from the completion.
    """
    kwargs["system"] = EXTRACT_SYSTEM_MESSAGE
    return await self._extract_async(
        AnthropicCall, AnthropicTool, retries, **kwargs
    )

stream(retries=0, **kwargs)

Streams partial instances of extract_schema as the schema is streamed.

The extract_schema is converted into a partial(AnthropicTool), which allows for any field (i.e.function argument) in the tool to be None. This allows us to stream partial results as we construct the tool from the streamed chunks.

Parameters:

Name Type Description Default
retries Union[int, Retrying]

The maximum number of times to retry the query on validation error.

0
**kwargs Any

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

{}

Yields:

Type Description
T

The partial extract_schema instance from the current buffer.

Raises:

Type Description
AttributeError

if there is no tool in the call creation.

ValidationError

if the schema cannot be instantiated from the completion.

Source code in mirascope/anthropic/extractors.py
def stream(
    self, retries: Union[int, Retrying] = 0, **kwargs: Any
) -> Generator[T, None, None]:
    """Streams partial instances of `extract_schema` as the schema is streamed.

    The `extract_schema` is converted into a `partial(AnthropicTool)`, which allows
    for any field (i.e.function argument) in the tool to be `None`. This allows us
    to stream partial results as we construct the tool from the streamed chunks.

    Args:
        retries: The maximum number of times to retry the query on validation error.
        **kwargs: Additional keyword argument parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Yields:
        The partial `extract_schema` instance from the current buffer.

    Raises:
        AttributeError: if there is no tool in the call creation.
        ValidationError: if the schema cannot be instantiated from the completion.
    """
    yield from self._stream(
        AnthropicCall, AnthropicTool, AnthropicToolStream, retries, **kwargs
    )

stream_async(retries=0, **kwargs) async

Asynchronously streams partial instances of extract_schema as streamed.

The extract_schema is converted into a partial(AnthropicTool), which allows for any field (i.e.function argument) in the tool to be None. This allows us to stream partial results as we construct the tool from the streamed chunks.

Parameters:

Name Type Description Default
retries Union[int, AsyncRetrying]

The maximum number of times to retry the query on validation error.

0
**kwargs Any

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

{}

Yields:

Type Description
AsyncGenerator[T, None]

The partial extract_schema instance from the current buffer.

Raises:

Type Description
AttributeError

if there is no tool in the call creation.

ValidationError

if the schema cannot be instantiated from the completion.

Source code in mirascope/anthropic/extractors.py
async def stream_async(
    self, retries: Union[int, AsyncRetrying] = 0, **kwargs: Any
) -> AsyncGenerator[T, None]:
    """Asynchronously streams partial instances of `extract_schema` as streamed.

    The `extract_schema` is converted into a `partial(AnthropicTool)`, which allows
    for any field (i.e.function argument) in the tool to be `None`. This allows us
    to stream partial results as we construct the tool from the streamed chunks.

    Args:
        retries: The maximum number of times to retry the query on validation error.
        **kwargs: Additional keyword arguments parameters to pass to the call. These
            will override any existing arguments in `call_params`.

    Yields:
        The partial `extract_schema` instance from the current buffer.

    Raises:
        AttributeError: if there is no tool in the call creation.
        ValidationError: if the schema cannot be instantiated from the completion.
    """
    async for partial_tool in self._stream_async(
        AnthropicCall, AnthropicTool, AnthropicToolStream, retries, **kwargs
    ):
        yield partial_tool

AnthropicStream

Bases: BaseStream[AnthropicCallResponseChunk, MessageParam, MessageParam, AnthropicTool]

A class for streaming responses from Anthropic's Claude API.

Source code in mirascope/anthropic/types.py
class AnthropicStream(
    BaseStream[
        AnthropicCallResponseChunk,
        MessageParam,
        MessageParam,
        AnthropicTool,
    ]
):
    """A class for streaming responses from Anthropic's Claude API."""

    def __init__(
        self,
        stream: Generator[AnthropicCallResponseChunk, None, None],
        allow_partial: bool = False,
    ):
        """Initializes an instance of `AnthropicStream`."""
        AnthropicToolStream._check_version_for_partial(allow_partial)
        super().__init__(stream, MessageParam)
        self._allow_partial = allow_partial

    def __iter__(
        self,
    ) -> Generator[
        tuple[AnthropicCallResponseChunk, Optional[AnthropicTool]], None, None
    ]:
        """Iterator over the stream and constructs tools as they are streamed."""
        current_tool_call = ToolUseBlock(id="", input={}, name="", type="tool_use")
        current_tool_type = None
        buffer, content = "", []
        for chunk, _ in super().__iter__():
            (
                buffer,
                tool,
                current_tool_call,
                current_tool_type,
                starting_new,
            ) = _handle_chunk(
                buffer,
                chunk,
                current_tool_call,
                current_tool_type,
                self._allow_partial,
            )
            if tool is not None:
                yield chunk, tool
            elif current_tool_type is None:
                yield chunk, None
            if starting_new and self._allow_partial:
                yield chunk, None
            if chunk.chunk.type == "content_block_stop":
                content.append(chunk.chunk.content_block.model_dump())
        if content:
            self.message_param["content"] = content  # type: ignore

    @classmethod
    def tool_message_params(cls, tools_and_outputs: list[tuple[AnthropicTool, str]]):
        """Returns the tool message parameters for tool call results."""
        return AnthropicCallResponse.tool_message_params(tools_and_outputs)

tool_message_params(tools_and_outputs) classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/anthropic/types.py
@classmethod
def tool_message_params(cls, tools_and_outputs: list[tuple[AnthropicTool, str]]):
    """Returns the tool message parameters for tool call results."""
    return AnthropicCallResponse.tool_message_params(tools_and_outputs)

AnthropicTool

Bases: BaseTool[ToolUseBlock]

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

AnthropicTool internally handles the logic that allows you to use tools with simple calls such as AnthropicCallResponse.tool or AnthropicTool.fn, as seen in the example below.

Example:

from mirascope import AnthropicCall, AnthropicCallParams


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(AnthropicCall):
    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 = AnthropicCallParams(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/anthropic/tools.py
class AnthropicTool(BaseTool[ToolUseBlock]):
    '''A base class for easy use of tools with the Anthropic Claude client.

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

    Example:

    ```python
    from mirascope import AnthropicCall, AnthropicCallParams


    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(AnthropicCall):
        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 = AnthropicCallParams(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.
    ```
    '''

    @classmethod
    def tool_schema(cls) -> ToolParam:
        """Constructs JSON tool schema for use with Anthropic's Claude API."""
        schema = super().tool_schema()
        return ToolParam(
            input_schema=schema["parameters"],
            name=schema["name"],
            description=schema["description"],
        )

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

        Given the tool call contents in a `Message` from an Anthropic call response,
        this method parses out the arguments of the tool call and creates an
        `AnthropicTool` instance from them.

        Args:
            tool_call: The list of `TextBlock` contents.

        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.input
        model_json["tool_call"] = tool_call.model_dump()  # type: ignore
        return cls.model_validate(model_json)

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

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

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

from_base_type(base_type) classmethod

Constructs a AnthropicTool type from a BaseType type.

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

from_fn(fn) classmethod

Constructs a AnthropicTool type from a function.

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

from_model(model) classmethod

Constructs a AnthropicTool type from a BaseModel type.

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

from_tool_call(tool_call) classmethod

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

Given the tool call contents in a Message from an Anthropic call response, this method parses out the arguments of the tool call and creates an AnthropicTool instance from them.

Parameters:

Name Type Description Default
tool_call ToolUseBlock

The list of TextBlock contents.

required

Returns:

Type Description
AnthropicTool

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/anthropic/tools.py
@classmethod
def from_tool_call(cls, tool_call: ToolUseBlock) -> AnthropicTool:
    """Extracts an instance of the tool constructed from a tool call response.

    Given the tool call contents in a `Message` from an Anthropic call response,
    this method parses out the arguments of the tool call and creates an
    `AnthropicTool` instance from them.

    Args:
        tool_call: The list of `TextBlock` contents.

    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.input
    model_json["tool_call"] = tool_call.model_dump()  # type: ignore
    return cls.model_validate(model_json)

tool_schema() classmethod

Constructs JSON tool schema for use with Anthropic's Claude API.

Source code in mirascope/anthropic/tools.py
@classmethod
def tool_schema(cls) -> ToolParam:
    """Constructs JSON tool schema for use with Anthropic's Claude API."""
    schema = super().tool_schema()
    return ToolParam(
        input_schema=schema["parameters"],
        name=schema["name"],
        description=schema["description"],
    )

AnthropicToolStream

Bases: BaseToolStream[AnthropicCallResponseChunk, AnthropicTool]

A base class for streaming tools from response chunks.

Source code in mirascope/anthropic/types.py
class AnthropicToolStream(BaseToolStream[AnthropicCallResponseChunk, AnthropicTool]):
    """A base class for streaming tools from response chunks."""

    @classmethod
    @overload
    def from_stream(
        cls,
        stream: Generator[AnthropicCallResponseChunk, None, None],
        allow_partial: Literal[True],
    ) -> Generator[Optional[AnthropicTool], None, None]:
        yield ...  # type: ignore  # pragma: no cover

    @classmethod
    @overload
    def from_stream(
        cls,
        stream: Generator[AnthropicCallResponseChunk, None, None],
        allow_partial: Literal[False],
    ) -> Generator[AnthropicTool, None, None]:
        yield ...  # type: ignore  # pragma: no cover

    @classmethod
    @overload
    def from_stream(
        cls,
        stream: Generator[AnthropicCallResponseChunk, None, None],
        allow_partial: bool = False,
    ) -> Generator[Optional[AnthropicTool], None, None]:
        yield ...  # type: ignore  # pragma: no cover

    @classmethod
    def from_stream(cls, stream, allow_partial=False):
        """Yields partial tools from the given stream of chunks.

        Args:
            stream: The generator of chunks from which to stream tools.
            allow_partial: Whether to allow partial tools.

        Raises:
            RuntimeError: if a tool in the stream is of an unknown type.
        """
        cls._check_version_for_partial(allow_partial)
        current_tool_call = ToolUseBlock(id="", input={}, name="", type="tool_use")
        current_tool_type = None
        buffer = ""
        for chunk in stream:
            (
                buffer,
                tool,
                current_tool_call,
                current_tool_type,
                starting_new,
            ) = _handle_chunk(
                buffer,
                chunk,
                current_tool_call,
                current_tool_type,
                allow_partial,
            )
            if tool is not None:
                yield tool
            if starting_new and allow_partial:
                yield None

    @classmethod
    @overload
    async def from_async_stream(
        cls,
        stream: AsyncGenerator[AnthropicCallResponseChunk, None],
        allow_partial: Literal[True],
    ) -> AsyncGenerator[Optional[AnthropicTool], None]:
        yield ...  # type: ignore  # pragma: no cover

    @classmethod
    @overload
    async def from_async_stream(
        cls,
        stream: AsyncGenerator[AnthropicCallResponseChunk, None],
        allow_partial: Literal[False],
    ) -> AsyncGenerator[AnthropicTool, None]:
        yield ...  # type: ignore  # pragma: no cover

    @classmethod
    @overload
    async def from_async_stream(
        cls,
        stream: AsyncGenerator[AnthropicCallResponseChunk, None],
        allow_partial: bool = False,
    ) -> AsyncGenerator[Optional[AnthropicTool], None]:
        yield ...  # type: ignore  # pragma: no cover

    @classmethod
    async def from_async_stream(cls, async_stream, allow_partial=False):
        """Yields partial tools from the given stream of chunks asynchronously.

        Args:
            stream: The async generator of chunks from which to stream tools.
            allow_partial: Whether to allow partial tools.

        Raises:
            RuntimeError: if a tool in the stream is of an unknown type.
        """
        cls._check_version_for_partial(allow_partial)
        current_tool_call = ToolUseBlock(id="", input={}, name="", type="tool_use")
        current_tool_type = None
        buffer = ""
        async for chunk in async_stream:
            (
                buffer,
                tool,
                current_tool_call,
                current_tool_type,
                starting_new,
            ) = _handle_chunk(
                buffer,
                chunk,
                current_tool_call,
                current_tool_type,
                allow_partial,
            )
            if tool is not None:
                yield tool
            if starting_new and allow_partial:
                yield None

from_async_stream(async_stream, allow_partial=False) async classmethod

Yields partial tools from the given stream of chunks asynchronously.

Parameters:

Name Type Description Default
stream

The async generator of chunks from which to stream tools.

required
allow_partial

Whether to allow partial tools.

False

Raises:

Type Description
RuntimeError

if a tool in the stream is of an unknown type.

Source code in mirascope/anthropic/types.py
@classmethod
async def from_async_stream(cls, async_stream, allow_partial=False):
    """Yields partial tools from the given stream of chunks asynchronously.

    Args:
        stream: The async generator of chunks from which to stream tools.
        allow_partial: Whether to allow partial tools.

    Raises:
        RuntimeError: if a tool in the stream is of an unknown type.
    """
    cls._check_version_for_partial(allow_partial)
    current_tool_call = ToolUseBlock(id="", input={}, name="", type="tool_use")
    current_tool_type = None
    buffer = ""
    async for chunk in async_stream:
        (
            buffer,
            tool,
            current_tool_call,
            current_tool_type,
            starting_new,
        ) = _handle_chunk(
            buffer,
            chunk,
            current_tool_call,
            current_tool_type,
            allow_partial,
        )
        if tool is not None:
            yield tool
        if starting_new and allow_partial:
            yield None

from_stream(stream, allow_partial=False) classmethod

Yields partial tools from the given stream of chunks.

Parameters:

Name Type Description Default
stream

The generator of chunks from which to stream tools.

required
allow_partial

Whether to allow partial tools.

False

Raises:

Type Description
RuntimeError

if a tool in the stream is of an unknown type.

Source code in mirascope/anthropic/types.py
@classmethod
def from_stream(cls, stream, allow_partial=False):
    """Yields partial tools from the given stream of chunks.

    Args:
        stream: The generator of chunks from which to stream tools.
        allow_partial: Whether to allow partial tools.

    Raises:
        RuntimeError: if a tool in the stream is of an unknown type.
    """
    cls._check_version_for_partial(allow_partial)
    current_tool_call = ToolUseBlock(id="", input={}, name="", type="tool_use")
    current_tool_type = None
    buffer = ""
    for chunk in stream:
        (
            buffer,
            tool,
            current_tool_call,
            current_tool_type,
            starting_new,
        ) = _handle_chunk(
            buffer,
            chunk,
            current_tool_call,
            current_tool_type,
            allow_partial,
        )
        if tool is not None:
            yield tool
        if starting_new and allow_partial:
            yield None

anthropic_api_calculate_cost(usage, model='claude-3-haiku-20240229')

Calculate the cost of a completion using the Anthropic API.

https://www.anthropic.com/api

claude-instant-1.2 $0.80 / 1M tokens $2.40 / 1M tokens claude-2.0 $8.00 / 1M tokens $24.00 / 1M tokens claude-2.1 $8.00 / 1M tokens $24.00 / 1M tokens claude-3-haiku $0.25 / 1M tokens $1.25 / 1M tokens claude-3-sonnet $3.00 / 1M tokens $15.00 / 1M tokens claude-3-opus $15.00 / 1M tokens $75.00 / 1M tokens

Source code in mirascope/anthropic/utils.py
def anthropic_api_calculate_cost(
    usage: Usage, model="claude-3-haiku-20240229"
) -> Optional[float]:
    """Calculate the cost of a completion using the Anthropic API.

    https://www.anthropic.com/api

    claude-instant-1.2        $0.80 / 1M tokens   $2.40 / 1M tokens
    claude-2.0                $8.00 / 1M tokens   $24.00 / 1M tokens
    claude-2.1                $8.00 / 1M tokens   $24.00 / 1M tokens
    claude-3-haiku            $0.25 / 1M tokens   $1.25 / 1M tokens
    claude-3-sonnet           $3.00 / 1M tokens   $15.00 / 1M tokens
    claude-3-opus             $15.00 / 1M tokens   $75.00 / 1M tokens
    """
    pricing = {
        "claude-instant-1.2": {
            "prompt": 0.000_000_8,
            "completion": 0.000_002_4,
        },
        "claude-2.0": {
            "prompt": 0.000_008,
            "completion": 0.000_024,
        },
        "claude-2.1": {
            "prompt": 0.000_008,
            "completion": 0.000_024,
        },
        "claude-3-haiku-20240307": {
            "prompt": 0.000_002_5,
            "completion": 0.000_012_5,
        },
        "claude-3-sonnet-20240229": {
            "prompt": 0.000_003,
            "completion": 0.000_015,
        },
        "claude-3-opus-20240229": {
            "prompt": 0.000_015,
            "completion": 0.000_075,
        },
    }

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

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

    return total_cost

bedrock_client_wrapper(aws_secret_key=None, aws_access_key=None, aws_region=None, aws_session_token=None, base_url=None)

Returns a client wrapper for using Anthropic models on AWS Bedrock.

Source code in mirascope/anthropic/utils.py
def bedrock_client_wrapper(
    aws_secret_key: Optional[str] = None,
    aws_access_key: Optional[str] = None,
    aws_region: Optional[str] = None,
    aws_session_token: Optional[str] = None,
    base_url: Optional[Union[str, URL]] = None,
) -> Callable[
    [Union[Anthropic, AsyncAnthropic]], Union[AnthropicBedrock, AsyncAnthropicBedrock]
]:
    """Returns a client wrapper for using Anthropic models on AWS Bedrock."""

    def inner_wrapper(client: Union[Anthropic, AsyncAnthropic]):
        """Returns matching `AnthropicBedrock` or `AsyncAnthropicBedrock` client."""
        kwargs = {
            "aws_secret_key": aws_secret_key,
            "aws_access_key": aws_access_key,
            "aws_region": aws_region,
            "aws_session_token": aws_session_token,
            "base_url": base_url,
        }
        if isinstance(client, Anthropic):
            client = AnthropicBedrock(**kwargs)  # type: ignore
        elif isinstance(client, AsyncAnthropic):
            client = AsyncAnthropicBedrock(**kwargs)  # type: ignore
        return client

    return inner_wrapper