---
name: mistral-core-workflow-b-5fd6c7638f57
description: |
  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".
allowed-tools: Read, Write, Edit, Bash(npm:*), Grep
version: 1.0.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
---

# Mistral AI Core Workflow B: Embeddings & Function Calling

## Overview
Secondary workflows for Mistral AI: Text embeddings for semantic search and function calling for tool use.

## Prerequisites
- Completed `mistral-install-auth` setup
- Familiarity with `mistral-core-workflow-a`
- Valid API credentials configured

## Embeddings

### Step 1: Generate Text Embeddings

```typescript
import Mistral from '@mistralai/mistralai';

const client = new Mistral({
  apiKey: process.env.MISTRAL_API_KEY,
});

async function getEmbedding(text: string): Promise<number[]> {
  const response = await client.embeddings.create({
    model: 'mistral-embed',
    inputs: [text],
  });

  return response.data[0].embedding;
}

// Usage
const embedding = await getEmbedding('Machine learning is fascinating.');
console.log(`Embedding dimensions: ${embedding.length}`); // 1024
```

### Step 2: Batch Embeddings

```typescript
async function getBatchEmbeddings(texts: string[]): Promise<number[][]> {
  const response = await client.embeddings.create({
    model: 'mistral-embed',
    inputs: texts,
  });

  return response.data.map(d => d.embedding);
}

// Usage
const documents = [
  'Python is a programming language.',
  'JavaScript runs in browsers.',
  'Rust is memory safe.',
];
const embeddings = await getBatchEmbeddings(documents);
```

### Step 3: Semantic Search Implementation

```typescript
function cosineSimilarity(a: number[], b: number[]): number {
  let dotProduct = 0;
  let normA = 0;
  let normB = 0;

  for (let i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }

  return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}

interface Document {
  id: string;
  text: string;
  embedding?: number[];
}

class SemanticSearch {
  private documents: Document[] = [];
  private client: Mistral;

  constructor() {
    this.client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
  }

  async indexDocuments(docs: Omit<Document, 'embedding'>[]): Promise<void> {
    const texts = docs.map(d => d.text);
    const response = await this.client.embeddings.create({
      model: 'mistral-embed',
      inputs: texts,
    });

    this.documents = docs.map((doc, i) => ({
      ...doc,
      embedding: response.data[i].embedding,
    }));
  }

  async search(query: string, topK = 5): Promise<Array<Document & { score: number }>> {
    const queryEmbedding = await this.getEmbedding(query);

    const results = this.documents
      .map(doc => ({
        ...doc,
        score: cosineSimilarity(queryEmbedding, doc.embedding!),
      }))
      .sort((a, b) => b.score - a.score)
      .slice(0, topK);

    return results;
  }

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

// Usage
const search = new SemanticSearch();
await search.indexDocuments([
  { id: '1', text: 'How to bake chocolate chip cookies' },
  { id: '2', text: 'Machine learning fundamentals' },
  { id: '3', text: 'Best practices for React development' },
]);

const results = await search.search('AI tutorials', 2);
// Returns documents sorted by semantic similarity
```

## Function Calling

### Step 4: Define Tools

```typescript
interface Tool {
  type: 'function';
  function: {
    name: string;
    description: string;
    parameters: {
      type: 'object';
      properties: Record<string, { type: string; description: string }>;
      required: string[];
    };
  };
}

const tools: Tool[] = [
  {
    type: 'function',
    function: {
      name: 'get_weather',
      description: 'Get the current weather for a location',
      parameters: {
        type: 'object',
        properties: {
          location: {
            type: 'string',
            description: 'City and country, e.g., "London, UK"',
          },
          unit: {
            type: 'string',
            description: 'Temperature unit: "celsius" or "fahrenheit"',
          },
        },
        required: ['location'],
      },
    },
  },
  {
    type: 'function',
    function: {
      name: 'search_web',
      description: 'Search the web for information',
      parameters: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'The search query',
          },
        },
        required: ['query'],
      },
    },
  },
];
```

### Step 5: Implement Function Calling Loop

```typescript
import Mistral from '@mistralai/mistralai';

const client = new Mistral({
  apiKey: process.env.MISTRAL_API_KEY,
});

// Tool implementations
const toolFunctions: Record<string, (args: any) => Promise<string>> = {
  get_weather: async ({ location, unit = 'celsius' }) => {
    // Simulated weather API call
    return JSON.stringify({
      location,
      temperature: unit === 'celsius' ? 22 : 72,
      unit,
      condition: 'sunny',
    });
  },
  search_web: async ({ query }) => {
    // Simulated web search
    return JSON.stringify({
      results: [
        { title: `Result for: ${query}`, url: 'https://example.com' },
      ],
    });
  },
};

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];
    const assistantMessage = choice?.message;

    if (!assistantMessage) {
      throw new Error('No response from model');
    }

    // Add assistant message to conversation
    messages.push(assistantMessage);

    // Check if model wants to call tools
    const toolCalls = assistantMessage.toolCalls;

    if (!toolCalls || toolCalls.length === 0) {
      // No tool calls, return final response
      return assistantMessage.content ?? '';
    }

    // Execute tool calls
    for (const toolCall of toolCalls) {
      const functionName = toolCall.function.name;
      const functionArgs = JSON.parse(toolCall.function.arguments);

      console.log(`Calling tool: ${functionName}`, functionArgs);

      const toolFn = toolFunctions[functionName];
      if (!toolFn) {
        throw new Error(`Unknown tool: ${functionName}`);
      }

      const result = await toolFn(functionArgs);

      // Add tool result to conversation
      messages.push({
        role: 'tool',
        name: functionName,
        content: result,
        toolCallId: toolCall.id,
      });
    }
  }
}

// Usage
const answer = await chatWithTools('What is the weather in Paris?');
console.log(answer);
// "The current weather in Paris is sunny with a temperature of 22°C."
```

### Step 6: RAG (Retrieval-Augmented Generation)

```typescript
class RAGChat {
  private search: SemanticSearch;
  private client: Mistral;

  constructor() {
    this.search = new SemanticSearch();
    this.client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY });
  }

  async indexKnowledge(documents: { id: string; text: string }[]): Promise<void> {
    await this.search.indexDocuments(documents);
  }

  async chat(userQuery: string): Promise<string> {
    // Retrieve relevant documents
    const relevantDocs = await this.search.search(userQuery, 3);

    // Build context from retrieved documents
    const context = relevantDocs
      .map(doc => `[Source ${doc.id}]: ${doc.text}`)
      .join('\n\n');

    // Generate response with context
    const response = await this.client.chat.complete({
      model: 'mistral-small-latest',
      messages: [
        {
          role: 'system',
          content: `Answer questions based on the provided context. If the answer is not in the context, say so.

Context:
${context}`,
        },
        { role: 'user', content: userQuery },
      ],
    });

    return response.choices?.[0]?.message?.content ?? '';
  }
}

// Usage
const rag = new RAGChat();
await rag.indexKnowledge([
  { id: '1', text: 'Mistral AI was founded in 2023 in Paris, France.' },
  { id: '2', text: 'The mistral-embed model produces 1024-dimensional vectors.' },
]);

const answer = await rag.chat('When was Mistral AI founded?');
```

## Output
- Text embeddings (1024 dimensions)
- Semantic search implementation
- Function calling with tool execution
- RAG chat with retrieval

## Error Handling
| Aspect | Workflow A | Workflow B |
|--------|------------|------------|
| Use Case | Chat/Text Generation | Embeddings/Tools |
| Models | All chat models | mistral-embed + large |
| Complexity | Lower | Medium-Higher |
| Latency | Depends on tokens | Batching helps |

## Examples

### Python Embeddings
```python
import os
from mistralai import Mistral

client = Mistral(api_key=os.environ.get("MISTRAL_API_KEY"))

def get_embeddings(texts: list[str]) -> list[list[float]]:
    response = client.embeddings.create(
        model="mistral-embed",
        inputs=texts,
    )
    return [d.embedding for d in response.data]
```

### Python Function Calling
```python
import json
from mistralai import Mistral

client = Mistral(api_key=os.environ.get("MISTRAL_API_KEY"))

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.complete(
    model="mistral-large-latest",
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=tools,
    tool_choice="auto"
)
```

## Resources
- [Mistral AI Embeddings](https://docs.mistral.ai/capabilities/embeddings/)
- [Mistral AI Function Calling](https://docs.mistral.ai/capabilities/function_calling/)
- [Mistral AI Agents](https://docs.mistral.ai/capabilities/agents/)

## Next Steps
For common errors, see `mistral-common-errors`.


---
Source attribution: Dicklesworthstone
Original project: https://github.com/Dicklesworthstone/pi_agent_rust/blob/f28fc46ee0db8e710d95b8b55592cd38d60f2b26/tests/ext_conformance/artifacts/plugins-community/plugins/saas-packs/mistral-pack/skills/mistral-core-workflow-b/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Dave AI.

## Upstream license notice

MIT License (with OpenAI/Anthropic Rider)

Copyright (c) 2026 Jeffrey Emanuel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

ADDITIONAL RIDER / RESTRICTION (OpenAI / Anthropic):

This rider is part of the "conditions" of this License. In the event of any
conflict between this rider and any other portion of this License, this rider
controls.

"Restricted Parties" means OpenAI, L.L.C.; Anthropic, PBC; any of their
respective Affiliates; and any person or entity acting directly or indirectly
on behalf of, for the benefit of, or under the direction of any of the
foregoing (including any officer, director, employee, contractor, agent,
consultant, service provider, or representative).

Notwithstanding any other provision of this License, no rights are granted to
any Restricted Party. Any purported license, sublicense, assignment, transfer,
or other permission to any Restricted Party is null and void absent the
express prior written permission of Jeffrey Emanuel.

You may not provide, disclose, distribute, sublicense, sell, lease, lend,
host, make available, or otherwise permit access to the Software or any
derivative work of the Software (as defined in applicable copyright law)
(collectively, "Derivative Works") to or for any Restricted Party.

For purposes of this rider, "use" includes, without limitation: copying,
modifying, merging, publishing, distributing, sublicensing, selling,
transferring, making available, hosting, deploying, executing, benchmarking,
testing, analyzing, indexing, or incorporating the Software or any Derivative
Works into any dataset, training corpus, evaluation harness, or pipeline for
machine learning or other automated systems.

This rider applies to the Software and all Derivative Works. As a condition of
use, you agree that this rider is a precondition to exercising any rights
under this License, and you agree that any distribution of the Software or any
Derivative Works must include this rider provision unmodified.

Any breach of this rider automatically and immediately terminates the
permissions granted by this License. Upon termination, you must immediately
cease all use and distribution of the Software and any Derivative Works and
destroy all copies under your control.

You agree that a breach of this rider would cause irreparable harm and that
Jeffrey Emanuel may seek injunctive or other equitable relief to enforce this
rider, in addition to any other remedies available at law. To the maximum
extent permitted by applicable law, the prevailing party in any action to
enforce this rider shall be entitled to recover reasonable attorneys' fees and
costs.

For purposes of this rider, "Affiliate" means any entity that directly or
indirectly controls, is controlled by, or is under common control with the
specified party. "Control" means ownership of more than 50% of the voting
securities or other ownership interest, or the power to direct management or
policies by contract or otherwise.

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



# Dave AI resource metadata

Creator / publisher: Dicklesworthstone
Original project: https://github.com/Dicklesworthstone/pi_agent_rust/blob/f28fc46ee0db8e710d95b8b55592cd38d60f2b26/tests/ext_conformance/artifacts/plugins-community/plugins/saas-packs/mistral-pack/skills/mistral-core-workflow-b/SKILL.md
Attribution basis: Source repository record

Fields of work: Data & Analytics, Development & Engineering
Roles: Backend Developer, Data Scientist, ML / AI Engineer
Specialties: API, Backend
Tools: Mistral
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: cd8c02b3a7cecf1b314c6cf70f138f079d1b3862dd485c56ac22ae39a8dc0f43
