Skip to content
mistral-data-handling logo

Mistral AI Data Handling

mistral-data-handling

Implement Mistral AI PII handling, data retention, and GDPR/CCPA compliance patterns. Use when handling sensitive data, implementing data redaction, configuring retention policies, or ensuring compliance with privacy regulations for Mistral AI integrations. Trigger with phrases like "mistral data...

SKILL.md

Full skill instructions

Mistral AI Data Handling

Overview

Handle sensitive data correctly when integrating with Mistral AI, ensuring privacy compliance.

Prerequisites

  • Understanding of GDPR/​CCPA requirements
  • Mistral AI SDK installed
  • Database for audit logging
  • Understanding of Mistral's data handling policies

Mistral AI Data Policies

Key Points:

  • Mistral AI does NOT use customer data for training (by default)
  • API data is retained for 30 days for abuse monitoring
  • Enterprise plans offer data processing agreements (DPAs)
  • Check current policies at docs.mistral.ai

Instructions

Step 1: Data Classification

CategoryExamplesHandling
PIIEmail, name, phone, SSNRedact before sending
SensitiveMedical, financialAnonymize or don't send
CredentialsAPI keys, passwordsNEVER send
BusinessInternal dataConsider anonymization
PublicProduct names, general infoSafe to send

Step 2: PII Detection

interface PIIMatch {
  type: string;
  match: string;
  start: number;
  end: number;
}

const PII_PATTERNS: Array<{ type: string; regex: RegExp }> = [
  { type: 'email', regex: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/​g },
  { type: 'phone', regex: /\b(\+?1[-.]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/​g },
  { type: 'ssn', regex: /\b\d{3}-\d{2}-\d{4}\b/​g },
  { type: 'credit_card', regex: /\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/​g },
  { type: 'ip_address', regex: /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/​g },
  { type: 'date_of_birth', regex: /\b(0[1-9]|1[0-2])[\/\-](0[1-9]|[12]\d|3[01])[\/\-](19|20)\d{2}\b/​g },
];

function detectPII(text: string): PIIMatch[] {
  const findings: PIIMatch[] = [];

  for (const { type, regex } of PII_PATTERNS) {
    // Reset regex state
    regex.lastIndex = 0;
    let match;
    while ((match = regex.exec(text)) !== null) {
      findings.push({
        type,
        match: match[0],
        start: match.index,
        end: match.index + match[0].length,
      });
    }
  }

  return findings;
}

// Usage
const text = 'Contact John at [email protected] or 555-123-4567';
const pii = detectPII(text);
console.log(pii);
// [{ type: 'email', match: '[email protected]', ... }, { type: 'phone', match: '555-123-4567', ... }]

Step 3: Data Redaction

function redactPII(text: string, replacement = '[REDACTED]'): string {
  let redacted = text;

  for (const { regex } of PII_PATTERNS) {
    regex.lastIndex = 0;
    redacted = redacted.replace(regex, replacement);
  }

  return redacted;
}

function redactWithPlaceholders(text: string): { redacted: string; mapping: Map<string, string> } {
  const mapping = new Map<string, string>();
  let redacted = text;
  let counter = 0;

  for (const { type, regex } of PII_PATTERNS) {
    regex.lastIndex = 0;
    redacted = redacted.replace(regex, (match) => {
      const placeholder = `[${type.toUpperCase()}_${++counter}]`;
      mapping.set(placeholder, match);
      return placeholder;
    });
  }

  return { redacted, mapping };
}

// Usage
const input = 'Send report to [email protected] and [email protected]';
const { redacted, mapping } = redactWithPlaceholders(input);
console.log(redacted);
// 'Send report to [EMAIL_1] and [EMAIL_2]'

Step 4: Pre-Request Validation

interface ValidationResult {
  safe: boolean;
  warnings: string[];
  piiFound: PIIMatch[];
}

function validateBeforeSending(messages: Array<{ role: string; content: string }>): ValidationResult {
  const warnings: string[] = [];
  const allPII: PIIMatch[] = [];

  for (const message of messages) {
    const pii = detectPII(message.content);
    allPII.push(...pii);
  }

  // Group by type
  const piiByType = allPII.reduce((acc, p) => {
    acc[p.type] = (acc[p.type] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  if (allPII.length > 0) {
    const typeList = Object.entries(piiByType)
      .map(([type, count]) => `${count} ${type}(s)`)
      .join(', ');
    warnings.push(`PII detected: ${typeList}`);
  }

  return {
    safe: allPII.length === 0,
    warnings,
    piiFound: allPII,
  };
}

// Middleware
async function safeChat(
  client: Mistral,
  messages: Array<{ role: string; content: string }>,
  options?: { allowPII?: boolean; autoRedact?: boolean }
): Promise<string> {
  const validation = validateBeforeSending(messages);

  if (!validation.safe) {
    if (options?.autoRedact) {
      // Auto-redact PII
      messages = messages.map(m => ({
        ...m,
        content: redactPII(m.content),
      }));
    } else if (!options?.allowPII) {
      throw new Error(`PII detected in request: ${validation.warnings.join(', ')}`);
    }
  }

  const response = await client.chat.complete({
    model: 'mistral-small-latest',
    messages,
  });

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

Step 5: Audit Logging

interface AuditLog {
  timestamp: Date;
  requestId: string;
  userId?: string;
  operation: string;
  model: string;
  inputTokens: number;
  outputTokens: number;
  piiDetected: boolean;
  piiTypes: string[];
  redacted: boolean;
}

class MistralAuditLogger {
  private logs: AuditLog[] = [];

  async log(entry: Omit<AuditLog, 'timestamp'>): Promise<void> {
    const log: AuditLog = {
      ...entry,
      timestamp: new Date(),
    };

    // Store in database
    await db.auditLogs.insert(log);

    // Console log for immediate visibility
    console.log('[AUDIT]', JSON.stringify(log));
  }

  async getLogsForUser(userId: string, days = 30): Promise<AuditLog[]> {
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - days);

    return db.auditLogs.find({
      userId,
      timestamp: { $gte: cutoff },
    });
  }
}

Step 6: GDPR Data Subject Requests

// Right to Access (DSAR)
async function exportUserData(userId: string): Promise<{
  auditLogs: AuditLog[];
  exportedAt: string;
}> {
  const auditLogs = await auditLogger.getLogsForUser(userId);

  return {
    auditLogs: auditLogs.map(log => ({
      ...log,
      // Don't include actual content, just metadata
    })),
    exportedAt: new Date().toISOString(),
  };
}

// Right to Erasure
async function deleteUserData(userId: string): Promise<{
  success: boolean;
  deletedCount: number;
}> {
  // 1. Delete audit logs older than legal retention period
  const result = await db.auditLogs.deleteMany({
    userId,
    timestamp: { $lt: new Date(Date.now() - 7 * 365 * 24 * 60 * 60 * 1000) }, // Keep 7 years for compliance
  });

  // 2. Anonymize remaining logs
  await db.auditLogs.updateMany(
    { userId },
    { $set: { userId: '[DELETED]' } }
  );

  // 3. Record deletion for compliance
  await db.deletionLog.insert({
    userId,
    deletedAt: new Date(),
    recordsAffected: result.deletedCount,
  });

  return {
    success: true,
    deletedCount: result.deletedCount,
  };
}

Step 7: Data Retention Policy

interface RetentionPolicy {
  dataType: string;
  retentionDays: number;
  reason: string;
}

const RETENTION_POLICIES: RetentionPolicy[] = [
  { dataType: 'audit_logs', retentionDays: 90, reason: 'Operational debugging' },
  { dataType: 'error_logs', retentionDays: 30, reason: 'Error tracking' },
  { dataType: 'compliance_logs', retentionDays: 2555, reason: 'Legal requirement (7 years)' },
];

async function enforceRetention(): Promise<void> {
  for (const policy of RETENTION_POLICIES) {
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - policy.retentionDays);

    const result = await db.collection(policy.dataType).deleteMany({
      createdAt: { $lt: cutoff },
    });

    console.log(`Cleaned ${result.deletedCount} records from ${policy.dataType}`);
  }
}

// Run daily
// cron.schedule('0 3 * * *', enforceRetention);

Output

  • PII detection implemented
  • Data redaction active
  • Audit logging enabled
  • GDPR compliance procedures in place

Error Handling

IssueCauseSolution
PII in logsMissing redactionApply logging middleware
Deletion failedLocked recordsCheck foreign key constraints
False positivesOverly broad regexTune PII patterns
Audit gapsAsync failuresAdd retry logic

Examples

Safe Chat Wrapper

const response = await safeChat(client, messages, { autoRedact: true });

Quick PII Check

const hasPII = detectPII(userInput).length > 0;
if (hasPII) {
  console.warn('PII detected in user input');
}

Resources

Next Steps

For enterprise access control, see mistral-enterprise-rbac.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

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

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

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

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

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

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

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

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

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

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

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

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

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.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

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

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

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.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

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

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

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

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View