| name | mistral-webhooks-events |
| description | Implement event handling patterns for Mistral AI integrations.
Use when building async workflows, implementing queues,
or handling long-running Mistral AI operations.
Trigger with phrases like "mistral events", "mistral async",
"mistral queue", "mistral background jobs", "mistral webhook".
|
| allowed-tools | Read, Write, Edit, Bash(curl:*) |
| version | 1.0.0 |
| license | MIT |
| author | Jeremy Longshore <jeremy@intentsolutions.io> |
Mistral AI Events & Async Patterns
Overview
Implement async patterns and event handling for Mistral AI integrations. Note: Mistral AI does not have native webhooks, so this skill covers async patterns and event-driven architectures.
Prerequisites
- Mistral AI SDK installed
- Queue system (Redis, SQS, etc.) for async processing
- Event emitter or pub/sub for notifications
- Background job processor (BullMQ, etc.)
Instructions
Step 1: Event-Driven Chat Architecture
import { EventEmitter } from 'events';
import Mistral from '@mistralai/mistralai';
interface MistralEvents {
'chat:start': { requestId: string; model: string; timestamp: Date };
'chat:chunk': { requestId: string; content: string; index: number };
'chat:complete': { requestId: string; fullResponse: string; usage: any };
'chat:error': { requestId: string; error: Error };
}
class MistralEventEmitter extends EventEmitter {
private client: Mistral;
constructor() {
super();
this.client = new Mistral({ apiKey: process.env.! });
}
() {
.(, { requestId, model, : () });
{
stream = ...({ model, messages });
fullResponse = ;
index = ;
( event stream) {
content = event.?.?.[]?.?.;
(content) {
fullResponse += content;
.(, { requestId, content, : index++ });
}
}
usage = { : fullResponse. / };
.(, { requestId, fullResponse, usage });
fullResponse;
} (error) {
.(, { requestId, : error });
error;
}
}
}
mistral = ();
mistral.(, {
.();
});
mistral.(, {
process..(content);
});
mistral.(, {
.();
});
mistral.(, {
.(, error.);
});
mistral.(, [{ : , : }]);
Step 2: Background Job Processing with BullMQ
import { Queue, Worker, Job } from 'bullmq';
import Mistral from '@mistralai/mistralai';
import Redis from 'ioredis';
const connection = new Redis(process.env.REDIS_URL);
interface ChatJob {
id: string;
messages: Array<{ role: string; content: string }>;
model: string;
callback?: string;
}
const chatQueue = new Queue<ChatJob>('mistral-chat', { connection });
const chatWorker = new Worker<ChatJob>(
'mistral-chat',
async (job: Job<ChatJob>) => {
const client = new ({ : process..! });
response = client..({
: job..,
: job..,
});
result = {
: job.,
: job..,
: response.?.[]?.?.,
: response.,
: ().(),
};
(job..) {
(job.., {
: ,
: { : },
: .(result),
});
}
result;
},
{
connection,
: ,
: {
: ,
: ,
},
}
);
chatWorker.(, {
.(, result);
});
chatWorker.(, {
.(, err.);
});
() {
body = request.();
job = chatQueue.(, {
: crypto.(),
: body.,
: body. || ,
: body.,
}, {
: ,
: { : , : },
});
.({
: job.,
: ,
: ,
});
}
Step 3: Webhook Notification System
import crypto from 'crypto';
interface WebhookPayload {
event: string;
timestamp: string;
data: any;
}
class WebhookNotifier {
private secret: string;
constructor(secret: string) {
this.secret = secret;
}
private sign(payload: string): string {
return crypto
.createHmac('sha256', this.secret)
.update(payload)
.digest('hex');
}
async notify(url: string, event: string, data: any): Promise<boolean> {
const payload: WebhookPayload = {
event,
timestamp: new Date().toISOString(),
data,
};
const body = .(payload);
signature = .(body);
{
response = (url, {
: ,
: {
: ,
: signature,
: payload.,
},
body,
});
response.;
} (error) {
.(, error);
;
}
}
}
notifier = (process..!);
notifier.(
,
,
{
: ,
: response.?.[]?.?.,
: response.,
}
);
Step 4: Server-Sent Events (SSE) for Real-Time Updates
import Mistral from '@mistralai/mistralai';
export async function POST(request: Request) {
const { messages } = await request.json();
const client = new Mistral({ apiKey: process.env.MISTRAL_API_KEY! });
const stream = await client.chat.stream({
model: 'mistral-small-latest',
messages,
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
controller.enqueue(encoder.encode(`event: start\ndata: {"status":"started"}\n\n`));
try {
let tokenCount = 0;
for await (const event of stream) {
const content = event.data?.choices?.[]?.?.;
(content) {
tokenCount++;
controller.(
encoder.()
);
}
}
controller.(
encoder.()
);
} (: ) {
controller.(
encoder.()
);
}
controller.();
},
});
(readable, {
: {
: ,
: ,
: ,
},
});
}
Step 5: Client-Side SSE Consumption
function streamChat(messages: any[]): EventSource {
const eventSource = new EventSource('/api/chat/stream', {
});
eventSource.addEventListener('start', (e) => {
console.log('Stream started');
});
eventSource.addEventListener('chunk', (e) => {
const { content } = JSON.parse(e.data);
process.stdout.write(content);
});
eventSource.addEventListener('complete', (e) => {
const { totalTokens } = JSON.parse(e.data);
console.log(`\nComplete. Tokens: ${totalTokens}`);
eventSource.close();
});
eventSource.addEventListener('error', (e) => {
console.(, e);
eventSource.();
});
eventSource;
}
Output
- Event-driven Mistral AI integration
- Background job processing
- Webhook notification system
- Real-time streaming with SSE
Error Handling
| Issue | Cause | Solution |
|---|
| Job stuck in queue | Worker crashed | Implement job timeout and retry |
| Webhook failed | Network/auth issue | Retry with exponential backoff |
| SSE disconnected | Client timeout | Implement reconnection logic |
| Event backpressure | Too many events | Implement buffering |
Examples
Python Async Pattern
import asyncio
from mistralai import Mistral
async def process_batch(prompts: list[str]):
client = Mistral(api_key=os.environ.get("MISTRAL_API_KEY"))
async def process_one(prompt: str):
response = await client.chat.complete_async(
model="mistral-small-latest",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
results = await asyncio.gather(*[process_one(p) for p in prompts])
return results
Resources
Next Steps
For performance optimization, see mistral-performance-tuning.