chromamind-nexus / components /brain-database.js
ChatEngineAi's picture
can you make this ai understand a bit more, instead of: ive teached it 1+1=2. Nexus answer with: You learned me "1+1=2". instead of reapeating exactly what i said, can you make it understand and formulate my answer. make it his understanding so rather than telling you: you told me "1+1=2", it tells you something like: after what i know 1+1=2, or Based on my knowledge 1+1=2
006d494 verified
Raw History Blame Contribute Delete
16.4 kB
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');