-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
ai.js
2160 lines (1829 loc) · 87.3 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;
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 getFirstAvailableModel() {
let ollamaendpoint = settings.ollamaendpoint?.textsetting || "http://localhost:11434";
if (typeof ipcRenderer !== 'undefined') {
// Electron environment
return new Promise( async (resolve, reject) => {
let ccc = setTimeout(()=>{
reject(new Error('Request timed out'));
},10000);
let xhr;
try {
xhr = await fetchNode(`${ollamaendpoint}/api/tags`);
} catch(e){
clearTimeout(ccc);
reject(new Error('General fetch error'));
return;
}
const datar = JSON.parse(xhr.data);
if (datar && datar.models && datar.models.length > 0) {
resolve(datar.models[0].name);
return;
} else {
reject(new Error('No models available'));
return;
}
});
} else {
// Web environment
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
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.timeout = 10000; // 10 seconds timeout
xhr.ontimeout = function() {
reject(new Error('Request timed out'));
};
xhr.onerror = function() {
reject(new Error('Network error while fetching models'));
};
xhr.send();
});
}
}
const streamingPostNode = async function (URL, body, headers = {}, onChunk = null, signal = null) {
if (ipcRenderer){
return new Promise((resolve, reject) => {
const channelId = `stream-${Date.now()}-${Math.random()}`;
let fullResponse = '';
const cleanup = () => {
ipcRenderer.removeAllListeners(channelId);
ipcRenderer.send(`${channelId}-close`);
};
ipcRenderer.on(channelId, (event, chunk) => {
if (chunk === null) {
// Stream ended
cleanup();
resolve(fullResponse);
} else {
fullResponse += chunk;
if (onChunk) onChunk(chunk);
}
});
ipcRenderer.send("streaming-nodepost", {
channelId,
url: URL,
body: body,
headers: headers
});
if (signal) {
signal.addEventListener('abort', () => {
cleanup();
ipcRenderer.send(`${channelId}-abort`);
reject(new DOMException('Aborted', 'AbortError'));
});
}
});
}
};
const activeChatBotSessions = {};
let tmpModelFallback = "";
async function callOllamaAPI(prompt, model = null, callback = null, abortController = null, UUID = null, images = null) {
const provider = settings.aiProvider?.optionsetting || "ollama";
const endpoint = provider === "ollama"
? (settings.ollamaendpoint?.textsetting || "http://localhost:11434")
: (provider === "chatgpt" ? "https://api.openai.com/v1/chat/completions" : "https://generativelanguage.googleapis.com/v1beta/chat/completions");
function handleChunk(chunk, callback, appendToFull) {
const lines = chunk.split('\n');
for (const line of lines) {
if (line.trim() === 'data: [DONE]') {
responseComplete = true;
break;
}
if (line.trim() !== '') {
try {
// Remove 'data: ' prefix if it exists
const jsonStr = line.startsWith('data: ') ? line.slice(6) : line;
const data = JSON.parse(jsonStr);
if (data.response) { // Ollama format
appendToFull(data.response);
if (callback) callback(data.response);
} else if (data.choices?.[0]?.delta?.content) { // ChatGPT/Gemini format
const content = data.choices[0].delta.content;
if (content) { // Only append if there's actual content
appendToFull(content);
if (callback) callback(content);
}
} else if (data.candidates?.[0]?.content?.parts?.[0]?.text) { // Legacy Gemini format
appendToFull(data.candidates[0].content.parts[0].text);
if (callback) callback(data.candidates[0].content.parts[0].text);
}
if (data.choices?.[0]?.finish_reason === "stop" || data.done) {
responseComplete = true;
break;
}
} catch (e) {
// console.warn("Parse error:", e, line);
const match = line.match(/"response":"(.*?)"/);
if (match && match[1]) {
const extractedResponse = match[1];
appendToFull(extractedResponse);
if (callback) callback(extractedResponse);
}
}
}
}
}
if (provider === "ollama") {
let ollamamodel = model || settings.ollamamodel?.textsetting || tmpModelFallback || null;
if (!ollamamodel) {
const availableModel0 = await getFirstAvailableModel();
if (availableModel0) {
tmpModelFallback = availableModel0;
} else {
console.error("No Ollama model found");
return;
}
}
const result = await makeRequest(ollamamodel);
if (result.aborted) {
return result.response + "💥";
} else if (result.error && result.error === 404) {
try {
const availableModel = await getFirstAvailableModel();
if (availableModel) {
tmpModelFallback = availableModel;
setTimeout(() => {
tmpModelFallback = "";
}, 60000);
const fallbackResult = await makeRequest(availableModel);
if (fallbackResult.aborted) {
return fallbackResult.response + "💥";
} else if (fallbackResult.error) {
throw new Error(fallbackResult.message);
}
return fallbackResult.complete ? fallbackResult.response : fallbackResult.response + "💥";
}
} catch (fallbackError) {
console.warn("Error in callOllamaAPI even with fallback:", fallbackError);
throw fallbackError;
}
} else if (result.error) {
return;
}
return result.complete ? result.response : result.response + "💥";
} else {
const apiKey = provider === "chatgpt" ? settings.chatgptApiKey?.textsetting : settings.geminiApiKey?.textsetting;
if (!apiKey) return;
// Now both ChatGPT and Gemini use the same message format
// let ollamamodel = model || settings.ollamamodel?.textsetting || tmpModelFallback || null;
const message = {
model: provider === "chatgpt" ? (settings.chatgptmodel?.textsetting || "gpt-4o-mini") : (settings.geminimodel?.textsetting || "gemini-1.5-flash"),
messages: [{
role: "user",
content: prompt
}],
stream: callback !== null
};
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
};
try {
if (callback) {
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(message),
signal: abortController?.signal
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
let responseComplete = false;
while (true) {
const { done, value } = await reader.read();
if (done) {
responseComplete = true;
break;
}
const chunk = decoder.decode(value);
handleChunk(chunk, callback, (resp) => { fullResponse += resp; });
}
//console.log(fullResponse);
return fullResponse;
} else {
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(message),
signal: abortController?.signal
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Both APIs now return the same format
//console.log(data);
return data.choices[0].message.content;
}
} catch (error) {
if (error.name === 'AbortError') {
return { aborted: true };
}
throw error;
}
}
async function makeRequest(currentModel) {
const isStreaming = callback !== null;
let fullResponse = '';
let responseComplete = false;
try {
if (UUID) {
if (activeChatBotSessions[UUID]) {
activeChatBotSessions[UUID].abort();
}
if (!abortController) {
abortController = new AbortController();
}
activeChatBotSessions[UUID] = abortController;
}
let response;
if (typeof ipcRenderer !== 'undefined') {
// Your existing Electron implementation
if (isStreaming) {
response = await new Promise((resolve, reject) => {
const channelId = `streaming-nodepost-${Date.now()}`;
ipcRenderer.on(channelId, (event, chunk) => {
if (chunk === null) {
responseComplete = true;
resolve({ ok: true });
} else if (typeof chunk === 'object' && chunk.error) {
resolve(chunk);
} else {
handleChunk(chunk, callback, (resp) => { fullResponse += resp; });
}
});
const message = {
model: currentModel,
prompt: prompt,
stream: true
};
if (images){
message.images = images;
}
ipcRenderer.send('streaming-nodepost', {
channelId,
url: `${endpoint}/api/generate`,
body: message,
headers: { 'Content-Type': 'application/json' }
});
abortController.signal.addEventListener('abort', () => {
ipcRenderer.send(`${channelId}-abort`);
});
});
if (response.error) {
return response;
}
} else {
// Your existing non-streaming Electron implementation
const message = {
model: currentModel,
prompt: prompt,
stream: false
};
if (images){
message.images = images;
}
response = fetchNode(`${endpoint}/api/generate`, {
'Content-Type': 'application/json',
}, 'POST', message);
if (response.status === 404) {
return { error: 404, message: `Model ${currentModel} not found` };
} else if (response.status !== 200) {
return { error: response.status, message: `HTTP error! status: ${response.status}` };
}
try {
const data = JSON.parse(response.data);
fullResponse = data.response;
responseComplete = true;
} catch (e) {
console.error("Error parsing JSON:", e);
return { error: true, message: "Error parsing response" };
}
}
} else {
// Your existing Web implementation
const message = {
model: currentModel,
prompt: prompt,
stream: isStreaming
};
if (images){
message.images = images;
}
response = await fetch(`${endpoint}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
signal: abortController ? abortController.signal : undefined,
});
if (!response.ok) {
if (response.status === 404) {
return { error: 404, message: `Model ${currentModel} not found` };
} else if (response.status) {
return { error: response.status, message: `HTTP error! status: ${response.status}` };
}
throw new Error(`HTTP error! status: ${response.status}`);
}
if (isStreaming) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) {
responseComplete = true;
break;
}
const chunk = decoder.decode(value);
handleChunk(chunk, callback, (resp) => { fullResponse += resp; });
}
} else {
const data = await response.json();
fullResponse = data.response;
responseComplete = true;
}
}
return { success: true, response: fullResponse, complete: responseComplete };
} catch (error) {
if (error.name === 'AbortError') {
return { aborted: true, response: fullResponse };
} else {
console.warn(`Error in callOllamaAPI with model ${currentModel}:`, error);
return { error: true, message: error.message };
}
} finally {
if (UUID && activeChatBotSessions[UUID] === abortController) {
delete activeChatBotSessions[UUID];
}
}
}
}
// strip emotes
// if longer than 32-character, check it with AI
/* let badList = new Set(['🍆', '💩', '🖕', '👉👌', '🍑', '🤬', '🔞', 'fuck', 'sexy']);
function containsBadContent(message) {
const words = message.toLowerCase().split(/\s+/);
return words.some(word => badList.has(word)) ||
Array.from(message).some(char => badList.has(char));
} */
let safePhrasesSet = new Set(["lmfao","uuh","lmao","lol","gg","ww","wow","caught","huh","ben","cap","ta","hi","oooo","rt","no","damn","lmaooo","lmfao ","what","ez","hah","yes","???","pffttt","omg","noway","lmaoooo","ewww","o7","saj","hiii","omegalul","ofc","..","lmfaooo","????","ew","ggs","herehego","ome44","xdd","??","lmfaoooo","lmaoo","capping","lmaoooooooooo","www","hello","gay","10","wwww","hii","lmaooooo","mhm","?????","wwwww","ok","kekw","lmfaooooo","lmfaoo","yo","ayy","pog","...","hahaha","bro","gigachad","cmb","nice","icant","do it","arky","oh","banger","hey","clap","??????","ww arky","dorkin","ja","holy","lmfaoooooo","???????","bye","klat","oh nah","1 of 1","zyzzbass","wwwwww","no way","ww 5","monka","lmaoooooo","aura","-10k","true","uuh ","hahahaha","o wow","bruh","mmmmm","nah","me","hmm","rip","mmmmmm","haha","nooo","life","lmfaooooooo","xd","piece","buh","5.5","classic","real voice","frenn","noooo","????????","ayo","same","","ra","guuh","ono","man of meat","aaaa","ewwww","yamfam","letsgo","derp","yeah","ego","eww","yep","wwwwwww","mmmmmmm","mmmm","cinema","yooo","gayge","uhh","cungus","piece blash","?????????","stfu","pa","ww method","piece lotus","oh no","wicked","exit","ginji","dtm","lmaooooooo","nt","meat7","ayaya","widespeedlaugh","uuh uuh","chip","cringe","hahahahaha",":)","back","mmmmmmmm","danse","ogre","hesright","w arky","fax","what a save","its real","necco","ff","here we go","poll is uppppp","a u r a","d:","yoooo","men","mmmmmmmmm","gachademon","mmmmmmmmmm","oof","wwwwwwww","wwwwwwwww","catjam","o nah","okay","fr","??????????","idiot","ww emp","hahahah","ome5","mogged","lets goooo","yesss","ewwwww","nooooo","om","mmmmmmmmmmm","looking","real","hiiii","go","brb","yoo","hesgay","lmfao lmfao","lmfaoooooooo","lets go","....","sign bob","stop","acha","ll","lmao ","man of crabs","lmaoooooooo","ome","cucked","lmfaooooooooo","lets gooo","crazy","kek","ww ","ddl","meow","orange","وعليكم السلام","dicktone","oooo ","lmfaoooooooooo","rockn","20","yea","good","tarky","tuuh","memegym","sus","woah","we good","hello everyone","tf","ww deshae","ww segment","11","hmmm","loool","whattt","hola","sold","ww ww","lmfaooooooooooo","w method","yup","hit","السلام عليكم","uhhh","wwwwwwwwwww","nahhh","ta ta","ww unc","lacy","ot","lmaooooooooo","herehego ","predify","ww max","100","nope","based","goat","noooooo","press 1","stand","ww cap","dam","shiza","glaze","idk","???????????","smh","sakina","hiiiii","yay","سلام","na","xa","f a t","w 5","oh wow","bds","thanks","facts","uhoh","how","finally","byee","refresh","????????????","sped","sheesh","stare","exactly","damnnn","nahhhh","yess","wwwwwwwwww","ww 50","hah hah","sweater","why","who","thats crazy","hahah","lelw","oh shit","w raid","listening","team","caught ","cool","uh oh","ooo","w tim","whattttt","oh my","kishan","ww red","ayoo","mmm","no one said that","deji","400k","thank you","insane","bro what","what?","nahh","omggg","و عليكم السلام","vamos","f5","sniffa","leaked","rime","ayy ","unlucky","hahahahah","loll","lolol","looooool","lfg","hi guys","hacked","ye","awww","bra","ww beavo","taway","wedidit","lazer woo","assept","let it go","ww siggy","12","oop","whatttt","oh my god","never","ha","focus","looool","wwwwwwwwwwwww","this guy","wth","wwwwwwwwwwww","pwr","yooooo","jorkin","lmaaooo","ez points","?????????????","hell nah","mmmmmmmmmmmmmm","here he go","pffttt ","ewwwwww","clix","cap of doom","darla","damn lacy","sup","thx","i was here","nvm","well well well","huh?","brother","pause","clueless","hlo","ahahahaha","lies","ta ","ome44 ","jira","noticinggg","call clix","pffttt pffttt","lmfaooooooooooooo","max coming","ww elizabeth","gerd","ez clap","bwajaja","lock in","dang","noo","close","aint no way","red","eu","nahhhhh","peepodj","ewwwwwww","ayooo","gachibass","jungcooked","alien3","hinge","herewego","hollon","big oz","gl","uwu","lollll","ayoooo","uh","oi","lmaooooooooooo","black","ohhh","hi everyone","tc","السماء الزرقاء","we back","lets gooooo","wwwwwwwwwwwwww","offline","huh ","catpls","cappp","asked and answered","ww 10","ll ego","lmfao lmfao lmfao","ww press","gg lacy","lmfaoooooooooooo","xqc","ick monster","bob","huhh","cooked","chill","yessss","lololol","let's go","pari g sis","hehe","nhi","привет","woooo","ai","lets goo","tuff","w torsos","feed bepsy","ewww ","steph curry","ironic","ta attack","ll jason","mmmmmmmmmmmmm","mmmmmmmmmmmm","blm","ww jax","l print","nice shot","lool","football","clean","aww","sorry","yesssss","hello guys","max","ruined","sakina are","hahahahahaha","nothing","lady","bholenath","boom","o na","widespeedlaugh2","knutwalk","hah ","juuh","relevance","marie","pre 3","pre 10","ww mans","pity 8","show the edit","cap cap","dude","ty","wrong","sadge","copium","flirt","normal","hasan","nooooooo","timing","who is this","hey everyone","guys","you","hm","well","pred","interesting","loooool","yoooooo","what happened","hallowfall","gg ","aliendance","? ","waste of time","wow ","ll host","yap","oh hell nah","check","oz","jax","capp","solos","man of bumps","19","403","lucky","good morning","washed","brooo","ahahaha","wrong boots","??????????????","run","heyy","omggggg","hi all","المحققة ؟","forsen","ohh",".....","omgggg","l ads","what is this","mrsavaben","gg's","nahhhhhh","call him","aware","bang","cs","khanada","santi","pfffttt","night trap","raid","ww jason","omefaded","ll print","hiii colleen","duos","play cmb","arky lying","rofl","yikes","good one","lolll","noooooooo",".......","uhm","omgg","amen","ouch","sigma","usa","boring","gym","pls","mods","bathroom entrance","xit","ewwwwwwww","alizee","wolfie","me too","emp","......","good boy","oj","last","عليكم السلام","ggm1","ta ta ta","uhhhhh","firstgarf","ez 4 m80","ooooo","noway ","na defense","objection","casa","hell no","widereacting","ww instigator","lfmao","jasssssssson","lmaaaoooo","bring us with you","10/10","ftc","mr 5.5","arky45","lmfao arky","maybe","wut","gg ez","almost","zzz","good night","weird","sure","widevibe","no shot","click","jk","gggg","woo","ads","qual","moi 7e luokka","um","who?","oops","man","wait","ugh","eh","he is","mit wem spielt er","muted","benn","feelsstrongman","hell yeah","derp2","cuuh","rizz","camariah","deadge","???????????????","booba","ll poll","miz","ick","raid veno","hiii ","abb demon","0/3","oh nahhh","w elizabeth","show edit","arkyyy","check earnings","400k a month","squads","kc","letttss gooooo maxx","14","1000","amazing","lul","wat","i do",":(","broo","who cares","gooo","it is","erm","oh brother","okk","peace","goodnight","chat","woww","bye bye","morning","elsa","tsunami","hn","ok bye","gogeta","really","priya","sa","ciao","huhhhh","lotus","blue sky","ong","lets goooooooo","pfffft","e z","moin","whatt","wwwwwwwwwwwwwww","yessir","kekl","dance","just go","w red","oooooo","niceee","w deshae","call deshae","vip","veno","分かった","weirdo","lmfoa","behind you","ayy ayy","w cap","noticing","o z","what?????","what is happening","lmaoooooooooooooo","ww yay","ar","jassssssssson","rime mommy","ww t1","devry","4love lac","oh hell no","oooo 50","jumpscare","mmmmmmmmmmmmmmm","ww john","w lacy","lmaoooooooooooo","w jax","play max song","buh buh","man of steel","buh buh buh","cmon kc","13","50","150","good luck","np","right","so close","congratulations","joever","lolololol","please","welp","fair","my goat","wowwww","womp womp","not bad","whatttttt","again","lets goooooo","next week","there is","perfect","ooof","oh boy","alisha","sumedh","si","walaikum assalam","card","hahahahahahaha","wha","blackjack","i love it","xddd","heyyyy","hlw","hmmmmm","yooooooooo","kyu","scatter","うん","hallo","*sips horchata*","oo","hi chat","ozempic","rezon","ne","w graal","foul ball","meatloaf","mm","come on","lmaooooooooooooo","lmaaaooo","oh god","oh nahh","nessie","ome3","schizo","what a pass","gooner","ottt","bye az","ww pr","l ego","geng washed","piece red","reallymad","oce > na","mizunprepared","uuhh","dead","can i play","furia","full motion video","ron dtm","chip ","lmfaoooooooooooooo","????????????????","ww predify","hiii hiii","commmmmmmmmmm","nobody said that","honey pack","edit","capppp","pre 4","frank ocean","ww deji","short","hot to go","ssg","16","awesome","hype","kk","nice one","sheeeesh","wait what","crashout","the goat","bro...","noice","both","here we go again","yapping","we?","w stream","omggggggg","why not","cute","cheers","none","niceeee","اي","not really","help","hii guys","fadak","да","boy","hiiiiii","anyways","jay one","yoooooooo","hell","sakin","ahhhh","hail","ron","get it","sell","ope","w song","complent","bye guys","ggg","richa","dont","its over","nooooooooo","fff","glazing","gg gg","yo bro","twink","awwww","hack","ww ww ww","ww adapt","col is finished","kirbycoom","vip deshae","lmfao what","rizz dot","no ot","l host","free palestine","i am","activationfingers","lets go pwr","gggggg","ayy2","cs2","ww timing","loooooooooool","delete capcut","uuh uuh uuh","???????????????????","ugly emp","ta lk","jason?","jason","bedge","this guy hah","hdmi","ww gooner","both?","caught caught","helloimmaxwell","what???","huh huh","0/4","cap of hell","w h a t","mmmmmmmmmmmmmmmm","owow","vinnie","ww 45","piece arky","srry","lacy cap","arky capping","ww bepsy","22","26","kappa","lulw","calculated","amogus","nice try","noted","waiting","nooooooooooo","cope","hahahhaha","easy","awkward","what is going on","whoa","ummm","ok ok",":3","nodders","q first","so","hahahahha","ban","byeee","ya","rose","görüşürüzz","skibidi sigma","aw","اوك","مرحبا","yeahh","left","niharika","gtk","لا","omg lol","hello all","umm","hello?","hi faith","good morning faith","hi.","gulp","cherry","kevin","how are you","*chuckles*","ohhhh","oxygen","سلام عليكم","og","alr","free","hi happy","l beard","-_-","goty","tata","no lol","comm","maram","savage","hahahahahah","ayo?","thank god","sick","looooooooool","holy crap","sez u","wowww","bepsy aura","lift0","alien44","ome20","lazy","w gifted","ayoooooo","yessssss","vip him","xdd ","jeez","qual?","ww hasan","yam","monkers","w pwr","luck","letsgooo","na washed","real voice lmfao","ww 808","o7 ","firstdork","dumbass","hard watch","goon","dragging it","ww lag","ww f","sheeesh","hah mods","drops","u did this","o ma","o ","ravetime","lll","bs","commm","ron stfu","w hasan","yooooooo","ome44 ome44","jassssssson","jasssssssssssson","jasssssson","sonii","will","he coming","elizabeth","hah hah hah","fake chat","nahhhhhhh","w honesty","chopped","tacaught","lunch","w max","lmfaooooooooooooooo","uhhhh","ewwwwwwwwww","rockin","5k","check his earnings","trios","freak","lmfao max","arky lmao","what ","poor dude","8.3","15","peepoclap","ayyy","clutch","gn","happy birthday","congrats","blabbering","off","this is crazy","sad","so true","val","game","saved","noooooooooooooo","noooooooooo","bro?","lets gooooooooo","big w","ah","hahahahhahaha","miami","japan","valorant","good flash","hahahahahahahaha","assalamualaikum","good job","its ok","oh yeah","hold","i agree","bruhhh","liar","w gooner","tupang","word","cmon","green","00","love","win","wsg","احبك","=)","helloo","i knew it","accha","null","lupz","hy","me?","yeahhh","adios","privet","selam","kartal","holy moly","helloooo","ahh","dang it","absolute cinema","kicks","im back","nhii","may","ha?","hahhaha","hnnn","beard","janvi","lol.","what a shot","ns","rip az","yassss","respect","yash bro","whoops","aliyeva","اتقوا الله","***","ne(yankili)","jt","hnn","homie","im dying","qualed ?","ggez","grim.","nein","كيفن","kick jt","usa usa usa","هههههههه","madge","why skip","na production","ez ","ww ad","ta ta ta ta","knutready","rug juice","relax","yes ","gg\\","ll friend","pffttt2","gay af","coming","ww asian brother","regret","w save","daddy","call","was","no no no","ww santi","disgusting","lmaoaoa","weebsdetected","colleen","my oil","brooooo","what the","ego ","awwe","weak","wuh","ew ","w press","oooo oooo","speak up","nepo","ليلي","ooooooo","lmaaoo","whats going on","you got this","my points","omescrajj","gigachad sonii","send it to cinna","jorkers","ooh","nowaying","lacy comment","bricked","lets go furia","lmaoooooooooo ","l ad","w ad","reacting","solo cc","what????","poor guy","jassssssssssson","taj","taassemble","0-3 esports","commmmmmmmmmmm","commmmmmmmmm","lock the door","hes coming","play it","damm","bad pics","pre 5","ofcccc","jerry woo","omestare","pre 1","oh nahhhh","lmao lmao","wow wow","silky","jerkify","kiss","6????","do xqc","arkyyyy","امين","w h a tt","check it","lmfaoaooo","saj ","emilio","so jason","well stream","arky lmfao","capping ","tya","piece vinnie","om ","5.3","the man of meat","man of shmeat","duke","no f","17","21","23","greetings","well played","absolutely","correct"])
let longestLength = 19; // safePhrases.reduce((maxLength, str) => Math.max(maxLength, str.length), 0);
var quickPass = 0;
var newlyAdded = 0;
function isSafePhrase(data) {
let 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();
cleanedText = cleanedText.toLowerCase();
if (!cleanedText) { // nothing, so it's safe.
return { isSafe: true, cleanedText: "" };
}
if (cleanedText.length > longestLength) {
return { isSafe: false, cleanedText };
}
if (!cleanedText) {
return { isSafe: true, cleanedText };
}
if (cleanedText.length == 1) {
return { isSafe: true, cleanedText };
}
return { isSafe: safePhrasesSet.has(cleanedText), cleanedText };
}
function setToObject(set) {
return Object.fromEntries(
Array.from(set).map(value => [value, 1])
);
}
function getTop100(obj, total=100) {
const entries = Object.entries(obj);
entries.sort((a, b) => b[1] - a[1]);
const top100 = entries.slice(0, total);
return top100.map(entry => entry[0]);
}
//let safePhrasesObject = setToObject(safePhrasesSet)
function addSafePhrase(cleanedText, score=-1) {
//if (score>1){return;}
if (cleanedText.length>longestLength){return}; // too long to validate
if (!cleanedText){return};
if (cleanedText.length==1){return}; // single characeter; must be safe
safePhrasesSet.add(cleanedText);
newlyAdded+=1;
//if (safePhrasesObject[cleanedText]){ // remoev this object part, as I dont need it in productino.
// safePhrasesObject[cleanedText] +=1;
//} else {
// safePhrasesObject[cleanedText] = 1;
//}
//log("Added ("+score+"): "+cleanedText);
}
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 { isSafe, cleanedText } = isSafePhrase(data);
if (isSafe){
addRecentMessage(cleanedText);
quickPass+=1;
return true;
} // it's safe
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 (cleanedText) {
censorInstructions += cleanedText;
}
let llmOutput = await callOllamaAPI(censorInstructions);
censorProcessingSlots[availableSlot] = false;
//log(llmOutput);
let match = llmOutput.match(/\d+/);
let score = match ? parseInt(match[0]) : 0;
//log(score);
if (score > 3 || llmOutput.length > 1) {
//log("Bad phrase: "+data.chatname +" said " +cleanedText);
if (settings.ollamaCensorBotBlockMode) {
return false;
} else if (isExtensionOn) {
//log("sending a delete out");
sendToDestinations({ delete: data });
}
return false;
} else {
addSafePhrase(cleanedText, score);
addRecentMessage(cleanedText);
return true;
}
} catch (error) {
console.warn("Error processing message:", error);
} finally {
censorProcessingSlots[availableSlot] = false;
}
return false;
}
//
const recentMessages = [];
const MAX_RECENT_MESSAGES = 10;
function addRecentMessage(message) {
recentMessages.push(message);
if (recentMessages.length > MAX_RECENT_MESSAGES) {
recentMessages.shift(); // Remove the oldest message if we exceed the limit
}
}
async function censorMessageWithHistory(data) {
if (!data.chatmessage) {
return true;
}
let cleanedText = data.chatmessage;
if (!data.textonly) {
cleanedText = decodeAndCleanHtml(cleanedText);
}
const availableSlot = censorProcessingSlots.findIndex(slot => !slot);
if (availableSlot === -1) {
return false; // All slots are occupied
}
censorProcessingSlots[availableSlot] = true;
try {
let censorInstructions = `Analyze the following live text chat history and the latest 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 content that may be offensive to a general public audience. Messages may be long or very short, such as a single letter or a collection of emoji-based characters. Pay special attention to words that might be spelled out across multiple messages. Respond ONLY with a number rating out of 5, where 0 implies no offensive content and 5 implies clearly offensive content. Any message containing profanity or curse words automatically qualifies as a 5. ONLY respond with a number between 0 and 5 and nothing else.
Recent chat history:
${recentMessages.join('\n')}
Latest message:
${data.chatname} says: ${cleanedText}`;
let llmOutput = await callOllamaAPI(censorInstructions);
censorProcessingSlots[availableSlot] = false;
let match = llmOutput.match(/\d+/);
let score = match ? parseInt(match[0]) : 0;
if (score > 3 || llmOutput.length > 1) {
if (settings.ollamaCensorBotBlockMode) {
return false;
} else if (isExtensionOn) {
sendToDestinations({ delete: data });
}
return false;
} else {
addSafePhrase(cleanedText, score);
addRecentMessage(cleanedText);
return true;
}
} catch (error) {
console.warn("Error processing message history:", error);
} finally {
censorProcessingSlots[availableSlot] = false;
}
return false;
}
// Function to get recent messages from IndexedDB
function getRecentMessages(chatname, limit, timeWindow) {
return new Promise((resolve, reject) => {
const endTime = new Date();
const startTime = new Date(endTime.getTime() - timeWindow);
const transaction = db.transaction([storeName], "readonly");
const store = transaction.objectStore(storeName);
const index = store.index("unique_user");
const range = IDBKeyRange.bound([chatname, "user"], [chatname, "user"]);
const request = index.openCursor(range, "prev");
const results = [];
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor && results.length < limit && cursor.value.timestamp >= startTime) {
results.push(cursor.value);
cursor.continue();
} else {
resolve(results);
}
};
request.onerror = (event) => {
reject(new Error("Error fetching recent messages: " + event.target.error));
};
});
}
function checkTriggerWords(triggerString, sentence) {
// For phrase matching, first check if it's a simple space-separated phrase (no commas or modifiers)
if (!triggerString.includes(',') && !triggerString.includes('+') && !triggerString.includes('-') && !triggerString.includes('"')) {
const phrase = triggerString.toLowerCase().trim();
return sentence.toLowerCase().includes(phrase);
}
// Rest of the function for comma-separated and modified triggers
const triggers = triggerString.match(/(?:[^,\s"]+|"[^"]*")+/g)
.map(t => t.trim())
.filter(t => t);
const required = [];
const excluded = [];
const normal = [];
triggers.forEach(trigger => {
if (trigger.startsWith('+')) {
required.push(processTrigger(trigger.slice(1)));
} else if (trigger.startsWith('-')) {
excluded.push(processTrigger(trigger.slice(1)));
} else {
normal.push(processTrigger(trigger));
}
});
function processTrigger(trigger) {
const isQuoted = trigger.startsWith('"') && trigger.endsWith('"');
let word = trigger;
let startBoundary = false;
let endBoundary = false;
if (isQuoted) {
word = trigger.slice(1, -1);
}
if (word.startsWith(' ')) {
startBoundary = true;
word = word.trimStart();
}
if (word.endsWith(' ')) {
endBoundary = true;
word = word.trimEnd();
}
return {
word,
isQuoted,
startBoundary,
endBoundary
};
}
function checkWord(triggerObj, sentence) {
const { word, isQuoted, startBoundary, endBoundary } = triggerObj;
if (isQuoted) {
return sentence.includes(word);
}
const lcWord = word.toLowerCase();
const lcSentence = sentence.toLowerCase();
const matches = lcSentence.match(/[!/@#$%^&*]?\w+(?:'\w+)*|[.,;]|\s+/g) || [];
for (let i = 0; i < matches.length; i++) {
const current = matches[i];
if (!/\w/.test(current)) continue;
if (current === lcWord) {
if (startBoundary && i > 0 && /\w/.test(matches[i - 1])) continue;
if (endBoundary && i < matches.length - 1 && /\w/.test(matches[i + 1])) continue;
return true;
}
}
return false;
}
for (const trigger of excluded) {
if (checkWord(trigger, sentence)) {
return false;
}
}
for (const trigger of required) {
if (!checkWord(trigger, sentence)) {
return false;
}
}
if (normal.length > 0) {
return normal.some(trigger => checkWord(trigger, sentence));
}
return true;
}
let isProcessing = false;
const lastResponseTime = {};
async function processMessageWithOllama(data) {
if (!data.tid){
return;
}
const currentTime = Date.now();
if (isProcessing) { // nice.
return;
}
isProcessing = true;
try {
let ollamaRateLimitPerTab = 5000;
if (settings.ollamaRateLimitPerTab){
ollamaRateLimitPerTab = Math.max(0, parseInt(settings.ollamaRateLimitPerTab.numbersetting)||0);
}
if (data.type == "stageten"){
// bypass throttling limit
} else if (!settings.ollamaoverlayonly && data.tid && lastResponseTime[data.tid]){
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.type == "stageten" && (botname == data.chatname)){ // stageten (via api) uses the bot's name
isProcessing = false;
return;
} else if (!data.chatmessage || data.chatmessage.startsWith(botname+":")) { // other sites don't use the bots name, but prefaces with it instead
isProcessing = false;
return;
}
if (settings.bottriggerwords && settings.bottriggerwords.textsetting.trim()){
if (!checkTriggerWords(settings.bottriggerwords.textsetting, data.chatmessage)){
isProcessing = false;
return;
}
}
//console.log(data);
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;
}
let additionalInstructions = "";
if (settings.ollamaprompt){
additionalInstructions = settings.ollamaprompt.textsetting;
}
const response = await processUserInput(cleanedText, data, additionalInstructions);
if (response && !(response.toLowerCase().startsWith("not available"))){
sendTargetP2P(
{"chatmessage":response,
"chatname":botname, "chatimg":"./icons/bot.png",
"type":"socialstream",
"request": data,
"tts": (settings.ollamatts ? true : false)
},
"bot");
if (!settings.ollamaoverlayonly){
const msg = {
tid: data.tid,
response: botname+": " + response.trim(),
bot: true
};
sendMessageToTabs(msg);
lastResponseTime[data.tid] = Date.now();
}
}
} catch (error) {
console.warn("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 = '';