| name | mistral-core-workflow-b |
| 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
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;
}
const embedding = await getEmbedding('Machine learning is fascinating.');
console.log(`Embedding dimensions: ${embedding.length}`);
Step 2: Batch Embeddings
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);
}
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
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<, >[]): <> {
texts = docs.( d.);
response = ...({
: ,
: texts,
});
. = docs.( ({
...doc,
: response.[i].,
}));
}
(: , topK = ): << & { : }>> {
queryEmbedding = .(query);
results = .
.( ({
...doc,
: (queryEmbedding, doc.!),
}))
.( b. - a.)
.(, topK);
results;
}
(: ): <[]> {
response = ...({
: ,
: [text],
});
response.[].;
}
}
search = ();
search.([
{ : , : },
{ : , : },
{ : , : },
]);
results = search.(, );
Function Calling
Step 4: Define Tools
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: {
: ,
: ,
: {
: ,
: {
: {
: ,
: ,
},
},
: [],
},
},
},
];
Step 5: Implement Function Calling Loop
import Mistral from '@mistralai/mistralai';
const client = new Mistral({
apiKey: process.env.MISTRAL_API_KEY,
});
const toolFunctions: Record<string, (args: any) => Promise<string>> = {
get_weather: async ({ location, unit = 'celsius' }) => {
return JSON.stringify({
location,
temperature: unit === 'celsius' ? 22 : 72,
unit,
condition: 'sunny',
});
},
search_web: async ({ query }) => {
return JSON.stringify({
results: [
{ title: `Result for: ${query}`, url: 'https://example.com' },
],
});
},
};
async function chatWithTools(userMessage: ): <> {
: [] = [
{ : , : userMessage },
];
() {
response = client..({
: ,
messages,
tools,
: ,
});
choice = response.?.[];
assistantMessage = choice?.;
(!assistantMessage) {
();
}
messages.(assistantMessage);
toolCalls = assistantMessage.;
(!toolCalls || toolCalls. === ) {
assistantMessage. ?? ;
}
( toolCall toolCalls) {
functionName = toolCall..;
functionArgs = .(toolCall..);
.(, functionArgs);
toolFn = toolFunctions[functionName];
(!toolFn) {
();
}
result = (functionArgs);
messages.({
: ,
: functionName,
: result,
: toolCall.,
});
}
}
}
answer = ();
.(answer);
Step 6: RAG (Retrieval-Augmented Generation)
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> {
const relevantDocs = await this.search.search(userQuery, 3);
const context = relevantDocs
.map( => )
.();
response = ...({
: ,
: [
{
: ,
: ,
},
{ : , : userQuery },
],
});
response.?.[]?.?. ?? ;
}
}
rag = ();
rag.([
{ : , : },
{ : , : },
]);
answer = rag.();
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
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
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
Next Steps
For common errors, see mistral-common-errors.