environment-setup-guide
Guide developers through setting up development environments with proper tools, dependencies, and configurations
mistral-performance-tuning
Optimize Mistral AI performance with caching, batching, and latency reduction. Use when experiencing slow API responses, implementing caching strategies, or optimizing request throughput for Mistral AI integrations. Trigger with phrases like "mistral performance", "optimize mistral", "mistral lat...
Full skill instructions
Optimize Mistral AI API performance with caching, batching, and latency reduction techniques.
| Model | P50 | P95 | P99 | Use Case |
|---|---|---|---|---|
| mistral-small-latest | 200ms | 500ms | 1s | Fast responses |
| mistral-large-latest | 500ms | 1.5s | 3s | Complex reasoning |
| mistral-embed | 50ms | 150ms | 300ms | Embeddings |
import { LRUCache } from 'lru-cache';
import crypto from 'crypto';
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 5 * 60 * 1000, // 5 minutes
updateAgeOnGet: true,
});
function getCacheKey(messages: any[], model: string, options?: any): string {
const data = JSON.stringify({ messages, model, options });
return crypto.createHash('sha256').update(data).digest('hex');
}
async function cachedChat(
client: Mistral,
messages: any[],
model: string,
options?: { temperature?: number; maxTokens?: number }
): Promise<string> {
// Only cache deterministic requests (temperature = 0)
const isCacheable = (options?.temperature ?? 0.7) === 0;
if (isCacheable) {
const key = getCacheKey(messages, model, options);
const cached = cache.get(key);
if (cached) {
console.log('Cache hit');
return cached;
}
}
const response = await client.chat.complete({
model,
messages,
...options,
});
const content = response.choices?.[0]?.message?.content ?? '';
if (isCacheable) {
const key = getCacheKey(messages, model, options);
cache.set(key, content);
}
return content;
}
import Redis from 'ioredis';
import crypto from 'crypto';
const redis = new Redis(process.env.REDIS_URL);
async function cachedWithRedis<T>(
key: string,
fetcher: () => Promise<T>,
ttlSeconds = 300
): Promise<T> {
const cached = await redis.get(key);
if (cached) {
return JSON.parse(cached);
}
const result = await fetcher();
await redis.setex(key, ttlSeconds, JSON.stringify(result));
return result;
}
// Semantic cache for similar queries
async function semanticCache(
client: Mistral,
query: string,
threshold = 0.95
): Promise<string | null> {
// Get embedding for query
const queryEmbed = await client.embeddings.create({
model: 'mistral-embed',
inputs: [query],
});
const queryVector = queryEmbed.data[0].embedding;
// Check cache for similar queries
const cachedQueries = await redis.keys('semantic:*');
for (const key of cachedQueries) {
const cached = JSON.parse(await redis.get(key) || '{}');
const similarity = cosineSimilarity(queryVector, cached.embedding);
if (similarity >= threshold) {
console.log(`Semantic cache hit (similarity: ${similarity.toFixed(3)})`);
return cached.response;
}
}
return null;
}
import DataLoader from 'dataloader';
// Batch embedding requests
const embeddingLoader = new DataLoader<string, number[]>(
async (texts) => {
const response = await client.embeddings.create({
model: 'mistral-embed',
inputs: texts as string[],
});
return response.data.map(d => d.embedding);
},
{
maxBatchSize: 100, // Mistral limit
batchScheduleFn: callback => setTimeout(callback, 10), // 10ms window
}
);
// Usage - automatically batched
const [embed1, embed2, embed3] = await Promise.all([
embeddingLoader.load('Text 1'),
embeddingLoader.load('Text 2'),
embeddingLoader.load('Text 3'),
]);
import { Agent } from 'https';
import Mistral from '@mistralai/mistralai';
// Keep-alive connection pooling
const agent = new Agent({
keepAlive: true,
maxSockets: 10,
maxFreeSockets: 5,
timeout: 60000,
});
// Note: Check if Mistral client supports custom agents
// If not, connection pooling happens at the HTTP level
// Streaming reduces Time to First Token (TTFT)
async function* streamWithMetrics(
client: Mistral,
messages: any[],
model: string
): AsyncGenerator<{ content: string; metrics: any }> {
const startTime = Date.now();
let firstTokenTime: number | null = null;
let tokenCount = 0;
const stream = await client.chat.stream({ model, messages });
for await (const event of stream) {
const content = event.data?.choices?.[0]?.delta?.content;
if (content) {
if (!firstTokenTime) {
firstTokenTime = Date.now();
}
tokenCount++;
yield {
content,
metrics: {
ttft: firstTokenTime - startTime,
tokensPerSecond: tokenCount / ((Date.now() - startTime) / 1000),
},
};
}
}
}
// Usage
let fullResponse = '';
for await (const { content, metrics } of streamWithMetrics(client, messages, 'mistral-small-latest')) {
fullResponse += content;
process.stdout.write(content);
}
console.log(`\nTTFT: ${metrics.ttft}ms, Speed: ${metrics.tokensPerSecond.toFixed(1)} tok/s`);
type SpeedTier = 'fastest' | 'balanced' | 'quality';
function selectModelForSpeed(tier: SpeedTier, taskComplexity: 'low' | 'medium' | 'high'): string {
const matrix = {
fastest: {
low: 'mistral-small-latest',
medium: 'mistral-small-latest',
high: 'mistral-small-latest',
},
balanced: {
low: 'mistral-small-latest',
medium: 'mistral-small-latest',
high: 'mistral-large-latest',
},
quality: {
low: 'mistral-small-latest',
medium: 'mistral-large-latest',
high: 'mistral-large-latest',
},
};
return matrix[tier][taskComplexity];
}
interface PerformanceMetrics {
model: string;
latencyMs: number;
ttftMs?: number;
tokensPerSecond?: number;
inputTokens: number;
outputTokens: number;
cached: boolean;
}
async function measurePerformance(
operation: () => Promise<any>,
metadata: Partial<PerformanceMetrics>
): Promise<{ result: any; metrics: PerformanceMetrics }> {
const start = Date.now();
const result = await operation();
const metrics: PerformanceMetrics = {
model: metadata.model || 'unknown',
latencyMs: Date.now() - start,
inputTokens: result.usage?.promptTokens || 0,
outputTokens: result.usage?.completionTokens || 0,
cached: metadata.cached || false,
...metadata,
};
// Log to monitoring system
console.log('[PERF]', JSON.stringify(metrics));
return { result, metrics };
}
// Usage
const { result, metrics } = await measurePerformance(
() => client.chat.complete({ model, messages }),
{ model, cached: false }
);
| Issue | Cause | Solution |
|---|---|---|
| Cache miss storm | TTL expired | Use stale-while-revalidate |
| Batch timeout | Too many items | Reduce batch size |
| Memory pressure | Cache too large | Set max cache entries |
| Slow TTFT | Large prompts | Reduce prompt size or use smaller model |
const withPerformance = async <T>(
name: string,
fn: () => Promise<T>
): Promise<T> => {
const start = Date.now();
const result = await fn();
console.log(`[${name}] ${Date.now() - start}ms`);
return result;
};
// Usage
const response = await withPerformance('chat', () =>
client.chat.complete({ model, messages })
);
import pLimit from 'p-limit';
const limit = pLimit(5); // Max 5 concurrent requests
const results = await Promise.all(
prompts.map(prompt =>
limit(() => client.chat.complete({
model: 'mistral-small-latest',
messages: [{ role: 'user', content: prompt }],
}))
)
);
For cost optimization, see mistral-cost-tuning.
Guide developers through setting up development environments with proper tools, dependencies, and configurations
Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...
Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".
Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.
Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...
Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".
Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".
Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.
Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...
Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.
Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...
Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience