mistral-pack
Complete Mistral AI integration skill pack with 24 skills covering model inference, embeddings, fine-tuning, and production deployments. Flagship tier vendor pack.
Installation
Open Claude Code and run this command:
/plugin install mistral-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> 24 production-ready skills for Mistral AI integration — chat completions, embeddings, function calling, agents, batch API, vision, code generation, and enterprise operations.
SDK: @mistralai/mistralai (TypeScript, ESM-only) | mistralai (Python) API Base: api.mistral.ai | Console: console.mistral.ai By: Tons of Skills / Intent Solutions
Skills (24) plugin-local skills
Configure Mistral AI CI/CD integration with GitHub Actions and prompt testing.
Mistral CI Integration
Overview
Integrate Mistral AI validation into CI/CD pipelines: prompt regression tests, model response quality checks, cost estimation in PR comments, and deployment gates for prompt changes. Uses GitHub Actions with MISTRAL_API_KEY stored as a repository secret.
Prerequisites
MISTRAL_API_KEYstored as GitHub repository secret- GitHub Actions configured
- Test framework (Vitest recommended)
Instructions
Step 1: GitHub Actions Workflow
# .github/workflows/mistral-tests.yml
name: Mistral AI Tests
on:
pull_request:
paths:
- 'src/prompts/**'
- 'src/ai/**'
- 'tests/ai/**'
jobs:
prompt-tests:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- name: Run prompt regression tests
env:
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
run: npx vitest run tests/ai/ --reporter=verbose
- name: Cost estimation
env:
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
run: npx tsx scripts/estimate-costs.ts >> $GITHUB_STEP_SUMMARY
Step 2: Prompt Regression Tests
// tests/ai/mistral-prompts.test.ts
import { describe, it, expect } from 'vitest';
import { Mistral } from '@mistralai/mistralai';
const apiKey = process.env.MISTRAL_API_KEY;
describe.skipIf(!apiKey)('Mistral Prompt Regression', () => {
const client = new Mistral({ apiKey: apiKey! });
it('summarization produces 2-3 sentences', async () => {
const result = await client.chat.complete({
model: 'mistral-small-latest',
messages: [
{ role: 'system', content: 'Summarize in 2-3 sentences.' },
{ role: 'user', content: 'TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing and class-based OOP.' },
],
maxTokens: 150,
temperature: 0, // Deterministic for regression
});
const content = result.choices?.[0]?.message?.content ?? '';
expect(content.length).toBeGreaterThan(20);
expect(content.split(/[.!?]+/).filter(Boolean).length).toBeGreaterThanOrEqual(2);
}, 15_000);
it('classification returns valid category', async () => {
const result = await client.chat.complete({
model: 'mistral-small-latest',
messages: [
{ role: 'system', content: 'Classify as: bug, feature, question. Reply with one word only.' },
{ role: 'user', content: 'The login page crashes on mobile devices' },
],
maxTokens: 10,
Diagnose and fix Mistral AI common errors and exceptions.
Mistral AI Common Errors
Overview
Quick reference for diagnosing and fixing Mistral AI API errors. Covers HTTP status codes, SDK-specific issues, streaming failures, and tool calling problems with real solutions.
Prerequisites
- Mistral AI SDK installed
MISTRAL_API_KEYconfigured- Access to application logs
Instructions
Step 1: Quick Diagnostic
set -euo pipefail
# Test API connectivity and auth
curl -s -w "\nHTTP Status: %{http_code}\n" \
-H "Authorization: Bearer ${MISTRAL_API_KEY}" \
https://api.mistral.ai/v1/models | jq '.data[].id' 2>/dev/null || echo "FAILED"
# Check env
echo "Key set: ${MISTRAL_API_KEY:+yes}"
echo "Key length: ${#MISTRAL_API_KEY}"
Step 2: Error Reference
401 Unauthorized
Error: Authentication failed. Invalid API key.
Causes: Key missing, expired, revoked, or wrong workspace.
Fix:
const apiKey = process.env.MISTRAL_API_KEY;
if (!apiKey) throw new Error('MISTRAL_API_KEY is not set');
// Test the key
const client = new Mistral({ apiKey });
try {
await client.models.list();
} catch (e: any) {
if (e.status === 401) {
console.error('API key invalid — regenerate at console.mistral.ai');
}
}
Verify manually:
set -euo pipefail
curl -H "Authorization: Bearer ${MISTRAL_API_KEY}" https://api.mistral.ai/v1/models
429 Too Many Requests
Error: Rate limit exceeded. Retry-After: 60
Causes: Exceeded RPM (requests/min) or TPM (tokens/min) for your tier.
Fix:
async function withBackoff<T>(fn: () => Promise<T>, maxRetries = 5): Promise<T> {
for (let i = 0; i <= maxRetries; i++) {
try {
return await fn();
} catch (error: any) {
if (error.status !== 429 || i === maxRetries) throw error;
const wait = Math.min(2 ** i * 1000, 60_000);
console.warn(`Rate limited, retrying in ${wait}ms...`);
await new Promise(r => setTimeout(r, wait));
}
}
throw new Error('Max retries exceeded');
}
Check your limits: Visit console.mistral.ai/limits for workspace RPM/TPM caps.
400 Bad Request — Invalid Model
{"message": "Unknown model: mistral-ultra"}
Fix: Use valid model IDs:
const VALID_MODELS = [
'mistral-large-latest',
'mistral-small-latest',
'codestral-latest',
'pixtExecute Mistral AI chat completions with streaming, multi-turn, and guardrails.
Mistral AI Core Workflow A: Chat Completions
Overview
Production chat completion patterns for Mistral AI: multi-turn conversations, streaming responses, JSON mode structured output, guardrails/moderation, and model selection. Uses the @mistralai/mistralai SDK.
Prerequisites
- Completed
mistral-install-authsetup MISTRAL_API_KEYenvironment variable set- Understanding of Mistral model tiers
Instructions
Step 1: Basic Chat Completion
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function chat(userMessage: string): Promise<string> {
const response = await client.chat.complete({
model: 'mistral-small-latest',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: userMessage },
],
});
return response.choices?.[0]?.message?.content ?? '';
}
Step 2: Multi-Turn Conversation Manager
interface Message {
role: 'system' | 'user' | 'assistant';
content: string;
}
class MistralConversation {
private messages: Message[] = [];
private client: Mistral;
private model: string;
constructor(systemPrompt: string, model = 'mistral-small-latest') {
this.client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
this.model = model;
this.messages.push({ role: 'system', content: systemPrompt });
}
async send(userMessage: string): Promise<string> {
this.messages.push({ role: 'user', content: userMessage });
const response = await this.client.chat.complete({
model: this.model,
messages: this.messages,
});
const reply = response.choices?.[0]?.message?.content ?? '';
this.messages.push({ role: 'assistant', content: reply });
return reply;
}
// Prevent context window overflow
trimHistory(maxTurns = 20): void {
const system = this.messages[0];
const recent = this.messages.slice(1).slice(-maxTurns * 2);
this.messages = [system, ...recent];
}
}
// Usage
const conv = new MistralConversation('You are a coding tutor.');
await conv.send('How do I reverse a list in Python?');
await conv.send('What about in-place?');
Step 3: Streaming Responses
async function streamChat(
messages: Message[],
onChunk: (text: string) => void,
): Promise<string> {
const stream = await client.chat.stream({
model: 'mistral-small-latest',
messages,
});
let full = '';
for await (const event of stream) {
const text = event.data?.choices?.[0]?.delta?.content;
if (text) {
full += text;
onExecute Mistral AI embeddings, function calling, and RAG pipelines.
Mistral AI Core Workflow B: Embeddings & Function Calling
Overview
Secondary workflows for Mistral AI: text/code embeddings with mistral-embed (1024 dimensions), function calling (tool use) with any chat model, and RAG pipeline combining both. Mistral supports auto, any, and none tool choice modes.
Prerequisites
- Completed
mistral-install-authsetup MISTRAL_API_KEYenvironment variable set- Familiarity with
mistral-core-workflow-a
Instructions
Step 1: Generate Text Embeddings
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
// Single text embedding
const response = await client.embeddings.create({
model: 'mistral-embed',
inputs: ['Machine learning is fascinating.'],
});
const vector = response.data[0].embedding;
console.log(`Dimensions: ${vector.length}`); // 1024
console.log(`Tokens used: ${response.usage.totalTokens}`);
Step 2: Batch Embeddings with Rate Awareness
async function batchEmbed(
texts: string[],
batchSize = 64,
): Promise<number[][]> {
const allEmbeddings: number[][] = [];
for (let i = 0; i < texts.length; i += batchSize) {
const batch = texts.slice(i, i + batchSize);
const response = await client.embeddings.create({
model: 'mistral-embed',
inputs: batch,
});
allEmbeddings.push(...response.data.map(d => d.embedding));
}
return allEmbeddings;
}
// Embed 1000 documents in batches of 64
const docs = ['doc1...', 'doc2...', /* ... */];
const embeddings = await batchEmbed(docs);
Step 3: Semantic Search with Cosine Similarity
function cosineSimilarity(a: number[], b: number[]): number {
let dot = 0, normA = 0, normB = 0;
for (let i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
class SemanticSearch {
private documents: Array<{ text: string; embedding: number[] }> = [];
private client: Mistral;
constructor() {
this.client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
}
async index(texts: string[]): Promise<void> {
const response = await this.client.embeddings.create({
model: 'mistral-embed',
inputs: texts,
});
this.documents = texts.map((text, i) => ({
text,
embedding: response.data[i].embedding,
}));
}
async search(query: string, topK = 5): Promise<Array<{ text: string; score: number }>> {
const qEmbed = await this.client.embeddings.create({
model: 'mistral-embed',
inputs: [query],
});Optimize Mistral AI costs through model selection, token management, and usage monitoring.
Mistral AI Cost Tuning
Overview
Optimize Mistral AI costs through model selection, token management, caching, batch inference, and budget monitoring. Mistral offers the best price-performance in the market with models from $0.1/M tokens (Ministral/Small) to $0.5/M tokens (Large).
Prerequisites
- Access to Mistral AI console for usage data
- Understanding of current usage patterns
- Database for usage tracking (optional)
Pricing Reference (as of 2025)
| Model | Input $/M tokens | Output $/M tokens | Best For |
|---|---|---|---|
ministral-latest (3B) |
$0.10 | $0.10 | Simple tasks, edge |
mistral-small-latest |
$0.10 | $0.30 | General purpose, fast |
codestral-latest |
$0.30 | $0.90 | Code generation |
mistral-large-latest |
$0.50 | $1.50 | Complex reasoning |
pixtral-large-latest |
$2.00 | $6.00 | Vision + text |
mistral-embed |
$0.10 | — | Embeddings |
| Batch API (any model) | 50% off | 50% off | Non-realtime bulk |
Always check docs.mistral.ai/deployment/laplateforme/pricing for current rates.
Instructions
Step 1: Cost Calculator
const PRICING: Record<string, { input: number; output: number }> = {
'ministral-latest': { input: 0.10, output: 0.10 },
'mistral-small-latest': { input: 0.10, output: 0.30 },
'codestral-latest': { input: 0.30, output: 0.90 },
'mistral-large-latest': { input: 0.50, output: 1.50 },
'pixtral-large-latest': { input: 2.00, output: 6.00 },
'mistral-embed': { input: 0.10, output: 0 },
};
function calculateCost(
model: string,
inputTokens: number,
outputTokens: number,
isBatch = false,
): number {
const p = PRICING[model] ?? PRICING['mistral-small-latest'];
const multiplier = isBatch ? 0.5 : 1.0;
return ((inputTokens / 1e6) * p.input + (outputTokens / 1e6) * p.output) * multiplier;
}
// Example: 100K requests/month, avg 500 in + 200 out tokens
const monthlySmall = calculateCost('mistral-small-latest', 50_000_000, 20_000_000);
const monthlyLarge = calculateCost('mistral-large-latest', 50_000_000, 20_000_000);
console.log(`Small: $${monthlySmall.toFixed(2)}/month`); // $11.00
console.log(`Large: $${monthlyLarge.toFixed(2)}/month`); // $55.00
Step 2: Smart Model Router
Implement Mistral AI PII handling, data retention, and GDPR/CCPA compliance patterns.
Mistral Data Handling
Overview
Manage data flows through Mistral AI APIs with PII redaction, audit logging, fine-tuning dataset sanitization, and conversation retention policies. Mistral's data policy: API requests on La Plateforme are not used for training by default. Self-deployed models give full data sovereignty.
Prerequisites
- Mistral API key configured
- Understanding of data classification (PII, PHI, PCI)
- Logging infrastructure for audit trails
Instructions
Step 1: PII Redaction Before API Calls
interface RedactionRule {
pattern: RegExp;
replacement: string;
type: string;
}
const PII_RULES: RedactionRule[] = [
{ pattern: /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, replacement: '[EMAIL]', type: 'email' },
{ pattern: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g, replacement: '[PHONE]', type: 'phone' },
{ pattern: /\b\d{3}-\d{2}-\d{4}\b/g, replacement: '[SSN]', type: 'ssn' },
{ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, replacement: '[CARD]', type: 'credit_card' },
{ pattern: /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, replacement: '[IP]', type: 'ip_address' },
];
function redactPII(text: string): { cleaned: string; redactions: string[] } {
const redactions: string[] = [];
let cleaned = text;
for (const rule of PII_RULES) {
const matches = cleaned.match(rule.pattern);
if (matches) {
redactions.push(...matches.map(m => `${rule.type}: ${m.slice(0, 4)}***`));
cleaned = cleaned.replace(rule.pattern, rule.replacement);
}
}
return { cleaned, redactions };
}
Step 2: Safe Mistral API Wrapper
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function safeChatCompletion(
messages: Array<{ role: string; content: string }>,
options: { redactPII?: boolean; model?: string; auditLog?: boolean } = {},
) {
const processed = messages.map(msg => {
if (options.redactPII !== false) {
const { cleaned, redactions } = redactPII(msg.content);
if (redactions.length > 0 && options.auditLog) {
console.warn(`Redacted ${redactions.length} PII items from ${msg.role} message`);
}
return { ...msg, content: cleaned };
}
return msg;
});
const response = await client.chat.complete({
model: options.model ?? 'mistral-small-latest',
messages: processed,
});
// Optionally redact PII in output too
const output = response.choices?.[0]?.message?.content ?? '';
if (options.redactPII !== false) {
const { cleaned } = redactPII(output);
if (response.choices?.[0]?.message) {
response.choices[0].message.content = cleaned;
}
}
return response;
}
Collect Mistral AI debug evidence for support tickets and troubleshooting.
Mistral AI Debug Bundle
Current State
!node --version 2>/dev/null || echo 'N/A' !python3 --version 2>/dev/null || echo 'N/A'
Overview
Collect all necessary diagnostic information for Mistral AI support tickets. Creates a redacted bundle with environment info, SDK versions, API connectivity test, available models, and recent error logs.
Prerequisites
- Mistral AI SDK installed
- Access to application logs
MISTRAL_API_KEYset (for connectivity test)
Instructions
Step 1: Complete Debug Script
#!/bin/bash
# mistral-debug-bundle.sh — Creates redacted support bundle
set -e
BUNDLE_DIR="mistral-debug-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BUNDLE_DIR"
echo "Creating Mistral AI debug bundle..."
# === Environment Info ===
cat > "$BUNDLE_DIR/summary.txt" << EOF
=== Mistral AI Debug Bundle ===
Generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)
Hostname: $(hostname)
--- Environment ---
Node.js: $(node --version 2>/dev/null || echo 'not installed')
Python: $(python3 --version 2>/dev/null || echo 'not installed')
npm: $(npm --version 2>/dev/null || echo 'not installed')
OS: $(uname -a)
MISTRAL_API_KEY: ${MISTRAL_API_KEY:+[SET, length=${#MISTRAL_API_KEY}]}${MISTRAL_API_KEY:-[NOT SET]}
EOF
# === SDK Versions ===
echo -e "\n--- SDK Versions ---" >> "$BUNDLE_DIR/summary.txt"
npm list @mistralai/mistralai 2>/dev/null >> "$BUNDLE_DIR/summary.txt" \
|| echo "Node SDK: not installed" >> "$BUNDLE_DIR/summary.txt"
pip show mistralai 2>/dev/null | grep -E "^(Name|Version)" >> "$BUNDLE_DIR/summary.txt" \
|| echo "Python SDK: not installed" >> "$BUNDLE_DIR/summary.txt"
# === API Connectivity ===
echo -e "\n--- API Connectivity ---" >> "$BUNDLE_DIR/summary.txt"
if [ -n "${MISTRAL_API_KEY:-}" ]; then
HTTP_STATUS=$(curl -s -o "$BUNDLE_DIR/api-response.json" -w "%{http_code}" \
-H "Authorization: Bearer ${MISTRAL_API_KEY}" \
https://api.mistral.ai/v1/models 2>/dev/null)
echo "HTTP Status: $HTTP_STATUS" >> "$BUNDLE_DIR/summary.txt"
if [ "$HTTP_STATUS" = "200" ]; then
echo -e "\n--- Available Models ---" >> "$BUNDLE_DIR/summary.txt"
jq -r '.data[].id' "$BUNDLE_DIR/api-response.json" >> "$BUNDLE_DIR/summary.txt" 2>/dev/null
fi
rm -f "$BUNDLE_DIR/api-response.json"
else
echo "Skipped (no API key)" >> "$BUNDLE_DIR/summary.txt"
fi
# === Dependencies ===
if [ -f "package.json" ]; then
echo -e "\n--- Dependencies ---" >> "$BUDeploy Mistral AI integrations to Vercel, Docker, and Cloud Run platforms.
Mistral AI Deploy Integration
Overview
Deploy Mistral AI-powered applications to production with secure API key management. Covers Vercel (Edge + Serverless), Docker, Cloud Run, and self-hosted vLLM deployments. All connect to api.mistral.ai or your own inference endpoint.
Prerequisites
- Mistral AI production API key
- Platform CLI installed (vercel, docker, or gcloud)
- Application using
@mistralai/mistralaiSDK
Instructions
Step 1: Platform Secret Configuration
set -euo pipefail
# Vercel
vercel env add MISTRAL_API_KEY production
vercel env add MISTRAL_MODEL production # optional: default model
# Cloud Run
echo -n "your-key" | gcloud secrets create mistral-api-key --data-file=-
# Docker
echo "MISTRAL_API_KEY=your-key" > .env.production
echo ".env.production" >> .gitignore
Step 2: Vercel Edge Function
// api/chat.ts — Vercel Edge Function with streaming
import { Mistral } from '@mistralai/mistralai';
export const config = { runtime: 'edge' };
export default async function handler(req: Request) {
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY! });
const { messages, stream = false } = await req.json();
if (stream) {
const streamResponse = await client.chat.stream({
model: process.env.MISTRAL_MODEL ?? 'mistral-small-latest',
messages,
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const event of streamResponse) {
const content = event.data?.choices?.[0]?.delta?.content;
if (content) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ content })}\n\n`));
}
}
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
controller.close();
},
});
return new Response(readable, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
},
});
}
const response = await client.chat.complete({
model: process.env.MISTRAL_MODEL ?? 'mistral-small-latest',
messages,
});
return Response.json(response);
}
Step 3: Docker Deployment
FROM node:20-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production=false
COPY . .
RUN npm run build
FROM node:20-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
ENV NODE_ENV=production
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s \
CMD curl -sf http://localhost:3000/health || exit 1
CMD ["node", "dist/index.js"]
Configure Mistral AI enterprise access control and workspace management.
Mistral AI Enterprise RBAC
Overview
Control access to Mistral AI at the organization level using La Plateforme workspace management: scoped API keys per team, model access restrictions, spending limits, key auditing, and automated rotation. Mistral organizes access via Organizations > Workspaces > API Keys, with rate limits set at the workspace level.
Prerequisites
- Mistral La Plateforme organization account (console.mistral.ai)
- Organization admin or owner role
- Understanding of workspace vs key-level controls
Instructions
Step 1: Workspace Strategy
| Workspace | Team | Models Allowed | RPM | Monthly Budget |
|---|---|---|---|---|
| dev-workspace | All developers | mistral-small, codestral | 60 | $50 |
| ml-workspace | ML engineers | All models | 200 | $500 |
| prod-workspace | CI/CD only | Per-service scoped | 500 | $2000 |
Create workspaces via La Plateforme console: Organization > Workspaces > Create.
Step 2: Scoped API Keys per Team
Create keys with model restrictions and rate limits in the console, or via API:
set -euo pipefail
# Dev team — restricted to cost-effective models
curl -X POST https://api.mistral.ai/v1/api-keys \
-H "Authorization: Bearer $MISTRAL_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "dev-team-key",
"description": "Dev team — small models only",
"workspace_id": "ws_dev_xxx"
}'
# ML team — full model access
curl -X POST https://api.mistral.ai/v1/api-keys \
-H "Authorization: Bearer $MISTRAL_ADMIN_KEY" \
-H "Content-Type: application/json" \
-d '{
"name": "ml-team-key",
"description": "ML team — all models",
"workspace_id": "ws_ml_xxx"
}'
Step 3: Application-Level Model Gateway
Enforce model access in your application layer:
const ROLE_PERMISSIONS: Record<string, {
allowedModels: string[];
maxTokensPerRequest: number;
dailyTokenBudget: number;
}> = {
analyst: {
allowedModels: ['mistral-small-latest', 'mistral-embed'],
maxTokensPerRequest: 500,
dailyTokenBudget: 100_000,
},
developer: {
allowedModels: ['mistral-small-latest', 'codestral-latest', 'mistral-embed'],
maxTokensPerRequest: 2000,
dailyTokenBudget: 500_000,
},
senior: {
allowedModels: ['mistral-small-latest', 'mistral-large-latest', 'codestral-latest', Create a minimal working Mistral AI chat completion example.
Mistral AI Hello World
Overview
Minimal working examples demonstrating Mistral AI chat completions, streaming, multi-turn conversation, and JSON mode. Uses the official @mistralai/mistralai TypeScript SDK and mistralai Python SDK.
Prerequisites
- Completed
mistral-install-authsetup - Valid
MISTRAL_API_KEYenvironment variable set - Node.js 18+ or Python 3.9+
Instructions
Step 1: Basic Chat Completion
TypeScript (hello-mistral.ts)
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function main() {
const response = await client.chat.complete({
model: 'mistral-small-latest',
messages: [
{ role: 'user', content: 'Say "Hello, World!" in a creative way.' },
],
});
console.log(response.choices?.[0]?.message?.content);
console.log('Tokens used:', response.usage);
}
main().catch(console.error);
Python (hello_mistral.py)
import os
from mistralai import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.complete(
model="mistral-small-latest",
messages=[
{"role": "user", "content": "Say 'Hello, World!' in a creative way."}
],
)
print(response.choices[0].message.content)
print(f"Tokens: {response.usage}")
Step 2: Run the Example
# TypeScript
npx tsx hello-mistral.ts
# Python
python hello_mistral.py
Step 3: Streaming Response
Streaming delivers the first token in ~200ms instead of waiting 1-2s for the full response.
TypeScript
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function streamChat() {
const stream = await client.chat.stream({
model: 'mistral-small-latest',
messages: [
{ role: 'user', content: 'Tell me a short story about AI.' },
],
});
for await (const event of stream) {
const content = event.data?.choices?.[0]?.delta?.content;
if (content) process.stdout.write(content);
}
console.log(); // newline
}
streamChat().catch(console.error);
Python
stream = client.chat.stream(
model="mistral-small-latest",
messages=[{"role": "user", "content": "Tell me a short story about AI."}],
)
for event in stream:
content = event.data.choices[0].delta.content
if content:
print(content, end="&Execute Mistral AI incident response procedures with triage, mitigation, and postmortem.
Mistral AI Incident Runbook
Overview
Rapid incident response procedures for Mistral AI integration failures. Covers severity classification, quick triage script, decision tree, per-error mitigations, communication templates, and postmortem process.
Severity Levels
| Level | Definition | Response Time | Example |
|---|---|---|---|
| P1 | Complete outage | < 15 min | All Mistral requests failing |
| P2 | Degraded service | < 1 hour | High latency, partial 429s |
| P3 | Minor impact | < 4 hours | Occasional errors, non-critical feature |
| P4 | No user impact | Next business day | Monitoring gaps, docs |
Quick Triage Script
#!/bin/bash
set -euo pipefail
echo "=== Mistral AI Quick Triage ==="
echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
# 1. API health
echo -e "\n1. Mistral API status:"
HTTP=$(curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer ${MISTRAL_API_KEY}" \
https://api.mistral.ai/v1/models 2>/dev/null)
echo " HTTP: $HTTP"
case $HTTP in
200) echo " OK — API is reachable" ;;
401) echo " AUTH FAILURE — API key invalid or revoked" ;;
429) echo " RATE LIMITED — check workspace limits" ;;
5*) echo " SERVER ERROR — Mistral service issue" ;;
000) echo " NETWORK ERROR — cannot reach api.mistral.ai" ;;
esac
# 2. Our service health
echo -e "\n2. App health endpoint:"
curl -sf https://yourapp.com/health 2>/dev/null | jq '.services.mistral' || echo " UNREACHABLE"
# 3. Error rate (if Prometheus available)
echo -e "\n3. Error rate (last 5m):"
curl -sf "localhost:9090/api/v1/query?query=rate(mistral_errors_total[5m])" 2>/dev/null \
| jq -r '.data.result[] | "\(.metric.model): \(.value[1])/s"' || echo " Prometheus unavailable"
Decision Tree
API returning errors?
|-- YES: curl -H "Authorization: Bearer $KEY" https://api.mistral.ai/v1/models
| |-- 401 → API key issue (Step 1 below)
| |-- 429 → Rate limited (Step 2 below)
| |-- 5xx → Mistral service issue (Step 3 below)
| +-- Timeout → Network issue (Step 4 below)
+-- NO: Our service returning errors?
|-- YES → Check app logs and config
+-- NO → Resolved, continue monitoring
Immediate Actions
Step 1: 401 — Authentication Failure (P1)
set -euo pipefail
# Verify key
echo "Key length: ${#MISTRAL_API_KEY}"
echo "Key prefix: ${MISTRAL_API_KEY:0:8}..."
# Test directly
curl -v -H "Authorization: Bearer ${MISTRAL_API_KEY}" \
https://aInstall and configure the Mistral AI SDK with authentication.
Mistral AI Install & Auth
Overview
Set up the official Mistral AI SDK (@mistralai/mistralai for TypeScript, mistralai for Python) and configure authentication for chat completions, embeddings, function calling, vision, and agents.
Prerequisites
- Node.js 18+ or Python 3.9+
- Package manager (npm, pnpm, yarn, or pip)
- Mistral AI account at console.mistral.ai
- API key from La Plateforme (Settings > API Keys)
Instructions
Step 1: Install SDK
Node.js (TypeScript/JavaScript) — ESM only
set -euo pipefail
# npm
npm install @mistralai/mistralai
# pnpm
pnpm add @mistralai/mistralai
# yarn
yarn add @mistralai/mistralai
Python
set -euo pipefail
pip install mistralai
Step 2: Configure Authentication
Environment Variables (Recommended)
# Set in shell
export MISTRAL_API_KEY="your-api-key"
# Or create .env file (add to .gitignore!)
echo 'MISTRAL_API_KEY=your-api-key' >> .env
echo '.env' >> .gitignore
Using dotenv (Node.js)
set -euo pipefail
npm install dotenv
import 'dotenv/config';
Step 3: Verify Connection
TypeScript
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({
apiKey: process.env.MISTRAL_API_KEY,
});
async function testConnection() {
try {
const models = await client.models.list();
console.log('Connection successful! Available models:');
for (const model of models.data ?? []) {
console.log(` - ${model.id}`);
}
} catch (error: any) {
if (error.status === 401) {
console.error('Invalid API key. Check your key at console.mistral.ai');
} else {
console.error('Connection failed:', error.message);
}
}
}
testConnection();
Python
import os
from mistralai import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
def test_connection():
try:
models = client.models.list()
print("Connection successful! Available models:")
for model in models.data:
print(f" - {model.id}")
except Exception as e:
print(f"Connection failed: {e}")
test_connection()
Step 4: Production — Secret Manager
// GCP Secret Manager (recommended for production)
import { SecretManagerServiceClient } from '@google-cloud/secret-manager';
const sm =Configure Mistral AI local development with hot reload, testing, and mocking.
Mistral AI Local Dev Loop
Overview
Set up a fast, reproducible local development workflow for Mistral AI integrations: project scaffold, environment config, hot reload with tsx, unit tests with Vitest mocking, and integration tests against the live API.
Prerequisites
- Completed
mistral-install-authsetup - Node.js 18+ with npm/pnpm
MISTRAL_API_KEYset in environment
Instructions
Step 1: Project Structure
my-mistral-project/
├── src/
│ ├── mistral/
│ │ ├── client.ts # Singleton client
│ │ ├── config.ts # Config with Zod validation
│ │ └── types.ts # TypeScript types
│ └── index.ts
├── tests/
│ ├── unit/
│ │ └── mistral.test.ts
│ └── integration/
│ └── mistral.integration.test.ts
├── .env.local # Local secrets (git-ignored)
├── .env.example # Template for team
├── tsconfig.json
├── vitest.config.ts
└── package.json
Step 2: Package Configuration
package.json
{
"type": "module",
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"test": "vitest run",
"test:watch": "vitest",
"test:integration": "vitest run tests/integration/",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@mistralai/mistralai": "^1.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"dotenv": "^16.0.0",
"tsx": "^4.0.0",
"typescript": "^5.0.0",
"vitest": "^1.0.0"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Step 3: Environment Setup
# Create environment template
cat > .env.example << 'EOF'
MISTRAL_API_KEY=your-api-key-here
MISTRAL_MODEL=mistral-small-latest
LOG_LEVEL=debug
EOF
cp .env.example .env.local
echo '.env.local' >> .gitignore
echo '.env' >> .gitignore
Step 4: Client Module
// src/mistral/client.ts
import { Mistral } from '@mistralai/mistralai';
importExecute migration to Mistral AI from OpenAI, Anthropic, or other providers.
Mistral AI Migration Deep Dive
Current State
!npm list openai @anthropic-ai/sdk @mistralai/mistralai 2>/dev/null | grep -E "openai|anthropic|mistral" || echo 'No AI SDKs found'
Overview
Comprehensive migration guide from OpenAI or Anthropic to Mistral AI using the adapter pattern with feature-flag controlled rollout. Covers model mapping, API differences, prompt adjustments, validation testing, and rollback procedures.
Prerequisites
- Current AI integration documented
- Mistral AI SDK installed (
@mistralai/mistralai) - Feature flag infrastructure (env vars or LaunchDarkly)
- Rollback plan tested
Migration Complexity
| Migration | Effort | Duration | Risk |
|---|---|---|---|
| Fresh install (no existing AI) | Low | Days | Low |
| OpenAI to Mistral | Medium | 1-2 weeks | Medium |
| Anthropic to Mistral | Medium | 1-2 weeks | Medium |
| Multi-provider to Mistral | High | 2-4 weeks | Medium |
Instructions
Step 1: Assessment — Find All AI Touchpoints
set -euo pipefail
# Count integration points
echo "=== AI Integration Assessment ==="
echo "OpenAI imports: $(grep -r "from 'openai'" src/ --include='*.ts' -l 2>/dev/null | wc -l)"
echo "Anthropic imports: $(grep -r "from '@anthropic'" src/ --include='*.ts' -l 2>/dev/null | wc -l)"
echo "Chat completions: $(grep -r "chat\.completions\|messages\.create" src/ --include='*.ts' -c 2>/dev/null | wc -l)"
echo "Embeddings: $(grep -r "embeddings\.create" src/ --include='*.ts' -c 2>/dev/null | wc -l)"
echo "Streaming: $(grep -r "stream\|for await" src/ --include='*.ts' -c 2>/dev/null | wc -l)"
Step 2: Model Mapping
| OpenAI | Anthropic | Mistral | Notes | |
|---|---|---|---|---|
| gpt-4o | claude-3-5-sonnet | mistral-large-latest |
Complex reasoning | |
| gpt-4o-mini | claude-3-5-haiku | mistral-small-latest |
Fast, cheap | |
| gpt-3.5-turbo | — | mistral-small-latest |
General purpose | |
| text-embedding-3-small | — | mistral-embed |
1024 dims (vs 1536) | |
| — | — | codestral-latest |
Code-specialized | |
| gpt-4-vision | claude-3-5-sonnet | pixtral-large-latest |
Vision + text |
| Environment | API Key | Default Model | Rate Limit | Cache |
|---|---|---|---|---|
| Development | Dev key (low quota) | mistral-small-latest | 10 RPM | Off |
| Staging | Staging key | Same as prod | 60 RPM | On |
| Production | Prod key (full quota) | Optimized per task | Full RPM | On |
Instructions
Step 1: Configuration Structure
// config/mistral/base.ts
export interface MistralEnvConfig {
apiKey: string;
defaultModel: string;
timeoutMs: number;
maxRetries: number;
debug: boolean;
cache: { enabled: boolean; ttlMs: number };
rateLimits: { rpm: number; tpm: number };
}
export const baseConfig: Omit<MistralEnvConfig, 'apiKey'> = {
defaultModel: 'mistral-small-latest',
timeoutMs: 30_000,
maxRetries: 3,
debug: false,
cache: { enabled: true, ttlMs: 300_000 },
rateLimits: { rpm: 60, tpm: 500_000 },
};
Step 2: Per-Environment Configs
// config/mistral/environments.ts
import { baseConfig, type MistralEnvConfig } from './base.js';
const configs: Record<string, Partial<MistralEnvConfig>> = {
development: {
debug: true,
cache: { enabled: false, ttlMs: 60_000 },
rateLimits: { rpm: 10, tpm: 100_000 },
},
staging: {
cache: { enabled: true, ttlMs: 300_000 },
},
production: {
timeoutMs: 60_000,
maxRetries: 5,
cache: { enabled: true, ttlMs: 600_000 },
},
};
export function getMistralConfig(): MistralEnvConfig {
const env = detectEnvironment();
const envConfig = configs[env] ?? {};
// API key sourced from environment
const apiKeyVar = {
development: 'MISTRAL_API_KEY_DEV',
staging: 'MISTRAL_API_KEY_STAGING',
production: 'MISTRAL_API_KEY',
}[env] ?? 'MISTRAL_API_KEY';
const apiKey = process.env[apiKeyVar] ?? process.env.MISTRAL_API_KEY;
if (!apiKey) throw new Error(`Mistral API key not set for ${env} (expected ${apiKeyVar})`);
return { ...baseConfig, ...envConfig, apiKey } as MistralEnvConfig;
}
Step 3: Environment Detection
type Environment = 'development' | 'staging' |Set up comprehensive observability for Mistral AI with metrics, traces, and alerts.
Mistral AI Observability
Overview
Monitor Mistral AI API usage, latency, token consumption, error rates, and costs. Covers instrumented client wrapper, Prometheus metrics, Grafana dashboard panels, alerting rules, and structured logging.
Prerequisites
- Mistral API integration in production
- Prometheus or OpenTelemetry-compatible metrics backend
- Alerting system (Alertmanager, PagerDuty, or similar)
Instructions
Step 1: Instrumented Client Wrapper
import { Mistral } from '@mistralai/mistralai';
const PRICING: Record<string, { input: number; output: number }> = {
'mistral-small-latest': { input: 0.10, output: 0.30 },
'mistral-large-latest': { input: 0.50, output: 1.50 },
'codestral-latest': { input: 0.30, output: 0.90 },
'mistral-embed': { input: 0.10, output: 0 },
};
interface MetricsEvent {
model: string;
endpoint: string;
durationMs: number;
status: 'success' | 'error';
statusCode?: number;
inputTokens?: number;
outputTokens?: number;
costUsd?: number;
}
function emitMetrics(event: MetricsEvent): void {
// Push to your metrics backend (Prometheus, Datadog, etc.)
console.log(JSON.stringify({ type: 'mistral_metric', ...event }));
}
async function instrumentedChat(
client: Mistral,
model: string,
messages: any[],
options?: any,
) {
const start = performance.now();
try {
const response = await client.chat.complete({ model, messages, ...options });
const duration = Math.round(performance.now() - start);
const pricing = PRICING[model] ?? PRICING['mistral-small-latest'];
const pt = response.usage?.promptTokens ?? 0;
const ct = response.usage?.completionTokens ?? 0;
emitMetrics({
model,
endpoint: 'chat.complete',
durationMs: duration,
status: 'success',
inputTokens: pt,
outputTokens: ct,
costUsd: (pt / 1e6) * pricing.input + (ct / 1e6) * pricing.output,
});
return response;
} catch (error: any) {
emitMetrics({
model,
endpoint: 'chat.complete',
durationMs: Math.round(performance.now() - start),
status: 'error',
statusCode: error.status,
});
throw error;
}
}
Step 2: Prometheus Metrics
// Using prom-client
import { Counter, Histogram, Gauge } from 'prom-client';
const mistralRequests = new Counter({
name: 'mistral_requests_total',
help: 'Total Mistral API requests',
labelNames: ['model', 'endpoint', 'status'],
});
const mistralDuration = new Histogram({
name: 'mistral_request_duration_ms',
help: 'Mistral request duration in milliseconds',
labelNames: ['model', 'endpoint'],
buckets: [100, 250, 500, 10Optimize Mistral AI performance with caching, batching, and latency reduction.
Mistral AI Performance Tuning
Overview
Optimize Mistral AI API response times and throughput. Key levers: model selection (Mistral Small ~200ms TTFT vs Large ~500ms), prompt length (fewer tokens = faster), streaming (perceived speed), caching (zero-latency repeats), and concurrent request management.
Prerequisites
- Mistral API integration in production
- Understanding of RPM/TPM limits for your tier
- Application architecture supporting streaming
Instructions
Step 1: Model Selection by Latency Budget
const MODELS_BY_USE_CASE: Record<string, { model: string; ttftMs: string; note: string }> = {
realtime_chat: { model: 'mistral-small-latest', ttftMs: '~200ms', note: '256k ctx, cheapest' },
code_completion: { model: 'codestral-latest', ttftMs: '~150ms', note: 'Optimized for code + FIM' },
code_agents: { model: 'devstral-latest', ttftMs: '~300ms', note: 'Agentic coding tasks' },
reasoning: { model: 'mistral-large-latest', ttftMs: '~500ms', note: '256k ctx, strongest' },
vision: { model: 'pixtral-large-latest', ttftMs: '~600ms', note: 'Image + text multimodal' },
embeddings: { model: 'mistral-embed', ttftMs: '~50ms', note: '1024-dim, batch-friendly' },
edge_devices: { model: 'ministral-latest', ttftMs: '~100ms', note: '3B-14B, fastest' },
};
Step 2: Streaming for User-Facing Responses
Streaming reduces perceived latency from 1-2s (full response) to ~200ms (first token):
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function* streamChat(messages: any[], model = 'mistral-small-latest') {
const stream = await client.chat.stream({ model, messages });
for await (const chunk of stream) {
const content = chunk.data?.choices?.[0]?.delta?.content;
if (content) yield content;
}
}
// Web Response with SSE
function streamToSSE(messages: any[]): Response {
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const text of streamChat(messages)) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text })}\n\n`));
}
controller.enqueue(encoder.encode('data: [DONE]\n\n'));
controller.close();
},
});
return new Response(readable, {
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
});
}
Step 3: Response Caching
import { createHash } from 'crypto';
import { LRUCache } frExecute Mistral AI production deployment checklist and rollback procedures.
Mistral AI Production Checklist
Overview
Complete checklist for deploying Mistral AI integrations to production. Covers credential management, code quality gates, health endpoints, circuit breaker resilience, gradual rollout, and rollback procedures.
Prerequisites
- Staging environment tested and verified
- Production API keys from La Plateforme
- Deployment pipeline (CI/CD) configured
- Monitoring and alerting ready (see
mistral-observability)
Instructions
Step 1: Pre-Deployment Verification
Credentials
- [ ] Production API key stored in secret manager (never in env files or code)
- [ ] Key tested with
curl -H "Authorization: Bearer $KEY" https://api.mistral.ai/v1/models - [ ] Key has appropriate model access scope
- [ ] Fallback key available for rotation
Code Quality
- [ ]
npm run typecheckpasses - [ ]
npm testpasses (unit + integration) - [ ] No hardcoded keys:
grep -r "MISTRAL_API_KEY\|sk-" src/ --include="*.ts" - [ ] Error handling covers 401, 429, 500+ status codes
- [ ] Rate limiting/backoff implemented
- [ ] Logging excludes message content and API keys
Model Configuration
- [ ] Using versioned model IDs or
-latestaliases intentionally - [ ]
maxTokensset to prevent runaway costs - [ ]
temperatureset appropriately (0 for deterministic, 0.7 for creative) - [ ] Token budget alerts configured
Step 2: Health Check Endpoint
import { Mistral } from '@mistralai/mistralai';
interface HealthStatus {
status: 'healthy' | 'degraded' | 'unhealthy';
provider: 'mistral';
latencyMs: number;
model?: string;
error?: string;
}
export async function checkHealth(): Promise<HealthStatus> {
const start = performance.now();
try {
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY! });
const models = await client.models.list();
const latencyMs = Math.round(performance.now() - start);
return {
status: latencyMs > 5000 ? 'degraded' : 'healthy',
provider: 'mistral',
latencyMs,
model: models.data?.[0]?.id,
};
} catch (error: any) {
return {
status: 'unhealthy',
provider: 'mistral',
latencyMs: Math.round(performance.now() - start),
error: error.message,
};
}
}
// Express route
app.get('/health', async (req, res) => {
const health = await checkHealth();
res.status(health.status === 'unhealthy' ? 503 : 200).json(health);
});
Step 3: Circuit Breaker
Implement Mistral AI rate limiting, backoff, and request management.
Mistral Rate Limits
Overview
Rate limit management for Mistral AI API. Mistral enforces per-workspace RPM (requests/minute) and TPM (tokens/minute) limits that vary by usage tier (Experiment free tier vs Scale pay-as-you-go). View your workspace limits at admin.mistral.ai/plateforme/limits.
Prerequisites
- Mistral API key configured
- Understanding of workspace tier (Experiment vs Scale)
- Application with retry infrastructure
Mistral Rate Limit Architecture
Limits are set at the workspace level, not per key. All API keys in a workspace share the same RPM/TPM budget.
| Endpoint | What's limited |
|---|---|
/v1/chat/completions |
RPM + TPM (input + output) |
/v1/embeddings |
RPM + TPM (input only) |
/v1/fim/completions |
RPM + TPM |
/v1/moderations |
RPM |
Headers returned on every response:
x-ratelimit-limit-requests— your RPM capx-ratelimit-remaining-requests— remaining RPMx-ratelimit-limit-tokens— your TPM capx-ratelimit-remaining-tokens— remaining TPMRetry-After— seconds to wait (on 429 only)
Instructions
Step 1: Token-Aware Rate Limiter
class MistralRateLimiter {
private requestTimes: number[] = [];
private tokenBuckets: Array<{ time: number; tokens: number }> = [];
private readonly rpm: number;
private readonly tpm: number;
constructor(rpm: number, tpm: number) {
this.rpm = rpm;
this.tpm = tpm;
}
async waitIfNeeded(estimatedTokens: number): Promise<void> {
const now = Date.now();
const windowStart = now - 60_000;
// Prune old entries
this.requestTimes = this.requestTimes.filter(t => t > windowStart);
this.tokenBuckets = this.tokenBuckets.filter(b => b.time > windowStart);
// Check RPM
if (this.requestTimes.length >= this.rpm) {
const waitMs = this.requestTimes[0] - windowStart + 100;
console.warn(`RPM limit (${this.rpm}), waiting ${waitMs}ms`);
await new Promise(r => setTimeout(r, waitMs));
}
// Check TPM
const currentTPM = this.tokenBuckets.reduce((sum, b) => sum + b.tokens, 0);
if (currentTPM + estimatedTokens > this.tpm) {
const waitMs = this.tokenBuckets[0].time - windowStart + 100;
console.warn(`TPM limit (${this.tpm}), waiting ${waitMs}ms`);
await new Promise(r => setTimeout(r, waitMs));
}
this.requestTimes.push(Date.now());
}
recordUsage(tokens: number): void {
this.tokenBuckets.push({ time: Date.now(), tokImplement Mistral AI reference architecture with best-practice project layout.
Mistral AI Reference Architecture
Overview
Production-ready architecture patterns for Mistral AI integrations: layered project structure, singleton client, Zod-validated config, custom error classes, service layer with caching, health checks, prompt templates, and model routing.
Prerequisites
- TypeScript/Node.js project (ESM)
@mistralai/mistralaiSDKzodfor config validation- Testing framework (Vitest)
Layer Architecture
API Layer (Routes, Controllers, Middleware)
|
Service Layer (Business Logic, Orchestration)
|
Mistral Layer (Client, Config, Errors, Prompts)
|
Infrastructure Layer (Cache, Queue, Monitoring)
Instructions
Step 1: Directory Structure
src/
├── mistral/
│ ├── client.ts # Singleton client factory
│ ├── config.ts # Zod-validated config
│ ├── errors.ts # Custom error classes
│ ├── types.ts # Shared types
│ └── prompts.ts # Prompt templates
├── services/
│ ├── chat.service.ts # Chat with caching + retry
│ ├── embed.service.ts # Embeddings + search
│ └── rag.service.ts # RAG pipeline
├── api/
│ ├── chat.route.ts # HTTP endpoints
│ └── health.route.ts # Health check
└── config/
├── base.ts # Shared config
├── development.ts # Dev overrides
└── production.ts # Prod overrides
Step 2: Config with Zod Validation
// src/mistral/config.ts
import { z } from 'zod';
const MistralConfigSchema = z.object({
apiKey: z.string().min(10, 'MISTRAL_API_KEY required'),
defaultModel: z.string().default('mistral-small-latest'),
timeoutMs: z.number().default(30_000),
maxRetries: z.number().default(3),
cache: z.object({
enabled: z.boolean().default(true),
ttlMs: z.number().default(3_600_000),
maxSize: z.number().default(5000),
}).default({}),
});
export type MistralConfig = z.infer<typeof MistralConfigSchema>;
export function loadConfig(): MistralConfig {
return MistralConfigSchema.parse({
apiKey: process.env.MISTRAL_API_KEY,
defaultModel: process.env.MISTRAL_MODEL,
timeoutMs: process.env.MISTRAL_TIMEOUT ? Number(process.env.MISTRAL_TIMEOUT) : undefined,
});
}
Step 3: Singleton Client
// src/mistral/client.ts
import { Mistral } from '@mistralai/mistralai';
import { loadConfig, type MistralConfig } from './config.js';
let _client: Mistral | null = null;
let _config: MistralConfig | null = null;
export function getMistralClient(): Mistral {
if (!_client) {
_config = loadConfig();
_client = new Mistral({
apiKey: _config.apiKey,
timeoutMs: _config.timeoutMs,
maxRetries: _config.maxRetries,
});
}
return _client;
}
export function getConfig(): MistrApply production-ready Mistral AI SDK patterns for TypeScript and Python.
Mistral SDK Patterns
Overview
Production-ready patterns for the Mistral AI SDK. Covers singleton client, retry/backoff, structured output, streaming, function calling, batch embeddings, and async Python — all with proper error handling. SDK is ESM-only for TypeScript (@mistralai/mistralai), sync+async for Python (mistralai).
Prerequisites
@mistralai/mistralai(TypeScript) ormistralai(Python) installedMISTRAL_API_KEYenvironment variable set
Instructions
Step 1: Singleton Client with Configuration
TypeScript
import { Mistral } from '@mistralai/mistralai';
let _client: Mistral | null = null;
export function getMistralClient(): Mistral {
if (!_client) {
const apiKey = process.env.MISTRAL_API_KEY;
if (!apiKey) throw new Error('MISTRAL_API_KEY not set');
_client = new Mistral({
apiKey,
timeoutMs: 30_000,
maxRetries: 3,
});
}
return _client;
}
// Reset for testing
export function resetClient(): void {
_client = null;
}
Python
import os
from mistralai import Mistral
_client = None
def get_client() -> Mistral:
global _client
if _client is None:
api_key = os.environ.get("MISTRAL_API_KEY")
if not api_key:
raise RuntimeError("MISTRAL_API_KEY not set")
_client = Mistral(api_key=api_key, timeout_ms=30_000, max_retries=3)
return _client
Step 2: Structured Output with JSON Schema
import { z } from 'zod';
// Define schema with Zod, then convert to JSON Schema for Mistral
const TicketSchema = z.object({
category: z.enum(['bug', 'feature', 'question']),
severity: z.enum(['low', 'medium', 'high', 'critical']),
summary: z.string(),
});
type Ticket = z.infer<typeof TicketSchema>;
async function classifyTicket(text: string): Promise<Ticket> {
const client = getMistralClient();
const response = await client.chat.complete({
model: 'mistral-small-latest',
messages: [
{ role: 'system', content: 'Classify the support ticket.' },
{ role: 'user', content: text },
],
responseFormat: {
type: 'json_schema',
jsonSchema: {
name: 'ticket_classification',
schema: {
type: 'object',
properties: {
category: { type: 'string', enum: ['bug', 'feature', 'question'] },
severity: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },
summary: { type: 'string' },
},
reqApply Mistral AI security best practices for secrets, prompt injection, and access control.
Mistral Security Basics
Overview
Security practices for Mistral AI integrations: API key management, prompt injection defense, output sanitization, content moderation with mistral-moderation-latest, request logging without secrets, and key rotation.
Prerequisites
- Mistral API key provisioned
- Understanding of OWASP LLM Top 10 risks
- Secret management infrastructure
Instructions
Step 1: API Key Management
import os
# NEVER: api_key = "sk-abc123"
# Development — env vars
api_key = os.environ.get("MISTRAL_API_KEY")
if not api_key:
raise RuntimeError("MISTRAL_API_KEY not set")
# Production — secret manager
from google.cloud import secretmanager
def get_api_key() -> str:
client = secretmanager.SecretManagerServiceClient()
response = client.access_secret_version(
name="projects/my-project/secrets/mistral-api-key/versions/latest"
)
return response.payload.data.decode("UTF-8")
Step 2: Prompt Injection Defense
function sanitizeUserInput(input: string): string {
// Strip common injection patterns
const patterns = [
/ignore (?:previous|all|above) instructions/gi,
/you are now/gi,
/system prompt/gi,
/\boverride\b/gi,
/\bforget\b.*\binstructions\b/gi,
];
let sanitized = input;
for (const pattern of patterns) {
sanitized = sanitized.replace(pattern, '[FILTERED]');
}
// Limit length to prevent context stuffing
return sanitized.slice(0, 4000);
}
function buildSafeMessages(system: string, userInput: string) {
return [
{ role: 'system', content: system },
{
role: 'user',
content: `<user_query>\n${sanitizeUserInput(userInput)}\n</user_query>`,
},
];
}
Step 3: Content Moderation with Mistral API
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
async function moderateContent(text: string): Promise<{ safe: boolean; flags: string[] }> {
const result = await client.classifiers.moderate({
model: 'mistral-moderation-latest',
inputs: [text],
});
const categories = result.results[0].categories;
const flags = Object.entries(categories)
.filter(([, flagged]) => flagged)
.map(([category]) => category);
return { safe: flags.length === 0, flags };
}
// Gate user input before processing
async function safeChatFlow(userInput: string) {
const inputCheck = await moderateContent(userInput);
if (!inputCheck.safe) {
throw new Error(`Input flagged: ${inputCheck.flags.join(', ')}`);
}
const response = await client.chat.complete({
model: 'mistral-small-latest',
messages: [{ role: 'user', cAnalyze, plan, and execute Mistral AI SDK upgrades with breaking change detection.
Mistral AI Upgrade & Migration
Current State
!npm list @mistralai/mistralai 2>/dev/null || echo 'not installed' !pip show mistralai 2>/dev/null | grep -E "^(Name|Version)" || echo 'not installed'
Overview
Guide for upgrading the Mistral AI SDK between major versions. The TypeScript SDK (@mistralai/mistralai) moved from CommonJS to ESM-only in v1.x, with significant API surface changes. This skill covers version detection, breaking change migration, automated code transforms, and rollback.
Prerequisites
- Current Mistral AI SDK installed
- Git for version control
- Test suite available
Instructions
Step 1: Check Versions
set -euo pipefail
# Current version
npm list @mistralai/mistralai 2>/dev/null
# Latest available
npm view @mistralai/mistralai version
# All versions
npm view @mistralai/mistralai versions --json | jq '.[-5:]'
# Python
pip show mistralai 2>/dev/null | grep Version
Step 2: Known Breaking Changes (v0.x to v1.x)
| Change | v0.x (old) | v1.x (current) |
|---|---|---|
| Module format | CommonJS + ESM | ESM only |
| Import | import MistralClient from '...' |
import { Mistral } from '...' |
| Constructor | new MistralClient(apiKey) |
new Mistral({ apiKey }) |
| Chat method | client.chat(params) |
client.chat.complete(params) |
| Streaming | client.chatStream(params) |
client.chat.stream(params) |
| Stream events | for await (const chunk of stream) |
for await (const event of stream) access .data |
| Embeddings | client.embeddings(params) |
client.embeddings.create(params) |
| Response types | Longer names | Shorter type names |
| Enum values | String constants | Forward-compatible unions |
Step 3: Automated Migration Script
// scripts/migrate-mistral-v1.ts
import { readFileSync, writeFileSync } from 'fs';
import { glob } from 'glob';
const TRANSFORMS = [
// Import statement
{
find: /import\s+MistralClient\s+from\s+['"]@mistralai\/mistralai['"]/g,
replace: "import { Mistral } from '@mistralai/mistralai'",
},
// Constructor
{
find: /new\s+MistralClient\((\w+)\)/g,
replace: 'new Mistral({ apiKey: $1 })',
},
// Chat method (careful: only top-leveImplement Mistral AI async patterns, batch API, agents, and event-driven workflows.
Mistral AI Events, Agents & Async Patterns
Overview
Async and event-driven patterns for Mistral AI: the Agents API for stateful multi-turn workflows, Batch API for cost-effective bulk inference (50% cheaper), SSE streaming endpoints, background job queues, and Python async processing. Mistral does not have native webhooks — this skill covers the patterns that replace them.
Prerequisites
@mistralai/mistralaiSDK installedMISTRAL_API_KEYconfigured- For agents: La Plateforme access to create agents
- For batch: JSONL file preparation
Instructions
Step 1: Mistral Agents API
Create stateful agents with instructions, tools, and model configuration:
import { Mistral } from '@mistralai/mistralai';
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
// Create an agent on La Plateforme
const agent = await client.agents.create({
name: 'Code Reviewer',
model: 'mistral-large-latest',
instructions: `You are an expert code reviewer. Analyze code for:
- Security vulnerabilities
- Performance issues
- Best practice violations
Provide actionable feedback with severity ratings.`,
description: 'Reviews code for security, performance, and best practices',
tools: [
{
type: 'function',
function: {
name: 'search_codebase',
description: 'Search the codebase for patterns',
parameters: {
type: 'object',
properties: { query: { type: 'string' } },
required: ['query'],
},
},
},
],
});
// Chat with the agent (stateful conversation)
const response = await client.agents.complete({
agentId: agent.id,
messages: [
{ role: 'user', content: 'Review this function:\n```\nfunction auth(pwd) { return pwd === "admin123"; }\n```' },
],
});
console.log(response.choices?.[0]?.message?.content);
Step 2: Batch API for Bulk Inference
50% cost reduction for non-time-sensitive workloads:
// 1. Prepare JSONL input file
const batchRequests = [
{
custom_id: 'req-1',
body: {
model: 'mistral-small-latest',
messages: [{ role: 'user', content: 'Summarize: ...' }],
max_tokens: 200,
},
},
{
custom_id: 'req-2',
body: {
model: 'mistral-small-latest',
messages: [{ role: 'user', content: 'Classify: ...' }],
max_tokens: 50,
},
},
];
// Write to JSONL
import { writeFileSync } from 'fs';
writeFileSync('batch-input.jsonl',
batchRequests.map(r => JSON.stringify(r)).join('\n')
);
// 2. Upload file and create batch job
const file = await client.files.upload({
file: { fileNameHow It Works
Skills activate automatically based on context:
- "Set up Mistral" activates
mistral-install-auth - "Debug this Mistral error" activates
mistral-common-errors - "Deploy my Mistral app" activates
mistral-deploy-integration - "Migrate from OpenAI" activates
mistral-migration-deep-dive - "Optimize Mistral costs" activates
mistral-cost-tuning
Ready to use mistral-pack?
Related Plugins
supabase-pack
Complete Supabase integration skill pack with 30 skills covering authentication, database, storage, realtime, edge functions, and production operations. Flagship+ tier vendor pack.
/plugin install supabase-pack@claude-code-plugins-plus
vercel-pack
Complete Vercel integration skill pack with 30 skills covering deployments, edge functions, preview environments, performance optimization, and production operations. Flagship+ tier vendor pack.
/plugin install vercel-pack@claude-code-plugins-plus
clay-pack
Complete Clay integration skill pack with 30 skills covering data enrichment, waterfall workflows, AI agents, and GTM automation. Flagship+ tier vendor pack.
/plugin install clay-pack@claude-code-plugins-plus
cursor-pack
Complete Cursor integration skill pack with 30 skills covering AI code editing, composer workflows, codebase indexing, and productivity features. Flagship+ tier vendor pack.
/plugin install cursor-pack@claude-code-plugins-plus
exa-pack
Complete Exa integration skill pack with 30 skills covering neural search, semantic retrieval, web search API, and AI-powered discovery. Flagship+ tier vendor pack.
/plugin install exa-pack@claude-code-plugins-plus
firecrawl-pack
Complete Firecrawl integration skill pack with 30 skills covering web scraping, crawling, markdown conversion, and LLM-ready data extraction. Flagship+ tier vendor pack.
/plugin install firecrawl-pack@claude-code-plugins-plus