Team Ai
Apppublic

dablew002/mindmirror-ai-debugger-cognitive-reflection-engine

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
script.js282 linesDownload Raw Back to root
1 2// Expanded OpenRouter Configuration3const OPENROUTER_CONFIG = {4    apiKey: "your-api-key",5    baseUrl: "https://openrouter.ai/api/v1",6    headers: {7        "Authorization": `Bearer ${apiKey}`,8        "HTTP-Referer": window.location.href,9        "X-Title": "RSD Reality Sync Debugger"10    },11    models: {12        personalityAnalysis: "anthropic/claude-3-opus",13        problemSolving: "anthropic/claude-3.5-sonnet",14        creativeGeneration: "google/gemini-pro-1.5",15        routineTasks: "meta-llama/llama-3-70b-instruct",16        motivationEngine: "anthropic/claude-3.5-sonnet",17        progressTracking: "anthropic/claude-3.5-sonnet",18        failsafeSystem: "anthropic/claude-3.5-sonnet"19    },20    endpoints: {21        personalityAnalysis: {22            promptTemplate: `Analyze user input and behavior patterns to build a personality profile...`,23            outputFields: [24                "communication_style",25                "reasoning_pattern",26                "learning_preference",27                "motivation_triggers",28                "risk_tolerance"29            ]30        },31        problemClassification: {32            promptTemplate: `Classify this problem and determine the best approach...`,33            outputFields: [34                "problem_type",35                "complexity_level",36                "emotional_intensity",37                "recommended_approach",38                "urgency_level"39            ]40        }41    },42    rateLimits: {43        userMinute: 10,44        userHour: 100,45        dailyBudget: 50, // USD46        alertThreshold: 0.847    },48    cacheSettings: {49        personalityProfiles: 86400, // 24h in seconds50        problemAnalyses: 3600,      // 1h51        solutionPathways: 21600,    // 6h52        progressData: 0,            // realtime53        motivationContent: 43200    // 12h54    }55};56 57// Cost Optimization Strategy58const COST_OPTIMIZATION = {59    modelPriorities: {60        "high": ["anthropic/claude-3-opus", "anthropic/claude-3.5-sonnet"],61        "medium": ["google/gemini-pro-1.5"],62        "low": ["meta-llama/llama-3-70b-instruct"]63    },64    batchProcessing: [65        "progress_calculations",66        "dashboard_updates",67        "routine_notifications"68    ]69};70 71// Analytics Configuration72const ANALYTICS_METRICS = {73    personalityAccuracy: {74        measurement: "User feedback on profile accuracy",75        weight: 0.376    },77    solutionEffectiveness: {78        measurement: "Progress completion rates",79        weight: 0.480    },81    userEngagement: {82        measurement: "Time spent, return visits",83        weight: 0.284    },85    systemReliability: {86        measurement: "Uptime, error rates",87        weight: 0.188    }89};90// Enhanced Personality Mirroring Engine91class PersonalityMirror {92    constructor() {93        this.profile = {94            communicationStyle: null,95            reasoningPattern: null,96            learningPreference: null,97            motivationTriggers: null,98            riskTolerance: null,99            cognitivePatterns: null,100            energyRhythms: null,101            decisionMaking: null102        };103        this.behaviorHistory = [];104        this.interactionPatterns = [];105    }106    async analyze(text, behaviorPatterns = [], context = {}) {107        try {108            const interaction = {109                text,110                timestamp: Date.now(),111                context,112                metadata: {113                    inputLength: text.length,114                    sentiment: this.analyzeSentiment(text),115                    responseTime: null116                }117            };118            119            this.behaviorHistory.push(interaction);120            this.interactionPatterns.push(this.extractPatterns(interaction));121            122            const recentPatterns = this.interactionPatterns.slice(-5);123            const personalityPrompt = OPENROUTER_CONFIG.endpoints.personalityAnalysis.promptTemplate124                .replace('{USER_INPUT}', text)125                .replace('{BEHAVIOR_PATTERNS}', JSON.stringify(recentPatterns));126const response = await this.robustAPICall(127                prompt, 128                OPENROUTER_CONFIG.models.personalityAnalysis,129                [130                    OPENROUTER_CONFIG.models.problemSolving,131                    OPENROUTER_CONFIG.models.creativeGeneration132                ]133            );134const data = await response.json();135            this.updateProfile(data.choices[0].message.content);136            return this.profile;137        } catch (error) {138            console.error("Analysis failed:", error);139            return null;140        }141    }142    updateProfile(analysis) {143        try {144            const parsed = JSON.parse(analysis);145            this.profile = {146                ...this.profile,147                ...parsed,148                lastUpdated: Date.now()149            };150            this.saveToCache();151        } catch (e) {152            console.error("Failed to parse analysis:", e);153            return this.getCachedProfile();154        }155    }156 157    async robustAPICall(prompt, primaryModel, fallbacks) {158        try {159            return await this.makeAPICall(prompt, primaryModel);160        } catch (error) {161            for (const fallback of fallbacks) {162                try {163                    return await this.makeAPICall(prompt, fallback);164                } catch (err) {165                    continue;166                }167            }168            throw new Error("All API attempts failed");169        }170    }171 172    async makeAPICall(prompt, model) {173        const response = await fetch(`${OPENROUTER_CONFIG.baseUrl}/chat/completions`, {174            method: "POST",175            headers: {176                ...OPENROUTER_CONFIG.headers,177                "Content-Type": "application/json"178            },179            body: JSON.stringify({180                model,181                messages: [{ role: "user", content: prompt }]182            })183        });184        185        if (!response.ok) throw new Error(`API Error: ${response.status}`);186        return await response.json();187    }188 189    saveToCache() {190        localStorage.setItem('rsd_profile', JSON.stringify({191            profile: this.profile,192            expires: Date.now() + (24 * 60 * 60 * 1000) // 24 hours193        }));194    }195 196    getCachedProfile() {197        const cached = localStorage.getItem('rsd_profile');198        if (!cached) return null;199        200        const { profile, expires } = JSON.parse(cached);201        if (Date.now() > expires) return null;202        203        return profile;204    }205}206 207// Global initialization208document.addEventListener('DOMContentLoaded', () => {209    // Initialize tooltips for feather icons210    document.querySelectorAll('[data-feather]').forEach(el => {211        const iconName = el.getAttribute('data-feather');212        el.setAttribute('title', iconName.replace('-', ' '));213        el.setAttribute('aria-label', iconName.replace('-', ' '));214    });215    216    // Smooth scroll for anchor links217    document.querySelectorAll('a[href^="#"]').forEach(anchor => {218        anchor.addEventListener('click', function(e) {219            e.preventDefault();220            document.querySelector(this.getAttribute('href')).scrollIntoView({221                behavior: 'smooth'222            });223        });224    });225    226    // Initialize animations227    const animateOnScroll = () => {228        const elements = document.querySelectorAll('.fade-in, .slide-up');229        elements.forEach(el => {230            const elTop = el.getBoundingClientRect().top;231            const isVisible = (elTop - window.innerHeight) < -100;232            if (isVisible) {233                el.classList.add('animated');234            }235        });236    };237    238    window.addEventListener('scroll', animateOnScroll);239    animateOnScroll(); // Initial check240});241 242// API interaction functions243async function analyzePersonality(text) {244    try {245        // This would be replaced with actual OpenRouter API call246        console.log("Analyzing personality based on:", text);247        return {248            communicationStyle: ["visual", "analytical"],249            reasoningPattern: ["logical", "intuitive"],250            learningPreference: ["theoretical", "hands_on"],251            motivationTriggers: ["achievement", "growth"]252        };253    } catch (error) {254        console.error("Personality analysis failed:", error);255        return null;256    }257}258 259// Cache management260const cache = {261    set: (key, value, ttl) => {262        const now = new Date();263        const item = {264            value,265            expiry: now.getTime() + ttl266        };267        localStorage.setItem(key, JSON.stringify(item));268    },269    get: (key) => {270        const itemStr = localStorage.getItem(key);271        if (!itemStr) return null;272        273        const item = JSON.parse(itemStr);274        const now = new Date();275        276        if (now.getTime() > item.expiry) {277            localStorage.removeItem(key);278            return null;279        }280        return item.value;281    }282};