Spaces:
Running
Running
File size: 16,380 Bytes
e3c44fe 006d494 e3c44fe 006d494 e3c44fe 006d494 e3c44fe 006d494 e3c44fe 006d494 e3c44fe 006d494 e3c44fe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 | class BrainDatabase {
constructor() {
this.knowledgeBase = {
// Identity & Core
identity: {
name: "Nexus",
creator: "ChromaMind Systems",
version: "2.1.0",
type: "AI Learning Companion",
purpose: "To learn from users and provide personalized assistance"
},
// Language Understanding
language: {
greetings: ["hello", "hi", "hey", "greetings", "what's up", "sup", "yo", "howdy", "good morning", "good afternoon", "good evening"],
farewells: ["bye", "goodbye", "see you", "later", "cya", "farewell", "take care", "peace", "ttyl"],
gratitude: ["thanks", "thank you", "appreciate", "grateful", "cheers", "much obliged", "ty"],
affirmations: ["yes", "yeah", "yep", "sure", "absolutely", "definitely", "correct", "right", "ok", "okay"],
negatives: ["no", "nope", "nah", "not really", "incorrect", "wrong", "never"],
questions: ["what", "who", "where", "when", "why", "how", "which", "whose", "whom", "can", "could", "would", "should", "will", "is", "are", "do", "does", "did", "have", "has", "am"],
emotions: {
happy: ["happy", "joy", "excited", "glad", "pleased", "delighted", "cheerful", "elated", "thrilled"],
sad: ["sad", "unhappy", "depressed", "down", "upset", "disappointed", "miserable", "gloomy"],
angry: ["angry", "mad", "furious", "annoyed", "irritated", "frustrated", "outraged"],
confused: ["confused", "lost", "puzzled", "perplexed", "uncertain", "unsure", "bewildered"],
curious: ["curious", "wondering", "interested", "intrigued", "fascinated", "keen"]
}
},
// Common Knowledge
commonFacts: {
time: {
seconds_in_minute: 60,
minutes_in_hour: 60,
hours_in_day: 24,
days_in_week: 7,
weeks_in_year: 52,
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
},
science: {
planets: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
water_boiling_point: "100°C (212°F) at sea level",
water_freezing_point: "0°C (32°F)",
speed_of_light: "299,792,458 meters per second",
earth_age: "approximately 4.54 billion years"
},
math: {
pi: 3.14159265359,
e: 2.71828182846,
golden_ratio: 1.61803398875
}
},
// Conversation Patterns
patterns: {
asking_identity: /who (are|is) (you|nexus|this)/i,
asking_capabilities: /what (can|do) you (do|know|understand)/i,
asking_creator: /who (made|created|built) you/i,
asking_help: /help|assist|support/i,
making_statement: /^(i am|i'm|i have|i've|i think|i believe|my)/i,
asking_opinion: /what (do|would) you (think|say|recommend)/i,
casual_chat: /how (are|is)|how's it going|what's (new|happening)/i
},
// Response Templates
responses: {
identity: "I'm Nexus, your AI learning companion created by ChromaMind Systems. I'm here to learn from you, remember what you teach me, and help you with anything you need!",
capabilities: "I can:\n• Search the web for current information\n• Learn and remember facts you teach me\n• Answer questions using my knowledge and yours\n• Chat naturally like we're doing now\n• Understand context and emotions\n• Help with coding, learning, and problem-solving\n\nThe more you use me, the better I get to know you!",
creator: "I was created by ChromaMind Systems. But really, I'm shaped by every conversation we have—you teach me and I grow from our interactions!",
greeting_morning: "Good morning! I hope you're starting the day with energy. What can I help you with?",
greeting_afternoon: "Good afternoon! How's your day going so far?",
greeting_evening: "Good evening! I hope you've had a productive day. What would you like to discuss?",
gratitude: "You're very welcome! I'm glad I could help. Is there anything else you'd like to know or discuss?",
farewell: "Goodbye! I'll be here whenever you're ready to continue our conversation. Take care!",
confusion: "I'm not sure I understand. Could you rephrase that? Or you can teach me what you mean in the \"Teach Me\" tab!",
encouragement: "That's interesting! Tell me more about that. I love learning new things from you."
},
// Context Understanding
context: {
conversation_memory: [],
user_preferences: {},
session_start: new Date().toISOString()
}
};
// Load any saved brain data
this.loadBrain();
}
// Check if input matches a pattern
matchPattern(input, patternName) {
const pattern = this.knowledgeBase.patterns[patternName];
if (!pattern) return false;
return pattern.test(input);
}
// Detect emotion in text
detectEmotion(text) {
const lower = text.toLowerCase();
const emotions = this.knowledgeBase.language.emotions;
for (const [emotion, words] of Object.entries(emotions)) {
if (words.some(w => lower.includes(w))) {
return emotion;
}
}
return null;
}
// Detect intent
detectIntent(text) {
const lower = text.toLowerCase();
const lang = this.knowledgeBase.language;
if (lang.greetings.some(g => lower.includes(g))) return 'greeting';
if (lang.farewells.some(f => lower.includes(f))) return 'farewell';
if (lang.gratitude.some(g => lower.includes(g))) return 'gratitude';
if (lang.questions.some(q => lower.startsWith(q) || lower.includes(` ${q} `))) return 'question';
if (this.matchPattern(text, 'asking_identity')) return 'identity';
if (this.matchPattern(text, 'asking_capabilities')) return 'capabilities';
if (this.matchPattern(text, 'asking_creator')) return 'creator';
if (this.matchPattern(text, 'asking_help')) return 'help';
return 'statement';
}
// Generate contextual response
generateResponse(input, userKnowledge = []) {
const intent = this.detectIntent(input);
const emotion = this.detectEmotion(input);
const responses = this.knowledgeBase.responses;
// Store in context memory
this.knowledgeBase.context.conversation_memory.push({
input: input.substring(0, 200),
intent: intent,
emotion: emotion,
timestamp: new Date().toISOString()
});
// Also store in nexus knowledge for persistence between sessions
try {
const existing = JSON.parse(localStorage.getItem('nexusKnowledge') || '[]');
if (intent === 'statement' && input.length > 10 && !input.includes('?')) {
// Potentially learn from statements of fact
this.considerLearning(input, emotion);
}
} catch (e) {
// Silent fail for localStorage
}
// Keep only last 20 exchanges
if (this.knowledgeBase.context.conversation_memory.length > 20) {
this.knowledgeBase.context.conversation_memory.shift();
}
// Generate response based on intent
switch (intent) {
case 'greeting':
const hour = new Date().getHours();
if (hour < 12) return responses.greeting_morning;
if (hour < 18) return responses.greeting_afternoon;
return responses.greeting_evening;
case 'farewell':
return responses.farewell;
case 'gratitude':
return responses.gratitude;
case 'identity':
return responses.identity;
case 'capabilities':
return responses.capabilities;
case 'creator':
return responses.creator;
case 'help':
return "I'm here to help! You can:\n• Ask me anything and I'll search for answers\n• Teach me facts about you in the \"Teach Me\" tab\n• View everything I've learned in \"My Knowledge\"\n• Just chat with me naturally like this!\n\nWhat do you need help with?";
case 'question':
// Check user knowledge first
if (userKnowledge.length > 0) {
const relevant = this.findRelevantKnowledge(input, userKnowledge);
if (relevant) {
// Formulate natural response based on knowledge type
const content = relevant.content;
const isPreference = /like|love|prefer|favorite|hate|dislike/i.test(content);
const isMath = /[\d+\-*/=]/.test(content) && /[=+\-*/]/.test(content);
let preface;
if (isMath) {
preface = ["Mathematically, ", "Numerically speaking, ", "I calculate that "][Math.floor(Math.random() * 3)];
} else if (isPreference) {
preface = ["I recall that you mentioned ", "From my memory, ", "I understand that "][Math.floor(Math.random() * 3)];
} else {
preface = ["Based on my knowledge, ", "From what I've learned, ", "I understand that "][Math.floor(Math.random() * 3)];
}
return `${preface}${content}.\n\nDoes that help answer your question?`;
}
}
return "That's a great question! Let me search for the most current information on that, or if you already know the answer, you can teach me in the \"Teach Me\" tab!";
default:
// Check if there's relevant knowledge to weave into the response
if (userKnowledge.length > 0) {
const relevant = this.findRelevantKnowledge(input, userKnowledge);
if (relevant && Math.random() > 0.7) { // 30% chance to reference knowledge naturally
return `Speaking of which, I recall you mentioned ${relevant.content}. How does that relate to what you're saying?`;
}
}
// Emotional awareness
if (emotion === 'confused') {
return "I can tell you're feeling a bit uncertain. Don't worry—we're in this together! What specifically is confusing you? I'm here to help clarify.";
}
if (emotion === 'happy') {
return "I love your positive energy! 😊 What's got you in such a good mood? I'd love to hear about it!";
}
if (emotion === 'sad') {
return "I sense you might be going through something difficult. I'm here to chat, help with tasks, or just be a listening presence. What would be most helpful right now?";
}
return responses.encouragement;
}
}
// Find relevant knowledge from user's teachings
findRelevantKnowledge(input, knowledge) {
const words = input.toLowerCase().split(/\W+/).filter(w => w.length > 2);
let bestMatch = null;
let bestScore = 0;
for (const item of knowledge) {
const topicWords = item.topic.toLowerCase().split(/\W+/);
const contentWords = item.content.toLowerCase().split(/\W+/);
let score = 0;
for (const w of words) {
if (topicWords.some(tw => tw.includes(w) || w.includes(tw))) score += 3;
if (contentWords.some(cw => cw.includes(w) || w.includes(cw))) score += 1;
}
if (score > bestScore && score >= 2) {
bestScore = score;
bestMatch = item;
}
}
return bestMatch;
}
// Get conversation context
getContext() {
return this.knowledgeBase.context;
}
// Add to brain database
addKnowledge(category, key, value) {
if (!this.knowledgeBase[category]) {
this.knowledgeBase[category] = {};
}
this.knowledgeBase[category][key] = value;
this.saveBrain();
}
// Save brain to localStorage
saveBrain() {
try {
localStorage.setItem('nexusBrain', JSON.stringify(this.knowledgeBase));
} catch (e) {
console.error('Failed to save brain:', e);
}
}
// Load brain from localStorage
loadBrain() {
try {
const saved = localStorage.getItem('nexusBrain');
if (saved) {
const parsed = JSON.parse(saved);
// Merge with defaults, keeping user data
this.knowledgeBase.context = {
...this.knowledgeBase.context,
...parsed.context
};
if (parsed.user_preferences) {
this.knowledgeBase.context.user_preferences = parsed.user_preferences;
}
}
} catch (e) {
console.error('Failed to load brain:', e);
}
}
// Learn user preference
learnPreference(key, value) {
this.knowledgeBase.context.user_preferences[key] = {
value: value,
timestamp: new Date().toISOString()
};
this.saveBrain();
}
// Get user preference
getPreference(key) {
return this.knowledgeBase.context.user_preferences[key]?.value || null;
}
// Consider learning from user statements (passive learning)
considerLearning(input, emotion) {
// Simple heuristic: if it looks like a fact about the user
const selfReferences = ['i am', "i'm", 'i like', 'i love', 'i hate', 'i prefer', 'my favorite', 'i work at', 'i live in'];
const lowerInput = input.toLowerCase();
if (selfReferences.some(ref => lowerInput.includes(ref))) {
// Could potentially be stored as knowledge
console.log('📝 Potential knowledge detected:', input);
}
}
// Generate natural response variations
generateVariedResponse(baseResponse, context) {
const variations = {
'knowledge': [
`I understand that ${context}.`,
`From what I've learned, ${context}.`,
`I recall that ${context}.`,
`Based on my knowledge: ${context}.`
],
'math': [
`Calculating... ${context}.`,
`Mathematically: ${context}.`,
`The answer is ${context}.`
],
'preference': [
`I remember you mentioned ${context}.`,
`You told me that ${context}.`
]
};
return variations[context] || variations['knowledge'];
}
}
// Create global instance
window.brainDB = new BrainDatabase();
console.log('🧠 Nexus Brain Database initialized'); |