Skip to content

Latest commit

 

History

History
148 lines (114 loc) · 117 KB

File metadata and controls

148 lines (114 loc) · 117 KB

Chat

Overview

Chat Completion API.

Available Operations

complete

Chat Completion

Example Usage

from mistralai.client import Mistral
import os


with Mistral(
    api_key=os.getenv("MISTRAL_API_KEY", ""),
) as mistral:

    res = mistral.chat.complete(model="mistral-large-latest", messages=[
        {
            "role": "user",
            "content": "Who is the best French painter? Answer in one short sentence.",
        },
    ], stream=False, response_format={
        "type": "text",
    })

    # Handle response
    print(res)

Parameters

Parameter Type Required Description Example
model str ✔️ ID of the model to use. You can use the List Available Models API to see all of your available models, or see our Model overview for model descriptions. mistral-large-latest
messages List[models.ChatCompletionRequestMessage] ✔️ The prompt(s) to generate completions for, encoded as a list of dict with role and content. [
{
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
}
]
temperature OptionalNullable[float] What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p but not both. The default value varies depending on the model you are targeting. Call the /models endpoint to retrieve the appropriate value.
top_p Optional[float] Nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both.
max_tokens OptionalNullable[int] The maximum number of tokens to generate in the completion. The token count of your prompt plus max_tokens cannot exceed the model's context length.
stream Optional[bool] Whether to stream back partial progress. If set, tokens will be sent as data-only server-side events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.
stop Optional[models.ChatCompletionRequestStop] Stop generation if this token is detected. Or if one of these tokens is detected when providing an array
random_seed OptionalNullable[int] The seed to use for random sampling. If set, different calls will generate deterministic results.
metadata Dict[str, Any] N/A
response_format Optional[models.ResponseFormat] Specify the format that the model must output. By default it will use { "type": "text" }. Setting to { "type": "json_object" } enables JSON mode, which guarantees the message the model generates is in JSON. When using JSON mode you MUST also instruct the model to produce JSON yourself with a system or a user message. Setting to { "type": "json_schema" } enables JSON schema mode, which guarantees the message the model generates is in JSON and follows the schema you provide. Example 1: {
"type": "text"
}
Example 2: {
"type": "json_object"
}
Example 3: {
"type": "json_schema",
"json_schema": {
"schema": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"authors": {
"items": {
"type": "string"
},
"title": "Authors",
"type": "array"
}
},
"required": [
"name",
"authors"
],
"title": "Book",
"type": "object",
"additionalProperties": false
},
"name": "book",
"strict": true
}
}
tools List[models.ChatCompletionRequestTool] A list of tools the model may call. Use this to provide a list of functions the model may generate JSON inputs for.
tool_choice Optional[models.ChatCompletionRequestToolChoice] Controls which (if any) tool is called by the model. none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. any or required means the model must call one or more tools. Specifying a particular tool via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool.
presence_penalty Optional[float] The presence_penalty determines how much the model penalizes the repetition of words or phrases. A higher presence penalty encourages the model to use a wider variety of words and phrases, making the output more diverse and creative.
frequency_penalty Optional[float] The frequency_penalty penalizes the repetition of words based on their frequency in the generated text. A higher frequency penalty discourages the model from repeating words that have already appeared frequently in the output, promoting diversity and reducing repetition.
n OptionalNullable[int] Number of completions to return for each request, input tokens are only billed once.
prediction Optional[models.Prediction] Enable users to specify an expected completion, optimizing response times by leveraging known or predictable content.
parallel_tool_calls Optional[bool] Whether to enable parallel function calling during tool use, when enabled the model can call multiple tools in parallel.
reasoning_effort OptionalNullable[models.ReasoningEffort] N/A
prompt_mode OptionalNullable[models.MistralPromptMode] Allows toggling between the reasoning mode and no system prompt. When set to reasoning the system prompt for reasoning models will be used.
guardrails List[models.GuardrailConfig] N/A
safe_prompt Optional[bool] Whether to inject a safety prompt before all conversations.
retries Optional[utils.RetryConfig] Configuration to override the default retry behavior of the client.

Response

models.ChatCompletionResponse

Errors

Error Type Status Code Content Type
errors.HTTPValidationError 422 application/json
errors.SDKError 4XX, 5XX */*

stream

Mistral AI provides the ability to stream responses back to a client in order to allow partial results for certain requests. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message. Otherwise, the server will hold the request open until the timeout or until completion, with the response containing the full result as JSON.

Example Usage

from mistralai.client import Mistral
import os


with Mistral(
    api_key=os.getenv("MISTRAL_API_KEY", ""),
) as mistral:

    res = mistral.chat.stream(model="mistral-large-latest", messages=[
        {
            "role": "user",
            "content": "Who is the best French painter? Answer in one short sentence.",
        },
    ], stream=True, response_format={
        "type": "text",
    })

    with res as event_stream:
        for event in event_stream:
            # handle event
            print(event, flush=True)

Parameters

Parameter Type Required Description Example
model str ✔️ ID of the model to use. You can use the List Available Models API to see all of your available models, or see our Model overview for model descriptions. mistral-large-latest
messages List[models.ChatCompletionStreamRequestMessage] ✔️ The prompt(s) to generate completions for, encoded as a list of dict with role and content. [
{
"role": "user",
"content": "Who is the best French painter? Answer in one short sentence."
}
]
temperature OptionalNullable[float] What sampling temperature to use, we recommend between 0.0 and 0.7. Higher values like 0.7 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p but not both. The default value varies depending on the model you are targeting. Call the /models endpoint to retrieve the appropriate value.
top_p Optional[float] Nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both.
max_tokens OptionalNullable[int] The maximum number of tokens to generate in the completion. The token count of your prompt plus max_tokens cannot exceed the model's context length.
stream Optional[bool] N/A
stop Optional[models.ChatCompletionStreamRequestStop] Stop generation if this token is detected. Or if one of these tokens is detected when providing an array
random_seed OptionalNullable[int] The seed to use for random sampling. If set, different calls will generate deterministic results.
metadata Dict[str, Any] N/A
response_format Optional[models.ResponseFormat] Specify the format that the model must output. By default it will use { "type": "text" }. Setting to { "type": "json_object" } enables JSON mode, which guarantees the message the model generates is in JSON. When using JSON mode you MUST also instruct the model to produce JSON yourself with a system or a user message. Setting to { "type": "json_schema" } enables JSON schema mode, which guarantees the message the model generates is in JSON and follows the schema you provide. Example 1: {
"type": "text"
}
Example 2: {
"type": "json_object"
}
Example 3: {
"type": "json_schema",
"json_schema": {
"schema": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"authors": {
"items": {
"type": "string"
},
"title": "Authors",
"type": "array"
}
},
"required": [
"name",
"authors"
],
"title": "Book",
"type": "object",
"additionalProperties": false
},
"name": "book",
"strict": true
}
}
tools List[models.ChatCompletionStreamRequestTool] A list of tools the model may call. Use this to provide a list of functions the model may generate JSON inputs for.
tool_choice Optional[models.ChatCompletionStreamRequestToolChoice] Controls which (if any) tool is called by the model. none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. any or required means the model must call one or more tools. Specifying a particular tool via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool.
presence_penalty Optional[float] The presence_penalty determines how much the model penalizes the repetition of words or phrases. A higher presence penalty encourages the model to use a wider variety of words and phrases, making the output more diverse and creative.
frequency_penalty Optional[float] The frequency_penalty penalizes the repetition of words based on their frequency in the generated text. A higher frequency penalty discourages the model from repeating words that have already appeared frequently in the output, promoting diversity and reducing repetition.
n OptionalNullable[int] Number of completions to return for each request, input tokens are only billed once.
prediction Optional[models.Prediction] Enable users to specify an expected completion, optimizing response times by leveraging known or predictable content.
parallel_tool_calls Optional[bool] Whether to enable parallel function calling during tool use, when enabled the model can call multiple tools in parallel.
reasoning_effort OptionalNullable[models.ReasoningEffort] N/A
prompt_mode OptionalNullable[models.MistralPromptMode] Allows toggling between the reasoning mode and no system prompt. When set to reasoning the system prompt for reasoning models will be used.
guardrails List[models.GuardrailConfig] N/A
safe_prompt Optional[bool] Whether to inject a safety prompt before all conversations.
retries Optional[utils.RetryConfig] Configuration to override the default retry behavior of the client.

Response

Union[eventstreaming.EventStream[models.CompletionEvent], eventstreaming.EventStreamAsync[models.CompletionEvent]]

Errors

Error Type Status Code Content Type
errors.HTTPValidationError 422 application/json
errors.SDKError 4XX, 5XX */*