mistral-migration-deep-dive

0
0
Source

Execute Mistral AI major migrations and re-architecture strategies. Use when migrating to Mistral AI from another provider, performing major refactoring, or re-platforming existing AI integrations to Mistral AI. Trigger with phrases like "migrate to mistral", "mistral migration", "switch to mistral", "mistral replatform", "openai to mistral".

Install

mkdir -p .claude/skills/mistral-migration-deep-dive && curl -L -o skill.zip "https://mcp.directory/api/skills/download/8055" && unzip -o skill.zip -d .claude/skills/mistral-migration-deep-dive && rm skill.zip

Installs to .claude/skills/mistral-migration-deep-dive

About this skill

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

MigrationEffortDurationRisk
Fresh install (no existing AI)LowDaysLow
OpenAI to MistralMedium1-2 weeksMedium
Anthropic to MistralMedium1-2 weeksMedium
Multi-provider to MistralHigh2-4 weeksMedium

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

OpenAIAnthropicMistralNotes
gpt-4oclaude-3-5-sonnetmistral-large-latestComplex reasoning
gpt-4o-miniclaude-3-5-haikumistral-small-latestFast, cheap
gpt-3.5-turbomistral-small-latestGeneral purpose
text-embedding-3-smallmistral-embed1024 dims (vs 1536)
codestral-latestCode-specialized
gpt-4-visionclaude-3-5-sonnetpixtral-large-latestVision + text

Step 3: Provider-Agnostic Adapter

// adapters/types.ts
export interface Message {
  role: 'system' | 'user' | 'assistant' | 'tool';
  content: string;
}

export interface ChatOptions {
  model?: string;
  temperature?: number;
  maxTokens?: number;
  stream?: boolean;
}

export interface ChatResponse {
  content: string;
  usage: { inputTokens: number; outputTokens: number };
  model: string;
}

export interface AIAdapter {
  chat(messages: Message[], options?: ChatOptions): Promise<ChatResponse>;
  chatStream(messages: Message[], options?: ChatOptions): AsyncGenerator<string>;
  embed(texts: string[]): Promise<number[][]>;
}

Step 4: Mistral Adapter

// adapters/mistral.adapter.ts
import { Mistral } from '@mistralai/mistralai';
import type { AIAdapter, Message, ChatOptions, ChatResponse } from './types.js';

export class MistralAdapter implements AIAdapter {
  private client: Mistral;
  private defaultModel: string;

  constructor(apiKey: string, defaultModel = 'mistral-small-latest') {
    this.client = new Mistral({ apiKey });
    this.defaultModel = defaultModel;
  }

  async chat(messages: Message[], options?: ChatOptions): Promise<ChatResponse> {
    const response = await this.client.chat.complete({
      model: options?.model ?? this.defaultModel,
      messages,
      temperature: options?.temperature,
      maxTokens: options?.maxTokens,
    });

    return {
      content: response.choices?.[0]?.message?.content ?? '',
      usage: {
        inputTokens: response.usage?.promptTokens ?? 0,
        outputTokens: response.usage?.completionTokens ?? 0,
      },
      model: response.model ?? this.defaultModel,
    };
  }

  async *chatStream(messages: Message[], options?: ChatOptions): AsyncGenerator<string> {
    const stream = await this.client.chat.stream({
      model: options?.model ?? this.defaultModel,
      messages,
      temperature: options?.temperature,
      maxTokens: options?.maxTokens,
    });

    for await (const event of stream) {
      const content = event.data?.choices?.[0]?.delta?.content;
      if (content) yield content;
    }
  }

  async embed(texts: string[]): Promise<number[][]> {
    const response = await this.client.embeddings.create({
      model: 'mistral-embed',
      inputs: texts,
    });
    return response.data.map(d => d.embedding);
  }
}

Step 5: Feature-Flag Controlled Rollout

// adapters/factory.ts
import { MistralAdapter } from './mistral.adapter.js';
import { OpenAIAdapter } from './openai.adapter.js';

export function createAdapter(): AIAdapter {
  const rolloutPercent = parseInt(process.env.MISTRAL_ROLLOUT_PERCENT ?? '0');
  const useMistral = Math.random() * 100 < rolloutPercent;

  if (useMistral) {
    console.log('[AI] Using Mistral');
    return new MistralAdapter(process.env.MISTRAL_API_KEY!);
  }

  console.log('[AI] Using OpenAI (legacy)');
  return new OpenAIAdapter(process.env.OPENAI_API_KEY!);
}

Step 6: Gradual Rollout Plan

PhaseRollout %DurationCriteria to Advance
0. Validation0%1-2 daysA/B tests pass
1. Canary5%2-3 daysError rate < 1%, latency OK
2. Partial25%3-5 daysQuality metrics match
3. Majority50%5-7 daysCost reduction confirmed
4. Full100%Remove old adapter code
# Advance rollout
export MISTRAL_ROLLOUT_PERCENT=5   # Canary
export MISTRAL_ROLLOUT_PERCENT=25  # Partial
export MISTRAL_ROLLOUT_PERCENT=100 # Full migration
export MISTRAL_ROLLOUT_PERCENT=0   # Emergency rollback

Step 7: A/B Validation Testing

async function validateMigration(adapter1: AIAdapter, adapter2: AIAdapter) {
  const testPrompts = [
    'Summarize: TypeScript adds static typing to JavaScript.',
    'Classify: "The app crashes on login" — bug, feature, or question?',
    'What is 2+2?',
  ];

  for (const prompt of testPrompts) {
    const messages = [{ role: 'user' as const, content: prompt }];
    const [r1, r2] = await Promise.all([
      adapter1.chat(messages, { temperature: 0 }),
      adapter2.chat(messages, { temperature: 0 }),
    ]);

    console.log(`Prompt: ${prompt.slice(0, 50)}...`);
    console.log(`  Provider 1: ${r1.content.slice(0, 100)} (${r1.usage.outputTokens} tokens)`);
    console.log(`  Provider 2: ${r2.content.slice(0, 100)} (${r2.usage.outputTokens} tokens)`);
    console.log();
  }
}

Key API Differences

FeatureOpenAIMistral
SDK importimport OpenAI from 'openai'import { Mistral } from '@mistralai/mistralai'
Chat methodclient.chat.completions.create()client.chat.complete()
Stream eventschunk.choices[0]?.delta?.contentevent.data?.choices?.[0]?.delta?.content
Embeddingsclient.embeddings.create()client.embeddings.create() (same)
Tool callingIdentical JSON Schema formatIdentical JSON Schema format
JSON moderesponse_format: { type: 'json_object' }responseFormat: { type: 'json_object' }
VisionBase64 in content arraySame approach with pixtral models

Error Handling

IssueCauseSolution
Different output qualityModel differencesAdjust prompts, tune temperature
Embedding dimension mismatch1536 vs 1024Re-embed all vectors, update vector DB config
Missing featureNot supported by MistralImplement fallback in adapter
Cost increaseToken counting differsMonitor and optimize prompts

Resources

Output

  • Integration assessment with effort estimation
  • Provider-agnostic adapter interface
  • Mistral adapter implementation
  • Feature-flag controlled gradual rollout
  • Model mapping and API difference reference
  • A/B validation test suite
  • Rollback procedure (set MISTRAL_ROLLOUT_PERCENT=0)

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

3114

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

4311

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

109

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

1128

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571699

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.