Skip to content

mistral.extractors

A class for extracting structured information using Mistral chat models.

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)

MistralCall

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

A class for" prompting Mistral's chat API.

Example:

from mirascope.mistral import MistralCall

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

    genre: str

response = BookRecommender(genre="fantasy").call()
print(response.content)
#> There are many great books to read, it ultimately depends...
Source code in mirascope/mistral/calls.py
class MistralCall(
    BaseCall[MistralCallResponse, MistralCallResponseChunk, MistralTool, UserMessage]
):
    """A class for" prompting Mistral's chat API.

    Example:

    ```python
    from mirascope.mistral import MistralCall

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

        genre: str

    response = BookRecommender(genre="fantasy").call()
    print(response.content)
    #> There are many great books to read, it ultimately depends...
    ```
    """

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

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

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

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

        Returns:
            A `MistralCallResponse` instance.

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

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

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

        Returns:
            A `MistralCallResponse` instance.

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

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

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

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

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

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

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

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

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

call(retries=0, **kwargs)

Makes a call to the model using this MistralCall instance.

Parameters:

Name Type Description Default
**kwargs Any

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

{}

Returns:

Type Description
MistralCallResponse

A MistralCallResponse instance.

Raises:

Type Description
MistralException

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

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

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

    Returns:
        A `MistralCallResponse` instance.

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

call_async(retries=0, **kwargs) async

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

Parameters:

Name Type Description Default
**kwargs Any

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

{}

Returns:

Type Description
MistralCallResponse

A MistralCallResponse instance.

Raises:

Type Description
MistralException

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

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

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

    Returns:
        A `MistralCallResponse` instance.

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

messages()

Returns the template as a formatted list of messages.

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

stream(retries=0, **kwargs)

Streams the response for a call using this MistralCall instance.

Parameters:

Name Type Description Default
**kwargs Any

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

{}

Returns:

Type Description
Generator[MistralCallResponseChunk, None, None]

A MistralCallResponseChunk for each chunk of the response.

Raises:

Type Description
MistralException

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

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

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

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

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

stream_async(retries=0, **kwargs) async

Streams the response for an asynchronous call using this MistralCall.

Parameters:

Name Type Description Default
**kwargs Any

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

{}

Returns:

Type Description
AsyncGenerator[MistralCallResponseChunk, None]

A MistralCallResponseChunk for each chunk of the response.

Raises:

Type Description
MistralException

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

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

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

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

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

MistralCallParams

Bases: BaseCallParams[MistralTool]

The parameters to use when calling the Mistral API.

Source code in mirascope/mistral/types.py
class MistralCallParams(BaseCallParams[MistralTool]):
    """The parameters to use when calling the Mistral API."""

    model: str = "open-mixtral-8x7b"
    endpoint: Optional[str] = None
    temperature: Optional[float] = None
    max_tokens: Optional[int] = None
    top_p: Optional[float] = None
    random_seed: Optional[int] = None
    safe_mode: Optional[bool] = None
    safe_prompt: Optional[bool] = None
    tool_choice: Optional[ToolChoice] = None
    model_config = ConfigDict(arbitrary_types_allowed=True)

MistralExtractor

Bases: BaseExtractor[MistralCall, MistralTool, Any, T], Generic[T]

A class for extracting structured information using Mistral Chat models.

Example:

from mirascope.mistral import MistralExtractor
from pydantic import BaseModel
from typing import Literal, Type

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

class TaskExtractor(MistralExtractor[TaskDetails]):
    extract_schema: Type[TaskDetails] = TaskDetails
    call_params = MistralCallParams(model="mistral-large-latest")

    prompt_template = """
    Prepare the budget report by next Monday. It's a high priority task.
    """


task = TaskExtractor().extract(retries=3)
assert isinstance(task, TaskDetails)
print(task)
# > title='Prepare the budget report' priority='high' due_date='next Monday'
Source code in mirascope/mistral/extractors.py
class MistralExtractor(BaseExtractor[MistralCall, MistralTool, Any, T], Generic[T]):
    '''A class for extracting structured information using Mistral Chat models.

    Example:

    ```python
    from mirascope.mistral import MistralExtractor
    from pydantic import BaseModel
    from typing import Literal, Type

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

    class TaskExtractor(MistralExtractor[TaskDetails]):
        extract_schema: Type[TaskDetails] = TaskDetails
        call_params = MistralCallParams(model="mistral-large-latest")

        prompt_template = """
        Prepare the budget report by next Monday. It's a high priority task.
        """


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

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

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

        The `extract_schema` is converted into an `MistralTool`, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of Mistrals'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.
            MistralException: raises any Mistral exceptions, see:
                https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
        """
        return self._extract(MistralCall, MistralTool, retries, **kwargs)

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

        The `extract_schema` is converted into an `MistralTool`, complete with a
        description of the tool, all of the fields, and their types. This allows us to
        take advantage of Mistrals'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.
            MistralException: raises any Mistral exceptions, see:
                https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
        """
        return await self._extract_async(MistralCall, MistralTool, retries, **kwargs)

extract(retries=0, **kwargs)

Extracts extract_schema from the Mistral call response.

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

MistralException

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

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

    The `extract_schema` is converted into an `MistralTool`, complete with a
    description of the tool, all of the fields, and their types. This allows us to
    take advantage of Mistrals'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.
        MistralException: raises any Mistral exceptions, see:
            https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
    """
    return self._extract(MistralCall, MistralTool, retries, **kwargs)

extract_async(retries=0, **kwargs) async

Asynchronously extracts extract_schema from the Mistral call response.

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

MistralException

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

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

    The `extract_schema` is converted into an `MistralTool`, complete with a
    description of the tool, all of the fields, and their types. This allows us to
    take advantage of Mistrals'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.
        MistralException: raises any Mistral exceptions, see:
            https://github.com/mistralai/client-python/blob/main/src/mistralai/exceptions.py
    """
    return await self._extract_async(MistralCall, MistralTool, retries, **kwargs)

MistralTool

Bases: BaseTool[ToolCall]

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

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

Example:

```python import os

from mirascope.mistral import MistralCall, MistralCallParams

def animal_matcher(fav_food: str, fav_color: str) -> str: """Tells you your most likely favorite animal from personality traits.

Args:
    fav_food: your favorite food.
    fav_color: your favorite color.

Returns:
    The animal most likely to be your favorite based on traits.
"""
return "Your favorite animal is the best one, a frog."

class AnimalMatcher(MistralCall): prompt_template = """\ Tell me my favorite animal if my favorite food is {food} and my favorite color is {color}. """

food: str
color: str

api_key = os.getenv("MISTRAL_API_KEY")
call_params = MistralCallParams(
    model="mistral-large-latest", tools=[animal_matcher]
)

prompt = AnimalMatcher(food="pizza", color="green") response = prompt.call()

if tools := response.tools: for tool in tools: print(tool.fn(**tool.args))

> Your favorite animal is the best one, a frog.

Source code in mirascope/mistral/tools.py
class MistralTool(BaseTool[ToolCall]):
    '''A base class for easy use of tools with the Mistral client.

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

    Example:

    ```python
    import os

    from mirascope.mistral import MistralCall, MistralCallParams


    def animal_matcher(fav_food: str, fav_color: str) -> str:
        """Tells you your most likely favorite animal from personality traits.

        Args:
            fav_food: your favorite food.
            fav_color: your favorite color.

        Returns:
            The animal most likely to be your favorite based on traits.
        """
        return "Your favorite animal is the best one, a frog."


    class AnimalMatcher(MistralCall):
        prompt_template = """\\
            Tell me my favorite animal if my favorite food is {food} and my
            favorite color is {color}.
        """

        food: str
        color: str

        api_key = os.getenv("MISTRAL_API_KEY")
        call_params = MistralCallParams(
            model="mistral-large-latest", tools=[animal_matcher]
        )


    prompt = AnimalMatcher(food="pizza", color="green")
    response = prompt.call()

    if tools := response.tools:
        for tool in tools:
            print(tool.fn(**tool.args))
    #> Your favorite animal is the best one, a frog.
    '''

    @classmethod
    def tool_schema(cls) -> dict[str, Any]:
        """Constructs a tool schema for use with the Mistral Chat client.

        A Mirascope `MistralTool` is deconstructed into a JSON schema, and relevant keys
        are renamed to match the Mistral API schema used to make functional/tool calls
        in Mistral API.

        Returns:
            The constructed tool schema.
        """
        fn = super().tool_schema()
        return {"type": "function", "function": fn}

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

        Given `ToolCall` from a Mistral chat completion response, takes its function
        arguments and creates a `MistralTool` instance from it.

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

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

        Raises:
            ValueError: if the tool call doesn't match the tool schema.
        """
        try:
            model_json = json.loads(tool_call.function.arguments)
        except json.JSONDecodeError as e:
            raise ValueError() from e

        model_json["tool_call"] = tool_call
        return cls.model_validate(model_json)

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

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

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

from_base_type(base_type) classmethod

Constructs a MistralTool type from a BaseType type.

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

from_fn(fn) classmethod

Constructs a MistralTool type from a function.

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

from_model(model) classmethod

Constructs a MistralTool type from a BaseModel type.

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

from_tool_call(tool_call) classmethod

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

Given ToolCall from a Mistral chat completion response, takes its function arguments and creates a MistralTool instance from it.

Parameters:

Name Type Description Default
tool_call ToolCall

The Mistral ToolCall to extract the tool from.

required

Returns:

Type Description
MistralTool

An instance of the tool constructed from the tool call.

Raises:

Type Description
ValueError

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

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

    Given `ToolCall` from a Mistral chat completion response, takes its function
    arguments and creates a `MistralTool` instance from it.

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

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

    Raises:
        ValueError: if the tool call doesn't match the tool schema.
    """
    try:
        model_json = json.loads(tool_call.function.arguments)
    except json.JSONDecodeError as e:
        raise ValueError() from e

    model_json["tool_call"] = tool_call
    return cls.model_validate(model_json)

tool_schema() classmethod

Constructs a tool schema for use with the Mistral Chat client.

A Mirascope MistralTool is deconstructed into a JSON schema, and relevant keys are renamed to match the Mistral API schema used to make functional/tool calls in Mistral API.

Returns:

Type Description
dict[str, Any]

The constructed tool schema.

Source code in mirascope/mistral/tools.py
@classmethod
def tool_schema(cls) -> dict[str, Any]:
    """Constructs a tool schema for use with the Mistral Chat client.

    A Mirascope `MistralTool` is deconstructed into a JSON schema, and relevant keys
    are renamed to match the Mistral API schema used to make functional/tool calls
    in Mistral API.

    Returns:
        The constructed tool schema.
    """
    fn = super().tool_schema()
    return {"type": "function", "function": fn}