Skip to content

gemini.extractors

BaseExtractor

Bases: BasePrompt, Generic[BaseCallT, BaseToolT, BaseToolStreamT, ExtractedTypeT], ABC

The base abstract interface for extracting structured information using LLMs.

Source code in mirascope/base/extractors.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
class BaseExtractor(
    BasePrompt, Generic[BaseCallT, BaseToolT, BaseToolStreamT, ExtractedTypeT], ABC
):
    """The base abstract interface for extracting structured information using LLMs."""

    extract_schema: ExtractionType

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

    @abstractmethod
    def extract(self, retries: int = 0) -> ExtractedTypeT:
        """Extracts the `extraction_schema` from an LLM call."""
        ...  # pragma: no cover

    @abstractmethod
    async def extract_async(self, retries: int = 0) -> ExtractedTypeT:
        """Asynchronously extracts the `extraction_schema` from an LLM call."""
        ...  # pragma: no cover

    # Note: only some model providers support streaming tools, so we only implement
    # streaming for those providers and do not require all extractors to implement
    # the `stream` and `stream_async` methods.
    # @abstractmethod
    # def stream(self, retries: int = 0) -> Generator[ExtractedTypeT, None, None]:
    #     """Streams extracted partial `extraction_schema` instances."""
    #     ...  # pragma: no cover

    # @abstractmethod
    # async def stream_async(
    #     self, retries: int = 0
    # ) -> AsyncGenerator[ExtractedTypeT, None]:
    #     """Asynchronously streams extracted partial `extraction_schema` instances."""
    #     ...  # pragma: no cover

    @classmethod
    def from_prompt(
        cls,
        prompt_type: type[BasePromptT],
        call_params: BaseCallParams,
        *,
        extract_schema: Optional[ExtractedType] = None,
    ) -> type[BasePromptT]:
        """Returns an extractor_type generated dynamically from this base extractor.

        Args:
            prompt_type: The prompt class to use for the extractor. Properties and class
                variables of this class will be used to create the new extractor class.
                Must be a class that can be instantiated.
            call_params: The call params to use for the extractor.
            extract_schema: The extract schema to use for the extractor. If none, the
                extractor will use the class' extract_schema.

        Returns:
            A new extractor class with new extractor type.
        """

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

        if extract_schema is not None:
            fields["extract_schema"] = (type[extract_schema], extract_schema)  # type: ignore
        else:
            extract_schema = fields["extract_schema"][1]

        class_vars = {
            name: value
            for name, value in prompt_type.__dict__.items()
            if name not in prompt_type.model_fields
        }
        new_extractor = create_model(
            prompt_type.__name__,
            __base__=cls[extract_schema],  # type: ignore
            **fields,
        )

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

        return cast(type[BasePromptT], new_extractor)

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

    def _extract(
        self,
        call_type: Type[BaseCallT],
        tool_type: Type[BaseToolT],
        retries: Union[int, Retrying] = 0,
        **kwargs: Any,
    ) -> ExtractedTypeT:
        """Extracts `extract_schema` from the call response.

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

        Args:
            call_type: The type of call to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            tool_type: The type of tool to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            retries: The number of call attempts to make on `ValidationError` before
                giving up and throwing the error to the user.
            **kwargs: Additional keyword arguments.

        Returns:
            An instance of the `extract_schema` with it's fields populated.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """

        def _extract_attempt(
            call_type: Type[BaseCallT],
            tool_type: Type[BaseToolT],
            error_messages: dict[str, Any],
            **kwargs: Any,
        ) -> ExtractedTypeT:
            kwargs, return_tool = self._setup(tool_type, kwargs)

            temp_call = self._generate_temp_call(call_type, error_messages)
            response = temp_call(
                **self.model_dump(exclude={"extract_schema"}),
            ).call(**kwargs)
            try:
                extracted_schema = self._extract_schema(
                    response.tool, self.extract_schema, return_tool, response=response
                )
                if extracted_schema is None:
                    raise AttributeError("No tool found in the completion.")
                return extracted_schema
            except (AttributeError, ValueError, ValidationError):
                raise

        if isinstance(retries, int):
            if retries > 0:
                retries = Retrying(stop=stop_after_attempt(retries))
            else:
                return _extract_attempt(call_type, tool_type, {}, **kwargs)
        try:
            error_messages: dict[str, Any] = {}
            for attempt in retries:
                with attempt:
                    try:
                        extraction = _extract_attempt(
                            call_type, tool_type, error_messages, **kwargs
                        )
                    except (AttributeError, ValueError, ValidationError) as e:
                        error_messages[str(e)] = None
                        if "logfire" in self.configuration.llm_ops:  # pragma: no cover
                            logfire.error(f"Retrying due to exception: {e}")
                        raise
        except RetryError as e:
            raise e
        return extraction

    async def _extract_async(
        self,
        call_type: Type[BaseCallT],
        tool_type: Type[BaseToolT],
        retries: Union[int, AsyncRetrying],
        **kwargs: Any,
    ) -> ExtractedTypeT:
        """Extracts `extract_schema` from the asynchronous call response.

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

        Args:
            call_type: The type of call to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            tool_type: The type of tool to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            retries: The number of call attempts to make on `ValidationError` before
                giving up and throwing the error to the user.
            **kwargs: Additional keyword arguments.

        Returns:
            An instance of the `extract_schema` with it's fields populated.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """

        async def _extract_attempt_async(
            call_type: Type[BaseCallT],
            tool_type: Type[BaseToolT],
            error_messages: dict[str, Any],
            **kwargs: Any,
        ) -> ExtractedTypeT:
            kwargs, return_tool = self._setup(tool_type, kwargs)

            temp_call = self._generate_temp_call(call_type, error_messages)

            response = await temp_call(
                **self.model_dump(exclude={"extract_schema"})
            ).call_async(**kwargs)
            try:
                extracted_schema = self._extract_schema(
                    response.tool, self.extract_schema, return_tool, response=response
                )
                if extracted_schema is None:
                    raise AttributeError("No tool found in the completion.")
                return extracted_schema
            except (AttributeError, ValueError, ValidationError):
                raise

        if isinstance(retries, int):
            if retries > 0:
                retries = AsyncRetrying(stop=stop_after_attempt(retries))
            else:
                return await _extract_attempt_async(call_type, tool_type, {}, **kwargs)
        try:
            error_messages: dict[str, Any] = {}
            async for attempt in retries:
                with attempt:
                    try:
                        extraction = await _extract_attempt_async(
                            call_type, tool_type, error_messages, **kwargs
                        )
                    except (AttributeError, ValueError, ValidationError) as e:
                        error_messages[str(e)] = None
                        if "logfire" in self.configuration.llm_ops:  # pragma: no cover
                            logfire.error(f"Retrying due to exception: {e}")
                        raise
        except RetryError as e:
            raise e
        return extraction

    def _stream(
        self,
        call_type: Type[BaseCallT],
        tool_type: Type[BaseToolT],
        tool_stream_type: Type[BaseToolStreamT],
        retries: Union[int, Retrying],
        **kwargs: Any,
    ) -> Generator[ExtractedTypeT, None, None]:
        """Streams partial `extract_schema` instances from the streamed chunks.

        The `extract_schema` is converted into a partial tool, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of tools/function calling functionality to stream information
        extracted from a prompt according to the context provided by the `BaseModel`
        schema.

        Args:
            call_type: The type of call to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            tool_type: The type of tool to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            tool_stream_type: The type of tool stream to use for streaming tools. This
                enables shared code across various model providers that have slight
                variations but the same internal interfaces.
            retries: The number of call attempts to make on `ValidationError` before
                giving up and throwing the error to the user.
            **kwargs: Additional keyword arguments.

        Yields:
            An instance of the partial `extract_schema` with it's available fields
            populated.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """

        def _stream_attempt(
            call_type: Type[BaseCallT],
            tool_type: Type[BaseToolT],
            tool_stream_type: Type[BaseToolStreamT],
            error_messages: dict[str, Any],
            **kwargs: Any,
        ) -> Generator[ExtractedTypeT, None, None]:
            kwargs, return_tool = self._setup(tool_type, kwargs)

            temp_call = self._generate_temp_call(call_type, error_messages)

            stream = temp_call(**self.model_dump(exclude={"extract_schema"})).stream(
                **kwargs
            )
            tool_stream = tool_stream_type.from_stream(stream, allow_partial=True)
            try:
                yielded = False
                for partial_tool in tool_stream:
                    extracted_schema = self._extract_schema(
                        partial_tool, self.extract_schema, return_tool, response=None
                    )
                    if extracted_schema is None:
                        break
                    yielded = True
                    yield extracted_schema

                if not yielded:
                    raise AttributeError("No tool found in the completion.")
            except (AttributeError, ValueError, ValidationError):
                raise

        if isinstance(retries, int):
            if retries > 0:
                retries = Retrying(stop=stop_after_attempt(retries))
            else:
                for partial_tool in _stream_attempt(
                    call_type,
                    tool_type,
                    tool_stream_type,
                    {},
                    **kwargs,
                ):
                    yield partial_tool
                return
        try:
            error_messages: dict[str, Any] = {}
            for attempt in retries:
                with attempt:
                    try:
                        for partial_tool in _stream_attempt(
                            call_type,
                            tool_type,
                            tool_stream_type,
                            error_messages,
                            **kwargs,
                        ):
                            yield partial_tool
                    except (AttributeError, ValueError, ValidationError) as e:
                        error_messages[str(e)] = None
                        if "logfire" in self.configuration.llm_ops:  # pragma: no cover
                            logfire.error(f"Retrying due to exception: {e}")
                        raise
        except RetryError as e:
            raise e

    async def _stream_async(
        self,
        call_type: Type[BaseCallT],
        tool_type: Type[BaseToolT],
        tool_stream_type: Type[BaseToolStreamT],
        retries: Union[int, AsyncRetrying],
        **kwargs: Any,
    ) -> AsyncGenerator[ExtractedTypeT, None]:
        """Asynchronously streams partial `extract_schema`s from streamed chunks.

        The `extract_schema` is converted into a partial tool, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of tools/function calling functionality to stream information
        extracted from a prompt according to the context provided by the `BaseModel`
        schema.

        Args:
            call_type: The type of call to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            tool_type: The type of tool to use for extraction. This enables shared code
                across various model providers that have slight variations but the same
                internal interfaces.
            tool_stream_type: The type of tool stream to use for streaming tools. This
                enables shared code across various model providers that have slight
                variations but the same internal interfaces.
            retries: The number of call attempts to make on `ValidationError` before
                giving up and throwing the error to the user.
            **kwargs: Additional keyword arguments.

        Yields:
            An instance of the partial `extract_schema` with it's available fields
            populated.

        Raises:
            AttributeError: if there is no tool in the call creation.
            ValidationError: if the schema cannot be instantiated from the completion.
        """

        async def _stream_attempt_async(
            call_type: Type[BaseCallT],
            tool_type: Type[BaseToolT],
            tool_stream_type: Type[BaseToolStreamT],
            error_messages: dict[str, Any],
            **kwargs: Any,
        ) -> AsyncGenerator[ExtractedTypeT, None]:
            kwargs, return_tool = self._setup(tool_type, kwargs)

            temp_call = self._generate_temp_call(call_type, error_messages)

            stream = temp_call(
                **self.model_dump(exclude={"extract_schema"})
            ).stream_async(**kwargs)
            tool_stream = tool_stream_type.from_async_stream(stream, allow_partial=True)
            try:
                yielded = False
                async for partial_tool in tool_stream:
                    extracted_schema = self._extract_schema(
                        partial_tool, self.extract_schema, return_tool, response=None
                    )
                    if extracted_schema is None:
                        break
                    yielded = True
                    yield extracted_schema

                if not yielded:
                    raise AttributeError("No tool found in the completion.")
            except (AttributeError, ValueError, ValidationError):
                raise

        if isinstance(retries, int):
            if retries > 0:
                retries = AsyncRetrying(stop=stop_after_attempt(retries))
            else:
                async for partial_tool in _stream_attempt_async(
                    call_type, tool_type, tool_stream_type, {}, **kwargs
                ):
                    yield partial_tool
                return
        try:
            error_messages: dict[str, Any] = {}
            async for attempt in retries:
                with attempt:
                    try:
                        async for partial_tool in _stream_attempt_async(
                            call_type,
                            tool_type,
                            tool_stream_type,
                            error_messages,
                            **kwargs,
                        ):
                            yield partial_tool
                    except (AttributeError, ValueError, ValidationError) as e:
                        error_messages[str(e)] = None
                        if "logfire" in self.configuration.llm_ops:  # pragma: no cover
                            logfire.error(f"Retrying due to exception: {e}")
                        raise
        except RetryError as e:
            raise e

    def _generate_temp_call(
        self, call_type: Type[BaseCallT], error_messages: dict[str, Any]
    ) -> Type[BaseCallT]:
        """Returns a `TempCall` generated using the extractors definition."""
        _prompt_template = self.prompt_template
        if error_messages:
            formatted_error_messages = [
                "- " + element for element in error_messages.keys()
            ]
            error_messages_list = "\n".join(formatted_error_messages)
            _prompt_template = (
                f"{_prompt_template}\n"
                "Errors found:\n\n"
                f"{error_messages_list}\n\n"
                "Please fix the errors and try again."
            )

        class TempCall(call_type):  # type: ignore
            prompt_template = _prompt_template

            base_url = self.base_url
            api_key = self.api_key
            call_params = self.call_params
            configuration = self.configuration

            model_config = ConfigDict(extra="allow")

        properties = getmembers(self)
        for name, value in properties:
            if not hasattr(TempCall, name) or (
                name == "messages" and "messages" in self.__class__.__dict__
            ):
                setattr(TempCall, name, value)

        return TempCall

    def _extract_schema(
        self,
        tool: Optional[BaseToolT],
        schema: ExtractedType,
        return_tool: bool,
        response: Optional[Any],
    ) -> Optional[ExtractedTypeT]:
        """Returns the extracted schema extracted depending on it's extraction type.

        Due to mypy issues with all these generics, we have to type ignore a bunch
        of stuff so it doesn't complain, but each conditional properly checks types
        before doing anything specific to that type (it's just that mypy is annoying).
        """
        if tool is None:
            return None
        if return_tool:
            return tool  # type: ignore
        if _is_base_type(schema):
            return tool.value  # type: ignore
        if response:
            model = schema(**tool.model_dump())  # type: ignore
            model._response = response
        else:
            schema = partial(schema)  # type: ignore
            model = schema(**tool.model_dump())
            model._tool_call = tool.tool_call  # type: ignore
        return model

    def _setup(
        self, tool_type: Type[BaseToolT], kwargs: dict[str, Any]
    ) -> tuple[dict[str, Any], bool]:
        """Returns the call params kwargs and whether to return the tool directly."""
        call_params = self.call_params.model_copy(update=kwargs)
        kwargs = call_params.kwargs(tool_type=tool_type)
        if _is_base_type(self.extract_schema):
            tool = tool_type.from_base_type(self.extract_schema)  # type: ignore
            return_tool = False
        elif not isclass(self.extract_schema):
            tool = tool_type.from_fn(self.extract_schema)
            return_tool = True
        elif not issubclass(self.extract_schema, tool_type):
            tool = tool_type.from_model(self.extract_schema)
            return_tool = False
        else:
            tool = self.extract_schema
            return_tool = True
        kwargs["tools"] = [tool]
        return kwargs, return_tool

extract(retries=0) abstractmethod

Extracts the extraction_schema from an LLM call.

Source code in mirascope/base/extractors.py
@abstractmethod
def extract(self, retries: int = 0) -> ExtractedTypeT:
    """Extracts the `extraction_schema` from an LLM call."""
    ...  # pragma: no cover

extract_async(retries=0) abstractmethod async

Asynchronously extracts the extraction_schema from an LLM call.

Source code in mirascope/base/extractors.py
@abstractmethod
async def extract_async(self, retries: int = 0) -> ExtractedTypeT:
    """Asynchronously extracts the `extraction_schema` from an LLM call."""
    ...  # pragma: no cover

from_prompt(prompt_type, call_params, *, extract_schema=None) classmethod

Returns an extractor_type generated dynamically from this base extractor.

Parameters:

Name Type Description Default
prompt_type type[BasePromptT]

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

required
call_params BaseCallParams

The call params to use for the extractor.

required
extract_schema Optional[ExtractedType]

The extract schema to use for the extractor. If none, the extractor will use the class' extract_schema.

None

Returns:

Type Description
type[BasePromptT]

A new extractor class with new extractor type.

Source code in mirascope/base/extractors.py
@classmethod
def from_prompt(
    cls,
    prompt_type: type[BasePromptT],
    call_params: BaseCallParams,
    *,
    extract_schema: Optional[ExtractedType] = None,
) -> type[BasePromptT]:
    """Returns an extractor_type generated dynamically from this base extractor.

    Args:
        prompt_type: The prompt class to use for the extractor. Properties and class
            variables of this class will be used to create the new extractor class.
            Must be a class that can be instantiated.
        call_params: The call params to use for the extractor.
        extract_schema: The extract schema to use for the extractor. If none, the
            extractor will use the class' extract_schema.

    Returns:
        A new extractor class with new extractor type.
    """

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

    if extract_schema is not None:
        fields["extract_schema"] = (type[extract_schema], extract_schema)  # type: ignore
    else:
        extract_schema = fields["extract_schema"][1]

    class_vars = {
        name: value
        for name, value in prompt_type.__dict__.items()
        if name not in prompt_type.model_fields
    }
    new_extractor = create_model(
        prompt_type.__name__,
        __base__=cls[extract_schema],  # type: ignore
        **fields,
    )

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

    return cast(type[BasePromptT], new_extractor)

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

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)

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)])