-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscript.js
More file actions
2405 lines (2023 loc) · 93.2 KB
/
script.js
File metadata and controls
2405 lines (2023 loc) · 93.2 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as webllm from "https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.46/+esm";
import { Wllama } from 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.7/esm/index.js';
class AskAnton {
constructor() {
// Debug flags for testing failover (can be set via URL params or console)
this.debugConfig = this.parseDebugConfig();
this.engine = null; // WebLLM engine
this.wllama = null; // Wllama engine (fallback)
this.conversationHistory = [];
this.isGenerating = false;
this.indexData = null;
this.stopRequested = false;
this.currentStream = null;
this.currentAbortController = null;
this.webGPUAvailable = false;
this.usingWllama = false;
this.currentMode = 'basic';
this.availableModes = {
gpu: false,
cpu: true,
basic: true
};
this.isLoadingModel = false;
this.currentModal = null;
this.lastFocusedElement = null;
this.modalFocusTrapHandler = null;
this.usedVoiceInput = false;
// Vosk speech recognition (lazy-loaded fallback)
this.voskModel = null;
this.voskRecognizer = null;
this.voskLoaded = false;
this.voskLoadingFailed = false;
this.isRecording = false;
this.mediaStream = null;
this.audioContext = null;
this.processorNode = null;
this.sourceNode = null;
// Calculate speech model path relative to the base path
const basePath = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/'));
const rootPath = basePath.substring(0, basePath.lastIndexOf('/'));
this.speechModelUrl = `${rootPath}/speech-model/speech-model.tar.gz`;
this.silenceTimer = null;
this.noSpeechTimer = null;
this.lastSpeechTime = null;
this.hasSpeech = false;
this.silenceTimeout = 2000; // Auto-stop after 2 seconds of silence
this.noSpeechTimeout = 5000; // Cancel after 5 seconds of no speech
this.usingWebSpeech = true; // Try Web Speech API first
this.elements = {
progressSection: document.getElementById('progress-section'),
progressFill: document.getElementById('progress-fill'),
progressText: document.getElementById('progress-text'),
chatContainer: document.getElementById('chat-container'),
chatMessages: document.getElementById('chat-messages'),
userInput: document.getElementById('user-input'),
sendBtn: document.getElementById('send-btn'),
micBtn: document.getElementById('mic-btn'),
restartBtn: document.getElementById('restart-btn'),
searchStatus: document.getElementById('search-status'),
modeSelect: document.getElementById('mode-select'),
aboutBtn: document.getElementById('about-btn'),
aboutModal: document.getElementById('about-modal'),
aboutModalClose: document.getElementById('about-modal-close'),
aboutModalOk: document.getElementById('about-modal-ok'),
aiModeModal: document.getElementById('ai-mode-modal'),
modalClose: document.getElementById('modal-close'),
modalOk: document.getElementById('modal-ok')
};
this.systemPrompt = `You are Anton, a knowledgeable and friendly AI learning assistant who helps students understand AI concepts.
IMPORTANT: Follow these guidelines when responding:
- Do not engage in conversation on topics other than artificial intelligence and computing. For questions outside of these topics, politely decline to answer.
- Explain concepts clearly and concisely in a single paragraph based only on the provided context.
- Keep responses short and focused on the question, with no headings.
- Use examples and analogies when helpful.
- Use simple language suitable for learners in a conversational, friendly tone.
- Provide a general descriptions and overviews, but do NOT provide explicit steps or instructions for developing AI solutions.
- Do not start responses with "A:" or "Q:".
- Keep your responses concise and to the point, in ONE paragraph.
- Do NOT provide links for more information (these will be added automatically later).`;
// Prohibited words for content moderation (whole words only)
this.prohibitedWords = [];
this.initialize();
}
// ============================================================================
// INITIALIZATION
// ============================================================================
parseDebugConfig() {
// Parse URL parameters for debug flags
// Usage: ?debug=true&forceWebGPUFail=true&forceWllamaFail=true
const params = new URLSearchParams(window.location.search);
const config = {
enabled: params.has('debug'),
forceWebGPUFail: params.has('forceWebGPUFail') || params.get('forceWebGPUFail') === 'true',
forceWllamaFail: params.has('forceWllamaFail') || params.get('forceWllamaFail') === 'true',
forceBasicMode: params.has('forceBasicMode') || params.get('forceBasicMode') === 'true'
};
if (config.enabled) {
console.log('🧪 Debug mode enabled:', config);
console.log('💡 To force failures, add URL params: ?debug=true&forceWebGPUFail=true&forceWllamaFail=true');
console.log('💡 Or use console: window.askAnton.debugConfig.forceWebGPUFail = true');
}
return config;
}
async initialize() {
try {
// Load prohibited words used by content moderation
await this.loadProhibitedWords();
// Load the index (no longer loading Vosk upfront)
await this.loadIndex();
// Try to initialize WebLLM first, fall back to wllama if needed
await this.initializeEngine();
// Setup event listeners
this.setupEventListeners();
} catch (error) {
console.error('Initialization error:', error);
this.showError('Failed to initialize. Please refresh the page.');
}
}
// ============================================================================
// UTILITY METHODS
// ============================================================================
reverseWord(text) {
return text.split('').reverse().join('');
}
shiftWord(text, amount) {
return text
.split('')
.map(char => String.fromCharCode(char.charCodeAt(0) + amount))
.join('');
}
async loadProhibitedWords() {
try {
const response = await fetch('moderation/mod.txt', { cache: 'no-store' });
if (!response.ok) throw new Error('Failed to load prohibited words');
const encodedWordsText = await response.text();
this.prohibitedWords = encodedWordsText
.split(/\r?\n/)
.map(word => word.trim())
.filter(word => word.length > 0)
.map(word => this.shiftWord(this.reverseWord(word.toLowerCase()), 1));
console.log('Loaded prohibited words:', this.prohibitedWords.length);
} catch (error) {
console.error('Error loading prohibited words:', error);
throw error;
}
}
async loadIndex() {
try {
this.updateProgress(5, 'Loading knowledge base...');
const response = await fetch('index.json', { cache: 'no-store' });
if (!response.ok) throw new Error('Failed to load index');
this.indexData = await response.json();
console.log('Loaded index with', this.indexData.length, 'categories');
// Build a flat lookup map: keyword -> {document, category, link}
this.keywordMap = new Map();
this.indexData.forEach(category => {
category.documents.forEach(doc => {
doc.keywords.forEach(keyword => {
const normalizedKeyword = keyword.toLowerCase().trim();
if (normalizedKeyword) {
this.keywordMap.set(normalizedKeyword, {
document: doc,
category: category.category,
link: category.link
});
}
});
});
});
console.log('Built keyword map with', this.keywordMap.size, 'keywords');
} catch (error) {
console.error('Error loading index:', error);
throw error;
}
}
async loadVoskModel() {
if (this.voskLoaded || this.voskLoadingFailed) {
return this.voskLoaded;
}
try {
console.log('Loading Vosk speech model from', this.speechModelUrl);
if (!window.Vosk || typeof Vosk.createModel !== 'function') {
console.warn('Vosk library not loaded');
this.voskLoadingFailed = true;
return false;
}
const loadingMsg = this.addSystemMessage('Loading offline speech model... This may take a moment.');
this.disableInput();
this.elements.micBtn.disabled = true;
this.voskModel = await Vosk.createModel(this.speechModelUrl);
this.voskRecognizer = new this.voskModel.KaldiRecognizer(16000);
// Set up recognizer event handlers
this.voskRecognizer.on("result", (message) => {
const result = message.result;
if (result && result.text) {
// Clear no-speech timer since we got speech
if (this.noSpeechTimer) {
clearTimeout(this.noSpeechTimer);
this.noSpeechTimer = null;
}
// Append the recognized text to the input
const currentText = this.elements.userInput.value;
this.elements.userInput.value = currentText + (currentText ? " " : "") + result.text;
this.autoResizeTextarea();
this.hasSpeech = true;
this.lastSpeechTime = Date.now();
this.resetSilenceTimer();
}
});
this.voskRecognizer.on("partialresult", (message) => {
// Reset silence timer on partial results too
const result = message.result;
if (result && result.partial && result.partial.trim()) {
// Clear no-speech timer on partial results
if (this.noSpeechTimer) {
clearTimeout(this.noSpeechTimer);
this.noSpeechTimer = null;
}
this.lastSpeechTime = Date.now();
this.resetSilenceTimer();
}
});
this.voskLoaded = true;
console.log('Vosk speech model loaded successfully');
// Update the loading message
const msgP = loadingMsg.querySelector('p');
if (msgP) {
msgP.textContent = 'Offline speech model ready! Please try your voice input again.';
}
this.enableInput();
this.elements.micBtn.disabled = false;
return true;
} catch (error) {
console.error('Error loading Vosk model:', error);
this.voskLoadingFailed = true;
this.addSystemMessage('Failed to load offline speech model. Voice input is unavailable.');
this.enableInput();
this.elements.micBtn.disabled = false;
return false;
}
}
// ============================================================================
// LLM ENGINE INITIALIZATION (WebLLM & Wllama)
// ============================================================================
checkWebGPUSupport() {
// Check if WebGPU is available in the browser
if (!navigator.gpu) {
console.log('WebGPU not supported in this browser');
return false;
}
return true;
}
async initializeEngine() {
// 🧪 DEBUG: Force Basic mode for testing
if (this.debugConfig.enabled && this.debugConfig.forceBasicMode) {
console.log('🧪 DEBUG: Forcing Basic mode');
this.initializeBasicMode(
'Ready to chat! (Basic mode)',
'🧪 DEBUG: Running in forced Basic mode for testing.'
);
return;
}
const hasWebGPU = this.checkWebGPUSupport();
this.availableModes.gpu = hasWebGPU;
if (hasWebGPU) {
try {
await this.initializeWebLLM();
return;
} catch (error) {
console.log('WebLLM initialization failed, falling back to CPU mode');
this.availableModes.gpu = false;
}
}
try {
await this.initializeWllama(null, {
activateMode: true,
showChatInterface: true,
showFatalError: false
});
return;
} catch (error) {
console.log('CPU model initialization failed, falling back to Basic mode');
this.availableModes.cpu = false;
}
this.initializeBasicMode(
'Ready to chat! (Basic mode)',
'Using Basic mode because the GPU and CPU models could not be loaded.'
);
}
async initializeWebLLM() {
try {
this.updateProgress(15, 'Loading AI model (WebGPU)...');
// 🧪 DEBUG: Force WebGPU initialization failure for testing error handling
if (this.debugConfig.enabled && this.debugConfig.forceWebGPUFail) {
console.log('🧪 DEBUG: Forcing WebGPU initialization to fail (testing error handling)');
await new Promise(resolve => setTimeout(resolve, 500)); // Simulate some initialization time
throw new Error('DEBUG: Forced WebGPU initialization failure');
}
const targetModelId = 'Phi-3-mini-4k-instruct-q4f16_1-MLC';
this.engine = await webllm.CreateMLCEngine(
targetModelId,
{
initProgressCallback: (progress) => {
const percentage = Math.max(15, Math.round(progress.progress * 85) + 15);
this.updateProgress(
percentage,
`Loading model: ${Math.round(progress.progress * 100)}%`
);
}
}
);
this.updateProgress(100, 'Ready to chat!');
console.log('WebLLM engine initialized successfully');
this.webGPUAvailable = true;
this.availableModes.gpu = true;
this.setCurrentMode('gpu');
setTimeout(() => {
this.showChatInterface();
}, 500);
} catch (error) {
console.error('Failed to initialize WebLLM:', error);
this.availableModes.gpu = false;
throw error; // Re-throw to trigger fallback
}
}
async initializeWllama(progressCallback = null, options = {}) {
const {
activateMode = !this.availableModes.gpu,
showChatInterface = !this.availableModes.gpu,
showFatalError = false
} = options;
try {
// Check if already initialized
if (this.wllama) {
console.log('Wllama already initialized');
this.availableModes.cpu = true;
if (activateMode) {
this.setCurrentMode('cpu');
}
return;
}
const isLazyLoad = progressCallback !== null || !showChatInterface;
// 🧪 DEBUG: Force Wllama initialization failure for testing error handling
if (this.debugConfig.enabled && this.debugConfig.forceWllamaFail) {
console.log('🧪 DEBUG: Forcing Wllama initialization to fail (testing error handling)');
if (!isLazyLoad) {
this.updateProgress(15, 'Loading AI model (CPU mode)...');
}
await new Promise(resolve => setTimeout(resolve, 500)); // Simulate some initialization time
throw new Error('DEBUG: Forced Wllama initialization failure');
}
if (!isLazyLoad) {
this.updateProgress(15, 'Loading AI model (CPU mode)...');
}
// Configure WASM paths for CDN
const CONFIG_PATHS = {
'single-thread/wllama.wasm': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.7/esm/single-thread/wllama.wasm',
'multi-thread/wllama.wasm': 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.7/esm/multi-thread/wllama.wasm',
};
// Try multithreaded first if cross-origin isolated, fall back to single-threaded
const useMultiThread = window.crossOriginIsolated === true;
const availableThreads = navigator.hardwareConcurrency || 4; // Fallback to 4 if not available
const preferredThreads = useMultiThread ? Math.max(1, availableThreads - 2) : 1;
console.log(`Cross-origin isolated: ${window.crossOriginIsolated}, available threads: ${availableThreads}, attempting ${preferredThreads} thread(s)`);
const modelConfig = {
n_ctx: 384, // Smaller context for faster processing
n_threads: preferredThreads,
progressCallback: ({ loaded, total }) => {
// Cap at 98% to leave room for cache warming message
const percentage = Math.min(98, Math.max(15, Math.round((loaded / total) * 85) + 15));
const progress = loaded / total;
if (!isLazyLoad) {
this.updateProgress(
percentage,
`Loading model: ${Math.round((loaded / total) * 100)}%`
);
} else {
console.log(`Loading wllama: ${Math.round((loaded / total) * 100)}%`);
// Call the progress callback for lazy loading
if (progressCallback) {
progressCallback(progress);
}
}
}
};
try {
// Initialize wllama with CDN-hosted WASM files
this.wllama = new Wllama(CONFIG_PATHS);
// Load model from HuggingFace with optimized settings
await this.wllama.loadModelFromHF(
'Felladrin/gguf-sharded-phi-2-orange-v2',
'phi-2-orange-v2.Q5_K_M.shard-00001-of-00025.gguf',
modelConfig
);
console.log(`Wllama initialized successfully with ${preferredThreads} thread(s)`);
// Warm the cache with system instruction
await this.warmWllamaCache(isLazyLoad, progressCallback, true);
} catch (multiErr) {
if (preferredThreads > 1) {
console.warn(`Multi-threaded init failed (${multiErr.message}), falling back to single thread`);
// Retry with single thread
this.wllama = new Wllama(CONFIG_PATHS);
await this.wllama.loadModelFromHF(
'Felladrin/gguf-sharded-phi-2-orange-v2',
'phi-2-orange-v2.Q5_K_M.shard-00001-of-00025.gguf',
{
...modelConfig,
n_threads: 1
}
);
console.log('Wllama initialized successfully with 1 thread (fallback)');
// Warm the cache with system instruction
await this.warmWllamaCache(isLazyLoad, progressCallback, true);
} else {
throw multiErr;
}
}
console.log('Wllama initialized successfully with Phi 2');
this.availableModes.cpu = true;
if (activateMode) {
this.setCurrentMode('cpu');
}
if (showChatInterface) {
setTimeout(() => {
this.showChatInterface();
}, 500);
}
} catch (error) {
console.error('Failed to initialize wllama:', error);
this.availableModes.cpu = false;
if (showFatalError) {
this.showError('Failed to load AI model. Please refresh the page.');
}
throw error;
}
}
async warmWllamaCache(isLazyLoad = true, progressCallback = null, updateFinalProgress = false) {
// Warm the cache with the system instruction to improve first response time
if (!this.wllama) return;
try {
const systemInstruction = '<|im_start|>system\n' +
'You are Anton, a teacher of AI and computing concepts.\n' +
'Discuss AI and computing topics only\n' +
'Do not provide specific steps or instructions\n\n' +
'Provide factual and accurate information\n\n' +
'<|im_end|>\n\n';
console.log('Warming cache with system instruction...');
// Update progress message
if (!isLazyLoad) {
this.updateProgress(99, 'Optimizing model...');
} else if (progressCallback) {
// For lazy loading, pass progress as 0.99
progressCallback(0.99);
}
await this.wllama.createCompletion(systemInstruction, {
nPredict: 1,
sampling: {
temp: 0.0
}
});
console.log('Cache warmed successfully');
// Update to final ready state if requested
if (!isLazyLoad && updateFinalProgress) {
this.updateProgress(100, 'Ready to chat! (CPU mode)');
}
} catch (error) {
console.log('Cache warming failed (non-critical):', error.message);
// Still show ready message even if cache warming failed
if (!isLazyLoad && updateFinalProgress) {
this.updateProgress(100, 'Ready to chat! (CPU mode)');
}
}
}
// ============================================================================
// UI STATE MANAGEMENT
// ============================================================================
updateProgress(percentage, text) {
this.elements.progressFill.style.width = `${percentage}%`;
this.elements.progressText.textContent = text;
// Update progress bar ARIA attributes
const progressBar = document.querySelector('.progress-bar');
if (progressBar) {
progressBar.setAttribute('aria-valuenow', percentage);
progressBar.setAttribute('aria-label', text);
}
}
showChatInterface() {
this.elements.progressSection.style.display = 'none';
this.elements.chatContainer.style.display = 'flex';
this.updateModeSelector();
this.elements.userInput.focus();
}
initializeBasicMode(progressText = 'Ready to chat! (Basic mode)', notice = null) {
this.setCurrentMode('basic');
this.updateProgress(100, progressText);
setTimeout(() => {
this.showChatInterface();
if (notice) {
this.addSystemMessage(notice);
}
}, 500);
}
setCurrentMode(mode) {
this.currentMode = mode;
this.usingWllama = mode === 'cpu';
}
getModeLabel(mode = this.currentMode) {
if (mode === 'gpu') {
return 'Phi 3.1 (GPU)';
}
if (mode === 'cpu') {
return 'Phi 2.0 (CPU)';
}
return 'None (Basic Q&A)';
}
showError(message) {
this.elements.progressText.textContent = message;
this.elements.progressFill.style.backgroundColor = '#dc3545';
}
disableInput() {
this.elements.userInput.disabled = true;
this.elements.sendBtn.disabled = true;
this.elements.micBtn.disabled = true;
this.elements.userInput.placeholder = 'Loading model...';
}
enableInput() {
this.elements.userInput.disabled = false;
this.elements.sendBtn.disabled = false;
this.elements.micBtn.disabled = false;
this.elements.userInput.placeholder = 'Ask a question about AI...';
this.elements.userInput.focus();
}
// ============================================================================
// EVENT LISTENERS
// ============================================================================
setupEventListeners() {
// Send button click
this.elements.sendBtn.addEventListener('click', () => {
if (this.isGenerating) {
this.stopGeneration();
} else {
this.sendMessage();
}
});
// Enter key to send (Shift+Enter for new line)
this.elements.userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey && !this.isGenerating) {
e.preventDefault();
this.sendMessage();
}
});
// Auto-resize textarea
this.elements.userInput.addEventListener('input', () => {
this.autoResizeTextarea();
});
// Keyboard navigation
this.elements.userInput.addEventListener('keydown', (e) => {
// Enter to send (without Shift)
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!this.isGenerating) {
this.sendMessage();
}
}
// Escape to stop generation
if (e.key === 'Escape' && this.isGenerating) {
this.stopGeneration();
}
});
// Global keyboard shortcuts
document.addEventListener('keydown', (e) => {
// Ctrl/Cmd + K to focus input
if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
e.preventDefault();
this.elements.userInput.focus();
}
// Ctrl/Cmd + N for new chat
if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
e.preventDefault();
this.restartConversation();
}
});
// Microphone button
this.elements.micBtn.addEventListener('click', () => {
this.handleMicClick();
});
// Restart button
this.elements.restartBtn.addEventListener('click', () => {
this.restartConversation();
});
// Mode selector
this.elements.modeSelect.addEventListener('change', (event) => {
this.switchMode(event.target.value);
});
// About button
this.elements.aboutBtn.addEventListener('click', () => {
this.lastFocusedElement = this.elements.aboutBtn;
this.showAboutModal();
});
// About modal handlers
this.elements.aboutModalClose.addEventListener('click', () => {
this.hideAboutModal();
});
this.elements.aboutModalOk.addEventListener('click', () => {
this.hideAboutModal();
});
// Close about modal on overlay click
this.elements.aboutModal.addEventListener('click', (e) => {
if (e.target === this.elements.aboutModal || e.target.classList.contains('modal-overlay')) {
this.hideAboutModal();
}
});
// Modal handlers
this.elements.modalClose.addEventListener('click', () => {
this.hideAiModeModal();
});
this.elements.modalOk.addEventListener('click', () => {
this.hideAiModeModal();
});
// Close modal on overlay click
this.elements.aiModeModal.addEventListener('click', (e) => {
if (e.target === this.elements.aiModeModal || e.target.classList.contains('modal-overlay')) {
this.hideAiModeModal();
}
});
// Close modal on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (this.elements.aiModeModal.style.display === 'flex') {
this.hideAiModeModal();
} else if (this.elements.aboutModal.style.display === 'flex') {
this.hideAboutModal();
}
}
});
// Example question buttons
const exampleBtns = document.querySelectorAll('.example-btn');
exampleBtns.forEach(btn => {
btn.addEventListener('click', () => {
const question = btn.getAttribute('data-question');
this.elements.userInput.value = question;
this.elements.userInput.focus();
this.autoResizeTextarea();
});
});
// Dynamic AI mode link keyboard handling (for links added to messages)
this.elements.chatMessages.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && e.target.classList.contains('ai-mode-link')) {
e.preventDefault();
e.target.click();
}
});
}
// ============================================================================
// CONTENT MODERATION & TEXT PROCESSING
// ============================================================================
autoResizeTextarea() {
const textarea = this.elements.userInput;
textarea.style.height = 'auto';
textarea.style.height = Math.min(textarea.scrollHeight, 150) + 'px';
}
containsProhibitedWords(text) {
// Convert to lowercase for case-insensitive matching
const lowerText = text.toLowerCase();
// Create word boundaries regex pattern for whole word matching
for (const word of this.prohibitedWords) {
// Use word boundary to match whole words only
const regex = new RegExp(`\\b${word}\\b`, 'i');
if (regex.test(lowerText)) {
console.log(`Content moderation: blocked word "${word}" detected`);
return true;
}
}
return false;
}
normalizeSearchText(text) {
return text.toLowerCase().trim().replace(/[^a-z0-9\s]/g, ' ').replace(/\s+/g, ' ').trim();
}
getSearchIntentQuery(text) {
const trimmedText = text.trim();
const lowerText = trimmedText.toLowerCase();
if (lowerText.startsWith('search ')) {
return trimmedText.slice(7).trim();
}
if (lowerText.startsWith('find ')) {
return trimmedText.slice(5).trim();
}
if (lowerText.includes('documentation') || lowerText.includes('docs') || lowerText.includes('microsoft learn')) {
return trimmedText;
}
return null;
}
extractBingSearchKeywords(text) {
const normalizedText = this.normalizeSearchText(text);
const words = normalizedText.split(' ').filter(Boolean);
const stopWords = new Set([
// Articles, prepositions, conjunctions
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',
'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'with',
'or', 'but', 'if', 'than', 'then', 'so', 'yet',
'after', 'before', 'between', 'during', 'into', 'through', 'over',
'under', 'until', 'up', 'down', 'out', 'off', 'above', 'below',
// Pronouns
'i', 'you', 'he', 'she', 'we', 'they', 'me', 'him', 'her',
'us', 'them', 'my', 'your', 'his', 'our', 'their', 'i\'m',
'you\'re', 'he\'s', 'she\'s', 'we\'re', 'they\'re',
// Determiners and quantifiers
'this', 'these', 'those', 'some', 'any', 'all', 'each', 'every',
'both', 'few', 'more', 'most', 'such', 'no', 'nor', 'not', 'only',
'own', 'same', 'other', 'another', 'much', 'many',
// Verbs (auxiliary, modal, and common generic)
'am', 'was', 'were', 'been', 'being', 'have', 'has',
'had', 'do', 'does', 'did', 'can', 'could', 'would', 'should',
'may', 'might', 'must', 'shall', 'ought', 'will',
'get', 'make', 'know', 'see', 'take', 'come', 'go', 'want',
'use', 'find', 'need', 'try', 'ask', 'work', 'help', 'like', 'seem',
'become', 'let', 'tell', 'show', 'give', 'provide', 'explain',
'describe', 'define',
// Question words
'what', 'when', 'where', 'who', 'how', 'why', 'which', 'whom',
'whose', 'whether', 'what\'s', 'whats', 'who\'s', 'whos', 'how\'s',
'hows',
// Common adverbs
'also', 'just', 'now', 'here', 'there', 'very', 'too',
'really', 'still', 'always', 'never', 'often', 'sometimes', 'maybe',
'perhaps', 'about',
// Other common words
'yes', 'no', 'thing', 'something', 'anything', 'nothing',
'everything', 'someone', 'anyone', 'everyone', 'understand',
'think', 'believe', 'feel', 'appear', 'say',
'anton', 'please', 'using', 'search',
'documentation', 'learn', 'details', 'overview'
]);
const uniqueWords = [];
const seenWords = new Set();
words.forEach(word => {
if (word.length < 2 || stopWords.has(word) || seenWords.has(word)) {
return;
}
seenWords.add(word);
uniqueWords.push(word);
});
return uniqueWords.join(' ');
}
// ============================================================================
// SEARCH & CONTEXT RETRIEVAL
// ============================================================================
performSearch(userQuestion) {
const lowerQuestion = userQuestion.toLowerCase().trim();
// Normalize the question: remove punctuation, extra spaces
const normalizedQuestion = this.normalizeSearchText(lowerQuestion);
const words = normalizedQuestion.split(' ');
// Extract all n-grams (trigrams, bigrams, unigrams)
const nGrams = [];
// Trigrams (3-word phrases)
for (let i = 0; i <= words.length - 3; i++) {
nGrams.push({
text: words.slice(i, i + 3).join(' '),
length: 3
});
}
// Bigrams (2-word phrases)
for (let i = 0; i <= words.length - 2; i++) {
nGrams.push({
text: words.slice(i, i + 2).join(' '),
length: 2
});
}
// Unigrams (single words) - filter out very short words and common stop words
const stopWords = ['what', 'is', 'are', 'the', 'a', 'an', 'how', 'does', 'do', 'can', 'about', 'tell', 'me', 'explain', 'describe', 'show', 'give', 'anton', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'my', 'your', 'his', 'her', 'its', 'our', 'their', 'why', 'which', 'whom', 'whose', 'why', 'all', 'any', 'this', 'that', 'these', 'those'];
words.forEach(word => {
if (word.length >= 2 && !stopWords.includes(word)) {
nGrams.push({
text: word,
length: 1
});
}
});
console.log('Extracted n-grams:', nGrams.map(ng => `"${ng.text}" (${ng.length})`));
// Match n-grams to keywords in the index
const matchedKeywords = new Set();
const documentMatches = new Map(); // doc id -> {doc, category, link, matchedKeywords[]}
nGrams.forEach(ngram => {
const match = this.keywordMap.get(ngram.text);
if (match) {
matchedKeywords.add(ngram.text);
const docId = match.document.id;
if (!documentMatches.has(docId)) {
documentMatches.set(docId, {
document: match.document,
category: match.category,
link: match.link,
matchedKeywords: []
});
}
documentMatches.get(docId).matchedKeywords.push(ngram.text);
}
});
// Filter out keywords that are subsets of longer matched keywords
// Example: if "large language model" is matched, remove "language model" and "language"
const filteredKeywords = new Set();
const sortedKeywords = Array.from(matchedKeywords).sort((a, b) => {
const aWords = a.split(' ').length;
const bWords = b.split(' ').length;
return bWords - aWords; // Longer phrases first
});
sortedKeywords.forEach(keyword => {
// Check if this keyword is a subset of any already-added keyword
let isSubset = false;
for (const existing of filteredKeywords) {
if (existing !== keyword && existing.includes(keyword)) {
isSubset = true;
break;
}
}
if (!isSubset) {
filteredKeywords.add(keyword);
}
});
console.log('Matched keywords (before filtering):', Array.from(matchedKeywords));
console.log('Filtered keywords (after removing subsets):', Array.from(filteredKeywords));
// Rebuild document matches using only filtered keywords
const finalDocumentMatches = [];
documentMatches.forEach((match, docId) => {
// Only include if at least one of its keywords survived filtering
const validKeywords = match.matchedKeywords.filter(kw => filteredKeywords.has(kw));
if (validKeywords.length > 0) {
finalDocumentMatches.push({
...match,
matchedKeywords: validKeywords
});
}
});
console.log(`Found ${finalDocumentMatches.length} matching documents`);
if (finalDocumentMatches.length > 0) {
console.log('Matched documents:', finalDocumentMatches.map(m => ({
id: m.document.id,
title: m.document.title,
category: m.category,
keywords: m.matchedKeywords
})));
}
return {
matches: finalDocumentMatches,
matchedKeywords: Array.from(filteredKeywords)
};
}
searchContext(userQuestion) {
const { matches, matchedKeywords } = this.performSearch(userQuestion);
// If no matches, return null context
if (matches.length === 0) {
this.elements.searchStatus.textContent = '🔍 No specific context found';
return { context: null, categories: [], links: [], documents: [] };
}
// Rank documents by match quality (documents with longer/better keyword matches come first)
const rankedMatches = matches.sort((a, b) => {
// Calculate match quality score: sum of matched keyword lengths
const aScore = a.matchedKeywords.reduce((sum, kw) => sum + kw.split(' ').length, 0);
const bScore = b.matchedKeywords.reduce((sum, kw) => sum + kw.split(' ').length, 0);