Open History to see the last commit
1---
2title: Mistral
3id: mistral-adapter
4order: 7
5description: "Use Mistral models in TanStack AI with @tanstack/ai-mistral: Mistral Large and Medium, Pixtral vision, Magistral reasoning, Codestral, and Mistral embeddings."
6keywords:
7 - tanstack ai
8 - mistral
9 - mistral large
10 - pixtral
11 - magistral
12 - codestral
13 - adapter
14 - llm
15---
16
17The Mistral adapter calls Mistral Large, Pixtral, Magistral, and Codestral. It also creates embeddings.
18
19## 1. Install
20
21<!-- ::start:tabs variant="package-manager" mode="install" -->
22
23react: @tanstack/ai-mistral
24vue: @tanstack/ai-mistral
25solid: @tanstack/ai-mistral
26svelte: @tanstack/ai-mistral
27preact: @tanstack/ai-mistral
28angular: @tanstack/ai-mistral
29vanilla: @tanstack/ai-mistral
30octane: @tanstack/ai-mistral
31
32<!-- ::end:tabs -->
33
34## 2. Set the API key
35
36Get a key from the [Mistral Console](https://console.mistral.ai/). Put it in the environment of your server:
37
38```bash
39MISTRAL_API_KEY=...
40```
41
42`mistralText` and `mistralEmbedding` read `MISTRAL_API_KEY`. To pass the key in code, use `createMistralText`:
43
44```typescript
45import { createMistralText } from "@tanstack/ai-mistral";
46
47const adapter = createMistralText("mistral-large-latest", process.env.MISTRAL_API_KEY!);
48```
49
50## 3. Stream a chat from the server
51
52```typescript
53import {
54 chat,
55 chatParamsFromRequest,
56 toServerSentEventsResponse,
57} from "@tanstack/ai";
58import { mistralText } from "@tanstack/ai-mistral";
59
60export async function POST(request: Request) {
61 const { messages, threadId, runId } = await chatParamsFromRequest(request);
62
63 const stream = chat({
64 adapter: mistralText("mistral-large-latest"),
65 messages,
66 threadId,
67 runId,
68 });
69
70 return toServerSentEventsResponse(stream);
71}
72```
73
74## 4. Render the chat
75
76The client is the same for every provider. Point `useChat` at your route:
77
78```tsx
79import { useState } from "react";
80import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
81
82export function Chat() {
83 const [input, setInput] = useState("");
84 const { messages, sendMessage } = useChat({
85 connection: fetchServerSentEvents("/api/chat"),
86 threadId: "support-chat",
87 });
88
89 return (
90 <form
91 onSubmit={(event) => {
92 event.preventDefault();
93 sendMessage(input);
94 setInput("");
95 }}
96 >
97 {messages.map((message) => (
98 <p key={message.id}>
99 {message.parts
100 .map((part) => (part.type === "text" ? part.content : ""))
101 .join("")}
102 </p>
103 ))}
104 <input value={input} onChange={(event) => setInput(event.target.value)} />
105 </form>
106 );
107}
108```
109
110For Vue, Solid, Svelte, Angular, and the other frameworks, see [Quick Start](../getting-started/quick-start#3-render-the-chat).
111
112You now have a streaming Mistral chat. [Tools](../tools/tools) work the same as with every adapter. Mistral has no provider tools of its own, so define your tools with `toolDefinition()`.
113
114## Images in a message
115
116Send an image with the text to a vision model: `pixtral-large-latest`, `pixtral-12b-2409`, `mistral-medium-latest`, or `mistral-small-latest`.
117
118```typescript
119import { chat } from "@tanstack/ai";
120import { mistralText } from "@tanstack/ai-mistral";
121
122const stream = chat({
123 adapter: mistralText("pixtral-large-latest"),
124 messages: [
125 {
126 role: "user",
127 content: [
128 { type: "text", content: "What's in this image?" },
129 {
130 type: "image",
131 source: {
132 type: "url",
133 value: "https://example.com/photo.jpg",
134 },
135 },
136 ],
137 },
138 ],
139 threadId: "thread-1",
140});
141```
142
143For base64 data, set `source.type` to `"data"` and add `mimeType`:
144
145```typescript
146import { chat } from "@tanstack/ai";
147import { mistralText } from "@tanstack/ai-mistral";
148
149const base64String = "..."; // your base64-encoded image bytes
150
151const stream = chat({
152 adapter: mistralText("pixtral-large-latest"),
153 messages: [
154 {
155 role: "user",
156 content: [
157 { type: "text", content: "What's in this image?" },
158 {
159 type: "image",
160 source: {
161 type: "data",
162 mimeType: "image/png",
163 value: base64String,
164 },
165 },
166 ],
167 },
168 ],
169 threadId: "thread-1",
170});
171```
172
173See [Multimodal Content](../advanced/multimodal-content) for the full shape of a content part.
174
175## Structured output
176
177Get JSON that matches a Zod schema. The adapter uses the `json_schema` response format of Mistral:
178
179```typescript
180import { chat } from "@tanstack/ai";
181import { mistralText } from "@tanstack/ai-mistral";
182import { z } from "zod";
183
184const recipeSchema = z.object({
185 name: z.string(),
186 ingredients: z.array(z.string()),
187 steps: z.array(z.string()),
188});
189
190const recipe = await chat({
191 adapter: mistralText("mistral-large-latest"),
192 messages: [
193 { role: "user", content: "Give me a chocolate chip cookie recipe." },
194 ],
195 threadId: "thread-1",
196 outputSchema: recipeSchema,
197});
198
199console.log(recipe.name); // typed as z.infer<typeof recipeSchema>
200```
201
202See [Structured Outputs](../chat/structured-outputs).
203
204## Embeddings
205
206```typescript
207import { embed } from "@tanstack/ai";
208import { mistralEmbedding } from "@tanstack/ai-mistral";
209
210const result = await embed({
211 adapter: mistralEmbedding("mistral-embed"),
212 input: ["a red guitar", "a blue drum kit"],
213});
214
215console.log(result.embeddings[0]?.vector); // 1024 dimensions
216```
217
218`mistral-embed` always gives 1024 dimensions. `codestral-embed` is tuned for code, and it takes the top-level `dimensions` option:
219
220```typescript
221import { embed } from "@tanstack/ai";
222import { mistralEmbedding } from "@tanstack/ai-mistral";
223
224const result = await embed({
225 adapter: mistralEmbedding("codestral-embed"),
226 input: "function add(a, b) { return a + b }",
227 dimensions: 512,
228});
229```
230
231See the [Embeddings guide](../embeddings.md).
232
233## What Mistral does not do
234
235- Image, audio, and video generation. Use [OpenAI](./openai), [Gemini](./gemini), or [fal.ai](./fal).
236- Text-to-speech and transcription. Use [OpenAI](./openai) or [ElevenLabs](./elevenlabs).
237
238## Models and options
239
240### Model options
241
242Provider options go in `modelOptions`, with the snake_case names of Mistral. This includes the sampling options `temperature`, `top_p`, and `max_tokens`:
243
244```typescript
245import { chat } from "@tanstack/ai";
246import { mistralText } from "@tanstack/ai-mistral";
247
248const stream = chat({
249 adapter: mistralText("mistral-large-latest"),
250 messages: [{ role: "user", content: "Hello!" }],
251 threadId: "thread-1",
252 modelOptions: {
253 temperature: 0.7,
254 top_p: 0.9,
255 max_tokens: 1024,
256 random_seed: 42,
257 stop: ["END"],
258 safe_prompt: true,
259 frequency_penalty: 0.5,
260 presence_penalty: 0.5,
261 parallel_tool_calls: true,
262 tool_choice: "auto",
263 },
264});
265```
266
267Sampling options do not go at the root of `chat()`. See [Moving Sampling Options into modelOptions](../migration/sampling-options-to-model-options).
268
269### Reasoning
270
271Set `reasoning` on `chat()` to turn thinking up, down, or off:
272
273```typescript
274import { chat } from "@tanstack/ai";
275import { mistralText } from "@tanstack/ai-mistral";
276
277const stream = chat({
278 adapter: mistralText("mistral-medium-latest"),
279 messages: [{ role: "user", content: "Why is the sky blue?" }],
280 threadId: "thread-1",
281 reasoning: "high",
282});
283```
284
285What goes to Mistral:
286
287- `mistral-medium-latest`, `mistral-small-latest`: `reasoning_effort`. They take `off` (sent as `none`) and `high`.
288- `magistral-medium-latest`, `magistral-small-latest`: they take `off` and `high`. `high` sends `prompt_mode: "reasoning"`. `off` sends nothing.
289
290The other models take no `reasoning`. The Magistral models stream their thinking before the answer. See [Magistral thinking events](#magistral-thinking-events).
291
292### Models
293
294| Group | Models |
295| --- | --- |
296| Chat | `mistral-large-latest` (flagship, 128k context), `mistral-medium-latest` (with vision), `mistral-small-latest` (fast, with vision), `ministral-8b-latest`, `ministral-3b-latest`, `open-mistral-nemo` |
297| Code | `codestral-latest` (256k context) |
298| Vision | `pixtral-large-latest`, `pixtral-12b-2409` |
299| Reasoning | `magistral-medium-latest`, `magistral-small-latest` |
300| Embeddings | `mistral-embed`, `codestral-embed` |
301| Chat on Vertex | `mistral-medium-3`, `mistral-small-2503`, `codestral-2` |
302
303See the [model comparison](https://docs.mistral.ai/getting-started/models/compare) of Mistral for the full details. `adapter.inputModalities` lists the input kinds of the selected model. See [Check what a model accepts](../advanced/extend-adapter#check-what-a-model-accepts).
304
305## Advanced
306
307### Configuration
308
309```typescript
310import {
311 createMistralText,
312 type MistralTextConfig,
313} from "@tanstack/ai-mistral";
314
315const config: Omit<MistralTextConfig, "apiKey"> = {
316 baseURL: "https://api.mistral.ai", // Optional, this is the default
317 defaultHeaders: {
318 "X-Custom-Header": "value",
319 },
320};
321
322const adapter = createMistralText(
323 "mistral-large-latest",
324 process.env.MISTRAL_API_KEY!,
325 config,
326);
327```
328
329### Behind a proxy
330
331Send every request through a gateway, such as Cloudflare AI Gateway or a corporate proxy, with `baseURL` and `defaultHeaders`. These two option names are the same on every TanStack AI adapter, so one gateway config works for all of them.
332
333```typescript
334import { createMistralText } from "@tanstack/ai-mistral";
335
336const adapter = createMistralText("mistral-large-latest", process.env.MISTRAL_API_KEY!, {
337 baseURL: "https://gateway.example.com/mistral",
338 defaultHeaders: { "cf-aig-authorization": `Bearer ${process.env.GATEWAY_TOKEN}` },
339});
340```
341
342- `serverURL` is an alias of `baseURL`. If you set both, `baseURL` wins.
343- Need more than a fixed header, such as a log of each model call? This adapter supports [`wrapFetch`](../advanced/middleware#change-the-http-requests-of-a-call).
344
345### Prompt caching
346
347Mistral caches the start of your requests by itself.
348
349- `chat()` sends `prompt_cache_key` by default. The key is the `threadId` that you pass, so one conversation shares a cache.
350- The key goes only to `api.mistral.ai`, on `chat()` and on structured output.
351- With `promptCache: 'none'`, no key goes out.
352- Cache reads show up in `usage.promptTokensDetails.cachedTokens`.
353
354See [Prompt Caching](../advanced/prompt-caching).
355
356### Magistral thinking events
357
358The Magistral models (`magistral-medium-latest`, `magistral-small-latest`) stream their thinking as separate events before the answer. The adapter sends AG-UI `REASONING_*` chunks for the thinking and `TEXT_MESSAGE_*` chunks for the answer:
359
360```typescript ignore
361// ignore: narrowing the raw AG-UI stream by `chunk.type` relies on @ag-ui/core's
362// discriminated-union `type` field, which kiira can't resolve in a source-only
363// check. The runtime behaviour is exactly as shown.
364import { chat } from "@tanstack/ai";
365import { mistralText } from "@tanstack/ai-mistral";
366
367const stream = chat({
368 adapter: mistralText("magistral-medium-latest"),
369 messages: [{ role: "user", content: "Why is the sky blue?" }],
370 threadId: "thread-1",
371});
372
373for await (const chunk of stream) {
374 if (chunk.type === "REASONING_MESSAGE_CONTENT") {
375 process.stdout.write(`[thinking] ${chunk.delta}`);
376 } else if (chunk.type === "TEXT_MESSAGE_CONTENT") {
377 process.stdout.write(chunk.delta);
378 }
379}
380```
381
382The reasoning events always close before any text or tool output starts. So you first see the full sequence: `REASONING_START`, `REASONING_MESSAGE_START`, `REASONING_MESSAGE_CONTENT` (one or more), `REASONING_MESSAGE_END`, `REASONING_END`.
383
384See [Thinking & Reasoning](../chat/thinking-content) for the event spec of all providers.
385
386### Mistral on Vertex
387
388Use `@tanstack/ai-mistral/vertex` when Mistral must run on Vertex AI. That path uses Google Cloud credentials and the publisher `rawPredict` endpoint.
389
390Mistral on Vertex is regional only. Use `us-central1` or `europe-west4`.
391
392<!-- ::start:tabs variant="package-manager" mode="install" -->
393
394react: @tanstack/ai-mistral google-auth-library
395vue: @tanstack/ai-mistral google-auth-library
396solid: @tanstack/ai-mistral google-auth-library
397svelte: @tanstack/ai-mistral google-auth-library
398preact: @tanstack/ai-mistral google-auth-library
399angular: @tanstack/ai-mistral google-auth-library
400vanilla: @tanstack/ai-mistral google-auth-library
401octane: @tanstack/ai-mistral google-auth-library
402
403<!-- ::end:tabs -->
404
405```typescript
406import { chat } from "@tanstack/ai";
407import { mistralVertexText } from "@tanstack/ai-mistral/vertex";
408
409const stream = chat({
410 adapter: mistralVertexText("mistral-medium-3", {
411 project: "my-project",
412 location: "europe-west4",
413 }),
414 messages: [{ role: "user", content: "Hello!" }],
415 threadId: "thread-1",
416});
417```
418
419- `project` and `location` use the same names as `@tanstack/ai-vertex`. `location` is required.
420- `mistralVertexText` accepts only the Mistral chat models that Vertex lists: `mistral-medium-3`, `mistral-small-2503`, and `codestral-2`.
421- Mistral API aliases such as `mistral-large-latest` and `mistral-medium-latest` are not Vertex model ids. Vertex also lists `mistral-ocr-2505`, but that model is OCR, not chat.
422- Install `google-auth-library` for Application Default Credentials, or pass `authClient` or `getAccessToken`.
423
424Gemini on Vertex is in [`@tanstack/ai-vertex`](./vertex).
425
426### API reference
427
428| Factory | Creates |
429| --- | --- |
430| `mistralText(model, config?)` | Text adapter. Reads `MISTRAL_API_KEY` |
431| `createMistralText(model, apiKey, config?)` | Text adapter with an explicit API key |
432| `mistralEmbedding(model, config?)` / `createMistralEmbedding(model, apiKey, config?)` | Embedding adapter |
433| `mistralVertexText(model, config)` | Text adapter on Vertex. Import from `@tanstack/ai-mistral/vertex` |
434
435- `config.baseURL`: a custom base URL. Optional. `serverURL` is an alias.
436- `config.defaultHeaders`: headers for every request. Optional.
437
438`adapter.inputModalities` lists the input kinds of the selected model. It is `undefined` for a model that this package does not know.