// ======================================== // DYNAMIC PROMPT ENGINE - SYSTÈME AVANCÉ // Responsabilité: Génération dynamique de prompts adaptatifs ultra-modulaires // ======================================== const { logSh } = require('../ErrorReporting'); const { tracer } = require('../trace'); /** * DYNAMIC PROMPT ENGINE * Système avancé de génération de prompts avec composition multi-niveaux */ class DynamicPromptEngine { constructor() { this.name = 'DynamicPromptEngine'; this.templates = new Map(); this.contextAnalyzers = new Map(); this.adaptiveRules = new Map(); // Initialiser templates par défaut this.initializeDefaultTemplates(); this.initializeContextAnalyzers(); this.initializeAdaptiveRules(); } // ======================================== // INITIALISATION TEMPLATES // ======================================== initializeDefaultTemplates() { // Templates de base modulaires this.templates.set('technical', { meta: { role: "Tu es un expert {domain} avec {experience} d'expérience", expertise: "Spécialisé en {specialization} et {methods}", approach: "Adopte une approche {style} et {precision}" }, context: { mission: "MISSION: {task_description}", domain_context: "CONTEXTE: {sector} - {activity_type}", target_audience: "PUBLIC: {audience_level} ({audience_characteristics})", constraints: "CONTRAINTES: {content_constraints}" }, task: { primary_objective: "OBJECTIF PRINCIPAL: {main_goal}", specific_actions: "ACTIONS SPÉCIFIQUES:\n{action_list}", quality_criteria: "CRITÈRES DE QUALITÉ: {quality_requirements}", success_metrics: "MÉTRIQUES DE SUCCÈS: {success_indicators}" }, instructions: { guidelines: "CONSIGNES {instruction_type}:\n{instruction_list}", restrictions: "INTERDICTIONS: {avoid_list}", emphasis: "PRIORITÉS: {emphasis_list}", style_guide: "STYLE: {style_requirements}" }, examples: { format: "FORMAT ATTENDU:\n{format_example}", sample_input: "EXEMPLE D'ENTRÉE: {input_example}", sample_output: "EXEMPLE DE SORTIE: {output_example}" } }); this.templates.set('style', { meta: { role: "Tu es un rédacteur expert en communication {communication_type}", personality: "Adopte la personnalité de {personality_profile}", tone_master: "Maîtrise parfaitement le ton {target_tone}" }, context: { brand_voice: "IDENTITÉ: {brand_characteristics}", target_emotion: "ÉMOTION CIBLE: {desired_emotion}", communication_goal: "BUT COMMUNICATIONNEL: {communication_objective}", audience_psychology: "PSYCHOLOGIE AUDIENCE: {audience_mindset}" }, task: { style_transformation: "TRANSFORMATION STYLISTIQUE: {transformation_type}", tone_adaptation: "ADAPTATION TONALE: {tone_specifications}", personality_injection: "INJECTION PERSONNALITÉ: {personality_traits}", emotional_calibration: "CALIBRAGE ÉMOTIONNEL: {emotional_targets}" } }); this.templates.set('adversarial', { meta: { role: "Tu es un expert en rédaction naturelle anti-détection", stealth_mode: "Mode furtif niveau {stealth_level}", human_mimicry: "Imite parfaitement l'écriture humaine {human_characteristics}" }, context: { detection_threats: "MENACES DÉTECTION: {detector_types}", target_metrics: "MÉTRIQUES CIBLES: {target_scores}", natural_patterns: "PATTERNS NATURELS: {natural_characteristics}", human_variance: "VARIANCE HUMAINE: {variance_patterns}" }, task: { stealth_rewrite: "RÉÉCRITURE FURTIVE: {stealth_techniques}", pattern_breaking: "CASSAGE PATTERNS: {pattern_break_methods}", human_errors: "ERREURS HUMAINES: {human_error_types}", style_diversification: "DIVERSIFICATION: {diversification_methods}" } }); logSh(`✅ ${this.templates.size} templates modulaires initialisés`, 'DEBUG'); } initializeContextAnalyzers() { // Analyseurs de contexte automatiques this.contextAnalyzers.set('domain_inference', (content, csvData) => { const mc0 = csvData?.mc0?.toLowerCase() || ''; if (mc0.includes('signalétique') || mc0.includes('plaque')) { return { domain: 'signalétique industrielle', specialization: 'communication visuelle B2B', sector: 'industrie/signalétique', activity_type: 'fabrication sur mesure' }; } if (mc0.includes('bijou') || mc0.includes('gravure')) { return { domain: 'artisanat créatif', specialization: 'joaillerie personnalisée', sector: 'artisanat/luxe', activity_type: 'création artisanale' }; } return { domain: 'communication visuelle', specialization: 'impression numérique', sector: 'services/impression', activity_type: 'prestation de services' }; }); this.contextAnalyzers.set('complexity_assessment', (content) => { const totalText = Object.values(content).join(' '); const technicalTerms = (totalText.match(/\b(technique|procédé|norme|ISO|DIN|matériau|aluminum|PMMA)\b/gi) || []).length; const complexity = technicalTerms / totalText.split(' ').length; return { complexity_level: complexity > 0.05 ? 'élevée' : complexity > 0.02 ? 'moyenne' : 'standard', technical_density: complexity, recommended_approach: complexity > 0.05 ? 'expert' : 'accessible' }; }); this.contextAnalyzers.set('audience_inference', (content, csvData, trend) => { const personality = csvData?.personality; if (trend?.id === 'generation-z') { return { audience_level: 'digital natives', audience_characteristics: 'connectés, inclusifs, authentiques', audience_mindset: 'recherche authenticité et transparence' }; } if (personality?.style === 'technique') { return { audience_level: 'professionnels techniques', audience_characteristics: 'expérimentés, précis, orientés solutions', audience_mindset: 'recherche expertise et fiabilité' }; } return { audience_level: 'grand public', audience_characteristics: 'curieux, pragmatiques, sensibles qualité', audience_mindset: 'recherche clarté et valeur ajoutée' }; }); logSh(`✅ ${this.contextAnalyzers.size} analyseurs de contexte initialisés`, 'DEBUG'); } initializeAdaptiveRules() { // Règles d'adaptation conditionnelles this.adaptiveRules.set('intensity_scaling', { condition: (config) => config.intensity, adaptations: { low: (config) => ({ precision: 'accessible', style: 'naturel et fluide', instruction_type: 'DOUCES', stealth_level: 'discret' }), medium: (config) => ({ precision: 'équilibrée', style: 'professionnel et engageant', instruction_type: 'STANDARD', stealth_level: 'modéré' }), high: (config) => ({ precision: 'maximale', style: 'expert et percutant', instruction_type: 'STRICTES', stealth_level: 'avancé' }) }, getLevel: (intensity) => { if (intensity < 0.7) return 'low'; if (intensity < 1.2) return 'medium'; return 'high'; } }); this.adaptiveRules.set('trend_adaptation', { condition: (config) => config.trend, adaptations: { 'eco-responsable': { communication_type: 'responsable et engagée', desired_emotion: 'confiance et respect', brand_characteristics: 'éthique, durable, transparente', communication_objective: 'sensibiliser et rassurer' }, 'tech-innovation': { communication_type: 'moderne et dynamique', desired_emotion: 'excitation et confiance', brand_characteristics: 'innovante, performante, avant-gardiste', communication_objective: 'impressionner et convaincre' }, 'artisanal-premium': { communication_type: 'authentique et raffinée', desired_emotion: 'admiration et désir', brand_characteristics: 'traditionnelle, qualitative, exclusive', communication_objective: 'valoriser et différencier' } } }); logSh(`✅ ${this.adaptiveRules.size} règles adaptatives initialisées`, 'DEBUG'); } // ======================================== // GÉNÉRATION DYNAMIQUE DE PROMPTS // ======================================== /** * MAIN METHOD - Génère un prompt adaptatif complet */ async generateAdaptivePrompt(config) { return await tracer.run('DynamicPromptEngine.generateAdaptivePrompt()', async () => { const { templateType = 'technical', content = {}, csvData = null, trend = null, layerConfig = {}, customVariables = {} } = config; await tracer.annotate({ templateType, hasTrend: !!trend, contentSize: Object.keys(content).length, hasCustomVars: Object.keys(customVariables).length > 0 }); logSh(`🧠 Génération prompt adaptatif: ${templateType}`, 'INFO'); try { // 1. ANALYSE CONTEXTUELLE AUTOMATIQUE const contextAnalysis = await this.analyzeContext(content, csvData, trend); // 2. APPLICATION RÈGLES ADAPTATIVES const adaptiveConfig = this.applyAdaptiveRules(layerConfig, trend, contextAnalysis); // 3. GÉNÉRATION VARIABLES DYNAMIQUES const dynamicVariables = this.generateDynamicVariables( contextAnalysis, adaptiveConfig, customVariables, layerConfig ); // 4. COMPOSITION TEMPLATE MULTI-NIVEAUX const composedPrompt = this.composeMultiLevelPrompt( templateType, dynamicVariables, layerConfig ); // 5. POST-PROCESSING ADAPTATIF const finalPrompt = this.postProcessPrompt(composedPrompt, adaptiveConfig); const stats = { templateType, variablesCount: Object.keys(dynamicVariables).length, adaptationRules: Object.keys(adaptiveConfig).length, promptLength: finalPrompt.length, contextComplexity: contextAnalysis.complexity_level }; logSh(`✅ Prompt adaptatif généré: ${stats.promptLength} chars, ${stats.variablesCount} variables`, 'DEBUG'); return { prompt: finalPrompt, metadata: { stats, contextAnalysis, adaptiveConfig, dynamicVariables: Object.keys(dynamicVariables) } }; } catch (error) { logSh(`❌ Erreur génération prompt adaptatif: ${error.message}`, 'ERROR'); throw error; } }); } /** * ANALYSE CONTEXTUELLE AUTOMATIQUE */ async analyzeContext(content, csvData, trend) { const context = {}; // Exécuter tous les analyseurs for (const [analyzerName, analyzer] of this.contextAnalyzers) { try { const analysis = analyzer(content, csvData, trend); Object.assign(context, analysis); logSh(` 🔍 ${analyzerName}: ${JSON.stringify(analysis)}`, 'DEBUG'); } catch (error) { logSh(` ⚠️ Analyseur ${analyzerName} échoué: ${error.message}`, 'WARNING'); } } return context; } /** * APPLICATION DES RÈGLES ADAPTATIVES */ applyAdaptiveRules(layerConfig, trend, contextAnalysis) { const adaptiveConfig = {}; for (const [ruleName, rule] of this.adaptiveRules) { try { if (rule.condition(layerConfig)) { let adaptation = {}; if (ruleName === 'intensity_scaling') { const level = rule.getLevel(layerConfig.intensity || 1.0); adaptation = rule.adaptations[level](layerConfig); } else if (ruleName === 'trend_adaptation' && trend) { adaptation = rule.adaptations[trend.id] || {}; } Object.assign(adaptiveConfig, adaptation); logSh(` 🎛️ Règle ${ruleName} appliquée`, 'DEBUG'); } } catch (error) { logSh(` ⚠️ Règle ${ruleName} échouée: ${error.message}`, 'WARNING'); } } return adaptiveConfig; } /** * GÉNÉRATION VARIABLES DYNAMIQUES */ generateDynamicVariables(contextAnalysis, adaptiveConfig, customVariables, layerConfig) { const variables = { // Variables contextuelles ...contextAnalysis, // Variables adaptatives ...adaptiveConfig, // Variables personnalisées ...customVariables, // Variables de configuration experience: this.generateExperienceLevel(contextAnalysis.complexity_level), methods: this.generateMethods(layerConfig), task_description: this.generateTaskDescription(layerConfig), action_list: this.generateActionList(layerConfig), instruction_list: this.generateInstructionList(layerConfig), // Variables dynamiques calculées timestamp: new Date().toISOString(), session_id: this.generateSessionId() }; return variables; } /** * COMPOSITION TEMPLATE MULTI-NIVEAUX */ composeMultiLevelPrompt(templateType, variables, layerConfig) { const template = this.templates.get(templateType); if (!template) { throw new Error(`Template ${templateType} introuvable`); } const sections = []; // Composer chaque niveau du template for (const [sectionName, sectionTemplate] of Object.entries(template)) { const composedSection = this.composeSection(sectionTemplate, variables); if (composedSection.trim()) { sections.push(composedSection); } } return sections.join('\n\n'); } /** * COMPOSITION SECTION INDIVIDUELLE */ composeSection(sectionTemplate, variables) { const lines = []; for (const [key, template] of Object.entries(sectionTemplate)) { const interpolated = this.interpolateTemplate(template, variables); if (interpolated && interpolated.trim() !== template) { lines.push(interpolated); } } return lines.join('\n'); } /** * INTERPOLATION TEMPLATE AVEC VARIABLES */ interpolateTemplate(template, variables) { return template.replace(/\{([^}]+)\}/g, (match, varName) => { return variables[varName] || match; }); } /** * POST-PROCESSING ADAPTATIF */ postProcessPrompt(prompt, adaptiveConfig) { let processed = prompt; // Suppression des lignes vides multiples processed = processed.replace(/\n\n\n+/g, '\n\n'); // Suppression des variables non résolues processed = processed.replace(/\{[^}]+\}/g, ''); // Suppression des lignes vides après suppression variables processed = processed.replace(/\n\s*\n/g, '\n\n'); return processed.trim(); } // ======================================== // GÉNÉRATEURS HELPER // ======================================== generateExperienceLevel(complexity) { switch (complexity) { case 'élevée': return '10+ années'; case 'moyenne': return '5+ années'; default: return '3+ années'; } } generateMethods(layerConfig) { const methods = []; if (layerConfig.targetTerms?.length > 0) { methods.push('terminologie spécialisée'); } if (layerConfig.focusAreas?.length > 0) { methods.push('approche métier'); } return methods.length > 0 ? methods.join(', ') : 'méthodes éprouvées'; } generateTaskDescription(layerConfig) { const type = layerConfig.layerType || 'enhancement'; const descriptions = { technical: 'Améliore la précision technique et le vocabulaire spécialisé', style: 'Adapte le style et la personnalité du contenu', adversarial: 'Rend le contenu plus naturel et humain' }; return descriptions[type] || 'Améliore le contenu selon les spécifications'; } generateActionList(layerConfig) { const actions = []; if (layerConfig.targetTerms) { actions.push(`- Intégrer naturellement: ${layerConfig.targetTerms.slice(0, 5).join(', ')}`); } if (layerConfig.avoidTerms) { actions.push(`- Éviter absolument: ${layerConfig.avoidTerms.slice(0, 3).join(', ')}`); } actions.push('- Conserver le message original et la structure'); actions.push('- Maintenir la cohérence stylistique'); return actions.join('\n'); } generateInstructionList(layerConfig) { const instructions = [ 'GARDE exactement le même sens et message', 'PRÉSERVE la structure et la longueur approximative', 'ASSURE-TOI que le résultat reste naturel et fluide' ]; if (layerConfig.preservePersonality) { instructions.push('MAINTIENS la personnalité et le ton existants'); } return instructions.map(i => `- ${i}`).join('\n'); } generateSessionId() { return Math.random().toString(36).substring(2, 15); } // ======================================== // API PUBLIQUE ÉTENDUE // ======================================== /** * Ajouter template personnalisé */ addCustomTemplate(name, template) { this.templates.set(name, template); logSh(`✨ Template personnalisé ajouté: ${name}`, 'INFO'); } /** * Ajouter analyseur de contexte */ addContextAnalyzer(name, analyzer) { this.contextAnalyzers.set(name, analyzer); logSh(`🔍 Analyseur personnalisé ajouté: ${name}`, 'INFO'); } /** * Ajouter règle adaptative */ addAdaptiveRule(name, rule) { this.adaptiveRules.set(name, rule); logSh(`🎛️ Règle adaptative ajoutée: ${name}`, 'INFO'); } /** * Status du moteur */ getEngineStatus() { return { templates: Array.from(this.templates.keys()), contextAnalyzers: Array.from(this.contextAnalyzers.keys()), adaptiveRules: Array.from(this.adaptiveRules.keys()), totalComponents: this.templates.size + this.contextAnalyzers.size + this.adaptiveRules.size }; } } // ============= EXPORTS ============= module.exports = { DynamicPromptEngine };