mistral-core-workflow-b

2
0
Source

Execute Mistral AI secondary workflows: Embeddings and Function Calling. Use when implementing semantic search, RAG applications, or tool-augmented LLM interactions. Trigger with phrases like "mistral embeddings", "mistral function calling", "mistral tools", "mistral RAG", "mistral semantic search".

Install

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

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

About this skill

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-auth setup
  • MISTRAL_API_KEY environment 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],
    });
    const qVec = qEmbed.data[0].embedding;

    return this.documents
      .map(doc => ({ text: doc.text, score: cosineSimilarity(qVec, doc.embedding) }))
      .sort((a, b) => b.score - a.score)
      .slice(0, topK);
  }
}

Step 4: Function Calling (Tool Use)

// 1. Define tools with JSON Schema
const tools = [
  {
    type: 'function' as const,
    function: {
      name: 'get_weather',
      description: 'Get current weather for a city',
      parameters: {
        type: 'object',
        properties: {
          city: { type: 'string', description: 'City name (e.g., "Paris")' },
          units: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' },
        },
        required: ['city'],
      },
    },
  },
  {
    type: 'function' as const,
    function: {
      name: 'search_database',
      description: 'Search product database by query',
      parameters: {
        type: 'object',
        properties: {
          query: { type: 'string' },
          limit: { type: 'integer', default: 10 },
        },
        required: ['query'],
      },
    },
  },
];

// 2. Send request with tools
const response = await client.chat.complete({
  model: 'mistral-large-latest', // Large recommended for complex tool use
  messages: [{ role: 'user', content: "What's the weather in Paris?" }],
  tools,
  toolChoice: 'auto', // 'auto' | 'any' | 'none'
});

Step 5: Tool Execution Loop

// Tool registry maps function names to implementations
const toolRegistry: Record<string, (args: any) => Promise<any>> = {
  get_weather: async ({ city, units }) => ({ city, temp: 22, units: units ?? 'celsius' }),
  search_database: async ({ query, limit }) => ({ results: [], total: 0 }),
};

async function chatWithTools(userMessage: string): Promise<string> {
  const messages: any[] = [{ role: 'user', content: userMessage }];

  while (true) {
    const response = await client.chat.complete({
      model: 'mistral-large-latest',
      messages,
      tools,
      toolChoice: 'auto',
    });

    const choice = response.choices?.[0];
    if (!choice) throw new Error('No response from model');

    // If model wants to call tools
    if (choice.message.toolCalls?.length) {
      messages.push(choice.message); // Add assistant message with tool_calls

      for (const call of choice.message.toolCalls) {
        const fn = toolRegistry[call.function.name];
        if (!fn) throw new Error(`Unknown tool: ${call.function.name}`);

        const args = JSON.parse(call.function.arguments);
        const result = await fn(args);

        messages.push({
          role: 'tool',
          name: call.function.name,
          content: JSON.stringify(result),
          toolCallId: call.id,
        });
      }
      continue; // Let model process tool results
    }

    // Model returned final text response
    return choice.message.content ?? '';
  }
}

Step 6: RAG Pipeline (Retrieval-Augmented Generation)

async function ragChat(
  query: string,
  searcher: SemanticSearch,
  topK = 3,
): Promise<{ answer: string; sources: string[] }> {
  // 1. Retrieve relevant documents
  const results = await searcher.search(query, topK);
  const context = results.map((r, i) => `[${i + 1}] ${r.text}`).join('\n\n');

  // 2. Generate answer grounded in context
  const response = await client.chat.complete({
    model: 'mistral-small-latest',
    messages: [
      {
        role: 'system',
        content: `Answer based ONLY on the provided context. Cite sources as [1], [2], etc. If the context doesn't contain the answer, say "I don't have enough information."`,
      },
      {
        role: 'user',
        content: `Context:\n${context}\n\nQuestion: ${query}`,
      },
    ],
    temperature: 0.1,
  });

  return {
    answer: response.choices?.[0]?.message?.content ?? '',
    sources: results.map(r => r.text),
  };
}

Output

  • Text embeddings with mistral-embed (1024 dimensions)
  • Semantic search with cosine similarity ranking
  • Function calling with tool execution loop
  • RAG pipeline combining retrieval and generation

Error Handling

IssueCauseResolution
Empty embeddingsInvalid input textValidate non-empty strings before API call
Tool not foundUnknown function nameCheck tool registry matches tool definitions
Infinite tool loopModel keeps calling toolsAdd max iteration count (e.g., 10)
RAG hallucinationInsufficient contextAdd more documents, increase topK
400 Bad RequestMissing toolCallIdEach tool result must include the matching toolCallId

Resources

Next Steps

For SDK patterns, see mistral-sdk-patterns. For agents, see mistral-webhooks-events.

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.

6532

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.

9029

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

15922

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.

4915

designing-database-schemas

jeremylongshore

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

12014

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.

5110

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,4071,302

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,2201,024

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

9001,013

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.

958658

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.

970608

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,033496

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.