Mistral AI
The Mistral AI provider supports language models,
embeddings, speech, transcription, and realtime voice agents.
You can use Mistral AI language models through AI Gateway (recommended) or connect directly with @ai-sdk/mistral.
Realtime voice agents require the direct @ai-sdk/mistral provider and are
not available through AI Gateway.
Using AI Gateway
The AI SDK uses AI Gateway by default for model strings. Gateway provides access to models across providers through a single API key, with usage and cost tracking. Install ai:
$ pnpm add ai
$ npm install ai
$ yarn add ai
$ bun add ai
Set an AI Gateway API key in your environment:
Vercel deployments can also use OIDC authentication. See the AI Gateway provider documentation for configuration and the model catalog for available models.
Gateway feature and provider-option support depends on the model and the provider serving the request. See Gateway provider options.
Using @ai-sdk/mistral
For direct access to Mistral AI, install ai and @ai-sdk/mistral:
$ pnpm add ai @ai-sdk/mistral
$ npm install ai @ai-sdk/mistral
$ yarn add ai @ai-sdk/mistral
$ bun add ai @ai-sdk/mistral
Set your Mistral AI API credential in the MISTRAL_API_KEY environment variable:
AI Gateway does not expose every API in @ai-sdk/mistral. Use the direct provider for provider-specific APIs or custom connection settings.
The following sections document the direct @ai-sdk/mistral provider,
including its model factories and settings. Gateway model and feature
availability can differ.
Provider Instance
You can import the default provider instance mistral from @ai-sdk/mistral:
If you need a customized setup, you can import createMistral from @ai-sdk/mistral
and create a provider instance with your settings:
You can use the following optional settings to customize the Mistral provider instance:
-
baseURL string
Use a different URL prefix for API calls, e.g. to use proxy servers. The default prefix is
https://api.mistral.ai/v1. -
apiKey string | PromiseLike<string> | (() => string | PromiseLike<string>)
Pass a function to resolve credentials before each request, including when keys rotate. The function can return a string or a promise. Credential caching and refresh are managed by the function.
API key that is being sent using the
Authorizationheader. It defaults to theMISTRAL_API_KEYenvironment variable. -
headers Record<string,string>
Custom headers to include in the requests.
-
fetch (input: RequestInfo, init?: RequestInit) => Promise<Response>
Custom fetch implementation. Defaults to the global
fetchfunction. You can use it as a middleware to intercept requests, or to provide a custom fetch implementation for e.g. testing. -
webSocket WebSocketConstructor
Custom WebSocket implementation for realtime transcription. Use a header-capable implementation such as
wsto send the required Authorization header.
Language Models
You can create models that call the Mistral chat API using a provider instance.
The first argument is the model id, e.g. mistral-large-latest.
Some Mistral chat models support tool calls.
For Chat Completions models, set
toolChoice: { type: 'tool', toolName: 'weather' } to request a specific function
from your tools definitions. The provider sends Mistral's native function choice
and keeps all function definitions in the request. This works with both
generateText and streamText. Use a model that supports tool calling.
See tool choice for the
shared API. The mistral.conversation() API handles tool selection separately.
Mistral chat models also support additional model settings that are not part of the standard call settings.
You can pass them as an options argument and utilize MistralLanguageModelChatOptions for typing:
The following optional provider options are available for Mistral models:
-
safePrompt boolean
Whether to inject a safety prompt before all conversations.
Defaults to
false. -
documentImageLimit number
Maximum number of images to process in a document.
-
documentPageLimit number
Maximum number of pages to process in a document.
-
strictJsonSchema boolean
Whether to use strict JSON schema validation for structured outputs. Only applies when a schema is provided and only sets the
strictflag in addition to using Custom Structured Outputs, which is used by default if a schema is provided.Defaults to
false. -
structuredOutputs boolean
Whether to use structured outputs. When enabled, tool calls and object generation will be strict and follow the provided schema.
Defaults to
true. -
parallelToolCalls boolean
Whether to enable parallel function calling during tool use. When set to false, the model will use at most one tool per response.
Defaults to
true. -
promptCacheKey string
A stable identifier used to improve cache affinity for requests that share a prompt prefix.
Prompt Cache Affinity
Mistral prompt caching
reuses shared prompt prefixes. Set promptCacheKey to a stable workflow,
session, or conversation identifier to improve cache affinity. The provider
sends it as Mistral's prompt_cache_key request field:
Use the same key for requests with the same stable prefix. Multi-step
generateText and streamText calls reuse their provider options for every
step, so a single key applies across the complete tool loop. Prompt cache
affinity is best-effort and does not guarantee a cache hit.
Treat cache keys as opaque identifiers. Do not include API keys, secrets, email addresses, or other sensitive personal data.
Document OCR
Mistral chat models support document OCR for PDF files. You can optionally set image and page limits using the provider options.
Reasoning Models
Mistral offers reasoning models that provide step-by-step thinking capabilities:
- magistral-small-latest: Smaller reasoning model for efficient step-by-step thinking
- magistral-medium-latest: More powerful reasoning model balancing performance and cost
These models return structured reasoning content that the AI SDK extracts automatically. The reasoning is available via the reasoningText property in the result:
The SDK automatically parses Mistral's native reasoning format and provides separate reasoningText and text properties in the result. No middleware is needed.
Configurable Reasoning
Some Mistral models support configurable reasoning, which you can control via the reasoning parameter.
You can use the AI SDK's top-level reasoning setting to control reasoning effort:
Most Mistral reasoning models support 'high' and 'none' as effort levels.
On the Chat API, mistral-large-4 and mistral-large-4-0 support 'low', 'medium', and 'high' and cannot disable reasoning. For these models, reasoning: 'none' maps to 'low' with a compatibility warning; reasoning: 'medium' is preserved. You can also set providerOptions.mistral.reasoningEffort: 'medium' directly.
GLM-5.3 models (zai-glm-5-3, zai-glm-5-3-flash, zai-glm-5, zai-glm-latest) support 'low', 'high', and 'max' and cannot disable reasoning.
Example
You can use Mistral language models to generate text with the generateText function:
Mistral language models can also be used in the streamText function
and support structured data generation with Output
(see AI SDK Core).
Structured Outputs
Mistral chat models support structured outputs using JSON Schema. You can use generateText or streamText with Output
and Zod, Valibot, or raw JSON Schema. The SDK sends your schema via Mistral's response_format: { type: 'json_schema' }.
You can enable strict JSON Schema validation using a provider option:
When using structured outputs, the SDK no longer injects an extra "answer with
JSON" instruction. It relies on Mistral's native json_schema/json_object
response formats instead. You can customize the schema name/description via
the standard structured-output APIs.
Conversations API
Use mistral.conversation(modelId) to create a model that calls Mistral's
Conversations API (/v1/conversations). It supports generateText and
streamText, including Mistral's built-in web search tools.
Web Search
The provider offers two tools:
mistral.tools.webSearch(): searches the web.mistral.tools.webSearchPremium(): searches the web and accesses news articles through Mistral's integrated news providers.
Mistral executes these tools on the server. No execute function is needed.
Search calls and results are available in result.toolCalls and
result.toolResults, and URL citations are available in result.sources.
Replace mistral.tools.webSearch() with mistral.tools.webSearchPremium() to use
premium search.
Web search requires mistral.conversation(). The default mistral() factory
and mistral.chat() use the Chat Completions API, which does not support
these tools. See Mistral's web search
documentation.
You can also stream the answer and access citations after the stream completes:
Multi-Turn Conversations
Pass the previous user messages and responseMessages into the next call.
Keep the complete response history, including search calls and results, so
follow-up questions can use the retrieved information. The model does not
retain conversation history between calls.
For streamText, consume the stream before appending
await result.responseMessages to your message history.
Model Capabilities
| Model | Image Input | Tool Usage |
|---|---|---|
labs-leanstral-1-5 | ||
magistral-medium-latest | ||
magistral-small-latest | ||
ministral-14b-latest | ||
ministral-8b-latest | ||
mistral-large-latest | ||
mistral-medium-latest | ||
mistral-small-latest | ||
voxtral-small-latest | ||
zai-glm-5-2 |
The table above lists popular models. Please see the Mistral docs for a full list of available models. You can also pass any available provider model ID as a string if needed.
Transcription Models
You can create models that call the
Mistral audio transcription API
using the .transcription() factory method:
Use Mistral transcription models with transcribe:
Mistral transcription models support additional provider options. Pass them
through providerOptions.mistral and use
MistralTranscriptionModelOptions for type checking:
The following optional provider options are available:
-
language string
The language of the audio, such as
en. Providing it can improve accuracy. -
returnLanguage boolean
Return the detected language with Voxtral 3. Without this option, the response language is normally absent. Cannot be
truewhenlanguageis provided. -
temperature number
The sampling temperature for the transcription.
-
timestampGranularities Array<'segment' | 'word'>
Timestamp granularities to include in the response. Voxtral 3 supports only
segmentand allows it to be combined withlanguage. The SDK rejects this combination for the legacy IDsvoxtral-mini-2507,voxtral-mini-2602, andvoxtral-mini-latest, throwing anInvalidArgumentError. Other model IDs are allowed to send the combination to Mistral. Model-specific timestamp and diarization requirements are validated by the Mistral API. -
diarize boolean
Whether to identify speakers in the transcription. Voxtral 3 requires
timestampGranularities: ['segment']for offline transcription when this option istrue. -
contextBias string[]
Words, phrases, or descriptions of the recording that guide spelling for names, technical terms, or domain-specific vocabulary. Voxtral 3 accepts spaces and punctuation and has no fixed entry limit; entries share the context window with the audio. Earlier models require entries without commas or whitespace and support up to 100 entries.
The normalized result includes transcript text, language, timed segments, and
duration when returned by Mistral. Mistral token and prompt-audio usage is
available under result.providerMetadata.mistral.usage. Segment scores and
speaker IDs from diarization are available under
result.providerMetadata.mistral.segments.
Realtime Transcription
Use experimental_streamTranscribe
with voxtral-mini-transcribe-realtime-3 or voxtral-mini-transcribe-realtime-3-0.
The realtime model uses a WebSocket connection instead of the file upload endpoint.
Audio chunks must contain raw mono, signed 16-bit little-endian PCM samples,
either as bytes or base64 strings. Do not send WAV headers or compressed audio.
Set inputAudioFormat.rate to the source sample rate; it defaults to 16000 Hz.
The provider splits large chunks, waits for session configuration before sending
audio, and waits for the final transcript after the input stream closes. Use
abortSignal to cancel a session.
Mistral requires an Authorization header on the WebSocket connection. Native
WebSocket implementations cannot send this header. On the server, pass a
header-capable implementation such as ws to createMistral({webSocket}).
Custom fetch does not intercept WebSocket connections. Keep the API key on
your server when relaying microphone audio from a browser.
Realtime transcription accepts language, contextBias, and diarize, plus:
-
targetStreamingDelayMs number
An integer from 80 to 1200, or 2400. Lower values reduce transcription delay; higher values give the model more context. Omit it to use Mistral's default.
-
speakerReferences Record<string, string>
Named, base64-encoded WAV, MP3, FLAC, or Opus reference clips. Requires
diarize: true. Mistral supports up to eight clips of 3–15 seconds each. The names become speaker IDs. This provider option is supported in realtime calls only.All reference clips are sent together in one
session.updatemessage; the SDK does not split them into chunks. When using AI Gateway, the entire serialized start frame, including all provider options and base64-encoded references, must fit within 256 KiB (262,144 bytes). Base64 increases file sizes by about one third, leaving less than 192 KiB for the combined original reference files after accounting for JSON and other options. Exceeding the frame limit can close the connection. Use short, compressed reference clips and account for the complete frame size; the clip count and duration limits alone do not guarantee that the references fit. -
turnDetection object
An empty object enables default turn detection. Optional fields are
startThreshold,eagerEndThreshold, andendThreshold(numbers from 0 to 1), plusminSilenceMsandendTimeoutMs(nonnegative integer milliseconds). Mistral validates threshold ordering and rejects combining turn detection with diarization.
temperature, returnLanguage, and timestampGranularities are not sent in
realtime calls and produce unsupported-option warnings. Realtime-only options
produce warnings when passed to transcribe.
With diarize: true, incoming segments become transcript-final parts with
part.providerMetadata.mistral.speakerId. Realtime timestamps may be absent:
only timed segments appear in result.segments, while all returned segments,
including speaker IDs, appear in result.providerMetadata.mistral.segments.
Usage is available in result.providerMetadata.mistral.usage when returned.
Set includeRawChunks: true to receive Mistral's turn.start, turn.eager_end,
turn.resume, and turn.end events in raw parts. These are not normalized
transcription events. A turn.end event can precede trailing text deltas;
continue reading until the stream completes for the final transcript.
See Mistral's realtime protocol, diarization, and turn detection documentation for the server-side constraints and event semantics.
Model Capabilities
The following table covers offline models. The realtime models listed above support streaming transcription, diarization, context bias, and turn detection; realtime timestamps can be absent.
| Model | Timestamps | Diarization | Context Bias |
|---|---|---|---|
voxtral-mini-transcribe-3-0 | |||
voxtral-small-transcribe-3-0 | |||
voxtral-mini-latest |
Speech Models
You can create models that call the
Mistral speech API using
the .speech() factory method:
Use a preset or saved voice ID with generateSpeech:
The Mistral speech model maps voice to Mistral's voice_id. It supports
mp3, wav, pcm, flac, and opus output formats and defaults to mp3.
The instructions, speed, and language settings are not supported and
produce warnings when provided. Voxtral 3 style instructions are not available
at launch. To control emotion and pace, include tags such as [emotion=happy]
and [pace=slow] directly in text.
Voxtral 3 supports additional delivery controls through providerOptions.mistral:
-
expressiveness number
A value from 1 to 5 controlling expressiveness. Higher values trade voice similarity and stability for stronger delivery. Omit it to use the service default.
-
phonemeHints Record<string, string[]>
Map words in the input to lists of IPA phonemes. Mistral validates the supported phoneme inventory. See custom pronunciation.
Mistral also supports one-off voice cloning with base64-encoded reference
audio. Pass it through providerOptions.mistral.refAudio and use
MistralSpeechModelOptions for type checking:
When refAudio is provided, it takes precedence over voice. Reference audio
is redacted from request metadata and API call errors returned by the provider.
Only use reference audio with the speaker's explicit consent. Follow Mistral's
voice cloning usage policy and disclose AI-generated audio when required. This
provider integration supports non-streaming speech generation; Mistral's
streaming speech API is not exposed through SpeechModelV4.
Model Capabilities
| Model | Saved Voices | Reference Audio | Non-Streaming |
|---|---|---|---|
voxtral-mini-tts-3-0 | |||
voxtral-mini-tts-2603 |
Realtime Voice Agents
Realtime voice agents require the direct @ai-sdk/mistral provider. AI Gateway
does not currently support Mistral voice agents.
mistral.experimental_realtime() connects to Mistral's
managed voice agents:
Mistral handles transcription, response generation, speech, and interruptions.
The provider handles the LiveKit connection internally. Your application uses the
existing realtime hook to send microphone audio and play the response.
Install the provider, React hook, and optional livekit-client peer dependency
required for browser voice connections:
$ pnpm add ai @ai-sdk/mistral @ai-sdk/react livekit-client
$ npm install ai @ai-sdk/mistral @ai-sdk/react livekit-client
$ yarn add ai @ai-sdk/mistral @ai-sdk/react livekit-client
$ bun add ai @ai-sdk/mistral @ai-sdk/react livekit-client
Server-side consumers that only create and close sessions or use other Mistral
models do not need livekit-client.
Keep MISTRAL_API_KEY on your server. Create a route that starts and closes
sessions with server-owned configuration:
Authenticate both routes and verify session ownership before closing a session in production. The browser receives session credentials, never the API key.
Use api.provider with the same route in the browser:
connect() requests microphone permission and starts playback. Use HTTPS or
localhost. If the browser blocks playback, call resumePlayback() from a user
gesture. Await close() to stop the microphone, leave the room, and close the
server-side session. Transcripts appear in messages; isCapturing, isPlaying,
and onError expose media state and failures.
Configure the session on the server with instructions, voice, and
providerOptions.mistral. The latter supports stt, tts, turn,
welcomeMessage, agentId, and agentVersion, and is typed by
Experimental_MistralRealtimeModelOptions. The factory's model ID selects the
language model; STT and TTS models are separate settings. voice takes precedence
over tts.voiceId.
This integration supports microphone conversations, transcripts, capture and
playback controls, client tools, and session cleanup. Pass tool definitions in
the server's sessionConfig.tools and handle calls with onToolCall or
addToolOutput, as described in Realtime tool calling.
Session updates support instructions, tools, and providerOptions.mistral.turn.
Text messages and manual audio-buffer or response commands are unsupported.
Audio formats are negotiated by LiveKit; omit inputAudioFormat,
outputAudioFormat, and normalized turnDetection. Configure turn behavior
through providerOptions.mistral instead. getToken() and the hook's api.token,
api.websocket, and api.session paths do not connect to these managed sessions.
The complete microphone-to-speaker example is at
examples/ai-e2e-next/app/mistral-realtime.
Embedding Models
You can create models that call the Mistral embeddings API
using the .embedding() factory method.
You can use Mistral embedding models to generate embeddings with the embed function:
Mistral embedding models support additional provider options through
providerOptions.mistral. You can validate them with
MistralEmbeddingModelOptions:
The following optional provider options are available for Mistral embedding models:
-
metadata Record<string, unknown>
Additional metadata to attach to the embedding request.
-
outputDimension number
The dimension of the output embeddings when supported by the model.
-
outputDtype string
The data type of the output embeddings when supported by the model. Accepts
'float','int8','uint8','binary', or'ubinary'.
Model Capabilities
| Model | Default Dimensions |
|---|---|
mistral-embed | 1024 |
codestral-embed | 1536 |