Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/chrlshc_huntaze.json
T
OpenCode 68a9071cf1 feat: reconcile local master with origin (exa/hot-platform hunters, leaks ledger, latest results)
Local branch had diverged from origin/master (sibling commits on the same base). Rewrote local history linearly on top of origin/master, folding in all local content: exa/hot-platform discovery hunters, leaks ledger, nightly sweep orchestrator, updated .gitignore and skill docs, plus the latest hunt output and vault state. Remote-only files (vault keys, channel scripts) were restored rather than dropped, so the resulting tree is a full union of both sides.
2026-08-07 12:53:47 +08:00

1 line
89 KiB
JSON
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{"repo": "chrlshc/huntaze", "files": {"deployment-beta-50users/AZURE-AI-COMPLET.md": {"dbaefa84387baf24f5fde1652a9d317b319e98bf": {"t": 1786068571.5352128, "n": 81605, "h": "3f0787cf60fd6c67", "c": "# đŸ€– Azure AI Foundry - Guide Complet\n\n**Contexte**: Huntaze - Plateforme SaaS pour crĂ©atrices OnlyFans \n**Budget Azure AI**: $1,000/mois (dĂ©jĂ  payĂ©) \n**Utilisation rĂ©elle**: ~$62/mois (6% du budget) \n**Cible**: 50 utilisatrices beta\n\n---\n\n## 📋 Table des MatiĂšres\n\n1. [Vue d'Ensemble](#vue-densemble)\n2. [Les 7 ModĂšles Azure AI](#les-7-modĂšles-azure-ai)\n3. [Le Majordome - Chatbot Orchestrateur](#le-majordome)\n4. [Architecture Technique](#architecture-technique)\n5. [Routing Intelligent](#routing-intelligent)\n6. [Cas d'Usage DĂ©taillĂ©s](#cas-dusage-dĂ©taillĂ©s)\n7. [Budget et Scaling](#budget-et-scaling)\n8. [ImplĂ©mentation Code](#implĂ©mentation-code)\n9. [Monitoring et Optimisation](#monitoring-et-optimisation)\n\n---\n\n## 🎯 Vue d'Ensemble\n\n### Architecture AI Quadrimodale\n\nHuntaze utilise une architecture AI complĂšte avec **7 modĂšles spĂ©cialisĂ©s** orchestrĂ©s par **Le Majordome**, un chatbot intelligent qui choisit automatiquement le bon modĂšle pour chaque tĂąche.\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ LE MAJORDOME (Orchestrateur) │\n│ Chatbot IA avec routing intelligent │\n└─────────────────────────────────────────────────────────────┘\n │\n ┌─────────────────────┌─────────────────────┐\n │ │ │\n â–Œ â–Œ â–Œ\n┌──────────────┐ ┌──────────────┐ ┌──────────────┐\n│ GÉNÉRATION │ │ RAISONNEMENT │ │ MULTIMODAL │\n├─────────────── ├─────────────── ├───────────────\n│ DeepSeek-V3 │ │ DeepSeek-R1 │ │ Phi-4 Multi │\n│ Phi-4 Mini │ │ │ │ Azure Speech │\n│ Llama 3.3 │ │ │ │ │\n│ Mistral │ │ │ │ │\n└──────────────┘ └──────────────┘ └──────────────┘\n```\n\n### Principes ClĂ©s\n\n✅ **SpĂ©cialisation**: Chaque modĂšle excelle dans son domaine \n✅ **Routing intelligent**: Le Majordome choisit le bon modĂšle \n✅ **Fallbacks**: Haute disponibilitĂ© avec modĂšles de secours \n✅ **Optimisation coĂ»ts**: Cache 80% hit rate, modĂšles Ă©conomiques \n✅ **ScalabilitĂ©**: Peut supporter 1,000+ users dans le budget\n\n---\n\n\n## đŸ€– Les 7 ModĂšles Azure AI\n\n### 1ïžâƒŁ DeepSeek-V3 (MoE 671B) - GĂ©nĂ©ration Rapide\n\n**Budget**: ~$34/mois | **Volume**: 300,000 appels/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Mixture-of-Experts (MoE)\n- **ParamĂštres**: 671B totaux, 37B actifs par token\n- **Context**: 128K tokens\n- **Latence**: 500-1000ms\n- **Pricing**: $0.00114/1K input, $0.00456/1K output\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**GĂ©nĂ©ration de contenu rapide et crĂ©ative** - C'est le workhorse de l'application.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Messages OnlyFans (300K calls/mois)**\n```typescript\n// app/api/onlyfans/ai/suggestions/route.ts\nconst response = await callAzureAI({\n model: 'deepseek-v3',\n messages: [\n { \n role: 'system', \n content: 'Tu es une crĂ©atrice OnlyFans sĂ©duisante et engageante...' \n },\n { \n role: 'user', \n content: `Fan: \"${fanMessage}\"\\nContexte: ${fanContext}` \n }\n ],\n temperature: 0.7,\n maxTokens: 300\n});\n```\n\n**Utilisations**:\n- ✅ RĂ©ponses personnalisĂ©es aux messages fans\n- ✅ Suggestions de messages de vente (PPV)\n- ✅ Messages de relance pour fans inactifs\n- ✅ Messages de bienvenue nouveaux abonnĂ©s\n- ✅ RĂ©ponses aux commentaires\n\n**2. GĂ©nĂ©ration de Contenu Marketing**\n```typescript\n// app/api/ai/generate-caption/route.ts\nconst caption = await callAzureAI({\n model: 'deepseek-v3',\n messages: [\n { \n role: 'system', \n content: 'GĂ©nĂšre une caption sĂ©duisante pour rĂ©seaux sociaux...' \n },\n { \n role: 'user', \n content: `Type: ${type}, Tone: ${tone}, Platform: ${platform}` \n }\n ],\n temperature: 0.8,\n maxTokens: 200\n});\n```\n\n**Utilisations**:\n- ✅ Captions Instagram/TikTok/Twitter\n- ✅ Descriptions de posts OnlyFans\n- ✅ Scripts de vidĂ©os courtes\n- ✅ Hooks accrocheurs\n- ✅ Call-to-actions\n\n**3. Campagnes Marketing AutomatisĂ©es**\n```typescript\n// app/api/ai/campaigns/generate/route.ts\nconst campaign = await callAzureAI({\n model: 'deepseek-v3',\n messages: [\n { \n role: 'system', \n content: 'CrĂ©e une campagne marketing complĂšte...' \n },\n { \n role: 'user', \n content: `Objectif: ${goal}, Budget: ${budget}, Audience: ${audience}` \n }\n ],\n temperature: 0.7,\n maxTokens: 500\n});\n```\n\n**Utilisations**:\n- ✅ Campagnes email marketing\n- ✅ SĂ©quences de messages automatisĂ©s\n- ✅ Offres promotionnelles\n- ✅ Bundles de contenu\n- ✅ Programmes de fidĂ©litĂ©\n\n#### 📊 Performance\n- **Vitesse**: 500-1000ms par requĂȘte\n- **QualitĂ©**: Excellente pour contenu crĂ©atif\n- **CoĂ»t**: $0.11 par 1000 messages gĂ©nĂ©rĂ©s\n- **Cache hit rate**: 80% (rĂ©utilisation de rĂ©ponses similaires)\n\n---\n\n### 2ïžâƒŁ DeepSeek-R1 (RL Reasoning) - Raisonnement Profond\n\n**Budget**: ~$10/mois | **Volume**: 50,000 appels/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Reinforcement Learning (RL pur, pas de SFT)\n- **SpĂ©cialitĂ©**: Chain-of-Thought reasoning\n- **Context**: 64K tokens\n- **Latence**: 2000-4000ms (plus lent mais plus intelligent)\n- **Pricing**: $0.00135/1K input, $0.0054/1K output\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**Analyses complexes et stratĂ©gies marketing** - Le cerveau stratĂ©gique.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Analyse de ViralitĂ© (Content Trends)**\n```typescript\n// lib/ai/content-trends/viral-prediction-engine.ts\nconst analysis = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Analyse les mĂ©canismes de viralitĂ© avec raisonnement profond...' \n },\n { \n role: 'user', \n content: `Video: ${videoData}\\nMetrics: ${metrics}\\n\\nPourquoi est-ce viral?` \n }\n ],\n temperature: 0.6,\n maxTokens: 1000\n});\n```\n\n**Utilisations**:\n- ✅ DĂ©tection de patterns viraux\n- ✅ Analyse de mĂ©canismes Ă©motionnels\n- ✅ PrĂ©diction de rĂ©plicabilitĂ©\n- ✅ Scoring de potentiel viral\n- ✅ Recommandations d'optimisation\n\n**2. StratĂ©gies Marketing Complexes**\n```typescript\n// app/api/ai/warroom/route.ts\nconst insights = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Analyse les campagnes et fournis des insights stratĂ©giques...' \n },\n { \n role: 'user', \n content: `Campaigns: ${campaigns}\\nMetrics: ${metrics}\\n\\nQue recommandes-tu?` \n }\n ],\n temperature: 0.5,\n maxTokens: 800\n});\n```\n\n**Utilisations**:\n- ✅ Analyse de performance campagnes\n- ✅ Recommandations d'optimisation\n- ✅ DĂ©tection de problĂšmes\n- ✅ StratĂ©gies de croissance\n- ✅ A/B testing insights\n\n**3. Segmentation de Fans Intelligente**\n```typescript\n// lib/ai/fan-segmentation.service.ts\nconst segments = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Segmente les fans par comportement et valeur...' \n },\n { \n role: 'user', \n content: `Fans: ${fansData}\\n\\nCrĂ©e des segments actionnables.` \n }\n ],\n temperature: 0.4,\n maxTokens: 600\n});\n```\n\n**Utilisations**:\n- ✅ Segmentation comportementale\n- ✅ Identification des VIP/Whales\n- ✅ DĂ©tection de churn risk\n- ✅ Personnalisation des offres\n- ✅ Lifetime value prediction\n\n#### 📊 Performance\n- **Vitesse**: 2000-4000ms (acceptable pour analyses)\n- **QualitĂ©**: Excellente pour raisonnement complexe\n- **CoĂ»t**: $0.20 par analyse complĂšte\n- **PrĂ©cision**: 85%+ sur prĂ©dictions virales\n\n---\n\n### 3ïžâƒŁ Phi-4 Multimodal (128K) - Vision + Audio\n\n**Budget**: ~$2.40/mois | **Volume**: 3,000 vidĂ©os/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Multimodal (Texte + Images + Audio context)\n- **Context**: 128K tokens (Ă©norme pour analyse vidĂ©o)\n- **Latence**: 1000-2000ms par vidĂ©o\n- **Pricing**: $0.0004/1K input, $0.0004/1K output\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**Analyse multimodale de contenu visuel et audio** - Les yeux et oreilles de l'IA.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Analyse de VidĂ©os Virales (Content Trends)**\n```typescript\n// lib/ai/content-trends/phi4-multimodal-service.ts\nconst analysis = await analyzeVideoFrames({\n frames: keyframes, // 9 frames extraites (dĂ©but, milieu, fin)\n audio: transcription,\n metadata: {\n duration: videoDuration,\n platform: 'tiktok',\n metrics: { views, likes, shares }\n }\n});\n```\n\n**Utilisations**:\n- ✅ Analyse de keyframes vidĂ©o\n- ✅ DĂ©tection d'Ă©motions faciales\n- ✅ OCR de texte dans vidĂ©os\n- ✅ Analyse de dynamique d'Ă©dition\n- ✅ Timeline analysis (dĂ©but/milieu/fin)\n- ✅ DĂ©tection de hooks visuels\n\n**2. Analyse de Contenu Visuel Instagram/TikTok**\n```typescript\n// app/api/ai/content-trends/analyze/route.ts\nconst insights = await analyzeImage({\n imageUrl: url,\n context: 'OnlyFans content analysis',\n analysisType: ['composition', 'style', 'emotions', 'trends']\n});\n```\n\n**Utilisations**:\n- ✅ Analyse de composition visuelle\n- ✅ DĂ©tection de style/esthĂ©tique\n- ✅ Suggestions d'amĂ©lioration\n- ✅ Comparaison avec tendances\n- ✅ Color grading analysis\n\n**3. Transcription + Analyse Audio Contextuelle**\n```typescript\n// lib/ai/content-trends/audio-transcription-service.ts\nconst audioAnalysis = await analyzeAudioWithContext({\n transcription: text,\n frames: keyframes,\n timeline: timestamps\n});\n```\n\n**Utilisations**:\n- ✅ Analyse de hooks audio\n- ✅ DĂ©tection de musique/sons tendance\n- ✅ Synchronisation audio-visuel\n- ✅ Analyse de rythme/tempo\n- ✅ Extraction de citations clĂ©s\n\n#### 📊 Performance\n- **Vitesse**: 1000-2000ms par vidĂ©o (9 frames)\n- **QualitĂ©**: Excellente pour analyse multimodale\n- **CoĂ»t**: $0.0008 par vidĂ©o analysĂ©e\n- **PrĂ©cision**: 90%+ sur dĂ©tection d'Ă©motions\n\n---\n\n\n### 4ïžâƒŁ Phi-4 Mini - Classification Rapide\n\n**Budget**: ~$1/mois | **Volume**: 100,000 appels/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Lightweight model (compact et rapide)\n- **SpĂ©cialitĂ©**: Classification et routing\n- **Latence**: 200-500ms (trĂšs rapide)\n- **Pricing**: $0.0004/1K input, $0.0004/1K output\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**Routing AI et classification temps rĂ©el** - Le dispatcher intelligent.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Routing AI (AI Router)**\n```python\n# lib/ai/router/classifier.py\nclassification = await classify_request({\n 'prompt': user_prompt,\n 'context': request_context,\n 'complexity': estimate_complexity(user_prompt)\n})\n# Returns: 'deepseek-v3', 'deepseek-r1', 'phi-4-multimodal', etc.\n```\n\n**Utilisations**:\n- ✅ Classification de requĂȘtes\n- ✅ Routing vers le bon modĂšle\n- ✅ DĂ©tection de complexitĂ©\n- ✅ Optimisation des coĂ»ts\n- ✅ Load balancing\n\n**2. Classification de Contenu**\n```typescript\n// app/api/ai/content/classify/route.ts\nconst category = await classifyContent({\n content: text,\n metadata: metadata,\n categories: ['seductive', 'playful', 'romantic', 'bold']\n});\n```\n\n**Utilisations**:\n- ✅ CatĂ©gorisation automatique\n- ✅ DĂ©tection de sentiment\n- ✅ Classification de prioritĂ©\n- ✅ Filtrage de contenu\n- ✅ Tag generation\n\n**3. Suggestions Rapides (Quick Replies)**\n```typescript\n// app/api/ofm/ai/draft/route.ts\nconst draft = await callAzureAI({\n model: 'phi4-mini',\n messages: [\n { \n role: 'system', \n content: 'GĂ©nĂšre une rĂ©ponse rapide et engageante...' \n },\n { \n role: 'user', \n content: fanMessage \n }\n ],\n temperature: 0.6,\n maxTokens: 100\n});\n```\n\n**Utilisations**:\n- ✅ RĂ©ponses rapides (< 500ms)\n- ✅ Suggestions temps rĂ©el\n- ✅ Auto-complĂ©tion\n- ✅ Quick replies\n- ✅ Smart compose\n\n#### 📊 Performance\n- **Vitesse**: 200-500ms (ultra-rapide)\n- **QualitĂ©**: Bonne pour tĂąches simples\n- **CoĂ»t**: $0.01 par 1000 classifications\n- **PrĂ©cision**: 92%+ sur routing\n\n---\n\n### 5ïžâƒŁ Azure Speech Batch - Transcription Audio\n\n**Budget**: ~$5/mois | **Volume**: 25 heures audio/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Batch Processing (asynchrone)\n- **Features**: Speaker diarization, timestamps\n- **Latence**: 1-5 minutes (asynchrone)\n- **Pricing**: $0.18/heure d'audio\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**Transcription audio Ă©conomique pour Content Trends** - L'oreille de l'IA.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Transcription de VidĂ©os Virales**\n```typescript\n// lib/ai/content-trends/audio-transcription-service.ts\nconst transcription = await transcribeAudio({\n audioUrl: videoAudioUrl,\n language: 'en-US',\n enableDiarization: true,\n enableWordTimestamps: true\n});\n```\n\n**Utilisations**:\n- ✅ Transcription de vidĂ©os TikTok\n- ✅ Extraction de hooks audio\n- ✅ Analyse de dialogues\n- ✅ DĂ©tection de musique/sons\n- ✅ Speaker identification\n\n**2. Analyse de Timeline Audio**\n```typescript\n// Analyse la timeline audio avec timestamps\nconst timeline = await analyzeAudioTimeline({\n transcription: text,\n timestamps: wordTimestamps,\n duration: videoDuration\n});\n```\n\n**Utilisations**:\n- ✅ DĂ©tection de moments clĂ©s\n- ✅ Analyse de rythme\n- ✅ Synchronisation audio-visuel\n- ✅ Extraction de citations\n- ✅ Hook timing analysis\n\n**3. DĂ©tection de Patterns Audio**\n```typescript\n// DĂ©tecte les patterns audio qui fonctionnent\nconst patterns = await detectAudioPatterns({\n transcriptions: viralVideosTranscriptions,\n metrics: engagementMetrics\n});\n```\n\n**Utilisations**:\n- ✅ Identification de hooks audio viraux\n- ✅ Analyse de musique tendance\n- ✅ DĂ©tection de sound effects\n- ✅ Tempo/rythme analysis\n- ✅ Voice tone analysis\n\n#### 📊 Performance\n- **Vitesse**: 1-5 minutes (asynchrone, acceptable)\n- **QualitĂ©**: Excellente (95%+ prĂ©cision)\n- **CoĂ»t**: $0.18/heure = $0.003 par vidĂ©o 30s\n- **Langues**: 100+ langues supportĂ©es\n\n---\n\n### 6ïžâƒŁ Llama 3.3-70B - Fallback GĂ©nĂ©raliste\n\n**Budget**: ~$5/mois | **Volume**: 20,000 appels/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Large Language Model (70B paramĂštres)\n- **SpĂ©cialitĂ©**: ModĂšle gĂ©nĂ©raliste polyvalent\n- **Latence**: 800-1500ms\n- **Pricing**: Variable selon usage (Marketplace)\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**ModĂšle alternatif et fallback** - Le backup fiable.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Fallback pour DeepSeek-V3**\n```typescript\n// lib/ai/llm-router.ts\nconst FALLBACKS = {\n standard: [\n { provider: 'azure', model: 'phi4' },\n { provider: 'azure', model: 'llama' }, // Fallback si DeepSeek down\n { provider: 'azure', model: 'deepseek' }\n ]\n};\n```\n\n**Utilisations**:\n- ✅ Backup si DeepSeek down\n- ✅ Alternative pour certains cas\n- ✅ Tests A/B de qualitĂ©\n- ✅ Diversification des modĂšles\n- ✅ Load balancing\n\n**2. GĂ©nĂ©ration de Contenu Long**\n```typescript\n// lib/ai/majordome.ts\nconst response = await callAzureAI({\n model: 'llama',\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt }\n ],\n temperature: 0.7,\n maxTokens: 2000\n});\n```\n\n**Utilisations**:\n- ✅ GĂ©nĂ©ration de contenu long\n- ✅ Analyses dĂ©taillĂ©es\n- ✅ Conversations complexes\n- ✅ TĂąches gĂ©nĂ©rales\n- ✅ Documentation generation\n\n**3. Tests et Comparaisons**\n```typescript\n// Compare la qualitĂ© Llama vs DeepSeek\nconst comparison = await Promise.all([\n callAzureAI({ model: 'llama', messages }),\n callAzureAI({ model: 'deepseek', messages })\n]);\n```\n\n**Utilisations**:\n- ✅ A/B testing de qualitĂ©\n- ✅ Benchmarking\n- ✅ Quality assurance\n- ✅ Model evaluation\n- ✅ Performance comparison\n\n#### 📊 Performance\n- **Vitesse**: 800-1500ms (bonne)\n- **QualitĂ©**: TrĂšs bonne (gĂ©nĂ©raliste)\n- **CoĂ»t**: ~$0.25 par 1000 tokens\n- **DisponibilitĂ©**: 99.9% (trĂšs fiable)\n\n---\n\n### 7ïžâƒŁ Mistral Large - CrĂ©ativitĂ©\n\n**Budget**: ~$5/mois | **Volume**: 15,000 appels/mois\n\n#### đŸ—ïž Architecture Technique\n- **Type**: Large model optimisĂ© pour crĂ©ativitĂ©\n- **SpĂ©cialitĂ©**: Contenu crĂ©atif et conversations naturelles\n- **Latence**: 1000-2000ms\n- **Pricing**: Variable selon usage (Marketplace)\n\n#### đŸ’Œ RĂŽle dans Huntaze\n**Contenu ultra-crĂ©atif et conversations naturelles** - L'artiste de l'Ă©quipe.\n\n#### 📍 Cas d'Usage Principaux\n\n**1. Contenu CrĂ©atif Original**\n```typescript\n// app/api/ai/content/creative/route.ts\nconst creative = await callAzureAI({\n model: 'mistral',\n messages: [\n { \n role: 'system', \n content: 'Tu es une crĂ©atrice ultra-crĂ©ative et originale...' \n },\n { \n role: 'user', \n content: `CrĂ©e un concept original pour: ${theme}` \n }\n ],\n temperature: 0.9,\n maxTokens: 500\n});\n```\n\n**Utilisations**:\n- ✅ Concepts de contenu originaux\n- ✅ Storytelling crĂ©atif\n- ✅ Scripts de vidĂ©os\n- ✅ IdĂ©es de campagnes\n- ✅ Brainstorming\n\n**2. Conversations Naturelles (Le Majordome)**\n```typescript\n// lib/ai/majordome.ts\nconst response = await callAzureAI({\n model: 'mistral',\n messages: conversationHistory,\n temperature: 0.7,\n maxTokens: 400\n});\n```\n\n**Utilisations**:\n- ✅ Assistant conversationnel\n- ✅ RĂ©ponses naturelles\n- ✅ Explications dĂ©taillĂ©es\n- ✅ Conseils personnalisĂ©s\n- ✅ Coaching crĂ©atif\n\n**3. GĂ©nĂ©ration de ScĂ©narios Complexes**\n```typescript\n// GĂ©nĂšre des scĂ©narios de contenu complexes\nconst scenario = await callAzureAI({\n model: 'mistral',\n messages: [\n { \n role: 'system', \n content: 'CrĂ©e un scĂ©nario de contenu dĂ©taillĂ©...' \n },\n { \n role: 'user', \n content: `Theme: ${theme}, Duration: ${duration}, Style: ${style}` \n }\n ],\n temperature: 0.8,\n maxTokens: 600\n});\n```\n\n**Utilisations**:\n- ✅ ScĂ©narios de vidĂ©os\n- ✅ SĂ©ries de contenu\n- ✅ Storylines complexes\n- ✅ Character development\n- ✅ Plot twists\n\n#### 📊 Performance\n- **Vitesse**: 1000-2000ms (acceptable)\n- **QualitĂ©**: Excellente pour crĂ©ativitĂ©\n- **CoĂ»t**: ~$0.33 par 1000 tokens\n- **OriginalitĂ©**: 95%+ (trĂšs crĂ©atif)\n\n---\n\n\n## đŸŽ© Le Majordome - Chatbot Orchestrateur\n\n### Vue d'Ensemble\n\n**Le Majordome** est l'assistant IA personnel des crĂ©atrices OnlyFans. C'est un chatbot intelligent qui orchestre tous les 7 modĂšles Azure AI pour fournir des rĂ©ponses et actions optimales.\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│ LE MAJORDOME │\n│ │\n│ \"Bonjour Madame, comment puis-je vous aider aujourd'hui?\" │\n│ │\n│ 🎯 Orchestration intelligente des 7 modĂšles Azure AI │\n│ 🧠 Routing automatique selon la complexitĂ© │\n│ 💬 Conversations naturelles et contextuelles │\n│ đŸ› ïž 5 outils principaux pour actions concrĂštes │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### Architecture du Majordome\n\n#### 1. SystĂšme de Routing Intelligent\n\nLe Majordome choisit automatiquement le bon modĂšle selon la tĂąche:\n\n```typescript\n// src/lib/ai/majordome.ts\n\nfunction selectModel(task: string, complexity: string) {\n // Vision/Audio → Phi-4 Multimodal\n if (task === 'vision' || task === 'audio') {\n return 'phi-4-multimodal';\n }\n \n // Transcription audio → Azure Speech Batch\n if (task === 'transcription') {\n return 'azure-speech-batch';\n }\n \n // Raisonnement profond → DeepSeek-R1\n if (task === 'reasoning' || complexity === 'high') {\n return 'deepseek-r1';\n }\n \n // GĂ©nĂ©ration simple → Phi-4 Mini (rapide)\n if (task === 'generation' && complexity === 'simple') {\n return 'phi4-mini';\n }\n \n // GĂ©nĂ©ration standard → DeepSeek-V3 (Ă©quilibrĂ©)\n if (task === 'generation' && complexity === 'standard') {\n return 'deepseek-v3';\n }\n \n // CrĂ©ativitĂ© → Mistral Large\n if (task === 'creative') {\n return 'mistral';\n }\n \n // Fallback → Llama 3.3-70B\n return 'llama';\n}\n```\n\n#### 2. Les 5 Outils du Majordome\n\nLe Majordome dispose de 5 outils principaux pour exĂ©cuter des actions:\n\n```typescript\nconst MAJORDOME_TOOLS = [\n {\n name: \"generate_content\",\n description: \"GĂ©nĂ©rer du contenu OnlyFans avec Azure AI\",\n parameters: {\n type: \"post\" | \"message\" | \"ppv\" | \"story\",\n tone: \"seductive\" | \"playful\" | \"romantic\" | \"bold\",\n topic: string,\n model: \"deepseek\" | \"phi4\" | \"llama\" | \"mistral\"\n }\n },\n {\n name: \"analyze_fans\",\n description: \"Analyser les donnĂ©es fans avec Azure AI\",\n parameters: {\n timeframe: \"7d\" | \"30d\" | \"90d\",\n segment: \"all\" | \"vip\" | \"new\" | \"at_risk\",\n deepAnalysis: boolean // Utilise DeepSeek-R1 si true\n }\n },\n {\n name: \"get_smart_replies\",\n description: \"Obtenir des rĂ©ponses depuis la Knowledge Base\",\n parameters: {\n fanMessage: string,\n context: string\n }\n },\n {\n name: \"schedule_post\",\n description: \"Programmer la publication de contenu\",\n parameters: {\n content: string,\n scheduleTime: string, // ISO date\n platforms: string[],\n optimize: boolean // Optimise avec Azure AI si true\n }\n },\n {\n name: \"track_performance\",\n description: \"Suivre les performances et gĂ©nĂ©rer des rapports\",\n parameters: {\n metric: \"revenue\" | \"engagement\" | \"growth\" | \"retention\",\n period: \"daily\" | \"weekly\" | \"monthly\",\n insights: boolean // GĂ©nĂšre insights avec DeepSeek si true\n }\n }\n];\n```\n\n### Exemples d'Utilisation\n\n#### Exemple 1: GĂ©nĂ©ration de Contenu\n\n**Utilisatrice**: \"CrĂ©e-moi un message sĂ©duisant pour mes fans VIP\"\n\n**Le Majordome**:\n1. DĂ©tecte: `task = 'generation'`, `complexity = 'standard'`\n2. Choisit: **DeepSeek-V3** (gĂ©nĂ©ration rapide)\n3. Appelle l'outil: `generate_content`\n4. Retourne: Message personnalisĂ© en 800ms\n\n```typescript\n// ExĂ©cution interne\nconst response = await callAzureAI({\n model: 'deepseek-v3',\n messages: [\n { \n role: 'system', \n content: 'Tu es une crĂ©atrice OnlyFans sĂ©duisante...' \n },\n { \n role: 'user', \n content: 'Type: message, Tone: seductive, Audience: VIP fans' \n }\n ],\n temperature: 0.7,\n maxTokens: 300\n});\n\n// RĂ©sultat\n\"Hey bĂ©bĂ© 💋 J'ai pensĂ© Ă  toi aujourd'hui... J'ai prĂ©parĂ© quelque chose de spĂ©cial juste pour mes VIP. Tu veux voir? 😏\"\n```\n\n#### Exemple 2: Analyse de Fans\n\n**Utilisatrice**: \"Analyse mes fans des 30 derniers jours et dis-moi qui risque de partir\"\n\n**Le Majordome**:\n1. DĂ©tecte: `task = 'reasoning'`, `complexity = 'high'`\n2. Choisit: **DeepSeek-R1** (raisonnement profond)\n3. Appelle l'outil: `analyze_fans` avec `deepAnalysis = true`\n4. Retourne: Analyse dĂ©taillĂ©e en 3000ms\n\n```typescript\n// ExĂ©cution interne\nconst analysis = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Analyse les donnĂ©es fans et identifie les risques de churn...' \n },\n { \n role: 'user', \n content: `Fans: ${fansData}\\nTimeframe: 30d\\nSegment: at_risk` \n }\n ],\n temperature: 0.4,\n maxTokens: 600\n});\n\n// RĂ©sultat\n\"đŸŽ© Madame, j'ai analysĂ© vos 247 fans sur 30 jours:\n\n📊 Statistiques:\n- 23 fans Ă  risque (9.3%)\n- 12 fans inactifs depuis 14+ jours\n- 8 fans avec engagement en baisse (-40%)\n\n⚠ Fans prioritaires Ă  contacter:\n1. @john_doe - VIP, $450 dĂ©pensĂ©s, inactif 18j\n2. @mike_smith - Whale, $890 dĂ©pensĂ©s, engagement -60%\n3. @alex_jones - Nouveau, 0 achat depuis 21j\n\n💡 Recommandations:\n- Envoyer message personnalisĂ© aux VIP inactifs\n- Offre exclusive pour rĂ©engager les whales\n- Contenu gratuit pour convertir les nouveaux\"\n```\n\n#### Exemple 3: RĂ©ponses Intelligentes\n\n**Utilisatrice**: \"Un fan me demande 'Tu fais des customs?'\"\n\n**Le Majordome**:\n1. DĂ©tecte: `task = 'generation'`, `complexity = 'simple'`\n2. Choisit: **Phi-4 Mini** (rĂ©ponse rapide)\n3. Appelle l'outil: `get_smart_replies`\n4. Consulte la **Knowledge Base** pour rĂ©ponses Ă©prouvĂ©es\n5. Retourne: RĂ©ponse optimisĂ©e en 400ms\n\n```typescript\n// ExĂ©cution interne\n// 1. Query Knowledge Base\nconst kbResults = await prisma.knowledgeBaseItem.findMany({\n where: {\n kind: 'CHAT_CLOSER_PLAY',\n status: 'ACTIVE',\n inputText: { contains: 'custom' }\n },\n orderBy: { score: 'desc' },\n take: 5\n});\n\n// 2. Utilise Phi-4 Mini pour adapter\nconst reply = await callAzureAI({\n model: 'phi4-mini',\n messages: [\n { \n role: 'system', \n content: 'Adapte la meilleure rĂ©ponse de la Knowledge Base...' \n },\n { \n role: 'user', \n content: `Fan: \"Tu fais des customs?\"\\n\\nRĂ©ponses KB:\\n${kbResults.map(k => k.outputText).join('\\n')}` \n }\n ],\n temperature: 0.6,\n maxTokens: 150\n});\n\n// RĂ©sultat\n\"Oui bĂ©bĂ© 😘 Je fais des customs personnalisĂ©s! Dis-moi ce que tu veux et je te fais un prix spĂ©cial 💋 Envoie-moi un message privĂ© pour en discuter 😏\"\n```\n\n#### Exemple 4: Analyse de Contenu Viral\n\n**Utilisatrice**: \"Analyse cette vidĂ©o TikTok virale et dis-moi pourquoi ça marche\"\n\n**Le Majordome**:\n1. DĂ©tecte: `task = 'vision'` + `task = 'reasoning'`\n2. Choisit: **Phi-4 Multimodal** (analyse vidĂ©o) + **DeepSeek-R1** (raisonnement)\n3. ExĂ©cute en 2 Ă©tapes:\n - Phi-4 analyse la vidĂ©o (frames + audio)\n - DeepSeek-R1 analyse les mĂ©canismes viraux\n4. Retourne: Analyse complĂšte en 5000ms\n\n```typescript\n// ExĂ©cution interne\n// Étape 1: Analyse multimodale avec Phi-4\nconst videoAnalysis = await analyzeVideoFrames({\n frames: extractedKeyframes, // 9 frames\n audio: transcription,\n metadata: videoMetadata\n});\n\n// Étape 2: Raisonnement profond avec DeepSeek-R1\nconst viralAnalysis = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Analyse les mĂ©canismes de viralitĂ©...' \n },\n { \n role: 'user', \n content: `Video Analysis: ${videoAnalysis}\\n\\nPourquoi est-ce viral?` \n }\n ],\n temperature: 0.6,\n maxTokens: 1000\n});\n\n// RĂ©sultat\n\"đŸŽ© Madame, j'ai analysĂ© cette vidĂ©o virale (2.3M vues):\n\n🎬 Analyse Visuelle (Phi-4):\n- Hook visuel: Transformation dramatique (0-3s)\n- Composition: Rule of thirds, visage centrĂ©\n- Émotions: Surprise → Joie → SĂ©duction\n- Éditing: 15 cuts en 30s (rythme rapide)\n- Texte overlay: 3 phrases courtes et impactantes\n\nđŸŽ” Analyse Audio (Azure Speech):\n- Musique: Trending sound \"XYZ\" (500K uses)\n- Hook audio: Beat drop Ă  3s (synchronisĂ© avec visuel)\n- Voix: Ton confiant et enjouĂ©\n- Tempo: 128 BPM (optimal pour engagement)\n\n🧠 MĂ©canismes Viraux (DeepSeek-R1):\n1. **Pattern Interrupt**: Transformation inattendue (hook)\n2. **Curiosity Gap**: \"Tu veux savoir comment?\" (retention)\n3. **Social Proof**: RĂ©action authentique (crĂ©dibilitĂ©)\n4. **Call-to-Action**: \"Essaie ça!\" (engagement)\n\n💡 RĂ©plicabilitĂ©: 85% (HAUTE)\n- Format facilement reproductible\n- Pas d'Ă©quipement spĂ©cial requis\n- Concept adaptable Ă  ton niche\n\n📋 Recommandations:\n1. Utilise le mĂȘme trending sound\n2. CrĂ©e ta version avec transformation\n3. Poste entre 18h-21h (peak engagement)\n4. Ajoute CTA vers OnlyFans dans bio\"\n```\n\n### IntĂ©gration avec Knowledge Base\n\nLe Majordome utilise la **Knowledge Base** pour apprendre des rĂ©ponses qui fonctionnent:\n\n```typescript\n// Feedback loop\nasync function learnFromSuccess(message: string, fanResponse: string, converted: boolean) {\n if (converted) {\n // Ajoute Ă  la Knowledge Base\n await prisma.knowledgeBaseItem.create({\n data: {\n kind: 'CHAT_CLOSER_PLAY',\n inputText: message,\n outputText: fanResponse,\n score: 1.0,\n status: 'ACTIVE',\n metadata: {\n conversionRate: 1.0,\n responseTime: '2m',\n fanSegment: 'vip'\n }\n }\n });\n }\n}\n```\n\n### Gestion des Confirmations\n\nPour les actions critiques, Le Majordome demande confirmation:\n\n```typescript\n// Exemple: Programmer un post\nconst response = await askMajordome(\n \"Programme un post pour demain 18h sur Instagram et OnlyFans\",\n { userId: '123' }\n);\n\n// RĂ©sultat\n{\n type: \"NEEDS_CONFIRMATION\",\n message: \"đŸŽ© Madame, je vais programmer un post pour demain 18h sur Instagram et OnlyFans. Dites 'CONFIRME' pour exĂ©cuter.\",\n pending: [\n {\n name: \"schedule_post\",\n arguments: {\n content: \"...\",\n scheduleTime: \"2025-12-23T18:00:00Z\",\n platforms: [\"instagram\", \"onlyfans\"],\n optimize: true\n }\n }\n ]\n}\n\n// Utilisatrice rĂ©pond: \"CONFIRME\"\n// Le Majordome exĂ©cute l'action\n```\n\n---\n\n\n## đŸ—ïž Architecture Technique\n\n### Diagramme d'Architecture Complet\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│ HUNTAZE APPLICATION │\n│ (Next.js 14 + Vercel) │\n└─────────────────────────────────────────────────────────────────┘\n │\n â–Œ\n┌─────────────────────────────────────────────────────────────────┐\n│ LE MAJORDOME (Orchestrateur) │\n│ src/lib/ai/majordome.ts │\n│ │\n│ ‱ Routing intelligent des requĂȘtes │\n│ ‱ Gestion des conversations │\n│ ‱ ExĂ©cution des outils │\n│ ‱ IntĂ©gration Knowledge Base │\n└─────────────────────────────────────────────────────────────────┘\n │\n â–Œ\n┌─────────────────────────────────────────────────────────────────┐\n│ LLM ROUTER (lib/ai/llm-router.ts) │\n│ │\n│ ‱ SĂ©lection du modĂšle optimal │\n│ ‱ Gestion des fallbacks │\n│ ‱ Circuit breaker │\n│ ‱ Cost tracking │\n└─────────────────────────────────────────────────────────────────┘\n │\n ┌─────────────────────┌─────────────────────┐\n │ │ │\n â–Œ â–Œ â–Œ\n┌──────────────┐ ┌──────────────┐ ┌──────────────┐\n│ GÉNÉRATION │ │ RAISONNEMENT │ │ MULTIMODAL │\n├─────────────── ├─────────────── ├───────────────\n│ DeepSeek-V3 │ │ DeepSeek-R1 │ │ Phi-4 Multi │\n│ $34/mois │ │ $10/mois │ │ $2.40/mois │\n│ 300K calls │ │ 50K calls │ │ 3K videos │\n├─────────────── └──────────────┘ ├───────────────\n│ Phi-4 Mini │ │ Azure Speech │\n│ $1/mois │ │ $5/mois │\n│ 100K calls │ │ 25h audio │\n├─────────────── └──────────────┘\n│ Llama 3.3 │\n│ $5/mois │\n│ 20K calls │\n├───────────────\n│ Mistral │\n│ $5/mois │\n│ 15K calls │\n└──────────────┘\n │\n â–Œ\n┌─────────────────────────────────────────────────────────────────┐\n│ AZURE AI FOUNDRY │\n│ (MaaS Endpoints) │\n│ │\n│ ‱ Managed Identity Authentication │\n│ ‱ Regional failover (us-east-2, us-west-2, eu-west-1) │\n│ ‱ Rate limiting (100 RPM, 100K TPM) │\n│ ‱ Cost tracking per model │\n└─────────────────────────────────────────────────────────────────┘\n │\n â–Œ\n┌─────────────────────────────────────────────────────────────────┐\n│ SUPPORTING SERVICES │\n│ │\n│ ‱ Redis Cache (80% hit rate) │\n│ ‱ PostgreSQL (Knowledge Base + Metrics) │\n│ ‱ Upstash QStash (Workers) │\n│ ‱ CloudWatch (Monitoring) │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n### Flux de RequĂȘte DĂ©taillĂ©\n\n#### 1. RequĂȘte Simple (GĂ©nĂ©ration de Message)\n\n```\nUser: \"GĂ©nĂšre un message pour mes fans\"\n │\n â–Œ\nLe Majordome\n │ 1. Parse la requĂȘte\n │ 2. DĂ©tecte: task='generation', complexity='simple'\n │ 3. SĂ©lectionne: Phi-4 Mini (rapide)\n â–Œ\nLLM Router\n │ 1. VĂ©rifie cache Redis (80% hit)\n │ 2. Si miss: appelle Phi-4 Mini\n │ 3. Log cost: $0.0008\n â–Œ\nAzure AI Foundry\n │ 1. Authentification Managed Identity\n │ 2. Appel MaaS endpoint Phi-4 Mini\n │ 3. Retourne rĂ©ponse en 300ms\n â–Œ\nLe Majordome\n │ 1. Formate la rĂ©ponse\n │ 2. Cache dans Redis (TTL 1h)\n │ 3. Retourne Ă  l'utilisatrice\n â–Œ\nUser: \"Hey bĂ©bĂ© 💋 Comment vas-tu aujourd'hui?\"\n```\n\n**Temps total**: 300-500ms \n**CoĂ»t**: $0.0008\n\n#### 2. RequĂȘte Complexe (Analyse de Fans)\n\n```\nUser: \"Analyse mes fans et dis-moi qui risque de partir\"\n │\n â–Œ\nLe Majordome\n │ 1. Parse la requĂȘte\n │ 2. DĂ©tecte: task='reasoning', complexity='high'\n │ 3. SĂ©lectionne: DeepSeek-R1 (raisonnement)\n │ 4. Appelle outil: analyze_fans\n â–Œ\nTool Execution\n │ 1. Query PostgreSQL (fans data)\n │ 2. PrĂ©pare contexte pour DeepSeek-R1\n â–Œ\nLLM Router\n │ 1. VĂ©rifie cache (miss pour analyse temps rĂ©el)\n │ 2. Appelle DeepSeek-R1\n │ 3. Log cost: $0.20\n â–Œ\nAzure AI Foundry\n │ 1. Authentification Managed Identity\n │ 2. Appel MaaS endpoint DeepSeek-R1\n │ 3. Retourne analyse en 3000ms\n â–Œ\nLe Majordome\n │ 1. Parse l'analyse\n │ 2. Formate avec statistiques\n │ 3. Ajoute recommandations actionnables\n │ 4. Retourne Ă  l'utilisatrice\n â–Œ\nUser: \"đŸŽ© Madame, j'ai analysĂ© vos 247 fans...\"\n```\n\n**Temps total**: 3000-4000ms \n**CoĂ»t**: $0.20\n\n#### 3. RequĂȘte Multimodale (Analyse VidĂ©o)\n\n```\nUser: \"Analyse cette vidĂ©o TikTok virale\"\n │\n â–Œ\nLe Majordome\n │ 1. Parse la requĂȘte + URL vidĂ©o\n │ 2. DĂ©tecte: task='vision' + task='reasoning'\n │ 3. Plan multi-Ă©tapes:\n │ a. Phi-4 Multimodal (analyse vidĂ©o)\n │ b. Azure Speech (transcription audio)\n │ c. DeepSeek-R1 (raisonnement viral)\n â–Œ\nStep 1: Video Processing\n │ 1. Download vidĂ©o (Upstash QStash worker)\n │ 2. Extract 9 keyframes (dĂ©but, milieu, fin)\n │ 3. Extract audio track\n â–Œ\nStep 2: Multimodal Analysis (Parallel)\n │\n ├─▶ Phi-4 Multimodal\n │ │ 1. Analyse 9 frames\n │ │ 2. DĂ©tecte Ă©motions, composition, texte\n │ │ 3. Timeline analysis\n │ │ 4. Retourne en 1500ms\n │ │ 5. Cost: $0.0008\n │\n └─▶ Azure Speech Batch\n │ 1. Transcription audio (30s)\n │ 2. Speaker diarization\n │ 3. Word timestamps\n │ 4. Retourne en 2000ms (async)\n │ 5. Cost: $0.0015\n â–Œ\nStep 3: Viral Reasoning\n │ 1. Combine visual + audio analysis\n │ 2. Appelle DeepSeek-R1\n │ 3. Analyse mĂ©canismes viraux\n │ 4. GĂ©nĂšre recommandations\n │ 5. Retourne en 3000ms\n │ 6. Cost: $0.20\n â–Œ\nLe Majordome\n │ 1. AgrĂšge toutes les analyses\n │ 2. Formate rapport complet\n │ 3. Ajoute score de rĂ©plicabilitĂ©\n │ 4. Retourne Ă  l'utilisatrice\n â–Œ\nUser: \"đŸŽ© Madame, j'ai analysĂ© cette vidĂ©o virale...\"\n```\n\n**Temps total**: 5000-6000ms \n**CoĂ»t**: $0.20\n\n### Gestion des Erreurs et Fallbacks\n\n```typescript\n// lib/ai/llm-router.ts\n\nconst FALLBACKS = {\n premium: [\n { provider: 'azure', model: 'deepseek' }, // Primary\n { provider: 'openai', model: 'gpt-4o' }, // Fallback 1\n { provider: 'anthropic', model: 'claude-3-5' }, // Fallback 2\n { provider: 'azure', model: 'phi4' }, // Fallback 3\n ],\n standard: [\n { provider: 'azure', model: 'phi4' }, // Primary\n { provider: 'azure', model: 'deepseek' }, // Fallback 1\n { provider: 'azure', model: 'llama' }, // Fallback 2\n ],\n economy: [\n { provider: 'azure', model: 'phi4' }, // Primary only\n ]\n};\n\n// Circuit breaker\nconst circuitBreaker = {\n 'deepseek': { failures: 0, lastFailure: null, state: 'CLOSED' },\n 'phi4': { failures: 0, lastFailure: null, state: 'CLOSED' },\n 'llama': { failures: 0, lastFailure: null, state: 'CLOSED' },\n};\n\n// Si un modĂšle fail 3 fois en 5 minutes → OPEN (skip pendant 1 minute)\n```\n\n### Cache Strategy\n\n```typescript\n// Redis cache avec TTL adaptatif\n\nconst CACHE_STRATEGY = {\n // Messages gĂ©nĂ©riques: cache long\n 'generation:simple': { ttl: 3600, hitRate: 85% },\n \n // Messages personnalisĂ©s: cache court\n 'generation:personalized': { ttl: 300, hitRate: 60% },\n \n // Analyses: pas de cache (donnĂ©es temps rĂ©el)\n 'reasoning:analysis': { ttl: 0, hitRate: 0% },\n \n // Classifications: cache moyen\n 'classification': { ttl: 1800, hitRate: 90% },\n \n // Contenu crĂ©atif: cache court\n 'creative': { ttl: 600, hitRate: 40% },\n};\n\n// Cache key format\nconst cacheKey = `ai:${model}:${hash(prompt)}:${userId}`;\n```\n\n### Rate Limiting\n\n```typescript\n// Rate limits par modĂšle (Azure AI Foundry)\n\nconst RATE_LIMITS = {\n 'deepseek-v3': {\n requestsPerMinute: 100,\n tokensPerMinute: 100000,\n burstAllowance: 20\n },\n 'deepseek-r1': {\n requestsPerMinute: 50,\n tokensPerMinute: 50000,\n burstAllowance: 10\n },\n 'phi-4-multimodal': {\n requestsPerMinute: 30,\n tokensPerMinute: 30000,\n burstAllowance: 5\n },\n 'phi4-mini': {\n requestsPerMinute: 200,\n tokensPerMinute: 200000,\n burstAllowance: 50\n },\n 'azure-speech-batch': {\n concurrentJobs: 10,\n hoursPerDay: 100\n }\n};\n\n// Queue system avec Upstash QStash si rate limit atteint\n```\n\n---\n\n## 🎯 Routing Intelligent\n\n### StratĂ©gie de SĂ©lection de ModĂšle\n\nLe Majordome utilise une stratĂ©gie de routing multi-critĂšres:\n\n```typescript\n// lib/ai/majordome.ts\n\ninterface RoutingDecision {\n model: ContentTrendsModel;\n reason: string;\n estimatedCost: number;\n estimatedLatency: number;\n}\n\nfunction decideModel(request: {\n task: string;\n complexity: 'simple' | 'standard' | 'high';\n priority: 'low' | 'normal' | 'high';\n budget: 'economy' | 'standard' | 'premium';\n}): RoutingDecision {\n \n // 1. Task-based routing (prioritĂ© haute)\n if (request.task === 'vision') {\n return {\n model: 'phi-4-multimodal',\n reason: 'Multimodal analysis required',\n estimatedCost: 0.0008,\n estimatedLatency: 1500\n };\n }\n \n if (request.task === 'transcription') {\n return {\n model: 'azure-speech-batch',\n reason: 'Audio transcription required',\n estimatedCost: 0.0015,\n estimatedLatency: 2000\n };\n }\n \n // 2. Complexity-based routing\n if (request.complexity === 'high') {\n return {\n model: 'deepseek-r1',\n reason: 'Deep reasoning required',\n estimatedCost: 0.20,\n estimatedLatency: 3000\n };\n }\n \n if (request.complexity === 'simple') {\n return {\n model: 'phi4-mini',\n reason: 'Fast generation sufficient',\n estimatedCost: 0.0008,\n estimatedLatency: 300\n };\n }\n \n // 3. Budget-based routing\n if (request.budget === 'economy') {\n return {\n model: 'phi4-mini',\n reason: 'Economy mode',\n estimatedCost: 0.0008,\n estimatedLatency: 300\n };\n }\n \n // 4. Priority-based routing\n if (request.priority === 'high') {\n return {\n model: 'phi4-mini',\n reason: 'Low latency required',\n estimatedCost: 0.0008,\n estimatedLatency: 300\n };\n }\n \n // 5. Default: DeepSeek-V3 (Ă©quilibrĂ©)\n return {\n model: 'deepseek-v3',\n reason: 'Standard generation',\n estimatedCost: 0.11,\n estimatedLatency: 800\n };\n}\n```\n\n### Matrice de DĂ©cision\n\n| CritĂšre | Phi-4 Mini | DeepSeek-V3 | DeepSeek-R1 | Phi-4 Multi | Mistral | Llama |\n|---------|-----------|-------------|-------------|-------------|---------|-------|\n| **Latence** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |\n| **CoĂ»t** | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |\n| **QualitĂ©** | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |\n| **CrĂ©ativitĂ©** | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |\n| **Raisonnement** | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |\n| **Vision** | ❌ | ❌ | ❌ | ⭐⭐⭐⭐⭐ | ❌ | ❌ |\n| **Audio** | ❌ | ❌ | ❌ | ⭐⭐⭐⭐ | ❌ | ❌ |\n\n### Exemples de Routing\n\n```typescript\n// Exemple 1: Message simple\ndecideModel({\n task: 'generation',\n complexity: 'simple',\n priority: 'high',\n budget: 'economy'\n})\n// → Phi-4 Mini (300ms, $0.0008)\n\n// Exemple 2: Message personnalisĂ©\ndecideModel({\n task: 'generation',\n complexity: 'standard',\n priority: 'normal',\n budget: 'standard'\n})\n// → DeepSeek-V3 (800ms, $0.11)\n\n// Exemple 3: Analyse stratĂ©gique\ndecideModel({\n task: 'reasoning',\n complexity: 'high',\n priority: 'normal',\n budget: 'premium'\n})\n// → DeepSeek-R1 (3000ms, $0.20)\n\n// Exemple 4: Analyse vidĂ©o\ndecideModel({\n task: 'vision',\n complexity: 'standard',\n priority: 'normal',\n budget: 'standard'\n})\n// → Phi-4 Multimodal (1500ms, $0.0008)\n\n// Exemple 5: Contenu crĂ©atif\ndecideModel({\n task: 'creative',\n complexity: 'standard',\n priority: 'low',\n budget: 'premium'\n})\n// → Mistral Large (1500ms, $0.33)\n```\n\n---\n\n\n## đŸ’Œ Cas d'Usage DĂ©taillĂ©s\n\n### 1. Messages OnlyFans (300K/mois)\n\n**ModĂšles utilisĂ©s**: DeepSeek-V3 (70%), Phi-4 Mini (30%)\n\n#### ScĂ©nario A: RĂ©ponse Ă  un nouveau fan\n\n```typescript\n// Input\nconst fanMessage = \"Hey bĂ©bĂ©, tu es magnifique 😍\";\nconst fanContext = {\n isNew: true,\n hasSubscribed: true,\n daysSinceSubscription: 1,\n totalSpent: 0\n};\n\n// Le Majordome dĂ©cide: Phi-4 Mini (rapide, nouveau fan)\nconst response = await askMajordome(\n `RĂ©ponds Ă  ce nouveau fan: \"${fanMessage}\"`,\n { userId: '123', history: [] }\n);\n\n// Output (300ms)\n\"Merci bĂ©bĂ© 💋 Bienvenue dans mon univers! Tu vas adorer ce que j'ai prĂ©parĂ© pour toi 😘\"\n\n// Cost: $0.0008\n```\n\n#### ScĂ©nario B: Message de vente PPV Ă  un VIP\n\n```typescript\n// Input\nconst fanContext = {\n isVIP: true,\n totalSpent: 450,\n lastPurchase: '2 days ago',\n preferredContent: ['lingerie', 'teasing']\n};\n\n// Le Majordome dĂ©cide: DeepSeek-V3 (qualitĂ©, VIP important)\nconst response = await askMajordome(\n `CrĂ©e un message de vente PPV pour ce fan VIP qui aime la lingerie`,\n { userId: '123', history: [] }\n);\n\n// Output (800ms)\n\"Hey bĂ©bĂ© 💋 J'ai shootĂ© quelque chose de spĂ©cial aujourd'hui... Une nouvelle collection de lingerie rouge qui va te rendre fou đŸ”„ Je te fais un prix VIP: $15 au lieu de $25. IntĂ©ressĂ©? 😏\"\n\n// Cost: $0.11\n```\n\n#### ScĂ©nario C: Relance d'un fan inactif\n\n```typescript\n// Input\nconst fanContext = {\n lastActive: '14 days ago',\n totalSpent: 120,\n churnRisk: 'high',\n previousInterests: ['feet', 'roleplay']\n};\n\n// Le Majordome dĂ©cide: DeepSeek-V3 (personnalisation importante)\nconst response = await askMajordome(\n `CrĂ©e un message de relance pour ce fan inactif depuis 14 jours`,\n { userId: '123', history: [] }\n);\n\n// Output (900ms)\n\"Hey toi 💋 Ça fait un moment! Tu me manques... J'ai pensĂ© Ă  toi en shootant ma nouvelle sĂ©rie pieds nus 👣 Tu veux un aperçu exclusif? 😘\"\n\n// Cost: $0.11\n```\n\n### 2. Content Trends (3K vidĂ©os/mois)\n\n**ModĂšles utilisĂ©s**: Phi-4 Multimodal (100%), Azure Speech (100%), DeepSeek-R1 (100%)\n\n#### ScĂ©nario: Analyse complĂšte d'une vidĂ©o TikTok virale\n\n```typescript\n// Input\nconst videoUrl = \"https://tiktok.com/@creator/video/123456\";\nconst videoMetrics = {\n views: 2300000,\n likes: 450000,\n shares: 89000,\n comments: 12000,\n duration: 30\n};\n\n// Étape 1: Download et extraction (Upstash QStash worker)\nconst { frames, audioUrl } = await extractVideoContent(videoUrl);\n// 9 keyframes extraites (0s, 3s, 6s, 9s, 12s, 15s, 18s, 21s, 27s)\n\n// Étape 2: Analyse multimodale (Phi-4 Multimodal)\nconst visualAnalysis = await analyzeVideoFrames({\n frames,\n metadata: videoMetrics\n});\n// Output: Composition, Ă©motions, texte, Ă©diting\n// Time: 1500ms, Cost: $0.0008\n\n// Étape 3: Transcription audio (Azure Speech Batch)\nconst audioAnalysis = await transcribeAudio({\n audioUrl,\n enableDiarization: true,\n enableWordTimestamps: true\n});\n// Output: Transcription + timestamps\n// Time: 2000ms, Cost: $0.0015\n\n// Étape 4: Raisonnement viral (DeepSeek-R1)\nconst viralAnalysis = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Analyse les mĂ©canismes de viralitĂ©...' \n },\n { \n role: 'user', \n content: `Visual: ${visualAnalysis}\\nAudio: ${audioAnalysis}\\nMetrics: ${videoMetrics}` \n }\n ]\n});\n// Output: MĂ©canismes viraux + recommandations\n// Time: 3000ms, Cost: $0.20\n\n// Total: 6500ms, $0.20\n```\n\n**RĂ©sultat complet**:\n\n```json\n{\n \"viralScore\": 95,\n \"replicabilityScore\": 85,\n \"visualAnalysis\": {\n \"hook\": {\n \"type\": \"transformation\",\n \"timing\": \"0-3s\",\n \"effectiveness\": \"high\"\n },\n \"composition\": {\n \"rule\": \"rule_of_thirds\",\n \"facePosition\": \"center\",\n \"backgroundClutter\": \"low\"\n },\n \"emotions\": [\n { \"frame\": 0, \"emotion\": \"surprise\", \"intensity\": 0.9 },\n { \"frame\": 3, \"emotion\": \"joy\", \"intensity\": 0.8 },\n { \"frame\": 6, \"emotion\": \"seduction\", \"intensity\": 0.95 }\n ],\n \"editing\": {\n \"cuts\": 15,\n \"tempo\": \"fast\",\n \"transitions\": [\"jump_cut\", \"zoom\", \"pan\"]\n },\n \"textOverlay\": [\n { \"text\": \"Wait for it...\", \"timing\": \"0-2s\" },\n { \"text\": \"OMG đŸ˜±\", \"timing\": \"3-5s\" },\n { \"text\": \"Try this!\", \"timing\": \"25-30s\" }\n ]\n },\n \"audioAnalysis\": {\n \"trendingSound\": {\n \"name\": \"XYZ Sound\",\n \"uses\": 500000,\n \"trending\": true\n },\n \"hook\": {\n \"type\": \"beat_drop\",\n \"timing\": \"3s\",\n \"synchronized\": true\n },\n \"voiceTone\": \"confident_playful\",\n \"tempo\": 128,\n \"transcription\": \"Hey guys! Watch this transformation...\"\n },\n \"viralMechanisms\": [\n {\n \"mechanism\": \"pattern_interrupt\",\n \"description\": \"Transformation inattendue capte l'attention\",\n \"effectiveness\": 0.95\n },\n {\n \"mechanism\": \"curiosity_gap\",\n \"description\": \"\\\"Wait for it\\\" crĂ©e anticipation\",\n \"effectiveness\": 0.90\n },\n {\n \"mechanism\": \"social_proof\",\n \"description\": \"RĂ©action authentique crĂ©e crĂ©dibilitĂ©\",\n \"effectiveness\": 0.85\n },\n {\n \"mechanism\": \"call_to_action\",\n \"description\": \"\\\"Try this!\\\" encourage engagement\",\n \"effectiveness\": 0.80\n }\n ],\n \"recommendations\": [\n {\n \"action\": \"use_trending_sound\",\n \"priority\": \"high\",\n \"impact\": \"high\",\n \"details\": \"Utilise le mĂȘme trending sound (500K uses)\"\n },\n {\n \"action\": \"replicate_hook\",\n \"priority\": \"high\",\n \"impact\": \"high\",\n \"details\": \"CrĂ©e ta version avec transformation (0-3s)\"\n },\n {\n \"action\": \"optimize_timing\",\n \"priority\": \"medium\",\n \"impact\": \"medium\",\n \"details\": \"Poste entre 18h-21h (peak engagement)\"\n },\n {\n \"action\": \"add_cta\",\n \"priority\": \"medium\",\n \"impact\": \"high\",\n \"details\": \"Ajoute CTA vers OnlyFans dans bio\"\n }\n ]\n}\n```\n\n### 3. Segmentation de Fans (50K/mois)\n\n**ModĂšles utilisĂ©s**: DeepSeek-R1 (100%)\n\n#### ScĂ©nario: Segmentation comportementale complĂšte\n\n```typescript\n// Input\nconst fansData = await prisma.fan.findMany({\n where: { creatorId: 123 },\n include: {\n messages: true,\n purchases: true,\n subscriptions: true\n }\n});\n// 247 fans\n\n// Le Majordome dĂ©cide: DeepSeek-R1 (raisonnement complexe)\nconst segmentation = await callAzureAI({\n model: 'deepseek-r1',\n messages: [\n { \n role: 'system', \n content: 'Segmente les fans par comportement et valeur...' \n },\n { \n role: 'user', \n content: `Fans: ${JSON.stringify(fansData)}` \n }\n ],\n temperature: 0.4,\n maxTokens: 1000\n});\n\n// Time: 3500ms, Cost: $0.20\n```\n\n**RĂ©sultat**:\n\n```json\n{\n \"segments\": [\n {\n \"name\": \"Whales\",\n \"count\": 12,\n \"percentage\": 4.9,\n \"characteristics\": {\n \"avgSpent\": 890,\n \"avgMessages\": 45,\n \"avgEngagement\": 0.85,\n \"churnRisk\": \"low\"\n },\n \"strategy\": {\n \"priority\": \"critical\",\n \"actions\": [\n \"Personal attention daily\",\n \"Exclusive content access\",\n \"Custom content offers\",\n \"VIP treatment\"\n ]\n }\n },\n {\n \"name\": \"VIP\",\n \"count\": 35,\n \"percentage\": 14.2,\n \"characteristics\": {\n \"avgSpent\": 250,\n \"avgMessages\": 20,\n \"avgEngagement\": 0.70,\n \"churnRisk\": \"low\"\n },\n \"strategy\": {\n \"priority\": \"high\",\n \"actions\": [\n \"Regular check-ins\",\n \"PPV offers with discount\",\n \"Early access to content\",\n \"Personalized messages\"\n ]\n }\n },\n {\n \"name\": \"Active\",\n \"count\": 89,\n \"percentage\": 36.0,\n \"characteristics\": {\n \"avgSpent\": 75,\n \"avgMessages\": 8,\n \"avgEngagement\": 0.50,\n \"churnRisk\": \"medium\"\n },\n \"strategy\": {\n \"priority\": \"medium\",\n \"actions\": [\n \"Regular content updates\",\n \"Occasional PPV offers\",\n \"Engagement campaigns\",\n \"Upsell to VIP\"\n ]\n }\n },\n {\n \"name\": \"At Risk\",\n \"count\": 23,\n \"percentage\": 9.3,\n \"characteristics\": {\n \"avgSpent\": 120,\n \"avgMessages\": 2,\n \"avgEngagement\": 0.15,\n \"churnRisk\": \"high\",\n \"daysSinceLastActive\": 14\n },\n \"strategy\": {\n \"priority\": \"urgent\",\n \"actions\": [\n \"Re-engagement message ASAP\",\n \"Exclusive offer to return\",\n \"Personalized content based on history\",\n \"Win-back campaign\"\n ]\n },\n \"urgentFans\": [\n {\n \"id\": \"fan_123\",\n \"username\": \"@john_doe\",\n \"totalSpent\": 450,\n \"daysSinceLastActive\": 18,\n \"reason\": \"VIP gone silent\"\n }\n ]\n },\n {\n \"name\": \"New\",\n \"count\": 45,\n \"percentage\": 18.2,\n \"characteristics\": {\n \"avgSpent\": 0,\n \"avgMessages\": 1,\n \"avgEngagement\": 0.30,\n \"daysSinceSubscription\": 7\n },\n \"strategy\": {\n \"priority\": \"high\",\n \"actions\": [\n \"Welcome sequence\",\n \"First purchase incentive\",\n \"Engagement content\",\n \"Convert to Active\"\n ]\n }\n },\n {\n \"name\": \"Lurkers\",\n \"count\": 43,\n \"percentage\": 17.4,\n \"characteristics\": {\n \"avgSpent\": 10,\n \"avgMessages\": 0,\n \"avgEngagement\": 0.05,\n \"churnRisk\": \"high\"\n },\n \"strategy\": {\n \"priority\": \"low\",\n \"actions\": [\n \"Automated engagement\",\n \"Free content to hook\",\n \"Low-effort maintenance\",\n \"Accept natural churn\"\n ]\n }\n }\n ],\n \"insights\": [\n {\n \"type\": \"revenue_concentration\",\n \"finding\": \"Top 20% fans generate 80% revenue\",\n \"action\": \"Focus on Whales + VIP retention\"\n },\n {\n \"type\": \"churn_risk\",\n \"finding\": \"23 fans at high churn risk (9.3%)\",\n \"action\": \"Urgent re-engagement campaign\"\n },\n {\n \"type\": \"conversion_opportunity\",\n \"finding\": \"45 new fans not yet converted (18.2%)\",\n \"action\": \"Optimize onboarding sequence\"\n }\n ],\n \"recommendations\": [\n {\n \"priority\": \"critical\",\n \"action\": \"Contact 23 at-risk fans within 24h\",\n \"expectedImpact\": \"Save $2,760 MRR\"\n },\n {\n \"priority\": \"high\",\n \"action\": \"Launch VIP upsell campaign for 89 Active fans\",\n \"expectedImpact\": \"Add $1,500 MRR\"\n },\n {\n \"priority\": \"medium\",\n \"action\": \"Optimize new fan onboarding (45 fans)\",\n \"expectedImpact\": \"Increase conversion by 30%\"\n }\n ]\n}\n```\n\n### 4. Campagnes Marketing (15K/mois)\n\n**ModĂšles utilisĂ©s**: DeepSeek-V3 (80%), Mistral (20%)\n\n#### ScĂ©nario: GĂ©nĂ©ration de campagne complĂšte\n\n```typescript\n// Input\nconst campaignGoal = {\n objective: 'increase_ppv_sales',\n target: 'vip_fans',\n budget: 0, // Temps seulement\n duration: '7_days'\n};\n\n// Le Majordome dĂ©cide: DeepSeek-V3 (gĂ©nĂ©ration structurĂ©e)\nconst campaign = await callAzureAI({\n model: 'deepseek-v3',\n messages: [\n { \n role: 'system', \n content: 'CrĂ©e une campagne marketing complĂšte...' \n },\n { \n role: 'user', \n content: `Goal: ${JSON.stringify(campaignGoal)}` \n }\n ],\n temperature: 0.7,\n maxTokens: 800\n});\n\n// Time: 1200ms, Cost: $0.11\n```\n\n**RĂ©sultat**:\n\n```json\n{\n \"campaignName\": \"VIP Exclusive Week\",\n \"duration\": \"7 days\",\n \"target\": \"35 VIP fans\",\n \"objective\": \"Increase PPV sales by 40%\",\n \"timeline\": [\n {\n \"day\": 1,\n \"action\": \"teaser_message\",\n \"content\": \"Hey bĂ©bĂ© 💋 J'ai quelque chose de spĂ©cial pour mes VIP cette semaine... Tu es prĂȘt? 😏\",\n \"timing\": \"18:00\",\n \"expectedEngagement\": 0.70\n },\n {\n \"day\": 2,\n \"action\": \"reveal_campaign\",\n \"content\": \"đŸ”„ VIP EXCLUSIVE WEEK đŸ”„\\n\\nPendant 7 jours, mes VIP ont accĂšs Ă :\\n- 20% off sur TOUS les PPV\\n- 1 custom photo gratuite\\n- Early access nouveau contenu\\n\\nIntĂ©ressĂ© bĂ©bĂ©? 😘\",\n \"timing\": \"19:00\",\n \"expectedEngagement\": 0.85\n },\n {\n \"day\": 3,\n \"action\": \"first_ppv_offer\",\n \"content\": \"Premier PPV de la semaine 💋\\n\\nNouvelle sĂ©rie lingerie rouge đŸ”„\\n- 15 photos HD\\n- 2 vidĂ©os exclusives\\n\\nPrix VIP: $12 (au lieu de $15)\\n\\nDispo 24h seulement! 😏\",\n \"timing\": \"20:00\",\n \"expectedConversion\": 0.40\n },\n {\n \"day\": 4,\n \"action\": \"social_proof\",\n \"content\": \"Wow bĂ©bĂ©! 12 VIP ont dĂ©jĂ  pris le PPV d'hier đŸ”„\\n\\nTu ne veux pas rater ça... Encore 6h pour profiter du prix VIP! 💋\",\n \"timing\": \"14:00\",\n \"expectedConversion\": 0.25\n },\n {\n \"day\": 5,\n \"action\": \"second_ppv_offer\",\n \"content\": \"Nouveau PPV VIP 😘\\n\\nSĂ©rie \\\"Behind the Scenes\\\" 📾\\n- 20 photos exclusives\\n- 1 vidĂ©o 5min\\n- Contenu jamais vu\\n\\nPrix VIP: $10 (au lieu de $15)\\n\\n48h seulement! đŸ”„\",\n \"timing\": \"19:00\",\n \"expectedConversion\": 0.35\n },\n {\n \"day\": 6,\n \"action\": \"custom_offer_reminder\",\n \"content\": \"Hey bĂ©bĂ© 💋\\n\\nN'oublie pas: tu as droit Ă  1 custom photo gratuite!\\n\\nDis-moi ce que tu veux voir... Je te fais ça avec amour 😘\",\n \"timing\": \"18:00\",\n \"expectedEngagement\": 0.60\n },\n {\n \"day\": 7,\n \"action\": \"final_push\",\n \"content\": \"🚹 DERNIER JOUR VIP WEEK 🚹\\n\\nDerniĂšre chance pour:\\n- 20% off PPV\\n- Custom photo gratuite\\n\\nÀ minuit, c'est fini! 💋\\n\\nTu profites bĂ©bĂ©? 😏\",\n \"timing\": \"20:00\",\n \"expectedConversion\": 0.30\n }\n ],\n \"expectedResults\": {\n \"totalMessages\": 245, // 35 fans × 7 days\n \"expectedEngagement\": 0.65,\n \"expectedPPVSales\": 28, // 40% increase\n \"expectedRevenue\": 336, // $12 avg × 28 sales\n \"roi\": \"infinite\" // No cost campaign\n },\n \"successMetrics\": [\n {\n \"metric\": \"engagement_rate\",\n \"target\": 0.65,\n \"measurement\": \"Messages opened / sent\"\n },\n {\n \"metric\": \"conversion_rate\",\n \"target\": 0.35,\n \"measurement\": \"PPV purchases / offers sent\"\n },\n {\n \"metric\": \"revenue\",\n \"target\": 336,\n \"measurement\": \"Total PPV sales\"\n }\n ]\n}\n```\n\n---\n\n\n## 💰 Budget et Scaling\n\n### Budget DĂ©taillĂ© (50 Users Beta)\n\n| ModĂšle | Usage/mois | CoĂ»t/mois | % Budget | Cas d'usage principal |\n|--------|------------|-----------|----------|----------------------|\n| **DeepSeek-V3** | 300,000 calls | **$34.00** | 55% | Messages OnlyFans, Contenu marketing |\n| **DeepSeek-R1** | 50,000 calls | **$10.00** | 16% | Analyses complexes, Segmentation |\n| **Llama 3.3-70B** | 20,000 calls | **$5.00** | 8% | Fallback, Tests A/B |\n| **Mistral Large** | 15,000 calls | **$5.00** | 8% | Contenu crĂ©atif, Conversations |\n| **Azure Speech** | 25h audio | **$5.00** | 8% | Transcription vidĂ©os virales |\n| **Phi-4 Multimodal** | 3,000 videos | **$2.40** | 4% | Analyse vidĂ©os/images |\n| **Phi-4 Mini** | 100,000 calls | **$1.00** | 1% | Classification, Routing |\n| **TOTAL** | **~488K ops** | **$62.40** | **100%** | **Tous cas d'usage** |\n\n### RĂ©partition par Cas d'Usage\n\n| Cas d'Usage | ModĂšles | Calls/mois | CoĂ»t/mois | % Total |\n|-------------|---------|------------|-----------|---------|\n| **Messages OnlyFans** | DeepSeek-V3 (70%), Phi-4 Mini (30%) | 300K | **$35.00** | 56% |\n| **Content Trends** | Phi-4 Multi, Speech, DeepSeek-R1 | 3K videos | **$17.40** | 28% |\n| **Marketing/Campagnes** | DeepSeek-V3, DeepSeek-R1 | 15K | **$5.00** | 8% |\n| **Fallback/Tests** | Llama, Mistral | 35K | **$5.00** | 8% |\n\n### CoĂ»t par Utilisatrice\n\n```\n50 utilisatrices × $62.40 = $1.25/user/mois\n\nBreakdown par user:\n- Messages OnlyFans: $0.70/user/mois (6K messages)\n- Content Trends: $0.35/user/mois (60 videos)\n- Marketing: $0.10/user/mois (300 calls)\n- Autres: $0.10/user/mois (700 calls)\n```\n\n### Scaling Plan\n\n#### 100 Users ($120/mois)\n\n| ModĂšle | Usage/mois | CoĂ»t/mois | Scaling factor |\n|--------|------------|-----------|----------------|\n| DeepSeek-V3 | 600K calls | $68 | 2x |\n| DeepSeek-R1 | 100K calls | $20 | 2x |\n| Phi-4 Multimodal | 6K videos | $5 | 2x |\n| Azure Speech | 50h audio | $9 | 2x |\n| Autres | - | $18 | 2x |\n| **TOTAL** | **~976K ops** | **$120** | **2x** |\n\n**Marge**: $880/mois restants (88% du budget)\n\n#### 500 Users ($500/mois)\n\n| ModĂšle | Usage/mois | CoĂ»t/mois | Scaling factor |\n|--------|------------|-----------|----------------|\n| DeepSeek-V3 | 3M calls | $340 | 10x |\n| DeepSeek-R1 | 500K calls | $100 | 10x |\n| Phi-4 Multimodal | 30K videos | $25 | 10x |\n| Azure Speech | 250h audio | $45 | 10x |\n| Autres | - | $90 | 10x |\n| **TOTAL** | **~4.88M ops** | **$500** | **10x** |\n\n**Marge**: $500/mois restants (50% du budget)\n\n#### 1,000 Users ($900/mois)\n\n| ModĂšle | Usage/mois | CoĂ»t/mois | Scaling factor |\n|--------|------------|-----------|----------------|\n| DeepSeek-V3 | 6M calls | $680 | 20x |\n| DeepSeek-R1 | 1M calls | $200 | 20x |\n| Phi-4 Multimodal | 60K videos | $50 | 20x |\n| Azure Speech | 500h audio | $90 | 20x |\n| Autres | - | $180 | 20x |\n| **TOTAL** | **~9.76M ops** | **$900** | **20x** |\n\n**Marge**: $100/mois restants (10% du budget)\n\n### Optimisations de CoĂ»ts\n\n#### 1. Cache Agressif (80% hit rate)\n\n```typescript\n// Sans cache\n300K calls × $0.11 = $33,000/mois ❌\n\n// Avec cache 80% hit rate\n60K calls × $0.11 = $6,600/mois ✅\nÉconomie: $26,400/mois (80%)\n```\n\n#### 2. Routing Intelligent\n\n```typescript\n// Sans routing (tout DeepSeek-V3)\n400K calls × $0.11 = $44,000/mois ❌\n\n// Avec routing intelligent\n- 100K Phi-4 Mini × $0.01 = $1,000\n- 300K DeepSeek-V3 × $0.11 = $33,000\nTotal: $34,000/mois ✅\nÉconomie: $10,000/mois (23%)\n```\n\n#### 3. Batch Processing\n\n```typescript\n// Transcription temps rĂ©el (Azure Speech Real-time)\n25h × $2.50/h = $62.50/mois ❌\n\n// Transcription batch (Azure Speech Batch)\n25h × $0.18/h = $4.50/mois ✅\nÉconomie: $58/mois (93%)\n```\n\n#### 4. Model Compression\n\n```typescript\n// RĂ©ponses longues (500 tokens)\n300K calls × 500 tokens × $0.00456/1K = $684/mois ❌\n\n// RĂ©ponses compactes (200 tokens)\n300K calls × 200 tokens × $0.00456/1K = $274/mois ✅\nÉconomie: $410/mois (60%)\n```\n\n### ROI Analysis\n\n#### CoĂ»t par FonctionnalitĂ©\n\n```\nMessages OnlyFans: $35/mois\n→ 300K messages gĂ©nĂ©rĂ©s\n→ $0.00012 par message\n→ Si 1% convertit Ă  $10 = $30,000 revenue\n→ ROI: 857x\n\nContent Trends: $17.40/mois\n→ 3K vidĂ©os analysĂ©es\n→ $0.0058 par vidĂ©o\n→ Si 10% rĂ©pliquĂ©es avec succĂšs = 300 vidĂ©os virales\n→ Valeur: Inestimable (croissance organique)\n\nSegmentation: $10/mois\n→ 50K analyses\n→ $0.0002 par analyse\n→ Si sauve 10% churn = $2,760 MRR saved\n→ ROI: 276x\n```\n\n#### Comparaison avec Alternatives\n\n| Solution | CoĂ»t/mois | QualitĂ© | Latence | ScalabilitĂ© |\n|----------|-----------|---------|---------|-------------|\n| **Azure AI (notre solution)** | **$62** | ⭐⭐⭐⭐⭐ | 300-3000ms | ⭐⭐⭐⭐⭐ |\n| OpenAI GPT-4 | $450 | ⭐⭐⭐⭐⭐ | 500-2000ms | ⭐⭐⭐⭐ |\n| Anthropic Claude | $380 | ⭐⭐⭐⭐⭐ | 800-2500ms | ⭐⭐⭐⭐ |\n| OpenAI GPT-3.5 | $120 | ⭐⭐⭐ | 300-1000ms | ⭐⭐⭐⭐⭐ |\n| Llama self-hosted | $200 | ⭐⭐⭐⭐ | 1000-3000ms | ⭐⭐⭐ |\n\n**Économie vs GPT-4**: $388/mois (86%) \n**Économie vs Claude**: $318/mois (84%) \n**Économie vs GPT-3.5**: $58/mois (48%)\n\n---\n\n## đŸ’» ImplĂ©mentation Code\n\n### Configuration Azure AI\n\n```typescript\n// lib/ai/content-trends/azure-foundry-config.ts\n\nexport const DEEPSEEK_V3_CONFIG: ModelEndpoint = {\n modelId: 'deepseek-v3',\n name: 'DeepSeek V3 (Generation)',\n deploymentName: process.env.AZURE_DEEPSEEK_V3_DEPLOYMENT || 'deepseek-v3-generation',\n region: process.env.AZURE_AI_REGION || 'eastus2',\n endpoint: process.env.AZURE_DEEPSEEK_V3_ENDPOINT || '',\n capabilities: ['generation', 'summarization', 'classification'],\n pricing: {\n inputPerMillion: 1.14,\n outputPerMillion: 4.56,\n },\n defaultParams: {\n temperature: 0.7,\n maxTokens: 4096,\n topP: 0.9,\n contextWindow: 128000,\n },\n};\n\nexport const DEEPSEEK_R1_CONFIG: ModelEndpoint = {\n modelId: 'deepseek-r1',\n name: 'DeepSeek R1 (Reasoning)',\n deploymentName: process.env.AZURE_DEEPSEEK_R1_DEPLOYMENT || 'deepseek-r1-reasoning',\n region: process.env.AZURE_AI_REGION || 'eastus2',\n endpoint: process.env.AZURE_DEEPSEEK_R1_ENDPOINT || '',\n capabilities: ['reasoning', 'classification'],\n pricing: {\n inputPerMillion: 1.35,\n outputPerMillion: 5.40,\n },\n defaultParams: {\n temperature: 0.6,\n maxTokens: 8192,\n topP: 0.95,\n contextWindow: 64000,\n },\n};\n\nexport const PHI4_MULTIMODAL_CONFIG: ModelEndpoint = {\n modelId: 'phi-4-multimodal-instruct',\n name: 'Phi-4 Multimodal (Vision + Audio)',\n deploymentName: process.env.AZURE_PHI4_MULTIMODAL_DEPLOYMENT || 'phi-4-multimodal-instruct',\n region: process.env.AZURE_AI_REGION || 'eastus2',\n endpoint: process.env.AZURE_PHI4_MULTIMODAL_ENDPOINT || '',\n capabilities: ['vision', 'multimodal', 'ocr', 'classification'],\n pricing: {\n inputPerMillion: 0.40,\n outputPerMillion: 0.40,\n },\n defaultParams: {\n temperature: 0.3,\n maxTokens: 4096,\n contextWindow: 128000,\n },\n};\n```\n\n### Variables d'Environnement\n\n```bash\n# .env.example\n\n# Azure AI Foundry - General\nAZURE_AI_REGION=eastus2\nAZURE_AI_FAILOVER_REGIONS=westus2,northeurope\nAZURE_USE_MANAGED_IDENTITY=true\nAZURE_AI_API_KEY=REDACTED_api_key_here\nAZURE_TENANT_ID=your_tenant_id_here\n\n# DeepSeek V3 (Generation)\nAZURE_DEEPSEEK_V3_ENDPOINT=https://your-endpoint.eastus2.inference.ai.azure.com\nAZURE_DEEPSEEK_V3_DEPLOYMENT=deepseek-v3-generation\nAZURE_DEEPSEEK_V3_API_KEY=REDACTED_key_here\n\n# DeepSeek R1 (Reasoning)\nAZURE_DEEPSEEK_R1_ENDPOINT=https://your-endpoint.eastus2.inference.ai.azure.com\nAZURE_DEEPSEEK_R1_DEPLOYMENT=deepseek-r1-reasoning\nAZURE_DEEPSEEK_R1_API_KEY=REDACTED_key_here\n\n# Phi-4 Multimodal\nAZURE_PHI4_MULTIMODAL_ENDPOINT=https://your-endpoint.eastus2.inference.ai.azure.com\nAZURE_PHI4_MULTIMODAL_DEPLOYMENT=phi-4-multimodal-instruct\nAZURE_PHI4_MULTIMODAL_API_KEY=REDACTED_key_here\n\n# Phi-4 Mini\nAZURE_PHI4_MINI_ENDPOINT=https://your-endpoint.eastus2.inference.ai.azure.com\nAZURE_PHI4_MINI_DEPLOYMENT=phi-4-mini\nAZURE_PHI4_MINI_API_KEY=REDACTED_key_here\n\n# Llama 3.3-70B\nAZURE_LLAMA_ENDPOINT=https://your-endpoint.eastus2.inference.ai.azure.com\nAZURE_LLAMA_DEPLOYMENT=llama-3-3-70b\nAZURE_LLAMA_API_KEY=REDACTED_key_here\n\n# Mistral Large\nAZURE_MISTRAL_ENDPOINT=https://your-endpoint.eastus2.inference.ai.azure.com\nAZURE_MISTRAL_DEPLOYMENT=mistral-large\nAZURE_MISTRAL_API_KEY=REDACTED_key_here\n\n# Azure Speech\nAZURE_SPEECH_ENDPOINT=https://your-region.api.cognitive.microsoft.com\nAZURE_SPEECH_KEY=REDACTED_speech_key_here\nAZURE_SPEECH_REGION=eastus2\n\n# Rate Limits\nAZURE_AI_RPM=100\nAZURE_AI_TPM=100000\n```\n\n### Client Azure AI\n\n```typescript\n// lib/ai/providers/azure-ai.ts\n\nimport { DefaultAzureCredential } from '@azure/identity';\nimport { getContentTrendsAIConfig } from '../content-trends/azure-foundry-config';\n\nexport interface AzureAIRequest {\n model: 'deepseek' | 'deepseek-v3' | 'deepseek-r1' | 'phi4' | 'phi4-mini' | 'llama' | 'mistral';\n messages: Array<{ role: string; content: string }>;\n temperature?: number;\n maxTokens?: number;\n topP?: number;\n tools?: any[];\n toolChoice?: string;\n abortSignal?: AbortSignal;\n}\n\nexport interface AzureAIResponse {\n content: string;\n usage: {\n input: number;\n output: number;\n total: number;\n };\n tool_calls?: any[];\n model: string;\n finishReason: string;\n}\n\nexport async function callAzureAI(request: AzureAIRequest): Promise<AzureAIResponse> {\n const config = getContentTrendsAIConfig();\n \n // Map model aliases\n const modelMap: Record<string, string> = {\n 'deepseek': 'deepseek-v3',\n 'phi4': 'phi4-mini',\n };\n const modelId = modelMap[request.model] || request.model;\n \n // Get model config\n const modelConfig = config.models[modelId as keyof typeof config.models];\n if (!modelConfig) {\n throw new Error(`Unknown model: ${modelId}`);\n }\n \n // Authentication\n let headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n \n if (config.auth.useManagedIdentity) {\n const credential = new DefaultAzureCredential();\n const token = await credential.getToken('https://cognitiveservices.azure.com/.default');\n headers['Authorization'] = `Bearer ${token.token}`;\n } else if (config.auth.apiKey) {\n headers['api-key'] = config.auth.apiKey;\n } else {\n throw new Error('No authentication configured');\n }\n \n // Build request body\n const body = {\n messages: request.messages,\n temperature: request.temperature ?? modelConfig.defaultParams.temperature,\n max_tokens: request.maxTokens ?? modelConfig.defaultParams.maxTokens,\n top_p: request.topP ?? modelConfig.defaultParams.topP,\n ...(request.tools && { tools: request.tools }),\n ...(request.toolChoice && { tool_choice: request.toolChoice }),\n };\n \n // Call Azure AI\n const response = await fetch(`${modelConfig.endpoint}/chat/completions`, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: request.abortSignal,\n });\n \n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Azure AI error: ${response.status} ${error}`);\n }\n \n const data = await response.json();\n \n // Parse response\n return {\n content: data.choices[0].message.content || '',\n usage: {\n input: data.usage.prompt_tokens,\n output: data.usage.completion_tokens,\n total: data.usage.total_tokens,\n },\n tool_calls: data.choices[0].message.tool_calls,\n model: modelId,\n finishReason: data.choices[0].finish_reason,\n };\n}\n\n// Helper: Clean DeepSeek output (removes thinking tags)\nexport function cleanDeepSeekOutput(content: string): string {\n return content\n .replace(/<think>[\\s\\S]*?<\\/think>/g, '')\n .replace(/<thinking>[\\s\\S]*?<\\/thinking>/g, '')\n .trim();\n}\n```\n\n### Le Majordome - Code Complet\n\n```typescript\n// src/lib/ai/majordome.ts\n\nimport { callAzureAI, cleanDeepSeekOutput } from './providers/azure-ai';\nimport { prisma } from '@/lib/prisma';\n\nexport async function askMajordome(\n userRequest: string, \n opts: AskMajordomeOptions = {}\n): Promise<MajordomeResult> {\n \n // Build conversation\n const messages: ChatMessage[] = [\n { role: \"system\", content: systemPrompt(opts) },\n ...(opts.history?.map((m) => ({ role: m.role, content: m.content })) ?? []),\n { role: \"user\", content: userRequest },\n ];\n \n // Multi-turn execution\n let safetyLoop = 0;\n while (safetyLoop < 3) {\n safetyLoop += 1;\n \n try {\n // Use Phi-4 Mini for orchestration (fast tool selection)\n const response = await callAzureAI({\n model: 'phi4-mini',\n messages,\n temperature: 0.2,\n maxTokens: 500,\n tools: MAJORDOME_TOOLS,\n toolChoice: 'auto',\n });\n \n const toolCalls = response.tool_calls;\n \n // No tools needed - direct reply\n if (!toolCalls?.length) {\n return { type: \"REPLY\", message: response.content };\n }\n \n // Execute tools in parallel\n const executed = await Promise.all(\n toolCalls.map(async (call) => {\n const parsed = safeJsonParse(call.function.arguments);\n const result = parsed.ok\n ? await executeTool(call.function.name, parsed.value, opts)\n : { ok: false, error: \"Invalid arguments\" };\n \n return {\n tool_call_id: call.id,\n content: JSON.stringify(result),\n };\n })\n );\n \n // Add tool results to conversation\n for (const toolResult of executed) {\n messages.push({\n role: \"tool\",\n tool_call_id: toolResult.tool_call_id,\n content: toolResult.content,\n });\n }\n \n // Continue if more tools needed\n } catch (error) {\n console.error(\"Majordome error:\", error);\n return {\n type: \"ERROR\",\n message: \"Erreur Azure AI. VĂ©rifiez votre configuration.\",\n details: error,\n };\n }\n }\n \n return {\n type: \"ERROR\",\n message: \"Trop d'actions. Simplifiez votre demande SVP.\",\n };\n}\n```\n\n---\n\n\n## 📊 Monitoring et Optimisation\n\n### MĂ©triques ClĂ©s\n\n#### 1. Performance Metrics\n\n```typescript\n// lib/ai/monitoring/metrics.ts\n\nexport interface AIMetrics {\n // Latency\n p50Latency: number; // MĂ©diane\n p95Latency: number; // 95e percentile\n p99Latency: number; // 99e percentile\n \n // Throughput\n requestsPerMinute: number;\n tokensPerMinute: number;\n \n // Quality\n successRate: number;\n errorRate: number;\n timeoutRate: number;\n \n // Cost\n costPerRequest: number;\n costPerToken: number;\n totalCost: number;\n \n // Cache\n cacheHitRate: number;\n cacheMissRate: number;\n}\n\n// Collect metrics\nexport async function collectMetrics(\n model: string,\n startTime: number,\n endTime: number,\n tokens: { input: number; output: number },\n success: boolean,\n cached: boolean\n): Promise<void> {\n const latency = endTime - startTime;\n \n await prisma.aiMetric.create({\n data: {\n model,\n latency,\n tokensInput: tokens.input,\n tokensOutput: tokens.output,\n success,\n cached,\n timestamp: new Date(),\n },\n });\n}\n```\n\n#### 2. Cost Tracking\n\n```typescript\n// lib/ai/cost-logger.ts\n\nexport interface CostLog {\n when: Date;\n plan: 'starter' | 'pro' | 'scale' | 'enterprise';\n model: string;\n provider: string;\n tier: 'economy' | 'standard' | 'premium';\n tokensIn: number;\n tokensOut: number;\n msgs: number;\n segment?: string;\n action?: string;\n accountId?: string;\n}\n\nexport async function logCost(log: CostLog): Promise<void> {\n // Calculate cost\n const config = getModelEndpoint(log.model as any);\n const inputCost = (log.tokensIn / 1_000_000) * config.pricing.inputPerMillion;\n const outputCost = (log.tokensOut / 1_000_000) * config.pricing.outputPerMillion;\n const totalCost = inputCost + outputCost;\n \n // Store in database\n await prisma.aiCostLog.create({\n data: {\n ...log,\n inputCost,\n outputCost,\n totalCost,\n },\n });\n \n // Update running totals\n await redis.hincrby(`ai:cost:${log.accountId}:${getMonth()}`, log.model, totalCost);\n}\n\n// Get cost summary\nexport async function getCostSummary(\n accountId: string,\n month: string\n): Promise<Record<string, number>> {\n return await redis.hgetall(`ai:cost:${accountId}:${month}`);\n}\n```\n\n#### 3. Quality Monitoring\n\n```typescript\n// lib/ai/monitoring/quality.ts\n\nexport interface QualityMetrics {\n // User satisfaction\n thumbsUp: number;\n thumbsDown: number;\n satisfactionRate: number;\n \n // Conversion\n messagesGenerated: number;\n messagesSent: number;\n messagesConverted: number;\n conversionRate: number;\n \n // Engagement\n avgResponseTime: number;\n avgEngagementRate: number;\n \n // Errors\n hallucinations: number;\n inappropriateContent: number;\n technicalErrors: number;\n}\n\n// Track quality\nexport async function trackQuality(\n messageId: string,\n feedback: 'positive' | 'negative' | 'neutral',\n converted: boolean,\n engagementRate: number\n): Promise<void> {\n await prisma.aiQualityLog.create({\n data: {\n messageId,\n feedback,\n converted,\n engagementRate,\n timestamp: new Date(),\n },\n });\n}\n```\n\n### Dashboards\n\n#### 1. Cost Dashboard\n\n```typescript\n// app/api/admin/ai-costs/route.ts\n\nexport async function GET(request: Request) {\n const { searchParams } = new URL(request.url);\n const month = searchParams.get('month') || getCurrentMonth();\n \n // Get all cost logs for the month\n const costs = await prisma.aiCostLog.findMany({\n where: {\n when: {\n gte: new Date(`${month}-01`),\n lt: new Date(`${month}-31`),\n },\n },\n orderBy: { when: 'desc' },\n });\n \n // Aggregate by model\n const byModel = costs.reduce((acc, log) => {\n acc[log.model] = (acc[log.model] || 0) + log.totalCost;\n return acc;\n }, {} as Record<string, number>);\n \n // Aggregate by day\n const byDay = costs.reduce((acc, log) => {\n const day = log.when.toISOString().split('T')[0];\n acc[day] = (acc[day] || 0) + log.totalCost;\n return acc;\n }, {} as Record<string, number>);\n \n return Response.json({\n month,\n totalCost: costs.reduce((sum, log) => sum + log.totalCost, 0),\n byModel,\n byDay,\n topAccounts: await getTopAccounts(month),\n });\n}\n```\n\n#### 2. Performance Dashboard\n\n```typescript\n// app/api/admin/ai-metrics/route.ts\n\nexport async function GET(request: Request) {\n const { searchParams } = new URL(request.url);\n const hours = parseInt(searchParams.get('hours') || '24');\n \n const metrics = await prisma.aiMetric.findMany({\n where: {\n timestamp: {\n gte: new Date(Date.now() - hours * 60 * 60 * 1000),\n },\n },\n });\n \n // Calculate percentiles\n const latencies = metrics.map(m => m.latency).sort((a, b) => a - b);\n const p50 = latencies[Math.floor(latencies.length * 0.5)];\n const p95 = latencies[Math.floor(latencies.length * 0.95)];\n const p99 = latencies[Math.floor(latencies.length * 0.99)];\n \n // Calculate rates\n const successRate = metrics.filter(m => m.success).length / metrics.length;\n const cacheHitRate = metrics.filter(m => m.cached).length / metrics.length;\n \n return Response.json({\n period: `${hours}h`,\n totalRequests: metrics.length,\n latency: { p50, p95, p99 },\n successRate,\n cacheHitRate,\n byModel: groupByModel(metrics),\n });\n}\n```\n\n### Alertes\n\n```typescript\n// lib/ai/monitoring/alerts.ts\n\nexport interface Alert {\n type: 'cost' | 'performance' | 'quality' | 'error';\n severity: 'low' | 'medium' | 'high' | 'critical';\n message: string;\n details: any;\n}\n\n// Cost alerts\nexport async function checkCostAlerts(accountId: string): Promise<Alert[]> {\n const alerts: Alert[] = [];\n const month = getCurrentMonth();\n const costs = await getCostSummary(accountId, month);\n const totalCost = Object.values(costs).reduce((sum, cost) => sum + cost, 0);\n \n // Budget threshold alerts\n if (totalCost > 900) {\n alerts.push({\n type: 'cost',\n severity: 'critical',\n message: 'Budget Azure AI presque Ă©puisĂ©',\n details: { totalCost, budget: 1000, remaining: 1000 - totalCost },\n });\n } else if (totalCost > 750) {\n alerts.push({\n type: 'cost',\n severity: 'high',\n message: 'Budget Azure AI Ă  75%',\n details: { totalCost, budget: 1000, remaining: 1000 - totalCost },\n });\n }\n \n return alerts;\n}\n\n// Performance alerts\nexport async function checkPerformanceAlerts(): Promise<Alert[]> {\n const alerts: Alert[] = [];\n const metrics = await getRecentMetrics(1); // Last hour\n \n // Latency alerts\n if (metrics.p95Latency > 5000) {\n alerts.push({\n type: 'performance',\n severity: 'high',\n message: 'Latence P95 Ă©levĂ©e',\n details: { p95: metrics.p95Latency, threshold: 5000 },\n });\n }\n \n // Error rate alerts\n if (metrics.errorRate > 0.05) {\n alerts.push({\n type: 'error',\n severity: 'high',\n message: 'Taux d\\'erreur Ă©levĂ©',\n details: { errorRate: metrics.errorRate, threshold: 0.05 },\n });\n }\n \n // Cache hit rate alerts\n if (metrics.cacheHitRate < 0.60) {\n alerts.push({\n type: 'performance',\n severity: 'medium',\n message: 'Cache hit rate faible',\n details: { cacheHitRate: metrics.cacheHitRate, threshold: 0.80 },\n });\n }\n \n return alerts;\n}\n\n// Quality alerts\nexport async function checkQualityAlerts(): Promise<Alert[]> {\n const alerts: Alert[] = [];\n const quality = await getRecentQuality(24); // Last 24h\n \n // Satisfaction alerts\n if (quality.satisfactionRate < 0.70) {\n alerts.push({\n type: 'quality',\n severity: 'high',\n message: 'Satisfaction utilisateurs faible',\n details: { satisfactionRate: quality.satisfactionRate, threshold: 0.80 },\n });\n }\n \n // Conversion alerts\n if (quality.conversionRate < 0.10) {\n alerts.push({\n type: 'quality',\n severity: 'medium',\n message: 'Taux de conversion faible',\n details: { conversionRate: quality.conversionRate, threshold: 0.15 },\n });\n }\n \n return alerts;\n}\n```\n\n### Optimisations Continues\n\n#### 1. A/B Testing\n\n```typescript\n// lib/ai/optimization/ab-testing.ts\n\nexport interface ABTest {\n id: string;\n name: string;\n variants: Array<{\n id: string;\n model: string;\n temperature: number;\n systemPrompt: string;\n weight: number;\n }>;\n metrics: {\n conversionRate: number;\n satisfactionRate: number;\n avgLatency: number;\n avgCost: number;\n };\n}\n\n// Run A/B test\nexport async function runABTest(\n testId: string,\n userRequest: string\n): Promise<{ variant: string; response: string }> {\n const test = await getABTest(testId);\n \n // Select variant based on weights\n const variant = selectVariant(test.variants);\n \n // Generate response with variant config\n const response = await callAzureAI({\n model: variant.model as any,\n messages: [\n { role: 'system', content: variant.systemPrompt },\n { role: 'user', content: userRequest },\n ],\n temperature: variant.temperature,\n });\n \n // Track result\n await trackABTestResult(testId, variant.id, response);\n \n return { variant: variant.id, response: response.content };\n}\n```\n\n#### 2. Prompt Optimization\n\n```typescript\n// lib/ai/optimization/prompt-optimizer.ts\n\nexport interface PromptVariant {\n id: string;\n systemPrompt: string;\n metrics: {\n avgConversionRate: number;\n avgSatisfaction: number;\n avgLatency: number;\n sampleSize: number;\n };\n}\n\n// Test prompt variants\nexport async function optimizePrompt(\n basePrompt: string,\n variants: string[]\n): Promise<PromptVariant[]> {\n const results: PromptVariant[] = [];\n \n for (const variant of variants) {\n // Test with sample requests\n const samples = await getSampleRequests(100);\n const metrics = await testPromptVariant(variant, samples);\n \n results.push({\n id: generateId(),\n systemPrompt: variant,\n metrics,\n });\n }\n \n // Sort by conversion rate\n return results.sort((a, b) => \n b.metrics.avgConversionRate - a.metrics.avgConversionRate\n );\n}\n```\n\n#### 3. Model Selection Optimization\n\n```typescript\n// lib/ai/optimization/model-selector.ts\n\nexport interface ModelPerformance {\n model: string;\n useCase: string;\n metrics: {\n avgLatency: number;\n avgCost: number;\n avgQuality: number;\n conversionRate: number;\n };\n score: number; // Weighted score\n}\n\n// Find optimal model for use case\nexport async function findOptimalModel(\n useCase: string,\n constraints: {\n maxLatency?: number;\n maxCost?: number;\n minQuality?: number;\n }\n): Promise<string> {\n const models = ['deepseek-v3', 'deepseek-r1', 'phi4-mini', 'llama', 'mistral'];\n const performances: ModelPerformance[] = [];\n \n for (const model of models) {\n const metrics = await getModelMetrics(model, useCase);\n \n // Check constraints\n if (constraints.maxLatency && metrics.avgLatency > constraints.maxLatency) continue;\n if (constraints.maxCost && metrics.avgCost > constraints.maxCost) continue;\n if (constraints.minQuality && metrics.avgQuality < constraints.minQuality) continue;\n \n // Calculate weighted score\n const score = \n metrics.avgQuality * 0.4 +\n (1 - metrics.avgLatency / 5000) * 0.3 +\n (1 - metrics.avgCost / 1.0) * 0.2 +\n metrics.conversionRate * 0.1;\n \n performances.push({ model, useCase, metrics, score });\n }\n \n // Return best model\n return performances.sort((a, b) => b.score - a.score)[0]?.model || 'deepseek-v3';\n}\n```\n\n---\n\n## ✅ RĂ©sumĂ© ExĂ©cutif\n\n### Ce que tu as\n\n**Une architecture AI de niveau enterprise pour $62/mois** 🚀\n\n#### 7 ModĂšles SpĂ©cialisĂ©s\n1. **DeepSeek-V3** - GĂ©nĂ©ration rapide ($34/mois)\n2. **DeepSeek-R1** - Raisonnement profond ($10/mois)\n3. **Phi-4 Multimodal** - Vision + Audio ($2.40/mois)\n4. **Phi-4 Mini** - Classification rapide ($1/mois)\n5. **Azure Speech Batch** - Transcription audio ($5/mois)\n6. **Llama 3.3-70B** - Fallback gĂ©nĂ©raliste ($5/mois)\n7. **Mistral Large** - CrĂ©ativitĂ© ($5/mois)\n\n#### Le Majordome - Orchestrateur Intelligent\n- Routing automatique vers le bon modĂšle\n- 5 outils principaux (generate_content, analyze_fans, get_smart_replies, schedule_post, track_performance)\n- IntĂ©gration Knowledge Base\n- Conversations naturelles\n- Gestion des confirmations\n\n#### Performance\n- **Latence**: 300ms (Phi-4 Mini) Ă  3000ms (DeepSeek-R1)\n- **Cache hit rate**: 80% (Ă©conomie massive)\n- **DisponibilitĂ©**: 99.9% (fallbacks multiples)\n- **ScalabilitĂ©**: Peut supporter 1,000+ users dans le budget\n\n#### Budget\n- **Actuel**: $62/mois (6% du budget)\n- **Budget disponible**: $1,000/mois\n- **Marge**: $938/mois pour scaler\n- **CoĂ»t par user**: $1.25/user/mois\n\n#### ROI\n- **Messages OnlyFans**: ROI 857x\n- **Segmentation**: ROI 276x\n- **Économie vs GPT-4**: $388/mois (86%)\n- **Économie vs Claude**: $318/mois (84%)\n\n### Points Forts\n\n✅ **Diversification**: 7 modĂšles, pas de single point of failure \n✅ **Routing intelligent**: Bon modĂšle pour chaque tĂąche \n✅ **CoĂ»ts optimisĂ©s**: Cache 80%, batch processing, model compression \n✅ **ScalabilitĂ©**: Peut 16x sans dĂ©passer le budget \n✅ **Fallbacks**: Haute disponibilitĂ© garantie \n✅ **Monitoring**: MĂ©triques complĂštes (cost, performance, quality) \n✅ **Optimisation continue**: A/B testing, prompt optimization\n\n### Prochaines Étapes\n\n1. **DĂ©ploiement** (Jour 1-3)\n - Configure Azure AI endpoints\n - Deploy Le Majordome\n - Test tous les modĂšles\n\n2. **Monitoring** (Jour 4-7)\n - Setup dashboards\n - Configure alertes\n - Track mĂ©triques\n\n3. **Optimisation** (Semaine 2+)\n - A/B testing prompts\n - Optimize cache strategy\n - Fine-tune routing\n\n4. **Scaling** (Mois 2+)\n - Monitor coĂ»ts\n - Adjust selon usage\n - Scale progressivement\n\n---\n\n**Tu es prĂȘt Ă  dĂ©ployer une architecture AI de classe mondiale** đŸŽ©\n\n"}}}}