Skip to content

gemini

A module for interacting with Google's Gemini models.

GeminiAsyncStream

Bases: BaseAsyncStream[GeminiCallResponseChunk, ContentDict, ContentDict, GeminiTool]

A class for streaming responses from Google's Gemini API.

Source code in mirascope/gemini/types.py
class GeminiAsyncStream(
    BaseAsyncStream[
        GeminiCallResponseChunk,
        ContentDict,
        ContentDict,
        GeminiTool,
    ]
):
    """A class for streaming responses from Google's Gemini API."""

    def __init__(self, stream: AsyncGenerator[GeminiCallResponseChunk, None]):
        """Initializes an instance of `GeminiAsyncStream`."""
        super().__init__(stream, ContentDict)

GeminiCall

Bases: BaseCall[GeminiCallResponse, GeminiCallResponseChunk, GeminiTool, ContentDict]

A class for prompting Google's Gemini Chat API.

This prompt supports the message types: USER, MODEL, TOOL

Example:

from google.generativeai import configure  # type: ignore
from mirascope.gemini import GeminiCall

configure(api_key="YOUR_API_KEY")


class BookRecommender(GeminiCall):
    prompt_template = """
    USER: You're the world's greatest librarian.
    MODEL: Ok, I understand I'm the world's greatest librarian. How can I help?
    USER: Please recommend some {genre} books.

    genre: str


response = BookRecommender(genre="fantasy").call()
print(response.content)
#> As the world's greatest librarian, I am delighted to recommend...
Source code in mirascope/gemini/calls.py
class GeminiCall(
    BaseCall[GeminiCallResponse, GeminiCallResponseChunk, GeminiTool, ContentDict]
):
    '''A class for prompting Google's Gemini Chat API.

    This prompt supports the message types: USER, MODEL, TOOL

    Example:

    ```python
    from google.generativeai import configure  # type: ignore
    from mirascope.gemini import GeminiCall

    configure(api_key="YOUR_API_KEY")


    class BookRecommender(GeminiCall):
        prompt_template = """
        USER: You're the world's greatest librarian.
        MODEL: Ok, I understand I'm the world's greatest librarian. How can I help?
        USER: Please recommend some {genre} books.

        genre: str


    response = BookRecommender(genre="fantasy").call()
    print(response.content)
    #> As the world's greatest librarian, I am delighted to recommend...
    ```
    '''

    call_params: ClassVar[GeminiCallParams] = GeminiCallParams()
    _provider: ClassVar[str] = "gemini"

    def messages(self) -> ContentsType:
        """Returns the `ContentsType` messages for Gemini `generate_content`.

        Raises:
            ValueError: if the docstring contains an unknown role.
        """
        return [
            {"role": message["role"], "parts": [message["content"]]}
            for message in self._parse_messages(
                [MessageRole.MODEL, MessageRole.USER, MessageRole.TOOL]
            )
        ]

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

        Args:
            **kwargs: Additional keyword arguments that will be used for generating the
                response. These will override any existing argument settings in call
                params.

        Returns:
            A `GeminiCallResponse` instance.
        """
        kwargs, tool_types = self._setup(kwargs, GeminiTool)
        model_name = kwargs.pop("model")
        gemini_pro_model = get_wrapped_client(
            GenerativeModel(model_name=model_name), self
        )
        generate_content = get_wrapped_call(
            gemini_pro_model.generate_content,
            self,
            response_type=GeminiCallResponse,
            tool_types=tool_types,
            model_name=model_name,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        start_time = datetime.datetime.now().timestamp() * 1000
        response = generate_content(
            messages,
            stream=False,
            tools=kwargs.pop("tools") if "tools" in kwargs else None,
            **kwargs,
        )
        return GeminiCallResponse(
            response=response,
            user_message_param=user_message_param,
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=None,
        )

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

        Args:
            **kwargs: Additional keyword arguments that will be used for generating the
                response. These will override any existing argument settings in call
                params.

        Returns:
            A `GeminiCallResponse` instance.
        """
        kwargs, tool_types = self._setup(kwargs, GeminiTool)
        model_name = kwargs.pop("model")
        gemini_pro_model = get_wrapped_async_client(
            GenerativeModel(model_name=model_name), self
        )
        generate_content_async = get_wrapped_call(
            gemini_pro_model.generate_content_async,
            self,
            is_async=True,
            response_type=GeminiCallResponse,
            tool_types=tool_types,
            model_name=model_name,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        start_time = datetime.datetime.now().timestamp() * 1000
        response = await generate_content_async(
            messages,
            stream=False,
            tools=kwargs.pop("tools") if "tools" in kwargs else None,
            **kwargs,
        )
        return GeminiCallResponse(
            response=response,
            user_message_param=user_message_param,
            tool_types=tool_types,
            start_time=start_time,
            end_time=datetime.datetime.now().timestamp() * 1000,
            cost=None,
        )

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

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

        Yields:
            A `GeminiCallResponseChunk` for each chunk of the response.
        """
        kwargs, tool_types = self._setup(kwargs, GeminiTool)
        model_name = kwargs.pop("model")
        gemini_pro_model = get_wrapped_client(
            GenerativeModel(model_name=model_name), self
        )
        generate_content = get_wrapped_call(
            gemini_pro_model.generate_content,
            self,
            response_chunk_type=GeminiCallResponseChunk,
            tool_types=tool_types,
            model_name=model_name,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        stream = generate_content(
            messages,
            stream=True,
            tools=kwargs.pop("tools") if "tools" in kwargs else None,
            **kwargs,
        )
        for chunk in stream:
            yield GeminiCallResponseChunk(
                chunk=chunk,
                user_message_param=user_message_param,
                tool_types=tool_types,
            )

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

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

        Yields:
            A `GeminiCallResponseChunk` for each chunk of the response.
        """
        kwargs, tool_types = self._setup(kwargs, GeminiTool)
        model_name = kwargs.pop("model")
        gemini_pro_model = get_wrapped_async_client(
            GenerativeModel(model_name=model_name), self
        )
        generate_content_async = get_wrapped_call(
            gemini_pro_model.generate_content_async,
            self,
            is_async=True,
            response_chunk_type=GeminiCallResponseChunk,
            tool_types=tool_types,
            model_name=model_name,
        )
        messages = self.messages()
        user_message_param = self._get_possible_user_message(messages)
        stream = generate_content_async(
            messages,
            stream=True,
            tools=kwargs.pop("tools") if "tools" in kwargs else None,
            **kwargs,
        )
        if inspect.iscoroutine(stream):
            stream = await stream
        async for chunk in stream:
            yield GeminiCallResponseChunk(
                chunk=chunk,
                user_message_param=user_message_param,
                tool_types=tool_types,
            )

call(retries=0, **kwargs)

Makes an call to the model using this GeminiCall instance.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments that will be used for generating the response. These will override any existing argument settings in call params.

{}

Returns:

Type Description
GeminiCallResponse

A GeminiCallResponse instance.

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

    Args:
        **kwargs: Additional keyword arguments that will be used for generating the
            response. These will override any existing argument settings in call
            params.

    Returns:
        A `GeminiCallResponse` instance.
    """
    kwargs, tool_types = self._setup(kwargs, GeminiTool)
    model_name = kwargs.pop("model")
    gemini_pro_model = get_wrapped_client(
        GenerativeModel(model_name=model_name), self
    )
    generate_content = get_wrapped_call(
        gemini_pro_model.generate_content,
        self,
        response_type=GeminiCallResponse,
        tool_types=tool_types,
        model_name=model_name,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    start_time = datetime.datetime.now().timestamp() * 1000
    response = generate_content(
        messages,
        stream=False,
        tools=kwargs.pop("tools") if "tools" in kwargs else None,
        **kwargs,
    )
    return GeminiCallResponse(
        response=response,
        user_message_param=user_message_param,
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=None,
    )

call_async(retries=0, **kwargs) async

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

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments that will be used for generating the response. These will override any existing argument settings in call params.

{}

Returns:

Type Description
GeminiCallResponse

A GeminiCallResponse instance.

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

    Args:
        **kwargs: Additional keyword arguments that will be used for generating the
            response. These will override any existing argument settings in call
            params.

    Returns:
        A `GeminiCallResponse` instance.
    """
    kwargs, tool_types = self._setup(kwargs, GeminiTool)
    model_name = kwargs.pop("model")
    gemini_pro_model = get_wrapped_async_client(
        GenerativeModel(model_name=model_name), self
    )
    generate_content_async = get_wrapped_call(
        gemini_pro_model.generate_content_async,
        self,
        is_async=True,
        response_type=GeminiCallResponse,
        tool_types=tool_types,
        model_name=model_name,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    start_time = datetime.datetime.now().timestamp() * 1000
    response = await generate_content_async(
        messages,
        stream=False,
        tools=kwargs.pop("tools") if "tools" in kwargs else None,
        **kwargs,
    )
    return GeminiCallResponse(
        response=response,
        user_message_param=user_message_param,
        tool_types=tool_types,
        start_time=start_time,
        end_time=datetime.datetime.now().timestamp() * 1000,
        cost=None,
    )

messages()

Returns the ContentsType messages for Gemini generate_content.

Raises:

Type Description
ValueError

if the docstring contains an unknown role.

Source code in mirascope/gemini/calls.py
def messages(self) -> ContentsType:
    """Returns the `ContentsType` messages for Gemini `generate_content`.

    Raises:
        ValueError: if the docstring contains an unknown role.
    """
    return [
        {"role": message["role"], "parts": [message["content"]]}
        for message in self._parse_messages(
            [MessageRole.MODEL, MessageRole.USER, MessageRole.TOOL]
        )
    ]

stream(retries=0, **kwargs)

Streams the response for a call using this GeminiCall.

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
GeminiCallResponseChunk

A GeminiCallResponseChunk for each chunk of the response.

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

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

    Yields:
        A `GeminiCallResponseChunk` for each chunk of the response.
    """
    kwargs, tool_types = self._setup(kwargs, GeminiTool)
    model_name = kwargs.pop("model")
    gemini_pro_model = get_wrapped_client(
        GenerativeModel(model_name=model_name), self
    )
    generate_content = get_wrapped_call(
        gemini_pro_model.generate_content,
        self,
        response_chunk_type=GeminiCallResponseChunk,
        tool_types=tool_types,
        model_name=model_name,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    stream = generate_content(
        messages,
        stream=True,
        tools=kwargs.pop("tools") if "tools" in kwargs else None,
        **kwargs,
    )
    for chunk in stream:
        yield GeminiCallResponseChunk(
            chunk=chunk,
            user_message_param=user_message_param,
            tool_types=tool_types,
        )

stream_async(retries=0, **kwargs) async

Streams the response asynchronously for a call using this GeminiCall.

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

A GeminiCallResponseChunk for each chunk of the response.

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

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

    Yields:
        A `GeminiCallResponseChunk` for each chunk of the response.
    """
    kwargs, tool_types = self._setup(kwargs, GeminiTool)
    model_name = kwargs.pop("model")
    gemini_pro_model = get_wrapped_async_client(
        GenerativeModel(model_name=model_name), self
    )
    generate_content_async = get_wrapped_call(
        gemini_pro_model.generate_content_async,
        self,
        is_async=True,
        response_chunk_type=GeminiCallResponseChunk,
        tool_types=tool_types,
        model_name=model_name,
    )
    messages = self.messages()
    user_message_param = self._get_possible_user_message(messages)
    stream = generate_content_async(
        messages,
        stream=True,
        tools=kwargs.pop("tools") if "tools" in kwargs else None,
        **kwargs,
    )
    if inspect.iscoroutine(stream):
        stream = await stream
    async for chunk in stream:
        yield GeminiCallResponseChunk(
            chunk=chunk,
            user_message_param=user_message_param,
            tool_types=tool_types,
        )

GeminiCallParams

Bases: BaseCallParams[GeminiTool]

The parameters to use when calling the Gemini API calls.

Example:

from mirascope.gemini import GeminiCall, GeminiCallParams


class BookRecommendation(GeminiPrompt):
    prompt_template = "Please recommend a {genre} book"

    genre: str

    call_params = GeminiCallParams(
        model="gemini-1.0-pro-001",
        generation_config={"candidate_count": 2},
    )


response = BookRecommender(genre="fantasy").call()
print(response.content)
#> The Name of the Wind
Source code in mirascope/gemini/types.py
class GeminiCallParams(BaseCallParams[GeminiTool]):
    """The parameters to use when calling the Gemini API calls.

    Example:

    ```python
    from mirascope.gemini import GeminiCall, GeminiCallParams


    class BookRecommendation(GeminiPrompt):
        prompt_template = "Please recommend a {genre} book"

        genre: str

        call_params = GeminiCallParams(
            model="gemini-1.0-pro-001",
            generation_config={"candidate_count": 2},
        )


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

    model: str = "gemini-1.0-pro"
    generation_config: Optional[dict[str, Any]] = {"candidate_count": 1}
    safety_settings: Optional[Any] = None
    request_options: Optional[dict[str, Any]] = None

GeminiCallResponse

Bases: BaseCallResponse[Union[GenerateContentResponse, AsyncGenerateContentResponse], GeminiTool]

Convenience wrapper around Gemini's GenerateContentResponse.

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

Example:

from mirascope.gemini import GeminiPrompt


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

    genre: str


response = BookRecommender(genre="fantasy").call()
print(response.content)
#> The Lord of the Rings
Source code in mirascope/gemini/types.py
class GeminiCallResponse(
    BaseCallResponse[
        Union[GenerateContentResponse, AsyncGenerateContentResponse], GeminiTool
    ]
):
    """Convenience wrapper around Gemini's `GenerateContentResponse`.

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

    Example:

    ```python
    from mirascope.gemini import GeminiPrompt


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

        genre: str


    response = BookRecommender(genre="fantasy").call()
    print(response.content)
    #> The Lord of the Rings
    ```
    """

    user_message_param: Optional[ContentDict] = None

    @property
    def message_param(self) -> ContentDict:
        """Returns the models's response as a message parameter."""
        return {"role": "model", "parts": self.response.parts}

    @property
    def tools(self) -> Optional[list[GeminiTool]]:
        """Returns the list of tools for the 0th candidate's 0th content part."""
        if self.tool_types is None:
            return None

        if self.response.candidates[0].finish_reason != 1:  # STOP = 1
            raise RuntimeError(
                "Generation stopped before the stop sequence. "
                "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"Finish Reason: {self.response.candidates[0].finish_reason}"
            )

        tool_calls = [
            part.function_call for part in self.response.candidates[0].content.parts
        ]

        extracted_tools = []
        for tool_call in 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[GeminiTool]:
        """Returns the 0th tool for the 0th candidate's 0th content part.

        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[GeminiTool, object]]
    ) -> list[FunctionResponse]:
        """Returns the tool message parameters for tool call results."""
        return [
            FunctionResponse(name=tool.name(), response={"result": output})
            for tool, output in tools_and_outputs
        ]

    @property
    def content(self) -> str:
        """Returns the contained string content for the 0th choice."""
        return self.response.candidates[0].content.parts[0].text

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

        google.generativeai does not return an id
        """
        return None

    @property
    def finish_reasons(self) -> list[str]:
        """Returns the finish reasons of the response."""
        finish_reasons = [
            "FINISH_REASON_UNSPECIFIED",
            "STOP",
            "MAX_TOKENS",
            "SAFETY",
            "RECITATION",
            "OTHER",
        ]

        return [
            finish_reasons[candidate.finish_reason]
            for candidate in self.response.candidates
        ]

    @property
    def model(self) -> None:
        """Returns the model name.

        google.generativeai does not return model, so we return None
        """
        return None

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

        google.generativeai does not have Usage, so we return None
        """
        return None

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

    @property
    def output_tokens(self) -> None:
        """Returns the number of 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": str(self.response),
            "cost": self.cost,
        }

content: str property

Returns the contained string content for the 0th choice.

finish_reasons: list[str] property

Returns the finish reasons of the response.

id: Optional[str] property

Returns the id of the response.

google.generativeai does not return an id

input_tokens: None property

Returns the number of input tokens.

message_param: ContentDict property

Returns the models's response as a message parameter.

model: None property

Returns the model name.

google.generativeai does not return model, so we return None

output_tokens: None property

Returns the number of output tokens.

tool: Optional[GeminiTool] property

Returns the 0th tool for the 0th candidate's 0th content part.

Raises:

Type Description
ValidationError

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

tools: Optional[list[GeminiTool]] property

Returns the list of tools for the 0th candidate's 0th content part.

usage: None property

Returns the usage of the chat completion.

google.generativeai does not have Usage, so we return None

dump()

Dumps the response to a dictionary.

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

tool_message_params(tools_and_outputs) classmethod

Returns the tool message parameters for tool call results.

Source code in mirascope/gemini/types.py
@classmethod
def tool_message_params(
    self, tools_and_outputs: list[tuple[GeminiTool, object]]
) -> list[FunctionResponse]:
    """Returns the tool message parameters for tool call results."""
    return [
        FunctionResponse(name=tool.name(), response={"result": output})
        for tool, output in tools_and_outputs
    ]

GeminiCallResponseChunk

Bases: BaseCallResponseChunk[GenerateContentResponse, GeminiTool]

Convenience wrapper around chat completion streaming chunks.

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

Example:

from mirascope.gemini import GeminiCall


class Math(GeminiCall):
    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/gemini/types.py
class GeminiCallResponseChunk(
    BaseCallResponseChunk[GenerateContentResponse, GeminiTool]
):
    """Convenience wrapper around chat completion streaming chunks.

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

    Example:

    ```python
    from mirascope.gemini import GeminiCall


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


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

    user_message_param: Optional[ContentDict] = None

    @property
    def content(self) -> str:
        """Returns the chunk content for the 0th choice."""
        return self.chunk.candidates[0].content.parts[0].text

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

        google.generativeai does not return an id
        """
        return None

    @property
    def finish_reasons(self) -> list[str]:
        """Returns the finish reasons of the response."""
        finish_reasons = [
            "FINISH_REASON_UNSPECIFIED",
            "STOP",
            "MAX_TOKENS",
            "SAFETY",
            "RECITATION",
            "OTHER",
        ]

        return [
            finish_reasons[candidate.finish_reason]
            for candidate in self.chunk.candidates
        ]

    @property
    def model(self) -> None:
        """Returns the model name.

        google.generativeai does not return model, so we return None
        """
        return None

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

        google.generativeai does not have Usage, so we return None
        """
        return None

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

    @property
    def output_tokens(self) -> None:
        """Returns the number of output tokens."""
        return None

content: str property

Returns the chunk content for the 0th choice.

finish_reasons: list[str] property

Returns the finish reasons of the response.

id: Optional[str] property

Returns the id of the response.

google.generativeai does not return an id

input_tokens: None property

Returns the number of input tokens.

model: None property

Returns the model name.

google.generativeai does not return model, so we return None

output_tokens: None property

Returns the number of output tokens.

usage: None property

Returns the usage of the chat completion.

google.generativeai does not have Usage, so we return None

GeminiExtractor

Bases: BaseExtractor[GeminiCall, GeminiTool, Any, T], Generic[T]

A class for extracting structured information using Google's Gemini Chat models.

Example:

from typing import Literal, Type
from pydantic import BaseModel
from mirascope.gemini import GeminiExtractor

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

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

    prompt_template = """
    USER: I need to extract task details.
    MODEL: Sure, please provide the task description.
    USER: {task}
    """

    task: str

task_description = "Prepare the budget report by next Monday. It's a high priority task."
task = TaskExtractor(task=task_description).extract(retries=3)
assert isinstance(task, TaskDetails)
print(task)
#> title='Prepare the budget report' priority='high' due_date='next Monday'
Source code in mirascope/gemini/extractors.py
class GeminiExtractor(BaseExtractor[GeminiCall, GeminiTool, Any, T], Generic[T]):
    '''A class for extracting structured information using Google's Gemini Chat models.

    Example:

    ```python
    from typing import Literal, Type
    from pydantic import BaseModel
    from mirascope.gemini import GeminiExtractor

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

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

        prompt_template = """
        USER: I need to extract task details.
        MODEL: Sure, please provide the task description.
        USER: {task}
        """

        task: str

    task_description = "Prepare the budget report by next Monday. It's a high priority task."
    task = TaskExtractor(task=task_description).extract(retries=3)
    assert isinstance(task, TaskDetails)
    print(task)
    #> title='Prepare the budget report' priority='high' due_date='next Monday'
    ```
    '''

    call_params: ClassVar[GeminiCallParams] = GeminiCallParams()
    _provider: ClassVar[str] = "gemini"

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

        The `extract_schema` is converted into a `GeminiTool`, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of Gemini'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.
            GeminiError: raises any Gemini errors.
        """
        return self._extract(GeminiCall, GeminiTool, retries, **kwargs)

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

        The `extract_schema` is converted into a `GeminiTool`, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of Gemini'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.
            GeminiError: raises any Gemini errors.
        """
        return await self._extract_async(GeminiCall, GeminiTool, retries, **kwargs)

extract(retries=0, **kwargs)

Extracts extract_schema from the Gemini call response.

The extract_schema is converted into a GeminiTool, complete with a description of the tool, all of the fields, and their types. This allows us to take advantage of Gemini'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.

GeminiError

raises any Gemini errors.

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

    The `extract_schema` is converted into a `GeminiTool`, complete with a
    description of the tool, all of the fields, and their types. This allows us to
    take advantage of Gemini'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.
        GeminiError: raises any Gemini errors.
    """
    return self._extract(GeminiCall, GeminiTool, retries, **kwargs)

extract_async(retries=0, **kwargs) async

Asynchronously extracts extract_schema from the Gemini call response.

The extract_schema is converted into a GeminiTool, complete with a description of the tool, all of the fields, and their types. This allows us to take advantage of Gemini'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.

GeminiError

raises any Gemini errors.

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

    The `extract_schema` is converted into a `GeminiTool`, complete with a
    description of the tool, all of the fields, and their types. This allows us to
    take advantage of Gemini'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.
        GeminiError: raises any Gemini errors.
    """
    return await self._extract_async(GeminiCall, GeminiTool, retries, **kwargs)

GeminiStream

Bases: BaseStream[GeminiCallResponseChunk, ContentDict, ContentDict, GeminiTool]

A class for streaming responses from Google's Gemini API.

Source code in mirascope/gemini/types.py
class GeminiStream(
    BaseStream[
        GeminiCallResponseChunk,
        ContentDict,
        ContentDict,
        GeminiTool,
    ]
):
    """A class for streaming responses from Google's Gemini API."""

    def __init__(self, stream: Generator[GeminiCallResponseChunk, None, None]):
        """Initializes an instance of `GeminiStream`."""
        super().__init__(stream, ContentDict)

GeminiTool

Bases: BaseTool[FunctionCall]

A base class for easy use of tools with the Gemini API.

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

Example:

from mirascope.gemini import GeminiCall, GeminiCallParams, GeminiTool


class CurrentWeather(GeminiTool):
    """A tool for getting the current weather in a location."""

    location: str


class WeatherForecast(GeminiPrompt):
    prompt_template = "What is the current weather in {city}?"

    city: str

    call_params = GeminiCallParams(
        model="gemini-pro",
        tools=[CurrentWeather],
    )


prompt = WeatherPrompt()
forecast = WeatherForecast(city="Tokyo").call().tool
print(forecast.location)
#> Tokyo
Source code in mirascope/gemini/tools.py
class GeminiTool(BaseTool[FunctionCall]):
    '''A base class for easy use of tools with the Gemini API.

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

    Example:

    ```python
    from mirascope.gemini import GeminiCall, GeminiCallParams, GeminiTool


    class CurrentWeather(GeminiTool):
        """A tool for getting the current weather in a location."""

        location: str


    class WeatherForecast(GeminiPrompt):
        prompt_template = "What is the current weather in {city}?"

        city: str

        call_params = GeminiCallParams(
            model="gemini-pro",
            tools=[CurrentWeather],
        )


    prompt = WeatherPrompt()
    forecast = WeatherForecast(city="Tokyo").call().tool
    print(forecast.location)
    #> Tokyo
    ```
    '''

    model_config = ConfigDict(arbitrary_types_allowed=True)

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

        A Mirascope `GeminiTool` is deconstructed into a `Tool` schema for use with the
        Gemini API.

        Returns:
            The constructed `Tool` schema.
        """
        tool_schema = super().tool_schema()
        if "parameters" in tool_schema:
            if "$defs" in tool_schema["parameters"]:
                raise ValueError(
                    "Unfortunately Google's Gemini API cannot handle nested structures "
                    "with $defs."
                )
            tool_schema["parameters"]["properties"] = {
                prop: {
                    key: value for key, value in prop_schema.items() if key != "title"
                }
                for prop, prop_schema in tool_schema["parameters"]["properties"].items()
            }
        return Tool(function_declarations=[FunctionDeclaration(**tool_schema)])

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

        Given a `GenerateContentResponse` from a Gemini chat completion response, this
        method extracts the tool call and constructs an instance of the tool.

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

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

        Raises:
            ValueError: if the tool call doesn't have any arguments.
            ValidationError: if the tool call doesn't match the tool schema.
        """
        if not tool_call.args:
            raise ValueError("Tool call doesn't have any arguments.")
        model_json = {key: value for key, value in tool_call.args.items()}
        model_json["tool_call"] = tool_call
        return cls.model_validate(model_json)

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

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

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

from_base_type(base_type) classmethod

Constructs a GeminiTool type from a BaseType type.

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

from_fn(fn) classmethod

Constructs a GeminiTool type from a function.

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

from_model(model) classmethod

Constructs a GeminiTool type from a BaseModel type.

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

from_tool_call(tool_call) classmethod

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

Given a GenerateContentResponse from a Gemini chat completion response, this method extracts the tool call and constructs an instance of the tool.

Parameters:

Name Type Description Default
tool_call FunctionCall

The GenerateContentResponse from which to extract the tool.

required

Returns:

Type Description
GeminiTool

An instance of the tool constructed from the tool call.

Raises:

Type Description
ValueError

if the tool call doesn't have any arguments.

ValidationError

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

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

    Given a `GenerateContentResponse` from a Gemini chat completion response, this
    method extracts the tool call and constructs an instance of the tool.

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

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

    Raises:
        ValueError: if the tool call doesn't have any arguments.
        ValidationError: if the tool call doesn't match the tool schema.
    """
    if not tool_call.args:
        raise ValueError("Tool call doesn't have any arguments.")
    model_json = {key: value for key, value in tool_call.args.items()}
    model_json["tool_call"] = tool_call
    return cls.model_validate(model_json)

tool_schema() classmethod

Constructs a tool schema for use with the Gemini API.

A Mirascope GeminiTool is deconstructed into a Tool schema for use with the Gemini API.

Returns:

Type Description
Tool

The constructed Tool schema.

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

    A Mirascope `GeminiTool` is deconstructed into a `Tool` schema for use with the
    Gemini API.

    Returns:
        The constructed `Tool` schema.
    """
    tool_schema = super().tool_schema()
    if "parameters" in tool_schema:
        if "$defs" in tool_schema["parameters"]:
            raise ValueError(
                "Unfortunately Google's Gemini API cannot handle nested structures "
                "with $defs."
            )
        tool_schema["parameters"]["properties"] = {
            prop: {
                key: value for key, value in prop_schema.items() if key != "title"
            }
            for prop, prop_schema in tool_schema["parameters"]["properties"].items()
        }
    return Tool(function_declarations=[FunctionDeclaration(**tool_schema)])