mistral-core-workflow-a

0
1
Source

Execute Mistral AI primary workflow: Chat Completions and Streaming. Use when implementing chat interfaces, building conversational AI, or integrating Mistral for text generation. Trigger with phrases like "mistral chat", "mistral completion", "mistral streaming", "mistral conversation".

Install

mkdir -p .claude/skills/mistral-core-workflow-a && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4744" && unzip -o skill.zip -d .claude/skills/mistral-core-workflow-a && rm skill.zip

Installs to .claude/skills/mistral-core-workflow-a

About this skill

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-auth setup
  • MISTRAL_API_KEY environment 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;
      onChunk(text);
    }
  }
  return full;
}

// Express.js SSE endpoint
app.post('/chat/stream', async (req, res) => {
  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');

  const stream = await client.chat.stream({
    model: 'mistral-small-latest',
    messages: req.body.messages,
  });

  for await (const event of stream) {
    const content = event.data?.choices?.[0]?.delta?.content;
    if (content) {
      res.write(`data: ${JSON.stringify({ content })}\n\n`);
    }
  }
  res.write('data: [DONE]\n\n');
  res.end();
});

Step 4: JSON Mode and JSON Schema Mode

// JSON mode — model returns valid JSON
const jsonResponse = await client.chat.complete({
  model: 'mistral-small-latest',
  messages: [
    { role: 'user', content: 'List 3 countries with capitals as JSON array.' },
  ],
  responseFormat: { type: 'json_object' },
});
const data = JSON.parse(jsonResponse.choices?.[0]?.message?.content ?? '{}');

// JSON Schema mode — guarantees structure conformance
const schemaResponse = await client.chat.complete({
  model: 'mistral-small-latest',
  messages: [
    { role: 'user', content: 'Classify this ticket: "Login page crashes on mobile"' },
  ],
  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' },
        },
        required: ['category', 'severity', 'summary'],
      },
    },
  },
});

Step 5: Guardrails and Moderation

// Built-in safe_prompt flag — injects safety system prompt
const safeResponse = await client.chat.complete({
  model: 'mistral-small-latest',
  messages: [{ role: 'user', content: userInput }],
  safePrompt: true,
});

// Dedicated moderation API — classify text against policy categories
const moderation = await client.classifiers.moderate({
  model: 'mistral-moderation-latest',
  inputs: [userInput],
});

const flagged = moderation.results[0].categories;
// Check: flagged.sexual, flagged.hate_and_discrimination, flagged.violence, etc.
if (Object.values(flagged).some(Boolean)) {
  throw new Error('Content flagged by moderation');
}

Step 6: Model Selection Guide

type UseCase = 'realtime' | 'analysis' | 'code' | 'vision' | 'embedding';

const MODEL_MAP: Record<UseCase, { model: string; note: string }> = {
  realtime:  { model: 'mistral-small-latest',   note: '256k ctx, fast, $0.1/M in' },
  analysis:  { model: 'mistral-large-latest',   note: '256k ctx, reasoning, $0.5/M in' },
  code:      { model: 'codestral-latest',        note: '256k ctx, code + FIM, $0.3/M in' },
  vision:    { model: 'pixtral-large-latest',    note: '128k ctx, multimodal' },
  embedding: { model: 'mistral-embed',           note: '1024-dim vectors, $0.1/M in' },
};

function selectModel(use: UseCase): string {
  return MODEL_MAP[use].model;
}

Output

  • Chat completions with configurable parameters
  • Multi-turn conversation management with history trimming
  • Real-time streaming responses
  • JSON and JSON Schema structured output
  • Content moderation via guardrails

Error Handling

ErrorCauseSolution
401 UnauthorizedInvalid API keyVerify MISTRAL_API_KEY
429 Rate LimitedRPM or TPM exceededImplement backoff (see mistral-rate-limits)
400 Bad RequestInvalid model or paramsCheck model ID and message format
Context exceededToo many tokensTrim conversation history
Empty JSON responseMissing instructionTell model to respond in JSON in prompt

Resources

Next Steps

For embeddings and function calling, see mistral-core-workflow-b.

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.

10735

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.

8833

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".

18728

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.

5519

designing-database-schemas

jeremylongshore

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

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

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.

1,6791,424

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."

1,2561,315

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.

1,5251,142

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.

1,347807

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.

1,260725

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,465674