MI

mistral-migration-deep-dive

A guide for migrating AI applications to Mistral AI with adapter patterns.

Install

mkdir -p .claude/skills/mistral-migration-deep-dive && curl -L -o skill.zip "https://agentskills.codes/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

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Execute migration to Mistral AI from OpenAI, Anthropic, or other providers.
75 charsno explicit “when” trigger
Advanced

Key capabilities

  • Assess existing AI integration points for migration to Mistral AI
  • Map models from OpenAI or Anthropic to Mistral AI equivalents
  • Implement a provider-agnostic adapter for AI services
  • Develop a Mistral adapter for chat and embedding functionalities
  • Execute feature-flag controlled gradual rollout of Mistral AI integration
  • Perform A/B validation testing between AI providers

How it works

The skill outlines a migration process starting with an assessment of current AI integration points. It then guides through creating a provider-agnostic adapter and a Mistral-specific adapter, enabling a feature-flag controlled rollout and A/B testing.

Inputs & outputs

You give it
Existing AI integration code (OpenAI, Anthropic) and desired Mistral AI models
You get back
Integration assessment, provider-agnostic adapter, Mistral adapter implementation, feature-flag controlled rollout, and A/B validation test suite

When to use mistral-migration-deep-dive

  • Migrate existing OpenAI integrations to Mistral
  • Refactor code for Mistral AI SDK compatibility
  • Implement adapter patterns for multi-provider AI
  • Plan AI provider rollback procedures

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)

When not to use it

  • When not migrating to Mistral AI
  • When not refactoring existing AI integrations

Prerequisites

Current AI integration documentedMistral AI SDK installed (@mistralai/mistralai)Feature flag infrastructure (env vars or LaunchDarkly)Rollback plan tested

Limitations

  • Requires the Mistral AI SDK to be installed
  • Assumes the presence of feature flag infrastructure
  • Embedding dimension mismatch between providers may require re-embedding all vectors

How it compares

This skill provides a structured, deep-dive approach to migrating AI integrations to Mistral AI using an adapter pattern and feature flags, which is more controlled and less disruptive than a direct, unmanaged switch.

Compared to similar skills

mistral-migration-deep-dive side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
mistral-migration-deep-dive (this skill)024dReviewAdvanced
apollo-upgrade-migration124dCautionIntermediate
exa-migration-deep-dive124dReviewIntermediate
instantly-upgrade-migration124dReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

apollo-upgrade-migration

jeremylongshore

Plan and execute Apollo.io SDK upgrades. Use when upgrading Apollo API versions, migrating to new endpoints, or updating deprecated API usage. Trigger with phrases like "apollo upgrade", "apollo migration", "update apollo api", "apollo breaking changes", "apollo deprecation".

11

exa-migration-deep-dive

jeremylongshore

Execute Exa major re-architecture and migration strategies with strangler fig pattern. Use when migrating to or from Exa, performing major version upgrades, or re-platforming existing integrations to Exa. Trigger with phrases like "migrate exa", "exa migration", "switch to exa", "exa replatform", "exa upgrade major".

10

instantly-upgrade-migration

jeremylongshore

Analyze, plan, and execute Instantly SDK upgrades with breaking change detection. Use when upgrading Instantly SDK versions, detecting deprecations, or migrating to new API versions. Trigger with phrases like "upgrade instantly", "instantly migration", "instantly breaking changes", "update instantly SDK", "analyze instantly version".

10

openrouter-upgrade-migration

jeremylongshore

Execute migrate and upgrade OpenRouter SDK versions safely. Use when updating dependencies or migrating configurations. Trigger with phrases like 'openrouter upgrade', 'openrouter migration', 'update openrouter', 'openrouter breaking changes'.

01

perplexity-upgrade-migration

jeremylongshore

Analyze, plan, and execute Perplexity SDK upgrades with breaking change detection. Use when upgrading Perplexity SDK versions, detecting deprecations, or migrating to new API versions. Trigger with phrases like "upgrade perplexity", "perplexity migration", "perplexity breaking changes", "update perplexity SDK", "analyze perplexity version".

10

aid-update-api

AndreVianna

>

00

Search skills

Search the agent skills registry