MI

mistral-reference-architecture

Best-practice project layout and architecture patterns for Mistral AI apps.

Install

mkdir -p .claude/skills/mistral-reference-architecture && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/4785" && unzip -o skill.zip -d .claude/skills/mistral-reference-architecture && rm skill.zip

Installs to .claude/skills/mistral-reference-architecture

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.

Implement Mistral AI reference architecture with best-practice project
70 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Implement layered project architecture
  • Configure Zod-validated environment variables
  • Manage singleton Mistral client instances
  • Define custom error classes with retry logic
  • Implement service-layer caching for deterministic requests
  • Create reusable prompt templates

How it works

It organizes code into distinct layers including API, Service, Mistral, and Infrastructure, using a singleton client and Zod for configuration validation.

Inputs & outputs

You give it
Configuration environment variables and service logic
You get back
A structured, production-ready project directory

When to use mistral-reference-architecture

  • Structuring new AI projects
  • Standardizing error handling
  • Configuring service layers
  • Designing production-grade integrations

About this skill

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/mistralai SDK
  • zod for 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(): MistralConfig {
  if (!_config) loadConfig();
  return _config!;
}

export function resetClient(): void {
  _client = null;
  _config = null;
}

Step 4: Custom Error Classes

// src/mistral/errors.ts
export type MistralErrorCode =
  | 'AUTH_ERROR'
  | 'RATE_LIMIT'
  | 'BAD_REQUEST'
  | 'SERVICE_ERROR'
  | 'TIMEOUT'
  | 'CONTEXT_OVERFLOW';

export class MistralServiceError extends Error {
  constructor(
    message: string,
    public readonly code: MistralErrorCode,
    public readonly status: number,
    public readonly retryable: boolean,
  ) {
    super(message);
    this.name = 'MistralServiceError';
  }

  static fromApiError(error: any): MistralServiceError {
    const status = error.status ?? error.statusCode ?? 500;
    if (status === 401) return new MistralServiceError('Authentication failed', 'AUTH_ERROR', 401, false);
    if (status === 429) return new MistralServiceError('Rate limit exceeded', 'RATE_LIMIT', 429, true);
    if (status === 400) return new MistralServiceError(error.message, 'BAD_REQUEST', 400, false);
    if (status >= 500) return new MistralServiceError('Service error', 'SERVICE_ERROR', status, true);
    return new MistralServiceError(error.message, 'SERVICE_ERROR', status, false);
  }
}

Step 5: Service Layer with Caching

// src/services/chat.service.ts
import { createHash } from 'crypto';
import { LRUCache } from 'lru-cache';
import { getMistralClient, getConfig } from '../mistral/client.js';
import { MistralServiceError } from '../mistral/errors.js';

const cache = new LRUCache<string, any>({ max: 5000, ttl: 3_600_000 });

export class ChatService {
  async complete(messages: any[], options?: {
    model?: string;
    temperature?: number;
    maxTokens?: number;
  }) {
    const config = getConfig();
    const model = options?.model ?? config.defaultModel;
    const temperature = options?.temperature ?? 0.7;

    // Cache deterministic requests
    if (temperature === 0 && config.cache.enabled) {
      const key = createHash('sha256').update(JSON.stringify({ model, messages })).digest('hex');
      const cached = cache.get(key);
      if (cached) return cached;

      const result = await this.executeChat(model, messages, { ...options, temperature: 0 });
      cache.set(key, result);
      return result;
    }

    return this.executeChat(model, messages, options);
  }

  async *stream(messages: any[], model?: string) {
    const client = getMistralClient();
    try {
      const stream = await client.chat.stream({
        model: model ?? getConfig().defaultModel,
        messages,
      });
      for await (const event of stream) {
        const text = event.data?.choices?.[0]?.delta?.content;
        if (text) yield text;
      }
    } catch (error: any) {
      throw MistralServiceError.fromApiError(error);
    }
  }

  private async executeChat(model: string, messages: any[], options: any = {}) {
    const client = getMistralClient();
    try {
      return await client.chat.complete({ model, messages, ...options });
    } catch (error: any) {
      throw MistralServiceError.fromApiError(error);
    }
  }
}

Step 6: Health Check

// src/api/health.route.ts
import { getMistralClient } from '../mistral/client.js';

export async function checkMistralHealth() {
  const start = performance.now();
  try {
    const client = getMistralClient();
    const models = await client.models.list();
    const latencyMs = Math.round(performance.now() - start);

    return {
      status: latencyMs > 5000 ? 'degraded' : 'healthy',
      latencyMs,
      modelCount: models.data?.length ?? 0,
    };
  } catch (error: any) {
    return {
      status: 'unhealthy',
      latencyMs: Math.round(performance.now() - start),
      error: error.message,
    };
  }
}

Step 7: Prompt Templates

// src/mistral/prompts.ts
interface PromptTemplate {
  name: string;
  system: string;
  userTemplate: (input: string) => string;
  model: string;
  maxTokens: number;
}

export const PROMPTS: Record<string, PromptTemplate> = {
  summarize: {
    name: 'summarize',
    system: 'Summarize the text in 2-3 sentences. Be factual and concise.',
    userTemplate: (text) => `Summarize:\n\n${text}`,
    model: 'mistral-small-latest',
    maxTokens: 200,
  },
  classify: {
    name: 'classify',
    system: 'Classify the input. Reply with one word only.',
    userTemplate: (text) => text,
    model: 'mistral-small-latest',
    maxTokens: 10,
  },
  codeReview: {
    name: 'codeReview',
    system: 'Review code for bugs, security issues, and improvements. Be specific.',
    userTemplate: (code) => `Review this code:\n\`\`\`\n${code}\n\`\`\``,
    model: 'mistral-large-latest',
    maxTokens: 1000,
  },
};

Error Handling

IssueCauseResolution
Config validation errorMissing/invalid env varsCheck Zod error message
Rate limit (429)RPM/TPM exceededMistralServiceError has retryable: true
Auth error (401)Invalid API keyNot retryable, check credentials
Cache ineffectiveHigh temperatureOnly cache temperature=0 requests

Resources

Output

  • Layered directory structure with clear separation
  • Zod-validated configuration from environment
  • Singleton client with lazy initialization
  • Custom error classes with retryability
  • Service layer with caching and streaming
  • Health check endpoint
  • Reusable prompt templates

When not to use it

  • High-temperature requests that are non-deterministic
  • Applications requiring non-TypeScript environments
  • Projects not utilizing the Mistral AI SDK

Prerequisites

TypeScript/Node.js project (ESM)@mistralai/mistralai SDKzodVitest

Limitations

  • Caching is only effective for temperature=0 requests
  • Requires manual configuration of environment variables

How it compares

It enforces a strict layered architecture and centralized error handling instead of ad-hoc integration scripts.

Compared to similar skills

mistral-reference-architecture side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
mistral-reference-architecture (this skill)127dReviewIntermediate
mcp-builder1363moReviewAdvanced
architecture-patterns552moNo flagsAdvanced
nodejs-best-practices286moNo flagsAdvanced

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

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

architecture-patterns

wshobson

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.

55214

nodejs-best-practices

davila7

Node.js development principles and decision-making. Framework selection, async patterns, security, and architecture. Teaches thinking, not copying.

28120

senior-fullstack

davila7

Comprehensive fullstack development skill for building complete web applications with React, Next.js, Node.js, GraphQL, and PostgreSQL. Includes project scaffolding, code quality analysis, architecture patterns, and complete tech stack guidance. Use when building new projects, analyzing code quality, implementing design patterns, or setting up development workflows.

35110

workflow-orchestration-patterns

wshobson

Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.

10117

langchain-architecture

wshobson

Design LLM applications using the LangChain framework with agents, memory, and tool integration patterns. Use when building LangChain applications, implementing AI agents, or creating complex LLM workflows.

899

Search skills

Search the agent skills registry