xlelords commited on
Commit
da2e7f2
·
verified ·
1 Parent(s): b1726f5

Delete omnimind-ai.js

Browse files
Files changed (1) hide show
  1. omnimind-ai.js +0 -652
omnimind-ai.js DELETED
@@ -1,652 +0,0 @@
1
- /**
2
- * OmniMind AI Simulator
3
- *
4
- * A JavaScript-based AI assistant that uses the OmniMind-100K dataset
5
- * to answer questions on coding, science, math, image generation,
6
- * general knowledge, and more.
7
- *
8
- * Usage: node omnimind-ai.js
9
- */
10
-
11
- const fs = require('fs');
12
- const readline = require('readline');
13
-
14
- // ============================================
15
- // CONFIGURATION
16
- // ============================================
17
-
18
- const CONFIG = {
19
- datasetPath: './omnimind-100k.jsonl',
20
- indexPath: './omnimind-index.json',
21
- similarityThreshold: 0.3,
22
- maxResults: 5,
23
- modelName: 'OmniMind-100K',
24
- version: '1.0.0'
25
- };
26
-
27
- // ============================================
28
- // TEXT PROCESSING UTILITIES
29
- // ============================================
30
-
31
- class TextProcessor {
32
- static stopWords = new Set([
33
- 'a', 'an', 'the', 'is', 'are', 'was', 'were', 'be', 'been', 'being',
34
- 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could',
35
- 'should', 'may', 'might', 'must', 'shall', 'can', 'need', 'dare',
36
- 'ought', 'used', 'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by',
37
- 'from', 'as', 'into', 'through', 'during', 'before', 'after', 'above',
38
- 'below', 'between', 'under', 'again', 'further', 'then', 'once', 'here',
39
- 'there', 'when', 'where', 'why', 'how', 'all', 'each', 'few', 'more',
40
- 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own',
41
- 'same', 'so', 'than', 'too', 'very', 'just', 'and', 'but', 'if', 'or',
42
- 'because', 'until', 'while', 'this', 'that', 'these', 'those', 'what',
43
- 'which', 'who', 'whom', 'it', 'its', 'i', 'me', 'my', 'myself', 'we',
44
- 'our', 'you', 'your', 'he', 'him', 'his', 'she', 'her', 'they', 'them'
45
- ]);
46
-
47
- static tokenize(text) {
48
- return text
49
- .toLowerCase()
50
- .replace(/[^\w\s]/g, ' ')
51
- .split(/\s+/)
52
- .filter(word => word.length > 1 && !this.stopWords.has(word));
53
- }
54
-
55
- static extractKeywords(text) {
56
- const tokens = this.tokenize(text);
57
- const frequency = {};
58
-
59
- tokens.forEach(token => {
60
- frequency[token] = (frequency[token] || 0) + 1;
61
- });
62
-
63
- return Object.entries(frequency)
64
- .sort((a, b) => b[1] - a[1])
65
- .slice(0, 10)
66
- .map(([word]) => word);
67
- }
68
-
69
- static calculateSimilarity(text1, text2) {
70
- const tokens1 = new Set(this.tokenize(text1));
71
- const tokens2 = new Set(this.tokenize(text2));
72
-
73
- if (tokens1.size === 0 || tokens2.size === 0) return 0;
74
-
75
- const intersection = new Set([...tokens1].filter(x => tokens2.has(x)));
76
- const union = new Set([...tokens1, ...tokens2]);
77
-
78
- // Jaccard similarity
79
- const jaccard = intersection.size / union.size;
80
-
81
- // Boost for exact keyword matches
82
- const keywordBoost = intersection.size / Math.min(tokens1.size, tokens2.size);
83
-
84
- return (jaccard + keywordBoost) / 2;
85
- }
86
-
87
- static fuzzyMatch(query, text) {
88
- const queryLower = query.toLowerCase();
89
- const textLower = text.toLowerCase();
90
-
91
- // Direct substring match
92
- if (textLower.includes(queryLower)) return 1.0;
93
-
94
- // Check individual words
95
- const queryWords = queryLower.split(/\s+/);
96
- const matchCount = queryWords.filter(word => textLower.includes(word)).length;
97
-
98
- return matchCount / queryWords.length;
99
- }
100
- }
101
-
102
- // ============================================
103
- // KNOWLEDGE BASE
104
- // ============================================
105
-
106
- class KnowledgeBase {
107
- constructor() {
108
- this.entries = [];
109
- this.index = {
110
- byCategory: {},
111
- bySubcategory: {},
112
- byKeyword: {}
113
- };
114
- this.loaded = false;
115
- }
116
-
117
- async load() {
118
- console.log('📚 Loading OmniMind knowledge base...');
119
-
120
- // Check if dataset exists
121
- if (!fs.existsSync(CONFIG.datasetPath)) {
122
- console.log('⚠️ Dataset not found. Please run: node generate-dataset.js');
123
- return false;
124
- }
125
-
126
- // Check for cached index
127
- if (fs.existsSync(CONFIG.indexPath)) {
128
- console.log('📑 Loading cached index...');
129
- const cached = JSON.parse(fs.readFileSync(CONFIG.indexPath, 'utf-8'));
130
- this.entries = cached.entries;
131
- this.index = cached.index;
132
- this.loaded = true;
133
- console.log(`✅ Loaded ${this.entries.length.toLocaleString()} entries from cache`);
134
- return true;
135
- }
136
-
137
- // Load and index the dataset
138
- const data = fs.readFileSync(CONFIG.datasetPath, 'utf-8');
139
- const lines = data.trim().split('\n');
140
-
141
- let processed = 0;
142
- const total = lines.length;
143
-
144
- for (const line of lines) {
145
- try {
146
- const entry = JSON.parse(line);
147
- this.addEntry(entry);
148
- processed++;
149
-
150
- if (processed % 10000 === 0) {
151
- process.stdout.write(`\r Processing: ${processed.toLocaleString()}/${total.toLocaleString()}`);
152
- }
153
- } catch (e) {
154
- // Skip malformed entries
155
- }
156
- }
157
-
158
- console.log(`\n✅ Loaded ${this.entries.length.toLocaleString()} entries`);
159
-
160
- // Cache the index
161
- console.log('💾 Caching index for faster loading...');
162
- fs.writeFileSync(CONFIG.indexPath, JSON.stringify({
163
- entries: this.entries,
164
- index: this.index
165
- }));
166
-
167
- this.loaded = true;
168
- return true;
169
- }
170
-
171
- addEntry(entry) {
172
- const idx = this.entries.length;
173
- this.entries.push(entry);
174
-
175
- // Index by category
176
- if (!this.index.byCategory[entry.category]) {
177
- this.index.byCategory[entry.category] = [];
178
- }
179
- this.index.byCategory[entry.category].push(idx);
180
-
181
- // Index by subcategory
182
- if (entry.subcategory) {
183
- if (!this.index.bySubcategory[entry.subcategory]) {
184
- this.index.bySubcategory[entry.subcategory] = [];
185
- }
186
- this.index.bySubcategory[entry.subcategory].push(idx);
187
- }
188
-
189
- // Index by keywords
190
- const keywords = TextProcessor.extractKeywords(entry.instruction);
191
- keywords.forEach(keyword => {
192
- if (!this.index.byKeyword[keyword]) {
193
- this.index.byKeyword[keyword] = [];
194
- }
195
- this.index.byKeyword[keyword].push(idx);
196
- });
197
- }
198
-
199
- search(query, options = {}) {
200
- const { category, maxResults = CONFIG.maxResults } = options;
201
-
202
- const keywords = TextProcessor.extractKeywords(query);
203
- const candidateIndices = new Set();
204
-
205
- // Find candidates by keywords
206
- keywords.forEach(keyword => {
207
- const indices = this.index.byKeyword[keyword] || [];
208
- indices.forEach(idx => candidateIndices.add(idx));
209
- });
210
-
211
- // If category specified, filter by category
212
- if (category && this.index.byCategory[category]) {
213
- const categoryIndices = new Set(this.index.byCategory[category]);
214
- candidateIndices.forEach(idx => {
215
- if (!categoryIndices.has(idx)) {
216
- candidateIndices.delete(idx);
217
- }
218
- });
219
- }
220
-
221
- // If no keyword matches, search all entries (limited)
222
- if (candidateIndices.size === 0) {
223
- const sampleSize = Math.min(5000, this.entries.length);
224
- for (let i = 0; i < sampleSize; i++) {
225
- candidateIndices.add(Math.floor(Math.random() * this.entries.length));
226
- }
227
- }
228
-
229
- // Score candidates
230
- const scored = [];
231
- candidateIndices.forEach(idx => {
232
- const entry = this.entries[idx];
233
- const similarity = TextProcessor.calculateSimilarity(query, entry.instruction);
234
- const fuzzy = TextProcessor.fuzzyMatch(query, entry.instruction);
235
- const score = (similarity * 0.6) + (fuzzy * 0.4);
236
-
237
- if (score > CONFIG.similarityThreshold) {
238
- scored.push({ entry, score, idx });
239
- }
240
- });
241
-
242
- // Sort by score and return top results
243
- scored.sort((a, b) => b.score - a.score);
244
- return scored.slice(0, maxResults);
245
- }
246
-
247
- getRandomEntry(category) {
248
- let pool = this.entries;
249
-
250
- if (category && this.index.byCategory[category]) {
251
- const indices = this.index.byCategory[category];
252
- pool = indices.map(idx => this.entries[idx]);
253
- }
254
-
255
- return pool[Math.floor(Math.random() * pool.length)];
256
- }
257
-
258
- getCategories() {
259
- return Object.keys(this.index.byCategory);
260
- }
261
-
262
- getStats() {
263
- const stats = {
264
- total: this.entries.length,
265
- categories: {}
266
- };
267
-
268
- Object.entries(this.index.byCategory).forEach(([cat, indices]) => {
269
- stats.categories[cat] = indices.length;
270
- });
271
-
272
- return stats;
273
- }
274
- }
275
-
276
- // ============================================
277
- // AI ASSISTANT
278
- // ============================================
279
-
280
- class OmniMindAI {
281
- constructor() {
282
- this.kb = new KnowledgeBase();
283
- this.context = [];
284
- this.maxContextLength = 5;
285
- }
286
-
287
- async initialize() {
288
- const success = await this.kb.load();
289
- if (!success) {
290
- throw new Error('Failed to load knowledge base');
291
- }
292
- return this;
293
- }
294
-
295
- async respond(userInput) {
296
- const input = userInput.trim();
297
-
298
- // Handle special commands
299
- if (input.startsWith('/')) {
300
- return this.handleCommand(input);
301
- }
302
-
303
- // Handle greetings
304
- if (this.isGreeting(input)) {
305
- return this.getGreetingResponse();
306
- }
307
-
308
- // Handle farewells
309
- if (this.isFarewell(input)) {
310
- return this.getFarewellResponse();
311
- }
312
-
313
- // Handle thanks
314
- if (this.isThanks(input)) {
315
- return this.getThanksResponse();
316
- }
317
-
318
- // Detect intent and category
319
- const intent = this.detectIntent(input);
320
-
321
- // Search knowledge base
322
- const results = this.kb.search(input, { category: intent.category });
323
-
324
- if (results.length > 0) {
325
- // Return best matching response
326
- const best = results[0];
327
- this.addToContext(input, best.entry.response);
328
- return this.formatResponse(best.entry, best.score);
329
- }
330
-
331
- // Generate fallback response
332
- return this.getFallbackResponse(input, intent);
333
- }
334
-
335
- handleCommand(input) {
336
- const [command, ...args] = input.slice(1).split(' ');
337
-
338
- switch (command.toLowerCase()) {
339
- case 'help':
340
- return this.getHelpMessage();
341
-
342
- case 'stats':
343
- return this.getStatsMessage();
344
-
345
- case 'categories':
346
- return this.getCategoriesMessage();
347
-
348
- case 'random':
349
- const category = args[0];
350
- const entry = this.kb.getRandomEntry(category);
351
- return `**Random Knowledge:**\n\n**Q:** ${entry.instruction}\n\n**A:** ${entry.response}`;
352
-
353
- case 'clear':
354
- this.context = [];
355
- return 'Context cleared. Starting fresh conversation.';
356
-
357
- case 'about':
358
- return this.getAboutMessage();
359
-
360
- default:
361
- return `Unknown command: /${command}\nType /help for available commands.`;
362
- }
363
- }
364
-
365
- detectIntent(input) {
366
- const inputLower = input.toLowerCase();
367
-
368
- // Coding indicators
369
- if (/\b(code|program|function|class|javascript|python|java|typescript|bug|debug|algorithm|api|database|sql|html|css|react|node|git)\b/i.test(input)) {
370
- return { category: 'coding', confidence: 0.8 };
371
- }
372
-
373
- // Math indicators
374
- if (/\b(math|calculate|equation|formula|algebra|geometry|calculus|trigonometry|derivative|integral|solve|number|percent)\b/i.test(input)) {
375
- return { category: 'math', confidence: 0.8 };
376
- }
377
-
378
- // Science indicators
379
- if (/\b(science|physics|chemistry|biology|atom|molecule|cell|dna|gravity|energy|evolution|quantum|element)\b/i.test(input)) {
380
- return { category: 'science', confidence: 0.8 };
381
- }
382
-
383
- // Image generation indicators
384
- if (/\b(image|picture|photo|draw|paint|art|generate|create|design|style|visual|render|illustration)\b/i.test(input)) {
385
- return { category: 'image_generation', confidence: 0.8 };
386
- }
387
-
388
- // Reasoning indicators
389
- if (/\b(puzzle|logic|riddle|think|reason|solve|problem|brain teaser|sequence|pattern)\b/i.test(input)) {
390
- return { category: 'reasoning', confidence: 0.7 };
391
- }
392
-
393
- // Advice indicators
394
- if (/\b(advice|recommend|suggest|should i|how can i|tips|help me|improve|better)\b/i.test(input)) {
395
- return { category: 'advice', confidence: 0.6 };
396
- }
397
-
398
- // General question indicators
399
- if (/^(what|who|where|when|why|how|which|is|are|can|do|does)/i.test(input)) {
400
- return { category: 'question_answering', confidence: 0.5 };
401
- }
402
-
403
- return { category: null, confidence: 0 };
404
- }
405
-
406
- isGreeting(input) {
407
- return /^(hi|hello|hey|greetings|good morning|good afternoon|good evening|howdy|what's up|sup)\b/i.test(input);
408
- }
409
-
410
- isFarewell(input) {
411
- return /^(bye|goodbye|see you|farewell|take care|later|cya|gtg)\b/i.test(input);
412
- }
413
-
414
- isThanks(input) {
415
- return /^(thanks|thank you|thx|appreciate|grateful)\b/i.test(input);
416
- }
417
-
418
- getGreetingResponse() {
419
- const responses = [
420
- "Hello! I'm OmniMind, your AI assistant. I can help you with coding, math, science, image generation prompts, and much more. What would you like to know?",
421
- "Hi there! Welcome to OmniMind. I'm trained on 100,000 examples covering various topics. How can I assist you today?",
422
- "Hey! Great to see you. I'm here to help with questions, explanations, coding, creative tasks, and more. What's on your mind?",
423
- "Greetings! I'm OmniMind AI - ask me anything about programming, science, math, or get creative prompts. What can I do for you?"
424
- ];
425
- return responses[Math.floor(Math.random() * responses.length)];
426
- }
427
-
428
- getFarewellResponse() {
429
- const responses = [
430
- "Goodbye! It was great chatting with you. Come back anytime you have questions!",
431
- "See you later! Feel free to return whenever you need help.",
432
- "Take care! I'll be here if you need any assistance in the future.",
433
- "Farewell! Thanks for using OmniMind. Have a great day!"
434
- ];
435
- return responses[Math.floor(Math.random() * responses.length)];
436
- }
437
-
438
- getThanksResponse() {
439
- const responses = [
440
- "You're welcome! I'm happy I could help. Is there anything else you'd like to know?",
441
- "My pleasure! Feel free to ask if you have more questions.",
442
- "Glad I could assist! Don't hesitate to ask about anything else.",
443
- "Anytime! That's what I'm here for. What else can I help with?"
444
- ];
445
- return responses[Math.floor(Math.random() * responses.length)];
446
- }
447
-
448
- getFallbackResponse(input, intent) {
449
- const category = intent.category ? ` about ${intent.category}` : '';
450
-
451
- const responses = [
452
- `I don't have a specific answer for that question${category}, but I can try to help! Could you rephrase your question or provide more details?`,
453
- `Interesting question! While I may not have an exact match in my knowledge base, I'd be happy to help explore this topic. Can you tell me more about what you're looking for?`,
454
- `I'm not sure I have the perfect answer for this, but let me suggest some related topics:\n- Try asking about specific programming languages\n- Ask about math formulas or scientific concepts\n- Request image generation prompts\n- Explore reasoning puzzles\n\nWhat interests you most?`
455
- ];
456
-
457
- return responses[Math.floor(Math.random() * responses.length)];
458
- }
459
-
460
- formatResponse(entry, score) {
461
- let response = entry.response;
462
-
463
- // Add category context if relevant
464
- if (score < 0.7) {
465
- response = `Based on my knowledge about **${entry.category.replace('_', ' ')}**:\n\n${response}`;
466
- }
467
-
468
- return response;
469
- }
470
-
471
- addToContext(userInput, response) {
472
- this.context.push({ user: userInput, assistant: response });
473
- if (this.context.length > this.maxContextLength) {
474
- this.context.shift();
475
- }
476
- }
477
-
478
- getHelpMessage() {
479
- return `
480
- **OmniMind AI Help**
481
-
482
- I can assist you with many topics including:
483
- • **Coding** - Programming questions, algorithms, code examples
484
- • **Math** - Formulas, calculations, problem solving
485
- • **Science** - Physics, chemistry, biology, astronomy
486
- • **Image Generation** - Create detailed prompts for AI art
487
- • **General Knowledge** - History, geography, facts
488
- • **Reasoning** - Logic puzzles, brain teasers
489
- • **Advice** - Productivity, health, learning tips
490
-
491
- **Commands:**
492
- • /help - Show this help message
493
- • /stats - Show knowledge base statistics
494
- • /categories - List all categories
495
- • /random [category] - Get random knowledge
496
- • /about - About OmniMind
497
- • /clear - Clear conversation context
498
-
499
- Just ask me anything!
500
- `;
501
- }
502
-
503
- getStatsMessage() {
504
- const stats = this.kb.getStats();
505
- let message = `**OmniMind Knowledge Base Statistics**\n\nTotal entries: ${stats.total.toLocaleString()}\n\n**By Category:**\n`;
506
-
507
- Object.entries(stats.categories)
508
- .sort((a, b) => b[1] - a[1])
509
- .forEach(([cat, count]) => {
510
- const pct = ((count / stats.total) * 100).toFixed(1);
511
- message += `• ${cat.replace('_', ' ')}: ${count.toLocaleString()} (${pct}%)\n`;
512
- });
513
-
514
- return message;
515
- }
516
-
517
- getCategoriesMessage() {
518
- const categories = this.kb.getCategories();
519
- return `**Available Categories:**\n\n${categories.map(c => `• ${c.replace('_', ' ')}`).join('\n')}\n\nYou can ask questions related to any of these topics!`;
520
- }
521
-
522
- getAboutMessage() {
523
- return `
524
- **About OmniMind AI**
525
-
526
- Version: ${CONFIG.version}
527
- Model: ${CONFIG.modelName}
528
-
529
- OmniMind is a knowledge-based AI assistant trained on 100,000 high-quality examples covering:
530
- - Programming and Software Development
531
- - Mathematics and Problem Solving
532
- - Science (Physics, Chemistry, Biology, Astronomy)
533
- - Image Generation Prompts
534
- - General Knowledge and Trivia
535
- - Logical Reasoning and Puzzles
536
- - Practical Advice and Tips
537
-
538
- This is a demonstration of how dataset-driven AI can provide helpful, accurate responses across many domains.
539
-
540
- Created for educational and demonstration purposes.
541
- `;
542
- }
543
- }
544
-
545
- // ============================================
546
- // INTERACTIVE CLI
547
- // ============================================
548
-
549
- async function startInteractiveSession() {
550
- console.log('\n' + '='.repeat(60));
551
- console.log(' 🧠 OmniMind AI - 100K Knowledge Base Assistant');
552
- console.log('='.repeat(60));
553
- console.log('\nInitializing...\n');
554
-
555
- const ai = new OmniMindAI();
556
-
557
- try {
558
- await ai.initialize();
559
- } catch (error) {
560
- console.error('Failed to initialize:', error.message);
561
- process.exit(1);
562
- }
563
-
564
- console.log('\n✨ OmniMind is ready! Type your questions or /help for commands.');
565
- console.log(' Type "exit" or "quit" to end the session.\n');
566
- console.log('-'.repeat(60) + '\n');
567
-
568
- const rl = readline.createInterface({
569
- input: process.stdin,
570
- output: process.stdout
571
- });
572
-
573
- const prompt = () => {
574
- rl.question('\n🧑 You: ', async (input) => {
575
- if (!input || input.trim() === '') {
576
- prompt();
577
- return;
578
- }
579
-
580
- const trimmed = input.trim().toLowerCase();
581
- if (trimmed === 'exit' || trimmed === 'quit') {
582
- console.log('\n👋 Goodbye! Thanks for using OmniMind AI.\n');
583
- rl.close();
584
- process.exit(0);
585
- }
586
-
587
- try {
588
- const response = await ai.respond(input);
589
- console.log('\n🤖 OmniMind:', response);
590
- } catch (error) {
591
- console.log('\n⚠️ Error:', error.message);
592
- }
593
-
594
- prompt();
595
- });
596
- };
597
-
598
- prompt();
599
- }
600
-
601
- // ============================================
602
- // PROGRAMMATIC API
603
- // ============================================
604
-
605
- class OmniMindAPI {
606
- constructor() {
607
- this.ai = null;
608
- this.initialized = false;
609
- }
610
-
611
- async init() {
612
- if (this.initialized) return this;
613
-
614
- this.ai = new OmniMindAI();
615
- await this.ai.initialize();
616
- this.initialized = true;
617
- return this;
618
- }
619
-
620
- async ask(question) {
621
- if (!this.initialized) {
622
- await this.init();
623
- }
624
- return this.ai.respond(question);
625
- }
626
-
627
- async search(query, options) {
628
- if (!this.initialized) {
629
- await this.init();
630
- }
631
- return this.ai.kb.search(query, options);
632
- }
633
-
634
- getStats() {
635
- if (!this.initialized) {
636
- throw new Error('API not initialized. Call init() first.');
637
- }
638
- return this.ai.kb.getStats();
639
- }
640
- }
641
-
642
- // ============================================
643
- // EXPORTS AND MAIN
644
- // ============================================
645
-
646
- // Export for programmatic use
647
- module.exports = { OmniMindAPI, OmniMindAI, KnowledgeBase, TextProcessor };
648
-
649
- // Run interactive session if executed directly
650
- if (require.main === module) {
651
- startInteractiveSession();
652
- }