---
name: mistral-sdk-patterns-6de74ba49f6d
description: |
  Apply production-ready Mistral AI SDK patterns for TypeScript and Python.
  Use when implementing Mistral integrations, refactoring SDK usage,
  or establishing team coding standards for Mistral AI.
  Trigger with phrases like "mistral SDK patterns", "mistral best practices",
  "mistral code patterns", "idiomatic mistral".
allowed-tools: Read, Write, Edit
version: 1.0.0
license: MIT
author: Jeremy Longshore <jeremy@intentsolutions.io>
---

# Mistral AI SDK Patterns

## Overview
Production-ready patterns for Mistral AI SDK usage in TypeScript and Python.

## Prerequisites
- Completed `mistral-install-auth` setup
- Familiarity with async/await patterns
- Understanding of error handling best practices

## Instructions

### Step 1: Implement Singleton Pattern (Recommended)

**TypeScript**
```typescript
// src/mistral/client.ts
import Mistral from '@mistralai/mistralai';

let instance: Mistral | null = null;

export interface MistralConfig {
  apiKey: string;
  timeout?: number;
  maxRetries?: number;
}

export function getMistralClient(config?: Partial<MistralConfig>): Mistral {
  if (!instance) {
    const apiKey = config?.apiKey || process.env.MISTRAL_API_KEY;
    if (!apiKey) {
      throw new Error('MISTRAL_API_KEY is required');
    }
    instance = new Mistral({
      apiKey,
      timeout: config?.timeout ?? 30000,
    });
  }
  return instance;
}

// For testing - reset singleton
export function resetMistralClient(): void {
  instance = null;
}
```

**Python**
```python
# src/mistral/client.py
import os
from mistralai import Mistral
from typing import Optional

_instance: Optional[Mistral] = None

def get_mistral_client(api_key: Optional[str] = None) -> Mistral:
    global _instance
    if _instance is None:
        key = api_key or os.environ.get("MISTRAL_API_KEY")
        if not key:
            raise ValueError("MISTRAL_API_KEY is required")
        _instance = Mistral(api_key=key)
    return _instance

def reset_mistral_client() -> None:
    global _instance
    _instance = None
```

### Step 2: Add Error Handling Wrapper

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

interface MistralResult<T> {
  data: T | null;
  error: Error | null;
  usage?: { promptTokens: number; completionTokens: number; totalTokens: number };
}

async function safeMistralCall<T>(
  operation: () => Promise<T>
): Promise<MistralResult<T>> {
  try {
    const data = await operation();
    return { data, error: null };
  } catch (err) {
    const error = err as Error;
    console.error({
      name: error.name,
      message: error.message,
      // Extract status code if available
      status: (err as any).status,
    });
    return { data: null, error };
  }
}

// Usage
const result = await safeMistralCall(() =>
  client.chat.complete({
    model: 'mistral-small-latest',
    messages: [{ role: 'user', content: 'Hello!' }],
  })
);

if (result.error) {
  console.error('Chat failed:', result.error.message);
} else {
  console.log(result.data?.choices?.[0]?.message?.content);
}
```

### Step 3: Implement Retry Logic with Exponential Backoff

```typescript
interface RetryConfig {
  maxRetries: number;
  baseDelayMs: number;
  maxDelayMs: number;
  jitterMs: number;
}

async function withRetry<T>(
  operation: () => Promise<T>,
  config: RetryConfig = { maxRetries: 3, baseDelayMs: 1000, maxDelayMs: 32000, jitterMs: 500 }
): Promise<T> {
  for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
    try {
      return await operation();
    } catch (err) {
      if (attempt === config.maxRetries) throw err;

      const status = (err as any).status;
      // Only retry on rate limits (429) or server errors (5xx)
      if (status !== 429 && (status < 500 || status >= 600)) throw err;

      const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);
      const jitter = Math.random() * config.jitterMs;
      const delay = Math.min(exponentialDelay + jitter, config.maxDelayMs);

      console.log(`Attempt ${attempt + 1} failed. Retrying in ${delay.toFixed(0)}ms...`);
      await new Promise(r => setTimeout(r, delay));
    }
  }
  throw new Error('Unreachable');
}
```

### Step 4: Type-Safe Chat Wrapper

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

type MistralModel =
  | 'mistral-large-latest'
  | 'mistral-medium-latest'
  | 'mistral-small-latest'
  | 'open-mistral-7b'
  | 'open-mixtral-8x7b';

interface ChatOptions {
  model?: MistralModel;
  temperature?: number;
  maxTokens?: number;
  topP?: number;
  stream?: boolean;
}

interface Message {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

export async function chat(
  client: Mistral,
  messages: Message[],
  options: ChatOptions = {}
): Promise<string> {
  const response = await client.chat.complete({
    model: options.model ?? 'mistral-small-latest',
    messages,
    temperature: options.temperature,
    maxTokens: options.maxTokens,
    topP: options.topP,
  });

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

### Step 5: Streaming Helper

```typescript
export async function* streamChat(
  client: Mistral,
  messages: Message[],
  options: ChatOptions = {}
): AsyncGenerator<string, void, unknown> {
  const stream = await client.chat.stream({
    model: options.model ?? 'mistral-small-latest',
    messages,
    temperature: options.temperature,
    maxTokens: options.maxTokens,
  });

  for await (const event of stream) {
    const content = event.data?.choices?.[0]?.delta?.content;
    if (content) {
      yield content;
    }
  }
}

// Usage
for await (const chunk of streamChat(client, messages)) {
  process.stdout.write(chunk);
}
```

## Output
- Type-safe client singleton
- Robust error handling with structured logging
- Automatic retry with exponential backoff
- Streaming support with async generators

## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| Safe wrapper | All API calls | Prevents uncaught exceptions |
| Retry logic | Transient failures | Improves reliability |
| Type guards | Response validation | Catches API changes |
| Logging | All operations | Debugging and monitoring |

## Examples

### Factory Pattern (Multi-tenant)
```typescript
const clients = new Map<string, Mistral>();

export function getClientForTenant(tenantId: string): Mistral {
  if (!clients.has(tenantId)) {
    const apiKey = getTenantApiKey(tenantId);
    clients.set(tenantId, new Mistral({ apiKey }));
  }
  return clients.get(tenantId)!;
}
```

### Python Context Manager
```python
from contextlib import contextmanager
from mistralai import Mistral

@contextmanager
def mistral_client():
    client = Mistral(api_key=os.environ.get("MISTRAL_API_KEY"))
    try:
        yield client
    finally:
        pass  # Cleanup if needed

# Usage
with mistral_client() as client:
    response = client.chat.complete(
        model="mistral-small-latest",
        messages=[{"role": "user", "content": "Hello!"}]
    )
```

### Zod Response Validation
```typescript
import { z } from 'zod';

const mistralResponseSchema = z.object({
  id: z.string(),
  object: z.literal('chat.completion'),
  model: z.string(),
  choices: z.array(z.object({
    index: z.number(),
    message: z.object({
      role: z.enum(['assistant']),
      content: z.string(),
    }),
    finishReason: z.string(),
  })),
  usage: z.object({
    promptTokens: z.number(),
    completionTokens: z.number(),
    totalTokens: z.number(),
  }),
});

function validateResponse(response: unknown) {
  return mistralResponseSchema.parse(response);
}
```

## Resources
- [Mistral AI API Reference](https://docs.mistral.ai/api/)
- [Mistral AI Client Libraries](https://docs.mistral.ai/getting-started/clients/)
- [Zod Documentation](https://zod.dev/)

## Next Steps
Apply patterns in `mistral-core-workflow-a` for chat completions.


---
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-sdk-patterns/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Mega AI Hub.

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



# Mega AI Hub 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-sdk-patterns/SKILL.md
Attribution basis: Source repository record

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