forked from steveseguin/social_stream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathai.js
1592 lines (1353 loc) · 55.8 KB
/
ai.js
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
// this file depends on background.js
// this file contains the LLM / RAG component
let globalLunrIndex = null;
let documentsRAG = []; // Store all documents here
const LunrDBLLM = "LunrDBLLM";
const DOCUMENT_STORE_NAME = 'documents';
const activeProcessing = {};
const uploadQueue = [];
let isUploading = false;
let lunrIndexPromise;
const maxContextSize = 31000;
const maxContextSizeFull = 32000;
function getFirstAvailableModel() {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
let ollamaendpoint = "http://localhost:11434";
if (settings.ollamaendpoint && settings.ollamaendpoint.textsetting){
ollamaendpoint = settings.ollamaendpoint.textsetting;
}
xhr.open('GET', ollamaendpoint+'/api/tags', true);
xhr.onload = function() {
if (xhr.status === 200) {
const datar = JSON.parse(xhr.responseText);
if (datar && datar.models && datar.models.length > 0) {
resolve(datar.models[0].name);
} else {
reject(new Error('No models available'));
}
} else {
reject(new Error('Failed to fetch models'));
}
};
xhr.onerror = function() {
reject(new Error('Network error while fetching models'));
};
xhr.send();
});
}
async function rebuildIndex() {
const db = await openDatabase();
const transaction = db.transaction(DOCUMENT_STORE_NAME, 'readonly');
const store = transaction.objectStore(DOCUMENT_STORE_NAME);
const allDocs = await new Promise((resolve, reject) => {
const request = store.getAll();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
const documents = [];
allDocs.forEach(doc => {
if (doc.chunks) {
doc.chunks.forEach((chunk, index) => {
documents.push({
id: `${doc.id}_${index}`, // Use doc.id instead of doc.id
title: chunk.title,
content: chunk.content,
summary: chunk.summary,
tags: chunk.tags.join(' '),
synonyms: chunk.synonyms.join(' '),
level: chunk.level
});
});
} else {
documents.push({
id: doc.id, // Use doc.id
title: doc.title,
content: doc.content,
summary: doc.overallSummary,
tags: doc.tags ? doc.tags.join(' ') : '',
synonyms: doc.synonyms ? doc.synonyms.join(' ') : ''
});
}
});
globalLunrIndex = initLunrIndex(documents);
}
async function callOllamaAPI(prompt, model = null, callback = null) {
const ollamaendpoint = settings.ollamaendpoint?.textsetting || "http://localhost:11434";
let ollamamodel = model || settings.ollamamodel?.textsetting || "llama3.1:latest";
async function makeRequest(currentModel) {
const isStreaming = callback !== null;
try {
if (postNode) {
let body = {
model: currentModel,
prompt: prompt,
stream: isStreaming
};
if (isStreaming) {
// Implement streaming for postNode (you may need to adjust this based on postNode's capabilities)
return await new Promise((resolve, reject) => {
let fullResponse = '';
postNode(`${ollamaendpoint}/api/generate`, body,
{ "Content-Type": 'application/json' },
(chunk) => {
try {
const data = JSON.parse(chunk);
if (data.response) {
fullResponse += data.response;
callback(data.response);
}
if (data.done) {
resolve(fullResponse);
}
} catch (e) {
console.error("Error parsing chunk:", e);
}
}
).catch(reject);
});
} else {
let data = await postNode(`${ollamaendpoint}/api/generate`, body, { "Content-Type": 'application/json' });
try {
data = JSON.parse(data);
} catch(e) {
console.log(data);
}
if (data && data.response) {
return data.response;
} else {
throw new Error("Failed to call Ollama API..");
}
}
} else {
if (isStreaming) {
const response = await fetch(`${ollamaendpoint}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: currentModel,
prompt: prompt,
stream: true
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.trim() !== '') {
try {
const data = JSON.parse(line);
if (data.response) {
fullResponse += data.response;
callback(data.response);
}
} catch (e) {
console.error("Error parsing line:", e);
}
}
}
}
return fullResponse;
} else {
const response = await fetch(`${ollamaendpoint}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: currentModel,
prompt: prompt,
stream: false
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.response;
}
}
} catch (error) {
console.error(`Error in callOllamaAPI with model ${currentModel}:`, error);
throw error;
}
}
try {
return await makeRequest(ollamamodel);
} catch (error) {
console.warn(`Failed to use model ${ollamamodel}. Attempting to get first available model.`);
try {
const availableModel = await getFirstAvailableModel();
console.log(`Attempting with available model: ${availableModel}`);
return await makeRequest(availableModel);
} catch (fallbackError) {
console.error("Error in callOllamaAPI even with fallback:", fallbackError);
throw new Error("Failed to call Ollama API with any available model: " + fallbackError.message);
}
}
}
let censorProcessingSlots = [false, false, false]; // ollama can handle 4 requests at a time by default I think, but 3 is a good number.
async function censorMessageWithOllama(data) {
if (!data.chatmessage) {
return true;
}
const availableSlot = censorProcessingSlots.findIndex(slot => !slot);
if (availableSlot === -1) {
return false; // All slots are occupied
}
censorProcessingSlots[availableSlot] = true;
try {
let censorInstructions = "You will analyze the following message for any signs of hate, extreme negativity, foul language, swear words, bad words, profanity, racism, sexism, political messaging, civil war, violence, threats, or any comment that may be found offensive to a general public audience. You will respond with a number rating out of 5, scoring it based on those factors. A score of 0 would imply it has none of those signs, while 5 would imply it clearly contains some of those signs, and a value in between would imply some level of ambiguity. Do not respond with anything other than a number between 0 and 5. Any message that contains profanity or a curse word automatically should qualify as a 5. There are no more instructions with the message you to rate as follows. MESSAGE: ";
if (data.chatname) {
censorInstructions += data.chatname + " says: ";
}
if (data.chatmessage) {
censorInstructions += data.chatmessage;
}
let llmOutput = await callOllamaAPI(censorInstructions);
//console.log(llmOutput);
let match = llmOutput.match(/\d+/);
let score = match ? parseInt(match[0]) : 0;
//console.log(score);
if (score > 3 || llmOutput.length > 1) {
if (settings.ollamaCensorBotBlockMode) {
return false;
} else if (isExtensionOn) {
//console.log("sending a delete out");
sendToDestinations({ delete: data });
}
} else {
return true;
}
} catch (error) {
console.error("Error processing message:", error);
} finally {
censorProcessingSlots[availableSlot] = false;
}
return false;
}
let isProcessing = false;
const lastResponseTime = {};
async function processMessageWithOllama(data) {
const currentTime = Date.now();
if (isProcessing) { // nice.
return;
}
isProcessing = true;
let ollamaRateLimitPerTab = 5000;
if (settings.ollamaRateLimitPerTab){
ollamaRateLimitPerTab = Math.max(0, parseInt(settings.ollamaRateLimitPerTab.numbersetting)||0);
}
if (lastResponseTime[data.tid] && (currentTime - lastResponseTime[data.tid] < ollamaRateLimitPerTab)) {
isProcessing = false;
return; // Skip this message if we've responded recently
}
let botname = "🤖💬";
if (settings.ollamabotname && settings.ollamabotname.textsetting){
botname = settings.ollamabotname.textsetting.trim();
}
if (!data.chatmessage || data.chatmessage.startsWith(botname+":")) {
isProcessing = false;
return;
}
var cleanedText = data.chatmessage;
if (!data.textonly) {
cleanedText = decodeAndCleanHtml(cleanedText);
}
cleanedText = cleanedText.replace(/\p{Emoji_Presentation}|\p{Emoji}\uFE0F/gu, "").replace(/[\u200D\uFE0F]/g, ""); // Remove zero-width joiner and variation selector
cleanedText = cleanedText.replace(/([\u2700-\u27BF]|[\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2011-\u26FF]|\uD83E[\uDD10-\uDDFF])/gi, ""); // fail safe?
cleanedText = cleanedText.replace(/[\r\n]+/g, "").replace(/\s+/g, " ").trim();
if (!cleanedText) {
isProcessing = false;
return;
}
var score = levenshtein(cleanedText, lastSentMessage);
if (score < 7) { // make sure bot doesn't respond to itself or to the host.
isProcessing = false;
return;
}
try {
let additionalInstructions = "";
if (settings.ollamaprompt){
additionalInstructions = settings.ollamaprompt.textsetting;
}
let botname = "🤖💬";
if (settings.ollamabotname && settings.ollamabotname.textsetting){
botname = settings.ollamabotname.textsetting.trim();
}
const response = await processUserInput(cleanedText, data, additionalInstructions);
log(response);
if (response){
const msg = {
tid: data.tid,
response: botname+": " + response.trim()
};
processResponse(msg);
lastResponseTime[data.tid] = Date.now();
}
} catch (error) {
console.error("Error processing message:", error);
} finally {
isProcessing = false;
}
}
function preprocessMarkdown(content) {
// Remove HTML comments
content = content.replace(/<!--[\s\S]*?-->/g, '');
// Process the content line by line
const lines = content.split('\n').map(line => {
// Trim whitespace
line = line.trim();
// Simplify headers
line = line.replace(/^#+\s*/, '# ');
// Remove emphasis markers
line = line.replace(/(\*\*|__)(.*?)\1/g, '$2').replace(/(\*|_)(.*?)\1/g, '$2');
// Remove inline code backticks
line = line.replace(/`([^`]+)`/g, '$1');
// Simplify links
line = line.replace(/\[([^\]]+)\]\([^\)]+\)/g, '$1');
// Simplify images
line = line.replace(/!\[([^\]]+)\]\([^\)]+\)/g, '$1');
// Remove horizontal rules
if (line.match(/^(-{3,}|_{3,}|\*{3,})$/)) {
return '';
}
return line;
}).filter(line => line.length > 0); // Remove empty lines
// Combine consecutive list items
for (let i = lines.length - 1; i > 0; i--) {
if ((lines[i].startsWith('- ') && lines[i-1].startsWith('- ')) ||
(lines[i].startsWith('* ') && lines[i-1].startsWith('* ')) ||
(lines[i].match(/^\d+\. /) && lines[i-1].match(/^\d+\. /))) {
lines[i-1] += ' ' + lines[i].replace(/^(-|\*|\d+\.) /, '');
lines.splice(i, 1);
}
}
// Remove code blocks or replace with placeholder
content = lines.join('\n');
content = content.replace(/```[\s\S]*?```/g, '[CODE BLOCK]');
// Remove any remaining multiple consecutive spaces
content = content.replace(/ {2,}/g, ' ');
return content;
}
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function preprocessDocument(docContent, docId, preprocess) {
activeProcessing[docId] = { cancel: false };
updateDocumentProgress(docId, 1, 'Preprocessing');
// Split the content into lines
const lines = docContent.split('\n');
// Initialize variables
const chunks = [];
let currentChunk = '';
let currentTitle = 'Document Start';
if (!preprocess){
currentTitle = "";
}
let currentLevel = 0;
function processCurrentChunk_old() {
if (currentChunk.trim()) {
chunks.push({
title: currentTitle,
content: currentChunk.trim(),
level: currentLevel
});
currentChunk = '';
}
}
function processCurrentChunk() {
if (currentChunk.trim()) {
if (chunks.length > 0 && chunks[chunks.length - 1].content.length + currentChunk.length <= maxContextSize) {
// Combine with the previous chunk if it fits
chunks[chunks.length - 1].content += '\n\n' + currentChunk.trim();
chunks[chunks.length - 1].title += ' & ' + currentTitle;
} else {
chunks.push({
title: currentTitle,
content: currentChunk.trim(),
level: currentLevel
});
}
currentChunk = '';
}
}
// Process each line
for (const line of lines) {
if (activeProcessing[docId].cancel) {
log(`Processing cancelled for document ${docId}`);
delete activeProcessing[docId];
return null;
}
// Check if the line is a header
const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
if (headerMatch) {
// If we're about to exceed 8K chars or encounter a new header, process the current chunk
if (currentChunk.length + line.length > maxContextSizeFull || currentChunk.length > 0) {
processCurrentChunk();
}
// Start a new chunk with the header
currentLevel = headerMatch[1].length;
currentTitle = headerMatch[2];
currentChunk = line + '\n';
} else {
// If adding this line would exceed 8K chars, process the current chunk and start a new one
if (currentChunk.length + line.length > maxContextSizeFull) {
processCurrentChunk();
// If the current line itself is very long, split it
if (line.length > maxContextSizeFull) {
for (let i = 0; i < line.length; i += maxContextSizeFull) {
chunks.push({
title: `${currentTitle} (continued)`,
content: line.substr(i, maxContextSizeFull),
level: currentLevel
});
}
} else {
currentChunk = line + '\n';
}
} else {
// Add the line to the current chunk
currentChunk += line + '\n';
}
}
}
// Process the last chunk
processCurrentChunk();
updateDocumentProgress(docId, 5, 'Chunking');
if (!preprocess){
delete activeProcessing[docId];
return {
chunks: chunks,
overallSummary: ""
};
}
// Process each chunk with Ollama
const processedChunks = [];
for (const [index, chunk] of chunks.entries()) {
if (activeProcessing[docId].cancel) {
log(`Processing cancelled for document ${docId}`);
delete activeProcessing[docId];
return null;
}
const prompt = `Analyze the following document chunk (${index + 1}/${chunks.length}) and provide the following information:
1. Summarize the main points in 2-3 sentences.
2. Generate 5-7 relevant tags.
3. Suggest 3-5 synonyms or related terms for the main concepts.
Document chunk title: ${chunk.title}
Document chunk:
${chunk.content}
Please format your response exactly as follows, including the delimiters:
[SUMMARY]
Your summary here.
[/SUMMARY]
[TAGS]
tag1, tag2, tag3, tag4, tag5
[/TAGS]
[SYNONYMS]
synonym1, synonym2, synonym3
[/SYNONYMS]
Do not include any other text or explanations outside these sections.`;
try {
const processedData = await callOllamaAPI(prompt);
let parsedData = parseChunkAnalysis(processedData);
parsedData.content = chunk.content; // Add the original content
parsedData.level = chunk.level;
parsedData.title = chunk.title;
processedChunks.push(parsedData);
const progress = 5 + ((index + 1) / chunks.length * 90);
updateDocumentProgress(docId, Math.round(progress), 'Processing');
// Log the processed chunk for debugging
logProcessedChunk(parsedData, index);
} catch (error) {
console.error(`Error processing chunk ${index + 1}:`, error);
}
// Add a small delay between chunks, to let things breath a bit.
await delay(500);
}
// Generate an overall summary
updateDocumentProgress(docId, 95, 'Summarizing');
const overallSummaryPrompt = `Summarize the main points of the following document in 3-4 sentences:
${processedChunks.map(chunk => chunk.summary).join('\n')}`;
let overallSummary;
try {
overallSummary = await callOllamaAPI(overallSummaryPrompt);
} catch (error) {
console.error("Error generating overall summary:", error);
overallSummary = "Failed to generate overall summary";
}
updateDocumentProgress(docId, 100, 'Processed');
delete activeProcessing[docId];
return {
chunks: processedChunks,
overallSummary: overallSummary.trim()
};
}
function parseChunkAnalysis(analysisText) {
const result = {
summary: '',
tags: [],
synonyms: [],
content: '' // We'll add this later
};
const summaryMatch = analysisText.match(/\[SUMMARY\]([\s\S]*?)\[\/SUMMARY\]/);
if (summaryMatch) {
result.summary = summaryMatch[1].trim();
}
const tagsMatch = analysisText.match(/\[TAGS\]([\s\S]*?)\[\/TAGS\]/);
if (tagsMatch) {
result.tags = tagsMatch[1].split(',').map(tag => tag.trim()).filter(tag => tag);
}
const synonymsMatch = analysisText.match(/\[SYNONYMS\]([\s\S]*?)\[\/SYNONYMS\]/);
if (synonymsMatch) {
result.synonyms = synonymsMatch[1].split(',').map(syn => syn.trim()).filter(syn => syn);
}
return result;
}
function updateDocumentProgress(docId, progress, status) {
const docIndex = documentsRAG.findIndex(doc => doc.id === docId);
if (docIndex !== -1) {
documentsRAG[docIndex].progress = progress;
documentsRAG[docIndex].status = status;
messagePopup({documents: documentsRAG});
}
}
async function isRAGConfigured() {
// Check if there are any documents in the database
const db = await openDatabase();
const transaction = db.transaction(DOCUMENT_STORE_NAME, 'readonly');
const store = transaction.objectStore(DOCUMENT_STORE_NAME);
const count = await new Promise((resolve, reject) => {
const request = store.count();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
return (count > 0) && settings.ollamaRagEnabled;
}
async function processUserInput(userInput, data={}, additionalInstructions) {
try {
if (await isRAGConfigured()) {
const databaseDescriptor = localStorage.getItem('databaseDescriptor') || 'Database description not available.';
const prompt = `You are an AI assistant with access to a database of information. ${additionalInstructions || ''}
Given the following user input, user name, and a description of the database contents, determine if a database search is necessary to respond appropriately. If a search is needed, provide relevant search keywords.
User Name: ${data.chatname || 'user'}
User Input: "${userInput}"
Database Description:
${databaseDescriptor}
For simple greetings, small talk, or queries that don't require specific information from the database, you may respond directly without a search.
If a search is needed, provide 3-5 relevant keywords or short phrases for the search, not a full question or sentence.
Please format your response exactly as follows, including the delimiters:
[NEEDS_SEARCH]
yes or no
[/NEEDS_SEARCH]
[SEARCH_QUERY]
keyword1 keyword2 keyword3
[/SEARCH_QUERY]
[RESPONSE]
Your direct response here if no search is needed, otherwise leave this blank
[/RESPONSE]
Ensure that if [NEEDS_SEARCH] is 'yes', [SEARCH_QUERY] is filled with keywords and [RESPONSE] is empty, and vice versa.
Do not include any other text or explanations outside these sections.`;
const llmOutput = await callOllamaAPI(prompt);
const decision = parseDecision(llmOutput);
if (decision.needsSearch) {
//console.log("Performing search with query:", decision.searchQuery);
const searchResults = await performSearch(decision.searchQuery);
//console.log("Search results:", searchResults);
return await generateResponseWithSearchResults(userInput, searchResults, data.chatname || 'user', additionalInstructions);
} else {
return decision.response;
}
} else {// If RAG is not configured, use the original instructions
const prompt = `${additionalInstructions || 'You are an AI in a family-friendly public chat room. Your responses must follow these rules: If the message warrants a response (e.g., it\'s directed at you or you have a relevant comment), provide ONLY the exact text of your reply. No explanations, context, or meta-commentary. Keep responses brief and engaging, suitable for a fast-paced chat environment. If no response is needed or appropriate, output only "NO_RESPONSE". Never use quotation marks or any formatting around your response. Never indicate that you are an AI or that this is your response.'}
Respond to the following message:
User ${data.chatname || 'user'} says: ${userInput}
Your response:`;
log(userInput);
let response = await callOllamaAPI(prompt);
if (!response || response.includes("NO_RESPONSE") || response.startsWith("No ") || response.startsWith("NO ")){
return false;
}
return response;
}
} catch (error) {
console.error("Error processing user input:", error);
return "I'm sorry, I encountered an error while processing your request.";
}
}
function parseDecision(decisionText) {
const result = {
needsSearch: false,
searchQuery: null,
response: null
};
const needsSearchMatch = decisionText.match(/\[NEEDS_SEARCH\]([\s\S]*?)\[\/NEEDS_SEARCH\]/);
if (needsSearchMatch) {
result.needsSearch = needsSearchMatch[1].trim().toLowerCase() === 'yes';
}
const searchQueryMatch = decisionText.match(/\[SEARCH_QUERY\]([\s\S]*?)\[\/SEARCH_QUERY\]/);
if (searchQueryMatch) {
result.searchQuery = searchQueryMatch[1].trim();
}
const responseMatch = decisionText.match(/\[RESPONSE\]([\s\S]*?)\[\/RESPONSE\]/);
if (responseMatch) {
result.response = responseMatch[1].trim();
}
return result;
}
async function clearDatabase() {
const db = await openDatabase();
const transaction = db.transaction([DOCUMENT_STORE_NAME, 'lunrIndex'], 'readwrite');
const documentStore = transaction.objectStore(DOCUMENT_STORE_NAME);
const indexStore = transaction.objectStore('lunrIndex');
try {
await Promise.all([
new Promise((resolve, reject) => {
const request = documentStore.clear();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
}),
new Promise((resolve, reject) => {
const request = indexStore.clear();
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
})
]);
// Clear the documentsRAG array
documentsRAG = [];
// Reset the Lunr index
resetLunrIndex();
// Update the database descriptor
await updateDatabaseDescriptor();
// Notify the popup about the change
messagePopup({documents: documentsRAG});
log("Database cleared successfully");
} catch (error) {
console.error("Error clearing database:", error);
}
}
async function performSearch(query) {
if (!globalLunrIndex) {
await loadLunrIndex();
}
const keywords = query.split(/\s+/);
const searchQuery = keywords.map(keyword => `+${keyword}`).join(' ');
const results = globalLunrIndex.search(query);
if (results.length === 0) {
//console.log("No results found for query:", query);
// Perform a more lenient search
return globalLunrIndex.search(keywords.map(word => `${word}~1`).join(' ')).map(result => ({
ref: result.ref,
score: result.score
}));
}
return results.map(result => ({
ref: result.ref,
score: result.score
}));
}
async function generateResponseWithSearchResults(userInput, searchResults, chatname, additionalInstructions) {
try {
const relevantDocs = await getDocumentsFromSearchResults(searchResults);
//console.log("Relevant docs:", relevantDocs);
const validDocs = relevantDocs.filter(doc => doc !== null && doc.content);
if (validDocs.length === 0) {
log("No valid documents found");
return `I'm sorry, but I couldn't find any specific information about "${userInput}" in my database.`;
}
// Concatenate chunks until we approach 8K characters
let combinedContent = '';
let usedChunks = 0;
for (const doc of validDocs) {
if (combinedContent.length + doc.content.length > maxContextSize) { // Leave some room for the prompt
break;
}
combinedContent += doc.content + '\n\n';
usedChunks++;
}
console.log("Combined content:", combinedContent);
const prompt = `You are an AI assistant. ${additionalInstructions || ''}
Given the following user input, user name, and relevant information from our database, generate an appropriate response:
User Name: ${chatname}
User Input: "${userInput}"
Relevant Information:
${combinedContent}
Provide a concise and informative response based on the above information. Your response should be suitable for a chat environment, ideally not exceeding 150 characters.`;
return await callOllamaAPI(prompt);
} catch (error) {
console.error("Error in generateResponseWithSearchResults:", error);
return "I'm sorry, I encountered an error while processing your request. Please try again later.";
}
}
async function getDocumentsFromSearchResults(searchResults) {
const db = await openDatabase();
const transaction = db.transaction([DOCUMENT_STORE_NAME], "readonly");
const store = transaction.objectStore(DOCUMENT_STORE_NAME);
return Promise.all(searchResults.map(async result => {
log(result.ref);
const splitIndex = result.ref.split('_');
if (splitIndex.length<=2){
//console.warn(`Invalid document ID: ${result.ref}`);
return null;
}
const chunkIndex = splitIndex[splitIndex.length - 1];
const docId = "doc_"+splitIndex[splitIndex.length - 2];
try {
const request = store.get(docId);
const doc = await new Promise((resolve, reject) => {
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
//console.log(`Retrieved document for id ${docId}:`, doc); // Add this line for debugging
if (!doc) {
//console.warn(`Document not found for id: ${docId}`);
return null;
}
if (doc.chunks && chunkIndex) {
const chunk = doc.chunks[parseInt(chunkIndex)];
//console.log(`Retrieved chunk for index ${chunkIndex}:`, chunk); // Add this line for debugging
return chunk ? {
content: chunk.content,
tags: chunk.tags,
synonyms: chunk.synonyms,
summary: chunk.summary
} : null;
}
return {
content: doc.content,
tags: doc.tags,
synonyms: doc.synonyms,
summary: doc.overallSummary
};
} catch (error) {
console.error(`Error retrieving document ${docId}:`, error);
return null;
}
}));
}
function removeUnnecessaryQuotes(input) {
const keepQuoted = ['needsSearch', 'searchQuery', 'response', 'summary', 'tags', 'synonyms', 'content'];
input = input.replace(/\s+/g, ' ');
return input.replace(/"(\w+)":?(?!,)|"(\w+)"/g, (match, p1, p2, offset, string) => {
const word = p1 || p2;
if (keepQuoted.includes(word)) {
return match;
}
if (match.endsWith('":')) {
return word + ':';
}
// Check if we're inside an array
let isInArray = false;
let openBrackets = 0;
for (let i = 0; i < offset; i++) {
if (string[i] === '[') openBrackets++;
if (string[i] === ']') openBrackets--;
}
isInArray = openBrackets > 0;
if (isInArray) {
return match;
}
if (string[offset + match.length] === ',') {
return match;
}
if (string[offset + match.length] === ' ]' || string[offset + match.length] === ']') {
return match;
}
if (string[offset + match.length] === ' }' || string[offset + match.length] === '}') {
return match;
}
return word;
});
}
function sanitizeAndParseJSON(jsonString) {
jsonString = jsonString.replace(/^```json\n/, '').replace(/\n```$/, '');
jsonString = jsonString.replace(/[\x00-\x1F\x7F-\x9F]/g, '');
jsonString = jsonString.replace(/(\r\n|\n|\r|\\n)/gm, " ");
jsonString = jsonString.replaceAll(`"https"`, 'https');
jsonString = jsonString.replaceAll(`"http":`, 'http');
jsonString = jsonString.replaceAll(`"https:"`, 'https:');
jsonString = jsonString.replaceAll(`"http:"`, 'http:');
jsonString = jsonString.trim();
if (!jsonString.endsWith("}")){
jsonString += "}";
}
let parsedJSON = tryParse(jsonString);
if (parsedJSON) return ensureCorrectStructure(parsedJSON);
jsonString = removeUnnecessaryQuotes(jsonString);
parsedJSON = tryParse(jsonString);
if (parsedJSON) return ensureCorrectStructure(parsedJSON);
// If still failing, try more aggressive fixes
jsonString = jsonString.replaceAll('""','"').replaceAll('""','"');
parsedJSON = tryParse(jsonString);
if (parsedJSON) return ensureCorrectStructure(parsedJSON);
jsonString = jsonString.replace(/(\w+):/g, '"$1":'); // Ensure all keys are quoted
jsonString = jsonString.replaceAll('""','"').replaceAll('""','"');
jsonString = jsonString.replace(/,\s*([\]}])/g, '$1'); // Remove trailing commas
jsonString = jsonString.trim();
if (!jsonString.endsWith("}")){
jsonString += "}";
}
parsedJSON = tryParse(jsonString);
if (parsedJSON) return ensureCorrectStructure(parsedJSON);
//console.warn("Failed to parse JSON even after sanitization");
//console.log("Problematic JSON string:", jsonString);
return false;
}
function tryParse(jsonString) {
try {
return JSON.parse(jsonString);
} catch (e) {
return null;
}
}
function ensureCorrectStructure(json) {
let result = {
summary: typeof json.summary === 'string' ? json.summary : '',
tags: Array.isArray(json.tags) ? json.tags.filter(tag => typeof tag === 'string') : [],
synonyms: Array.isArray(json.synonyms) ? json.synonyms.filter(synonym => typeof synonym === 'string') : [],
content: typeof json.content === 'string' ? json.content : JSON.stringify(json.content)
};
// If content is still not a string, convert it to a string
if (typeof result.content !== 'string') {
result.content = JSON.stringify(result.content);
}
return result;
}
function tryParse(jsonString) {
try {
return JSON.parse(jsonString);
} catch (e) {
return null;
}
}
function ensureCorrectStructure(json) {
let result = {
summary: typeof json.summary === 'string' ? json.summary : '',
tags: Array.isArray(json.tags) ? json.tags.filter(tag => typeof tag === 'string') : [],
synonyms: Array.isArray(json.synonyms) ? json.synonyms.filter(synonym => typeof synonym === 'string') : [],
content: typeof json.content === 'string' ? json.content : JSON.stringify(json.content)
};
// If content is still causing issues, convert all double quotes to single quotes
if (typeof result.content !== 'string') {
result.content = JSON.stringify(json.content).replace(/"/g, "'");