mistral¶
A module for interacting with Mistral models.
MistralCall
¶
Bases: BaseCall[MistralCallResponse, MistralCallResponseChunk, MistralTool]
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
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 |
|
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 |
{}
|
Returns:
Type | Description |
---|---|
MistralCallResponse
|
A |
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
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 |
{}
|
Returns:
Type | Description |
---|---|
MistralCallResponse
|
A |
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
messages()
¶
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 |
{}
|
Returns:
Type | Description |
---|---|
Generator[MistralCallResponseChunk, None, None]
|
A |
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
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 |
{}
|
Returns:
Type | Description |
---|---|
AsyncGenerator[MistralCallResponseChunk, None]
|
A |
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
MistralCallParams
¶
Bases: BaseCallParams[MistralTool]
The parameters to use when calling the Mistral API.
Source code in mirascope/mistral/types.py
MistralCallResponse
¶
Bases: BaseCallResponse[ChatCompletionResponse, MistralTool]
Convenience wrapper for Mistral's chat model completions.
When using Mirascope's convenience wrappers to interact with Mistral models via
MistralCall
, responses using MistralCall.call()
will return a
MistralCallResponse
, whereby the implemented properties allow for simpler syntax
and a convenient developer experience.
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)
#> The Name of the Wind
print(response.message)
#> ChatMessage(content='The Name of the Wind', role='assistant',
# function_call=None, tool_calls=None)
print(response.choices)
#> [Choice(finish_reason='stop', index=0, logprobs=None,
# message=ChatMessage(content='The Name of the Wind', role='assistant',
# function_call=None, tool_calls=None))]
Source code in mirascope/mistral/types.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 |
|
choice: ChatCompletionResponseChoice
property
¶
Returns the 0th choice.
choices: list[ChatCompletionResponseChoice]
property
¶
Returns the array of chat completion choices.
content: str
property
¶
The content of the chat completion for the 0th choice.
input_tokens: int
property
¶
Returns the number of input tokens.
message: ChatMessage
property
¶
Returns the message of the chat completion for the 0th choice.
output_tokens: Optional[int]
property
¶
Returns the number of output tokens.
tool: Optional[MistralTool]
property
¶
Returns the 0th tool for the 0th choice message.
Raises:
Type | Description |
---|---|
ValidationError
|
if the tool call doesn't match the tool's schema. |
tool_calls: Optional[list[ToolCall]]
property
¶
Returns the tool calls for the 0th choice message.
tools: Optional[list[MistralTool]]
property
¶
Returns the tools for the 0th choice message.
Raises:
Type | Description |
---|---|
ValidationError
|
if the tool call doesn't match the tool's schema. |
usage: UsageInfo
property
¶
Returns the usage of the chat completion.
dump()
¶
Dumps the response to a dictionary.
MistralCallResponseChunk
¶
Bases: BaseCallResponseChunk[ChatCompletionStreamResponse, MistralTool]
Convenience wrapper around chat completion streaming chunks.
When using Mirascope's convenience wrappers to interact with Mistral models via
MistralCall.stream
, responses will return an MistralCallResponseChunk
, whereby
the implemented properties allow for simpler syntax and a convenient developer
experience.
Example:
from mirascope.mistral import MistralCall
class Math(MistralCall):
prompt_template = "What is 1 + 2?"
content = ""
for chunk in Math().stream():
content += chunk.content
print(content)
#> 1
# 1 +
# 1 + 2
# 1 + 2 equals
# 1 + 2 equals
# 1 + 2 equals 3
# 1 + 2 equals 3.
Source code in mirascope/mistral/types.py
choice: ChatCompletionResponseStreamChoice
property
¶
Returns the 0th choice.
choices: list[ChatCompletionResponseStreamChoice]
property
¶
Returns the array of chat completion choices.
content: str
property
¶
Returns the content of the delta.
delta: DeltaMessage
property
¶
Returns the delta of the 0th choice.
tool_calls: Optional[list[ToolCall]]
property
¶
Returns the partial tool calls for the 0th choice message.
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
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 |
{}
|
Returns:
Type | Description |
---|---|
T
|
The |
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
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 |
{}
|
Returns:
Type | Description |
---|---|
T
|
The |
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
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
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 |
|
from_base_type(base_type)
classmethod
¶
Constructs a MistralTool
type from a BaseType
type.
from_fn(fn)
classmethod
¶
from_model(model)
classmethod
¶
Constructs a MistralTool
type from a BaseModel
type.
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 |
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
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
mistral_api_calculate_cost(usage, model='open-mistral-7b')
¶
Calculate the cost of a completion using the Mistral API.
https://mistral.ai/technology/#pricing
Model Input Output open-mistral-7b $0.25/1M tokens $0.25/1M tokens open-mixtral-8x7b $0.7/1M tokens $0.7/1M tokens open-mixtral-8x22b $2/1M tokens $6/1M tokens mistral-small $2/1M tokens $6/1M tokens mistral-medium $2.7/1M tokens $8.1/1M tokens mistral-large $8/1M tokens $24/1M tokens