Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

mistral.md

458 lines12.7 KB

1---
2title: Mistral
3id: mistral-adapter
4order: 7
5description: "Use Mistral models with TanStack AI — Mistral Large, Mistral Medium, Pixtral vision models, Magistral reasoning models, and Codestral via @tanstack/ai-mistral."
6keywords:
7 - tanstack ai
8 - mistral
9 - mistral large
10 - pixtral
11 - magistral
12 - codestral
13 - adapter
14 - llm
15---
16​
17The Mistral adapter provides access to Mistral's chat models, including Mistral Large, the multimodal Pixtral family, the Magistral reasoning models, and the Codestral code-specialized model.
18​
19## Installation
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## Basic Usage
35​
36```typescript
37import { chat } from "@tanstack/ai";
38import { mistralText } from "@tanstack/ai-mistral";
39​
40const stream = chat({
41 adapter: mistralText("mistral-large-latest"),
42 messages: [{ role: "user", content: "Hello!" }],
43});
44```
45​
46## Basic Usage - Custom API Key
47​
48```typescript
49import { chat } from "@tanstack/ai";
50import { createMistralText } from "@tanstack/ai-mistral";
51​
52const adapter = createMistralText(
53 "mistral-large-latest",
54 process.env.MISTRAL_API_KEY!,
55);
56​
57const stream = chat({
58 adapter,
59 messages: [{ role: "user", content: "Hello!" }],
60});
61```
62​
63## Configuration
64​
65```typescript
66import {
67 createMistralText,
68 type MistralTextConfig,
69} from "@tanstack/ai-mistral";
70​
71const config: Omit<MistralTextConfig, "apiKey"> = {
72 baseURL: "https://api.mistral.ai", // Optional, this is the default
73 defaultHeaders: {
74 "X-Custom-Header": "value",
75 },
76};
77​
78const adapter = createMistralText(
79 "mistral-large-latest",
80 process.env.MISTRAL_API_KEY!,
81 config,
82);
83```
84​
85## Behind a proxy
86​
87Route 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.
88​
89```typescript
90import { createMistralText } from "@tanstack/ai-mistral";
91​
92const adapter = createMistralText("mistral-large-latest", process.env.MISTRAL_API_KEY!, {
93 baseURL: "https://gateway.example.com/mistral",
94 defaultHeaders: { "cf-aig-authorization": `Bearer ${process.env.GATEWAY_TOKEN}` },
95});
96```
97​
98`serverURL` is an alias of `baseURL`. If you set both, `baseURL` wins.
99​
100## Mistral on Vertex
101​
102Use `@tanstack/ai-mistral/vertex` when Mistral must run on Vertex AI. That
103path uses Google Cloud credentials and the publisher `rawPredict` endpoint.
104​
105Mistral on Vertex is regional only. Use `us-central1` or `europe-west4`.
106​
107<!-- ::start:tabs variant="package-manager" mode="install" -->
108​
109react: @tanstack/ai-mistral google-auth-library
110vue: @tanstack/ai-mistral google-auth-library
111solid: @tanstack/ai-mistral google-auth-library
112svelte: @tanstack/ai-mistral google-auth-library
113preact: @tanstack/ai-mistral google-auth-library
114angular: @tanstack/ai-mistral google-auth-library
115vanilla: @tanstack/ai-mistral google-auth-library
116octane: @tanstack/ai-mistral google-auth-library
117​
118<!-- ::end:tabs -->
119​
120```typescript
121import { chat } from "@tanstack/ai";
122import { mistralVertexText } from "@tanstack/ai-mistral/vertex";
123​
124const stream = chat({
125 adapter: mistralVertexText("mistral-medium-3", {
126 project: "my-project",
127 location: "europe-west4",
128 }),
129 messages: [{ role: "user", content: "Hello!" }],
130});
131```
132​
133`project` and `location` use the same names as `@tanstack/ai-vertex`.
134`location` is required.
135​
136`mistralVertexText` accepts only the Mistral chat models that Vertex lists:
137​
138- `mistral-medium-3`
139- `mistral-small-2503`
140- `codestral-2`
141​
142Mistral API aliases such as `mistral-large-latest` and `mistral-medium-latest`
143are not Vertex model ids. Vertex also lists `mistral-ocr-2505`, but that
144model is OCR, not chat.
145​
146Install `google-auth-library` for Application Default Credentials, or pass
147`authClient` or `getAccessToken`.
148​
149Gemini on Vertex lives in [`@tanstack/ai-vertex`](./vertex).
150​
151## Example: Chat Completion
152​
153```typescript
154import { chat, toServerSentEventsResponse } from "@tanstack/ai";
155import { mistralText } from "@tanstack/ai-mistral";
156​
157export async function POST(request: Request) {
158 const { messages } = await request.json();
159​
160 const stream = chat({
161 adapter: mistralText("mistral-large-latest"),
162 messages,
163 });
164​
165 return toServerSentEventsResponse(stream);
167```
168​
169## Example: With Tools
170​
171```typescript
172import { chat, toolDefinition } from "@tanstack/ai";
173import { mistralText } from "@tanstack/ai-mistral";
174import { z } from "zod";
175​
176const getWeatherDef = toolDefinition({
177 name: "get_weather",
178 description: "Get the current weather for a location",
179 inputSchema: z.object({
180 location: z.string(),
181 }),
182});
183​
184const getWeather = getWeatherDef.server(async ({ location }) => {
185 return { temperature: 72, conditions: "sunny" };
186});
187​
188const stream = chat({
189 adapter: mistralText("mistral-large-latest"),
190 messages: [{ role: "user", content: "What's the weather in Paris?" }],
191 tools: [getWeather],
192});
193```
194​
195## Example: Multimodal (Vision)
196​
197Use a vision-capable model — `pixtral-large-latest`, `pixtral-12b-2409`, `mistral-medium-latest`, or `mistral-small-latest` — to send images alongside text:
198​
199```typescript
200import { chat } from "@tanstack/ai";
201import { mistralText } from "@tanstack/ai-mistral";
202​
203const stream = chat({
204 adapter: mistralText("pixtral-large-latest"),
205 messages: [
206 {
207 role: "user",
208 content: [
209 { type: "text", content: "What's in this image?" },
210 {
211 type: "image",
212 source: {
213 type: "url",
214 value: "https://example.com/photo.jpg",
215 },
216 },
217 ],
218 },
219 ],
220});
221```
222​
223For data-URL or base64 images, set `source.type` to `"data"` and provide `mimeType`:
224​
225```typescript
226import { chat } from "@tanstack/ai";
227import { mistralText } from "@tanstack/ai-mistral";
228​
229const base64String = "..."; // your base64-encoded image bytes
230​
231const stream = chat({
232 adapter: mistralText("pixtral-large-latest"),
233 messages: [
234 {
235 role: "user",
236 content: [
237 { type: "text", content: "What's in this image?" },
238 {
239 type: "image",
240 source: {
241 type: "data",
242 mimeType: "image/png",
243 value: base64String,
244 },
245 },
246 ],
247 },
248 ],
249});
250```
251​
252See [Multimodal Content](../advanced/multimodal-content) for the full content-part shape.
253​
254## Example: Reasoning (Magistral)
255​
256Magistral models (`magistral-medium-latest`, `magistral-small-latest`) stream their reasoning as separate events before the final answer. The adapter emits AG-UI `REASONING_*` chunks for the thinking content and `TEXT_MESSAGE_*` chunks for the answer:
257​
258```typescript ignore
259// ignore: narrowing the raw AG-UI stream by `chunk.type` relies on @ag-ui/core's
260// discriminated-union `type` field, which kiira can't resolve in a source-only
261// check. The runtime behaviour is exactly as shown.
262import { chat } from "@tanstack/ai";
263import { mistralText } from "@tanstack/ai-mistral";
264​
265const stream = chat({
266 adapter: mistralText("magistral-medium-latest"),
267 messages: [{ role: "user", content: "Why is the sky blue?" }],
268});
269​
270for await (const chunk of stream) {
271 if (chunk.type === "REASONING_MESSAGE_CONTENT") {
272 process.stdout.write(`[thinking] ${chunk.delta}`);
273 } else if (chunk.type === "TEXT_MESSAGE_CONTENT") {
274 process.stdout.write(chunk.delta);
275 }
277```
278​
279Reasoning events are always closed before any text or tool output begins, so consumers see a complete `REASONING_START → REASONING_MESSAGE_START → REASONING_MESSAGE_CONTENT* → REASONING_MESSAGE_END → REASONING_END` sequence first.
280​
281See [Thinking & Reasoning](../chat/thinking-content) for the cross-provider event spec.
282​
283## Example: Structured Output
284​
285Generate JSON that conforms to a Zod schema using Mistral's `json_schema` response format:
286​
287```typescript
288import { chat } from "@tanstack/ai";
289import { mistralText } from "@tanstack/ai-mistral";
290import { z } from "zod";
291​
292const recipeSchema = z.object({
293 name: z.string(),
294 ingredients: z.array(z.string()),
295 steps: z.array(z.string()),
296});
297​
298const recipe = await chat({
299 adapter: mistralText("mistral-large-latest"),
300 messages: [
301 { role: "user", content: "Give me a chocolate chip cookie recipe." },
302 ],
303 outputSchema: recipeSchema,
304});
305​
306console.log(recipe.name); // typed as z.infer<typeof recipeSchema>
307```
308​
309See [Structured Outputs](../chat/structured-outputs) for the full guide.
310​
311## Model Options
312​
313Mistral exposes provider-specific options via `modelOptions`:
314​
315```typescript
316import { chat } from "@tanstack/ai";
317import { mistralText } from "@tanstack/ai-mistral";
318​
319const stream = chat({
320 adapter: mistralText("mistral-large-latest"),
321 messages: [{ role: "user", content: "Hello!" }],
322 modelOptions: {
323 temperature: 0.7,
324 top_p: 0.9,
325 max_tokens: 1024,
326 random_seed: 42,
327 stop: ["END"],
328 safe_prompt: true,
329 frequency_penalty: 0.5,
330 presence_penalty: 0.5,
331 parallel_tool_calls: true,
332 tool_choice: "auto",
333 },
334});
335```
336​
337> All sampling parameters — including `temperature`, `top_p`, and `max_tokens` —
338> go inside `modelOptions` using Mistral's native (snake_case) names.
339​
340## Embeddings
341​
342Generate embedding vectors with mistral-embed or codestral-embed:
343​
344```typescript
345import { embed } from "@tanstack/ai";
346import { mistralEmbedding } from "@tanstack/ai-mistral";
347​
348const result = await embed({
349 adapter: mistralEmbedding("mistral-embed"),
350 input: ["a red guitar", "a blue drum kit"],
351});
352​
353console.log(result.embeddings[0]?.vector); // 1024 dimensions
354```
355​
356`mistral-embed` has fixed 1024-dimension output; `codestral-embed` (tuned for code) supports the top-level `dimensions` option:
357​
358```typescript
359import { embed } from "@tanstack/ai";
360import { mistralEmbedding } from "@tanstack/ai-mistral";
361​
362const result = await embed({
363 adapter: mistralEmbedding("codestral-embed"),
364 input: "function add(a, b) { return a + b }",
365 dimensions: 512,
366});
367```
368​
369See the [Embeddings guide](../embeddings.md) for the full API.
370​
371## Environment Variables
372​
373Set your API key in environment variables:
374​
375```bash
376MISTRAL_API_KEY=...
377```
378​
379Get a key from the [Mistral Console](https://console.mistral.ai/).
380​
381## Supported Models
382​
383### Chat
384​
385- `mistral-large-latest` — Flagship general-purpose model (128k context)
386- `mistral-medium-latest` — Multimodal mid-tier model with vision
387- `mistral-small-latest` — Fast, affordable multimodal model with vision
388- `ministral-8b-latest` — 8B edge model
389- `ministral-3b-latest` — 3B edge model
390- `open-mistral-nemo` — Open 12B model
391​
392### Code
393​
394- `codestral-latest` — Code-specialized model (256k context)
395​
396### Vision
397​
398- `pixtral-large-latest` — Large vision model
399- `pixtral-12b-2409` — 12B vision model
400​
401### Reasoning
402​
403Reasoning content is streamed as `REASONING_*` events before the final answer.
404​
405- `magistral-medium-latest` — Mid-tier reasoning model
406- `magistral-small-latest` — Small reasoning model
407​
408See [Mistral's model comparison](https://docs.mistral.ai/getting-started/models/compare) for full details.
409​
410## API Reference
411​
412### `mistralText(model, config?)`
413​
414Creates a Mistral text adapter using the `MISTRAL_API_KEY` environment variable.
415​
416**Parameters:**
417​
418- `model` — The model name (e.g., `'mistral-large-latest'`)
419- `config.baseURL?`: custom base URL (optional). `serverURL` is an alias.
420- `config.defaultHeaders?` — Headers to attach to every request (optional)
421​
422**Returns:** A Mistral text adapter instance.
423​
424### `createMistralText(model, apiKey, config?)`
425​
426Creates a Mistral text adapter with an explicit API key.
427​
428**Parameters:**
429​
430- `model` — The model name
431- `apiKey` — Your Mistral API key
432- `config.baseURL?`: custom base URL (optional). `serverURL` is an alias.
433- `config.defaultHeaders?` — Headers to attach to every request (optional)
434​
435**Returns:** A Mistral text adapter instance.
436​
437## Limitations
438​
439- **Embeddings**: Use the [Mistral SDK](https://github.com/mistralai/client-ts) directly for `mistral-embed`.
440- **Image / Audio / Video Generation**: Mistral does not provide these endpoints. Use OpenAI, Gemini, or fal.ai.
441- **Text-to-Speech / Transcription**: Not supported. Use OpenAI or ElevenLabs.
442​
443## Next Steps
444​
445- [Getting Started](../getting-started/quick-start) — Learn the basics
446- [Tools Guide](../tools/tools) — Define and call tools
447- [Structured Outputs](../chat/structured-outputs) — Generate typed JSON
448- [Multimodal Content](../advanced/multimodal-content) — Send images and other modalities
449- [Other Adapters](./openai) — Explore other providers
450​
451## Provider Tools
452​
453Mistral does not currently expose provider-specific tool factories.
454Define your own tools with `toolDefinition()` from `@tanstack/ai`.
455​
456See [Tools](../tools/tools.md) for the general tool-definition flow, or
457[Provider Tools](../tools/provider-tools.md) for other providers'
458native-tool offerings.