Official Mistral AI TypeScript SDK patterns — client setup, chat completions, streaming, function calling, structured outputs, embeddings, vision, Codestral FIM, and production best practices
Standardmäßig ist der Prompt ausgewählt, der zuerst die Quelle prüft. Sie können zu einem direkten Befehl wechseln oder eine lokale Kopie herunterladen.
Quelldateien prüfen
Lesen Sie SKILL.md und alle von SkillsMP angezeigten Begleitdateien, bevor Sie sich für eine Installation entscheiden.
Mit Codex oder Claude installieren Kopieren Sie diesen Prompt, fügen Sie ihn in Codex, Claude oder einen anderen Assistant ein und lassen Sie die Skill-Seite prüfen und installieren.
Ein direkter Befehl überspringt den Prüf-Prompt. Prüfen Sie die Quelle, bevor Sie ihn ausführen.
Official Mistral AI TypeScript SDK patterns — client setup, chat completions, streaming, function calling, structured outputs, embeddings, vision, Codestral FIM, and production best practices
Mistral SDK Patterns
Quick Guide: Use @mistralai/mistralai (ESM-only) to interact with Mistral's API. Use client.chat.complete() for chat, client.chat.stream() for streaming (async iterable via for await), client.chat.parse() with a Zod schema for structured outputs, and client.fim.complete() for Codestral fill-in-middle code completion. The SDK uses responseFormat (camelCase) not response_format. Streaming events expose content via event.data.choices[0]?.delta?.content. Retries default to strategy: "none" -- you must configure them explicitly for production.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)
(You MUST use responseFormat (camelCase) in SDK calls -- NOT response_format (snake_case). The SDK uses camelCase property names throughout.)
(You MUST configure retries explicitly -- the SDK defaults to strategy: "none" (no retries), unlike OpenAI's SDK which retries automatically)
(You MUST consume streaming results with for await (const event of result) and access content via event.data.choices[0]?.delta?.content -- the event shape differs from OpenAI)
(You MUST never hardcode API keys -- use process.env["MISTRAL_API_KEY"] with the bracket notation the SDK documents)
(You MUST use client.chat.parse() with a Zod schema for structured outputs -- NOT manual JSON.parse() on completion content)
Codestral FIM -- Fill-in-middle code completion, code generation
Quick API Reference -- Model IDs, method signatures, error types, configuration options
Philosophy
The @mistralai/mistralai SDK is auto-generated from Mistral's OpenAPI spec using Speakeasy, giving you a thin, type-safe wrapper over the REST API. It is ESM-only and uses camelCase property names (not snake_case like the REST API).
Core principles:
ESM-only -- The package is published as ESM only. CommonJS projects must use await import(). This is a hard constraint, not optional.
camelCase API surface -- SDK properties use camelCase (responseFormat, maxTokens, toolChoice) even though the REST API uses snake_case. This catches OpenAI SDK migrants who write response_format.
No automatic retries -- Unlike OpenAI's SDK (2 retries by default), Mistral defaults to strategy: "none". You must configure retries explicitly for production.
Streaming via async iterables -- chat.stream() returns an EventStream consumed with for await...of. Events have a data wrapper: event.data.choices[0]?.delta?.content.
Structured outputs via chat.parse() -- Pass a Zod schema directly to responseFormat and access message.parsed for typed results. No manual JSON schema construction needed.
Codestral FIM -- Dedicated fim.complete() endpoint for fill-in-middle code completion, separate from chat.
When to use the Mistral SDK directly:
You only use Mistral models and want the simplest, most direct integration
You need Mistral-specific features (Codestral FIM, Mistral Agents, Voxtral audio)
You want minimal dependencies and zero abstraction overhead
You need the latest Mistral API features on day one
When NOT to use:
You need to switch between providers (OpenAI, Anthropic, Mistral) -- use a unified provider SDK
You want React-specific chat UI hooks -- use a framework-integrated AI SDK
You want an OpenAI-compatible wrapper -- Mistral exposes an OpenAI-compatible endpoint, use the OpenAI SDK for that
Core Patterns
Pattern 1: Client Setup
Initialize the Mistral client. It reads MISTRAL_API_KEY from the environment.
Why good: Specific error types checked in order of specificity, re-throws unexpected errors
See:examples/core.md for full error handling, timeout handling, retry configuration
Performance Optimization
Model Selection
General purpose (most capable) -> mistral-large-latest (Mistral Large 3)
Balanced cost/quality -> mistral-medium-latest (Mistral Medium 3.1)
Cost-sensitive / fast -> mistral-small-latest (Mistral Small 4)
Edge / minimal -> ministral-3b-latest or ministral-8b-latest
Complex reasoning -> magistral-medium-latest
Code generation -> codestral-latest or devstral-latest
Code completion (FIM) -> codestral-latest (dedicated FIM endpoint)
Vision / images -> mistral-small-latest or mistral-large-latest
Embeddings -> mistral-embed (1024 dimensions)
Code embeddings -> codestral-embed-latest
Key Optimization Patterns
Configure retries -- Default is no retries. Always set retryConfig for production.
Set timeouts -- Default is no timeout (-1). Set timeoutMs to avoid hanging requests.
Use temperature: 0 for deterministic output (enables server-side caching).
Batch embedding inputs -- Pass multiple strings to inputs array in one call.
Use FIM for code completion -- fim.complete() is purpose-built and more efficient than chat for code completion tasks.
<decision_framework>
Decision Framework
Which Method to Use
What do you need?
+-- Chat completion (text in, text out)?
| +-- Need streaming? -> client.chat.stream()
| +-- Need structured JSON? -> client.chat.parse() with Zod schema
| +-- Basic completion? -> client.chat.complete()
+-- Code completion / fill-in-middle?
| +-- YES -> client.fim.complete() with Codestral
+-- Embeddings for search/RAG?
| +-- YES -> client.embeddings.create() with mistral-embed
+-- Pre-configured agent?
+-- YES -> client.agents.complete() with agent ID
Which Model to Choose
What is your task?
+-- Most capable general purpose -> mistral-large-latest
+-- Balanced cost/performance -> mistral-medium-latest
+-- Fast + cost-efficient -> mistral-small-latest
+-- Minimal / edge deployment -> ministral-3b-latest
+-- Complex reasoning / math -> magistral-medium-latest
+-- Code generation (chat) -> codestral-latest or devstral-latest
+-- Code completion (FIM) -> codestral-latest
+-- Vision / image analysis -> mistral-small-latest (or any vision-capable model)
+-- Embeddings -> mistral-embed
+-- Code embeddings -> codestral-embed-latest
Streaming vs Non-Streaming
Is the response user-facing?
+-- YES -> Use client.chat.stream()
| +-- Iterate with: for await (const event of result)
| +-- Access content: event.data.choices[0]?.delta?.content
+-- NO -> Use client.chat.complete()
+-- Background processing -> chat.complete()
+-- Structured output -> chat.parse() with Zod
When to Use This SDK vs a Provider-Agnostic SDK
Do you need multiple LLM providers (Mistral + others)?
+-- YES -> Not this skill's scope -- use a unified provider SDK
+-- NO -> Do you need Mistral-specific features?
+-- YES -> Use Mistral SDK directly
| Examples: Codestral FIM, Mistral Agents,
| Voxtral audio, OCR, custom endpoints
+-- NO -> Mistral SDK is simplest for Mistral-only use
</decision_framework>
<red_flags>
RED FLAGS
High Priority Issues:
Using response_format (snake_case) instead of responseFormat (camelCase) -- silently ignored, no error thrown
Using input (singular) for embeddings instead of inputs (plural) -- Mistral-specific naming
Not configuring retries for production (SDK defaults to strategy: "none" -- zero retries)
Hardcoding API keys instead of using environment variables
Accessing chunk.choices[0]?.delta?.content directly on streaming events instead of event.data.choices[0]?.delta?.content
Medium Priority Issues:
Not setting timeoutMs for production (default is -1, meaning no timeout -- requests can hang indefinitely)
Using max_tokens instead of maxTokens (camelCase SDK convention)
Missing system role message for behavior guidance
Using tool_choice instead of toolChoice
Using tool_calls instead of toolCalls when reading responses
Common Mistakes:
Importing from "mistralai" instead of "@mistralai/mistralai" -- the correct package name has the org scope
Using CommonJS require() -- the package is ESM-only, use import or await import()
Using client.chat.completions.create() (OpenAI pattern) instead of client.chat.complete() (Mistral pattern)
Assuming embedding dimensions match OpenAI's -- mistral-embed returns 1024-dimensional vectors, not 1536
Gotchas & Edge Cases:
The SDK is ESM-only. In CommonJS projects, you must use const { Mistral } = await import("@mistralai/mistralai").
Streaming content may be string | string[] -- cast or check type when writing to stdout.
chat.parse() requires a Zod schema passed to responseFormat -- it does not accept { type: "json_object" }.
The apiKey constructor option accepts a string OR an async function () => Promise<string> for dynamic key rotation.
Model aliases like mistral-large-latest resolve to the latest version of that model tier. Pin to specific versions (e.g., mistral-large-3-25-12) for reproducibility.
toolChoice: "any" forces the model to call a tool. toolChoice: "auto" lets the model decide. toolChoice: "none" prevents tool calls.
FIM endpoint (fim.complete()) uses prompt + suffix parameters, NOT the messages array.
safePrompt: true injects Mistral's safety system prompt before your messages.
The SDK provides standalone functions (e.g., chatComplete() from "@mistralai/mistralai/funcs/chatComplete.js") for tree-shaking in browser/edge runtimes.
</red_flags>
<critical_reminders>
CRITICAL REMINDERS
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)
(You MUST use responseFormat (camelCase) in SDK calls -- NOT response_format (snake_case). The SDK uses camelCase property names throughout.)
(You MUST configure retries explicitly -- the SDK defaults to strategy: "none" (no retries), unlike OpenAI's SDK which retries automatically)
(You MUST consume streaming results with for await (const event of result) and access content via event.data.choices[0]?.delta?.content -- the event shape differs from OpenAI)
(You MUST never hardcode API keys -- use process.env["MISTRAL_API_KEY"] with the bracket notation the SDK documents)
(You MUST use client.chat.parse() with a Zod schema for structured outputs -- NOT manual JSON.parse() on completion content)
Failure to follow these rules will produce broken API calls (snake_case properties silently ignored), unreliable production services (no retries), or incorrectly parsed streaming data.