-
Notifications
You must be signed in to change notification settings - Fork 21
/
promise_rag_worker.js
1614 lines (1229 loc) · 49.8 KB
/
promise_rag_worker.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
//import { pipeline } from './tjs/transformers.js';
//import { env, Tensor, AutoTokenizer, SpeechT5ForTextToSpeech, SpeechT5HifiGan } from '@xenova/transformers';
//import { env, Tensor, AutoTokenizer, SpeechT5ForTextToSpeech, SpeechT5HifiGan } from './tjs/transformers.js';
console.log("HELLO FROM RAG WORKER");
//console.log("RAG: ort: ", ort);
import { pipeline, env } from './tjs/transformers.min.js';
//import { registerPromiseWorker } from './js/promise-worker.register.js';
env.allowLocalModels = false;
env.allowRemoteModels = true;
env.useBrowserCache = true;
// Create a feature-extraction pipeline
//const extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
// Compute sentence embeddings
//const sentences = ['This is an example sentence', 'Each sentence is converted'];
//const output = await extractor(sentences, { pooling: 'mean', normalize: true });
//console.log(output);
// Tensor {
// dims: [ 2, 384 ],
// type: 'float32',
// data: Float32Array(768) [ 0.04592696577310562, 0.07328180968761444, ... ],
// size: 768
// }
/*
import './mememo/index.umd.js';
console.log("RAG WORKER: mememo imported?");
console.log("RAG WORKER: mememo: ", mememo);
const index = new mememo.HNSW({ distanceFunction: 'cosine' });
console.log("RAG WORKER: mememo: index: ", index);
*/
import { create, insert, insertMultiple, remove, removeMultiple, search } from './node_modules/@orama/orama/dist/index.js';
//import { persist,restore } from './node_modules/@orama/plugin-data-persistence/dist/index.js';
self.vector_db = null;
let prompt_embeddings = {};
self.extractor = null;
self.embedded_chunks = {};
// INDEXDB
// ldb, a simple indexDB wrapper
!function(){var s,c,e="undefined"!=typeof self?self:{},t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB;"undefined"==typeof self||t?((t=t.open("ldb",1)).onsuccess=function(e){s=this.result},t.onerror=function(e){console.error("indexedDB request error"),console.log(e)},t={get:(c={ready:!(t.onupgradeneeded=function(e){s=null,e.target.result.createObjectStore("s",{keyPath:"k"}).transaction.oncomplete=function(e){s=e.target.db}}),get:function(e,t){s?s.transaction("s").objectStore("s").get(e).onsuccess=function(e){e=e.target.result&&e.target.result.v||null;t(e)}:setTimeout(function(){c.get(e,t)},50)},set:function(t,n,o){if(s){let e=s.transaction("s","readwrite");e.oncomplete=function(e){"Function"==={}.toString.call(o).slice(8,-1)&&o()},e.objectStore("s").put({k:t,v:n}),e.commit()}else setTimeout(function(){c.set(t,n,o)},50)},delete:function(e,t){s?s.transaction("s","readwrite").objectStore("s").delete(e).onsuccess=function(e){t&&t()}:setTimeout(function(){c.delete(e,t)},50)},list:function(t){s?s.transaction("s").objectStore("s").getAllKeys().onsuccess=function(e){e=e.target.result||null;t(e)}:setTimeout(function(){c.list(t)},50)},getAll:function(t){s?s.transaction("s").objectStore("s").getAll().onsuccess=function(e){e=e.target.result||null;t(e)}:setTimeout(function(){c.getAll(t)},50)},clear:function(t){s?s.transaction("s","readwrite").objectStore("s").clear().onsuccess=function(e){t&&t()}:setTimeout(function(){c.clear(t)},50)}}).get,set:c.set,delete:c.delete,list:c.list,getAll:c.getAll,clear:c.clear},e.ldb=t,"undefined"!=typeof module&&(module.exports=t)):console.error("indexDB not supported")}();
console.log("RAG WORKER: ldb: ", ldb);
function savr(key,value){
//console.log("RAG WORKER: in savr. key: ", key, value);
return new Promise(function(resolve, reject) {
ldb.set(key, value, function (value) {
//console.log('savr: promise saved: callback: key,value: ', key, value); // key,value.substr(0,10) + '...'
resolve(value);
});
});
}
function getr(key) {
//console.log("RAG WORKER: in getr. key: ", key);
return new Promise(function(resolve) { // , reject
ldb.get(key, (value) => {
resolve(value);
});
});
}
let extractor = null;
let web_gpu_supported = false;
let web_gpu32_supported = false;
async function check_gpu(){
// CHECK WEB GPU SUPPORT
return
if (!navigator.gpu) {
console.error("RAG WORKER: WebGPU not supported.");
}else{
console.error("RAG WORKER: navigator.gpu exists: ", navigator.gpu);
const adapter = await navigator.gpu.requestAdapter();
if (typeof adapter != 'undefined' && adapter != null && typeof adapter.features != 'undefined') {
if(adapter.features.has("shader-f16")){
web_gpu_supported = true;
if (navigator.gpu.wgslLanguageFeatures && !navigator.gpu.wgslLanguageFeatures.has("packed_4x8_integer_dot_product")) {
//console.log(`RAG WORKER: webgpu DP4a built-in functions are not available`);
}
}
else{
console.warn("RAG WORKER: Web GPU: 16-bit floating-point value support is not available");
web_gpu32_supported = true;
}
}
else{
console.error("RAG WORKER: querying WebGPU was not a success");
}
}
}
check_gpu();
async function create_embedding(texts){
//console.log("in create_embedding. texts: ", texts);
let embeddings = null;
if(web_gpu_supported){
//console.log("create_embedding. calling webgpu16");
embeddings = await run_web_gpu_inference(texts);
}
else if(web_gpu32_supported){
//console.log("create_embedding. calling webgpu32");
embeddings = await run_web_gpu_inference(texts,32);
}
else{
//console.log("create_embedding. calling cpu version");
if(self.extractor == null){
let options = {
quantized: false,
progress_callback: data => {
//console.log("RAG WORKER: embedding progress: ", data);
self.postMessage(data);
/*
self.postMessage({
status: 'progress',
data
});
*/
}
}
if(web_gpu_supported){
options['device'] = 'webgpu';
}
self.extractor = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2', options);
}
//console.log("RAG WORKER: cpu transformers.js extractor: ", extractor);
embeddings = await self.extractor(texts, { pooling: 'mean', normalize: true });
}
//console.log("final embeddings: ", embeddings);
return embeddings;
}
async function run_web_gpu_inference(texts, bits=16) {
//console.log("RAG WORKER: in run_web_gpu_inference");
if(typeof texts == 'undefined' || texts == null){
console.error("run_web_gpu_inference: invalid texts provided");
}
if(typeof bits != 'number'){
console.error("run_web_gpu_inference: invalid bits provided");
return null;
}
let onnx_file_name = 'model_fp16.onnx';
if(bits == 32){
onnx_file_name = 'model.onnx';
}
if(bits == 8){
onnx_file_name = 'model_int8.onnx';
}
const session = await ort.InferenceSession.create('models/Xenova/all-MiniLM-L6-v2/onnx/' + onnx_file_name, { executionProviders: ['webgpu'], log_severity_level: 0 });
const tokenizer = await AutoTokenizer.from_pretrained('Xenova/all-MiniLM-L6-v2');
//const texts = ['This is an example sentence', 'Each sentence is converted']
const { input_ids, token_type_ids, attention_mask } = tokenizer(texts, {
padding: true,
truncation: true,
return_tensors: 'pt'
});
const feeds = {
input_ids: new ort.Tensor('int64', input_ids.data, [1, input_ids.data.length]),
token_type_ids: new ort.Tensor('int64', token_type_ids.data, [1, token_type_ids.data.length]),
attention_mask: new ort.Tensor('int64', attention_mask.data, [1, attention_mask.data.length])
};
const result = await session.run(feeds);
return result;
}
/*
const embeddings = new HuggingFaceTransformersEmbeddings({
modelName: "Xenova/all-MiniLM-L6-v2",
// Can use "nomic-ai/nomic-embed-text-v1" for more powerful but slower embeddings
// modelName: "nomic-ai/nomic-embed-text-v1",
});
*/
function isPromise (obj) {
// via https://unpkg.com/[email protected]/index.js
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
function registerPromiseWorker (callback) {
function postOutgoingMessage (e, messageId, error, result) {
function postMessage (msg) {
if (typeof self.postMessage !== 'function') { // service worker
e.ports[0].postMessage(msg)
} else { // web worker
self.postMessage(msg)
}
}
if (error) {
if (typeof console !== 'undefined' && 'error' in console) {
// This is to make errors easier to debug. I think it's important
// enough to just leave here without giving the user an option
// to silence it.
//console.error('Promise worker caught an error:', error);
}
postMessage([messageId, {
message: error.message
}])
} else {
postMessage([messageId, null, result])
}
}
function tryCatchFunc (callback, message) {
try {
return { res: callback(message) }
} catch (e) {
return { err: e }
}
}
function handleIncomingMessage (e, callback, messageId, message) {
console.log("registerPromiseWorker: in handleIncomingMessage");
var result = tryCatchFunc(callback, message)
if (result.err) {
postOutgoingMessage(e, messageId, result.err)
} else if (!isPromise(result.res)) {
postOutgoingMessage(e, messageId, null, result.res)
} else {
result.res.then(function (finalResult) {
postOutgoingMessage(e, messageId, null, finalResult)
}, function (finalError) {
postOutgoingMessage(e, messageId, finalError)
})
}
}
function onIncomingMessage (e) {
console.log("registerPromiseWorker: onIncomingMessage: e.data: ", e.data);
var payload = e.data
if (!Array.isArray(payload) || payload.length !== 2) {
console.log("onIncomingMessage: ignoring message with wrong format");
// message doens't match communication format; ignore
return
}
var messageId = payload[0]
var message = payload[1]
if (typeof callback !== 'function') {
postOutgoingMessage(e, messageId, new Error(
'Please pass a function into register().'))
} else {
handleIncomingMessage(e, callback, messageId, message)
}
}
self.addEventListener('message', onIncomingMessage)
}
console.log("RAG (PROMISE) WORKER EXISTS");
//console.log("RAG (PROMISE) WORKER: registerPromiseWorker: ", registerPromiseWorker);
// Do local model checks
env.allowLocalModels = true;
//env.allowRemoteModels = false;
let pipelines = {};
function extract_sentences(text){
//console.log("in extract_sentences");
//console.log("in extract_sentences. text: ", text);
if(typeof text != 'string'){
console.error("extract_sentences: returning empty array, as text was not a string: ", text);
return [];
}
function is_number(char) {
return !isNaN(parseInt(char));
}
let sentences = [];
if(text.indexOf('🕰️ ') != -1 && text.indexOf(' ( T+ ') != -1 && text.indexOf(' )') != -1){
//console.log("RAG_selection: it looks like the text contains 🕰️ scribe timestamps");
}
let lines = text.split("\n");
let timestamp_lines_removed = 0;
//console.log("extract_sentences: number of lines to check: ", lines.length);
if(lines.length){
for(let l = lines.length - 1; l >= 0; l--){
//console.log("extract_sentences: l: ", l,lines[l]);
if(typeof lines[l] == 'string'){
if(lines[l].startsWith('🕰️ ') && lines[l].endsWith(' )') && lines[l].indexOf(' ( T+ ') != -1){
//console.log("extract_sentences: removing timestamp line from source_text: ", lines[l]);
lines.splice(l,1);
l--;
timestamp_lines_removed++;
}
else if( (lines[l].trim()).length < 2){
//console.log("extract_sentences: removed empty line from lines: ", lines[l]);
lines.splice(l,1);
l--;
}
}
else{
console.error("extract_sentences: lines[l] was not a string??", l, lines, lines[l]);
}
}
}
//console.log("next: removing empty strings from sentences");
if(lines.length){
for(let l = lines.length - 1; l >= 0; l--){
if(lines[l].trim().length < 2){
//console.log("extract_sentences: removed empty line from lines: ", lines[l]);
lines.splice(l,1);
l--;
}
}
}
/*
//console.log("extract_sentences: number of lines after stripping: ", lines.length);
if(lines.length > 3 && timestamp_lines_removed > 3){
//console.log("RAG_selection: setting lines as prepared_lines: ", lines);
prepared_lines = lines;
}
*/
for(let l = 0; l < lines.length; l++){
const paragraph = lines[l];
let start = 0;
if(paragraph.length < 4 && l < (lines.length - 1) && paragraph.indexOf('.') == -1 && paragraph.indexOf('!') == -1 && paragraph.indexOf('?') == -1){
//console.log("extract_sentences: could scoot this very short paragraph over so it becomes part of the next one: ", lines[l], lines[l+1]);
//lines[l+1] = lines[l] + ' ' + lines[l+1];
}
for (let i = 0; i < paragraph.length; i++) {
if(i == paragraph.length - 5){
//console.log("extract_sentences: almost reached end of a paragraph, jumping to the end");
let sentence = paragraph.substring(start).trim();
if(sentence.length > 1){
sentences.push(sentence);
//break
}
break
}
else if (paragraph[i] === '.' || paragraph[i] === '?' || paragraph[i] === '!') {
let sentence = paragraph.substring(start, i + 1).trim();
if(sentence.length < 3){ // try to continue if the sentence is very short
//console.log("very short sentence, will try to get a longer one")
if( (paragraph.length - i) < 5){ // almost at the end
sentence = paragraph.substring(start).trim(); // grab everything until the end
sentences.push(sentence);
break
}
else{
//console.log("extract_sentences: aiming for a longer sentence");
}
}
else if(paragraph.length - i > 1){ // almost at the end
//if(paragraph[i+1] === ' '){
if(is_number(paragraph[i+1])){
}
else{
sentences.push(sentence);
start = i + 1;
}
}
else{
sentence = paragraph.substring(start).trim(); // grab everything until the end
sentences.push(sentence);
break
}
}
}
}
if(sentences.length){
for(let l = sentences.length - 1; l >= 0; l--){
if((sentences[l].trim()).length < 2){
//console.log("extract_sentences: removed empty line from sentences: ", sentences[l]);
sentences.splice(l,1);
l--;
}
}
}
//console.log("extract_sentences: final sentences: ", JSON.stringify(sentences));
return sentences
}
/*
// Use the Singleton pattern to enable lazy construction of the pipeline.
class PipelineSingleton {
static task = 'text-classification';
static model = 'Xenova/distilbert-base-uncased-finetuned-sst-2-english';
static instance = null;
static async getInstance(progress_callback = null) {
if (this.instance === null) {
this.instance = pipeline(this.task, this.model, { progress_callback });
}
return this.instance;
}
}
*/
/*
// non-promise-wrapped normal worker messages
self.addEventListener('message', async (message) => {
message = message.data;
//console.log("RAG WORKER: RECEIVED MESSAGE: ", message);
if(typeof message.task != 'undefined' && message.task != null){
//console.log("RAG WORKER: received a task: ", message.task);
let source_text = null;
let embedded_property = null;
let embedded_property_index = null;
if(typeof message.task.silent == 'boolean' && message.task.silent == true && typeof message.task.results != 'undefined' && Array.isArray(message.task.results) && message.task.results.length){
source_text = message.task.results[message.task.results.length - 1];
embedded_property = 'result';
embedded_property_index = message.task.results.length - 1;
//console.log("RAG WORKER: embedding result at index: ", embedded_property_index);
}
else if(typeof message.task.text == 'string' && message.task.text.length){
//console.log("RAG_WORKER: task had no source_text, but does have text. Using that as embedding input. ", message.task.text);
source_text = message.task.text;
embedded_property = 'text';
}
else if(typeof message.task.original_prompt == 'undefined' && typeof message.task.prompt == 'string' && message.task.prompt.length){
source_text = message.task.prompt;
embedded_property = 'prompt';
}
else if(typeof message.task.results != 'undefined' && Array.isArray(message.task.results) && message.task.results.length){
source_text = message.task.results[message.task.results.length - 1];
embedded_property = 'result';
embedded_property_index = message.task.results.length - 1;
//console.log("RAG WORKER: embedding result at index: ", embedded_property_index);
}
if(source_text){
function progressCallback(x){
//console.log("RAG embedding worker: progressCallback: ", x);
self.postMessage(x);
}
let previous_doc_cursor = 0;
let done_so_far = '';
let so_far = '';
let work_text = '' + source_text;
let to_go_part = '' + source_text;
let old_text = '' + source_text;
let new_text = '' + source_text;
let sentences = [];
if(typeof message.task.sentences_to_embed != 'undefined' && message.task.sentences_to_embed != null && Array.isArray(message.task.sentences_to_embed)){
//console.log("RAG WORKER: TASK HAS LIST OF PRE-SPLIT sentences_to_embed: ", message.task.sentences_to_embed);
sentences = message.task.sentences_to_embed;
}
else if(typeof extract_sentences != 'undefined'){
//console.log("WAR WORKER: going to send text to extract_sentences, which will split the text into sentences");
sentences = extract_sentences(source_text);
//console.log("RAG WORKER: used extract_sentences. Sentences list is now: ", sentences);
}
else{
sentences = source_text.replace(/([.?!\n])\s*(?=[A-Z])/g, "$1|!|!|").split("|!|!|");
//console.log("RAG WORKER:did split of text into sentences. Sentences list is now: ", sentences);
}
console.warn("RAG WORKER: sentences to embed: ", sentences.length, sentences);
let s = 0;
let chunks = [];
const do_embedding_loop = () => {
console.warn("RAG WORKER: in do_embedding_loop. s: ", s, " of ", sentences.length);
if(s < sentences.length){
let sentence = sentences[s].trim();
if(sentence.length < 250 && s < (sentences.length - 1)){
sentences[s+1] = sentences[s] + sentences[s+1];
console.warn("RAG WORKER: very short sentence, attempting to delay it until the next loop: ", sentences[s], " --> ", sentences[s+1]);
s++;
do_embedding_loop();
return
}
chunks.push(sentence);
s++;
do_embedding_loop();
}
else{
console.warn("RAG WORKER: RAG EMBEDDINGS: ALL CHUNKS CREATED. final chunks: ", chunks);
create_embedding(chunks)
.then((embeddings) => {
//console.log("HURRAY, RAG EMBEDDINGS!: ", embeddings);
//console.log("HURRAY, RAG EMBEDDINGS AS A LIST: ", embeddings.tolist())
if(typeof message.task.rag_full_document == 'boolean' && message.task.rag_full_document == true && typeof message.task.file != 'undefined' && message.task.file != null && typeof message.task.file.folder == 'string' && typeof message.task.file.filename == 'string'){
//console.log("HURRAY, RAG: can save embeddings, as file info is available. message.task.file: ", message.task.file);
}
})
.catch((err) => {
console.error("RAG WORKER: caught error creating embeddings: ", err);
})
}
}
do_embedding_loop();
}
else{
//console.log("RAG WORKER: TEXT/PROMPT TO RAG MISSING, NOT LONG ENOUGH, OR INVALID: ", message.task);
//postMessage({"error":"Invalid source_text provided",'task': message.task});
//reject({"status":"error","error":"Invalid source_text provided","task": message.task})
}
//postMessage({'embedding_data': message});
//postMessage( message);
}
else{
console.error("RAG WORKER: no valid task provided");
//postMessage({"error":"No valid task object provided"});
//reject({"status":"error","error":"No valid task object provided"});
}
});
*/
registerPromiseWorker(function (message) {
//console.log("registerPromiseWorker: got message: ", typeof message, message);
//console.log("PROMISE RAG WORKER: registerPromiseWorker: GOT MESSAGE: ", typeof message, message); // { hello: 'world', answer: 42, 'this is fun': true }
//console.log("PROMISE RAG WORKER RECEIVED MESSAGE");
//console.log("PROMISE RAG message: ", typeof message, message);
if(typeof message.action == 'string' && message.action == 'save_db'){
save_db();
return true;
}
else if(typeof message.action == 'string' && message.action == 'get_database'){
//console.log("PROMISE RAG WORKER: got action request to get_database");
return get_database();
}
/*
if(typeof message.task == 'undefined' && message['1'].task != 'undefined'){
}
*/
else if(typeof message.task == 'undefined'){
console.error("RAG PROMISE WORKER: message.task was undefined");
if(message.length && typeof message[0].task != 'undefined'){
message = message[1];
}
else if(message.length > 1){
if(typeof message[1].task != 'undefined'){
message = message[1];
}
}
}
if(typeof message.task != 'undefined' && message.task != null && typeof message.task.type == 'string'){
//console.log("PROMISE RAG WORKER: received a task: ", message.task.type, message.task);
// EMBEDDING OF DOCUMENTS
if(message.task.type == 'embedding' && typeof message.task.text == 'string'){
return do_embedding(message.task);
}
else if(message.task.type == 'get_database'){
return get_database();
}
// SEARCHING IN DOCUMENTS
else if(message.task.type == 'rag_search' && typeof message.task.prompt == 'string' && typeof message.task.files != 'undefined'){
return new Promise((resolve, reject) => {
let prompt_as_embedding = null;
if(typeof prompt_embeddings[message.task.prompt] != 'undefined'){
//console.log("do_rag: found an embedding for this prompt in window.prompt_embeddings: ", message.task.prompt);
prompt_as_embedding = prompt_embeddings[message.task.prompt];
//return search_in_documents(message.task,prompt_as_embedding);
search_in_documents(message.task, prompt_as_embedding)
.then((search_result) => {
//console.log("RAG WORKER: re-search_in_documents COMPLETE. search_result: ", search_result);
/*
resolve({
'task': task,
'status': 'search_complete',
//'embedded_property': embedded_property,
//'embedded_property_index': embedded_property_index,
'search_results': search_result
});
return {
'task': message.task,
'status': 'search_complete',
//'embedded_property': embedded_property,
//'embedded_property_index': embedded_property_index,
'search_results': search_result
}*/
const search_result_message = {
'task': message.task,
'status': 'search_complete',
//'embedded_property': embedded_property,
//'embedded_property_index': embedded_property_index,
'search_results': search_result
}
//postMessage({"status":"search_complete",'task':message.task,'search_result':search_result});
resolve(search_result_message);
return search_result_message;
})
.catch((err) => {
console.error("PROMISE RAG WORKER: caught error re-searching in documents: ", err);
reject({
'task': message.task,
'status': 'error',
'error':'searching in documents failed'
});
return {
'task': message.task,
'status': 'error',
'error':'searching in documents failed'
}
});
}
else{
create_embedding([message.task.prompt])
.then((embeddings) => {
//console.log("RAG WORKER: SEARCH: EMBEDDINGS: ", typeof embeddings, Array.isArray(embeddings), embeddings);
const embeddings_list = embeddings.tolist();
//console.log("RAG WORKER: SEARCH: embeddings_list: ", embeddings_list);
// Save prompt embedding for future reference
prompt_embeddings[message.task.prompt] = embeddings_list[0];
search_in_documents(message.task, embeddings_list[0])
.then((search_result) => {
//console.log("RAG WORKER: search_in_documents COMPLETE. search_result: ", search_result);
const search_result_message = {
'task': message.task,
'status': 'search_complete',
//'embedded_property': embedded_property,
//'embedded_property_index': embedded_property_index,
'search_results': search_result
}
postMessage({"status":"search_complete",'task':message.task,'search_result':search_result});
resolve(search_result_message);
return search_result_message;
})
.catch((err) => {
console.error("PROMISE RAG WORKER: caught error searching in documents: ", err);
reject({
'task': message.task,
'status': 'error',
'error':'searching in documents failed: ' + err
});
return {
'task': message.task,
'status': 'error',
'error':'searching in documents failed: ' + err
}
});
})
.catch((err) => {
console.error("PROMISE RAG WORKER: caught error searching: ", err);
reject({
'task': message.task,
'status': 'error',
'error':'embedding failed: ' + err
});
return {
'task': message.task,
'status': 'error',
'error':'embedding failed: ' + err
}
})
}
})
}
else{
return {"error":"action/tasks fell through"};
//return false
}
}
else{
console.error("PROMISE RAG WORKER: no valid task provided");
//postMessage({"error":"No valid task object provided"});
return {"error":"No valid task object provided"};
}
});
/*
// Listen for messages from the main thread
self.addEventListener('message', async (event) => {
//console.log("RAG WORKER RECEIVED TASK");
//console.log("RAG event.data: ", event.data);
if(typeof event.data.cache_name == 'string'){
//console.log("embedding_worker: setting cache_name to: ", event.data.cache_name)
cache_name = event.data.cache_name;
}
let source_text = null;
if(typeof event.data.task == 'object'){
//console.log("RAG WORKER: received a task: ", event.data.task);
if(typeof event.data.task.source_text == 'string' && event.data.task.source_text.length){
//console.log("RAG_WORKER: task has simple source_text property, using that as the input source_text: ", event.data.task.source_text);
source_text = event.data.task.source_text; // simpler shortcut option for simple tasks
}
else if(typeof event.data.task.text == 'string' && event.data.task.text.length){
//console.log("RAG_WORKER: task had no source_text, but does have text. Using that as embedding input. ", event.data.task.text);
source_text = event.data.task.text;
}
if(source_text != null){
//console.log("RAG WORKER: OK, source_text was not null: ", source_text);
let input_language = 'nl';
if(typeof event.data.task.input_language == 'string'){
input_language = event.data.task.input_language.toLowerCase();
}
let output_language = 'en';
if(typeof event.data.task.output_language == 'string'){
output_language = event.data.task.output_language.toLowerCase();
}
await caches.open("transformers").then((my_cache) => my_cache.add('./tjs/transformers.js'));
let hf_model_url = 'Xenova/opus-mt-' + input_language + '-' + output_language ;
function progressCallback(x){
//console.log("embedding worker: progressCallback: ", x);
self.postMessage(x);
}
//let pipe = await pipeline('embedding', 'Xenova/opus-mt-nl-en'); // ,{ dtype: 'fp32' }
let pipe = await pipeline('embedding', hf_model_url, {
progress_callback: progressCallback
}); // ,{ dtype: 'fp32' }
let embedding = await pipe("Wat is de hoofdstad van Frankrijk?");
console.log("embedding worker: ", embedding);
self.postMessage({
task: event.data.task,
status: 'complete',
embedding: embedding
});
}
else{
//console.log("RAG WORKER: TEXT TO RAG NOT LONG ENOUGH OR INVALID: ", source_text);
postMessage({"error":"Invalid source_text provided",'task':event.data.task});
return
}
//postMessage({'embedding_data':event.data});
//postMessage(event.data);
}
else{
console.error("RAG WORKER: no valid task provided");
postMessage({"error":"No valid task object provided"});
return
}
});
postMessage({"status":"exists"});
*/
/*
let pre_made_embeddings = await getr('$playground_rag_embeddings' + rag_path, files[current_file_name]);
console.log("start_rag_search: pre_made_embeddings: ", pre_made_embeddings);
if(pre_made_embeddings == null){
}
*/
async function do_embedding(task){
try{
// self.vector_db should have been created when this script was loaded in
if(self.vector_db == null){
console.error("do_embedding: self.vector_db was still null, calling create_db first");
await create_db();
}
if(self.vector_db == null){
console.error("do_embedding: self.vector_db was still null");
return {
'task': task,
'status': 'error',
'error':'vector_db was still null'
};
}
//console.log("self.vector_db: ", self.vector_db);
let search_result = [];
//console.log("do_embedding: task", task);
let quick_file_path = '$totallynonexistantpath$';
if(typeof task.file != 'undefined' && task.file != null && typeof task.file.folder == 'string' && typeof task.file.filename == 'string'){
quick_file_path = task.file.folder + '/' + task.file.filename;
}
//console.log("RAG WORKER: do_embedding: quick_file_path: ", quick_file_path);
// Below is an attempt to avoid re-scanning chunks
let initial_search_result = await search(self.vector_db, {
term: quick_file_path,
properties: ['path'],
exact: true,
})
let source_text = null;
let embedded_property = null;
let embedded_property_index = null;
if(typeof task.silent == 'boolean' && task.silent == true && typeof task.results != 'undefined' && Array.isArray(task.results) && task.results.length){
source_text = task.results[task.results.length - 1];
embedded_property = 'result';
embedded_property_index = task.results.length - 1;
//console.log("PROMISE RAG WORKER: embedding result at index: ", embedded_property_index);
}
else if(typeof task.text == 'string' && task.text.length && !task.text.startsWith('_PLAYGROUND_BINARY_')){
//console.log("PROMISE RAG WORKER: task had no source_text, but does have text. Using that as embedding input. ", task.text);
source_text = task.text;
embedded_property = 'text';
}
else if(typeof task.original_prompt == 'undefined' && typeof task.prompt == 'string' && task.prompt.length){
source_text = task.prompt;
embedded_property = 'prompt';
}
else if(typeof task.results != 'undefined' && Array.isArray(task.results) && task.results.length){
source_text = task.results[task.results.length - 1];
embedded_property = 'result';
embedded_property_index = task.results.length - 1;
//console.log("PROMISE RAG WORKER: embedding result at index: ", embedded_property_index);
}
if(typeof task.type != 'string' || typeof task.origin != 'string'){
return {"status":"error","error":"Task did not have valid type or origin property","task": task};
}
if( (task.origin == 'selection' || task.origin == 'document') && (typeof task.file == 'undefined' || task.file == null || typeof task.file.folder != 'string' || typeof task.file.filename != 'string') ){
return {"status":"error","error":"Task did not have required file info","task": task};
}
if(typeof source_text == 'string' && source_text.startsWith('_PLAYGROUND_BINARY_')){