-
Notifications
You must be signed in to change notification settings - Fork 21
/
llama_cpp.js
1727 lines (1354 loc) · 59.9 KB
/
llama_cpp.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 { Wllama } from './wllama/index.js';
window.llama_cpp_app = null;
// Wllama caches files in: wllama_cache
const CONFIG_PATHS = {
'single-thread/wllama.js' : './wllama/single-thread/wllama.js',
'single-thread/wllama.wasm' : './wllama/single-thread/wllama.wasm',
'multi-thread/wllama.js' : './wllama/multi-thread/wllama.js',
'multi-thread/wllama.wasm' : './wllama/multi-thread/wllama.wasm',
'multi-thread/wllama.worker.mjs': './wllama/multi-thread/wllama.worker.mjs',
};
// If you want to enforce single-thread, add { "n_threads": 1 } to LoadModelConfig
window.last_llama_cpp_crash_time = 0;
let called_on_model_loaded = false;
const UNLOADED = 'unloaded' // whisper not loaded
const LISTENING = 'listening'
const RECORDING = 'recording'
const DOING_STT = 'stt'
const DOING_ASSISTANT = 'assistant'
const DOING_TTS = 'tts'
const prompt_el = document.getElementById('prompt');
let my_task = null;
let response_so_far = "";
let pre_download_state = null;
window.sentences_parsed = [];
window.tts_queue = [];
//const onModelLoaded = async function (task=null){
const onModelLoaded = async (task=null,first_load=true) => {
window.interrupt_wllama = false;
called_on_model_loaded = true;
if(task==null){
//console.log("llama_cpp: onModelLoaded: no task provided. aborting.");
window.llama_cpp_busy = false;
return false
}
my_task = task;
if(typeof task.assistant == 'string'){
let download_progress_message_el = document.querySelector('.message.pane-' + task.assistant + '.download-progress-chat-message');
if(download_progress_message_el){
download_progress_message_el.classList.add('download-complete-chat-message');
setTimeout(() => {
download_progress_message_el.remove();
},1000);
}
}
if(typeof window.currently_loaded_llama_cpp_assistant != 'string'){
console.error("wllama_cpp: onModelLoaded: aborting, window.currently_loaded_llama_cpp_assistant was not a string: ", window.currently_loaded_llama_cpp_assistant);
window.llama_cpp_busy = false;
return false
}
window.sentences_parsed = [];
if(my_task == null){
window.remove_body_class('waiting-for-response'); // no longer used
if(window.state == DOING_ASSISTANT){
window.set_state(LISTENING);
}
window.llama_cpp_busy = false;
return false
}
else if(typeof my_task == 'object' && my_task != null && typeof my_task.type == 'string'){
if(my_task.type != 'chat'){
console.warn('llama_cpp: onModelLoaded: resetting llama_cpp before summarize task (DISABLED). my_task.type: ', my_task.type);
//window.restart_llama_cpp();
}
}
if(typeof my_task.prompt != 'string'){
console.error("llama_cpp: onModelLoaded: my_task.prompt was not a string. my_task: ", my_task);
window.llama_cpp_busy = false;
return false
}
let prompt = null;
let using_chatml = false;
let total_prompt = '';
let chat_history = []; // assumes the first message in this is always from the user
let ctx_size = 1024;
let temperature = 0.7;
let top_k = 10;
let top_p = 0.9;
if(typeof window.currently_loaded_llama_cpp_assistant != 'string'){
console.error("wllama: window.currently_loaded_llama_cpp_assistant was not a string?: ", window.currently_loaded_llama_cpp_assistant);
}
else{
if(typeof window.settings.assistants[window.currently_loaded_llama_cpp_assistant]['context'] == 'number'){
ctx_size = window.settings.assistants[window.currently_loaded_llama_cpp_assistant]['context'];
//console.log("wllama: found custom context size in user's settings: ", ctx_size);
}
else if(typeof window.assistants[window.currently_loaded_llama_cpp_assistant] != 'undefined' && typeof window.assistants[window.currently_loaded_llama_cpp_assistant]['context'] == 'number'){
ctx_size = window.assistants[window.currently_loaded_llama_cpp_assistant]['context'];
//console.log("wllama: using context size from assistants dict: ", ctx_size);
}
else{
console.error("wllama: getting context size fell through, so it's still the default: ", ctx_size);
}
if(typeof window.settings.assistants[window.currently_loaded_llama_cpp_assistant] != 'undefined' && typeof window.settings.assistants[window.currently_loaded_llama_cpp_assistant]['top_k'] == 'number'){
top_k = window.settings.assistants[window.currently_loaded_llama_cpp_assistant]['top_k'];
//console.log("wllama: settings.assistant has custom top_k: ", top_k);
}
if(typeof window.assistants[window.currently_loaded_llama_cpp_assistant] != 'undefined' && typeof window.assistants[window.currently_loaded_llama_cpp_assistant]['top_p'] == 'number'){
top_k = window.assistants[window.currently_loaded_llama_cpp_assistant]['top_p'];
//console.log("wllama: assistant has custom top_p: ", top_p);
}
// Get custom temperature from task if it is set
if(typeof my_task.temperature == 'number'){
temperature = my_task.temperature;
}
// Get custom temperature if it is set
else if(typeof window.currently_loaded_assistant == 'string' && typeof window.settings.assistants[window.currently_loaded_llama_cpp_assistant] != 'undefined' && typeof window.settings.assistants[window.currently_loaded_llama_cpp_assistant].temperature != 'undefined'){
temperature = window.assistants[window.currently_loaded_llama_cpp_assistant].temperature;
}
// Fall back to temperature in assistants dict if it exists
else if(typeof window.currently_loaded_assistant == 'string' && typeof window.assistants[window.currently_loaded_llama_cpp_assistant] != 'undefined' && typeof window.assistants[window.currently_loaded_llama_cpp_assistant].temperature != 'undefined'){
temperature = window.assistants[window.currently_loaded_llama_cpp_assistant].temperature;
}
if(typeof temperature != 'number'){
console.error("wllama: temperature was not a number!: " + temperature);
temperature = 0;
}
}
total_prompt = await window.get_total_prompt(my_task);
//total_prompt = window.apply_template(my_task);
//console.warn("* onModelLoaded: total_prompt: \n\n", total_prompt,"\n\n");
//console.log("* onModelLoaded: final ctx_size: ", ctx_size);
//console.log("* onModelLoaded: final temperature: ", temperature);
if(total_prompt == null){
console.error("wllama: total_prompt is null, aborting");
window.llama_cpp_busy = false;
return false
}
if(total_prompt == ''){
console.warn("wllama: total prompt was empty string");
if(typeof my_task.prompt == 'string' && my_task.prompt.length > 1){
total_prompt = my_task.prompt;
}
else{
console.error("wllama: total_prompt was empty string: ", total_prompt);
window.llama_cpp_busy = false;
return false
}
}
/*
OLD
llama_cpp_wasm
OPTIONS/DEFAULTS:
batch_size: 512
chatml: false
ctx_size: 2048
event: 2
n_gpu_layers: 0
n_predict: -2
no_display_prompt: true
prompt: ""
temp: 0.7
top_k: 40
top_p: 0.9
*/
if(total_prompt != null && total_prompt != ''){
if(typeof window.conversations[window.settings.assistant] == 'undefined'){
window.conversations[window.settings.assistant] = [];
}
//console.log("llama_cpp: adding user's prompt to conversation history");
//window.conversations[window.settings.assistant].push({'role':'user','content':my_task.prompt});
if(window.state == UNLOADED || window.state == DOING_STT){
window.set_state(DOING_ASSISTANT);
}
if(window.settings.settings_complexity == 'developer'){
console.warn("dev: Wllama: onModelLoaded: total_prompt: ", total_prompt);
}
//console.log("onModelLoaded: setting window.llama_cpp_busy to true");
window.llama_cpp_busy = true;
window.add_body_class('doing-assistant');
//console.log("onModelLoaded: total_prompt: ", total_prompt);
//console.log("onModelLoaded: ctx_size: ", ctx_size);
//console.log("onModelLoaded: temperature: ", temperature);
//console.log("onModelLoaded: window.llama_cpp_app: ", window.llama_cpp_app);
window.llama_cpp_fresh = false;
//console.log("onModelLoaded: model is no longer fresh"); // no longer needed
//console.log("\n\ncalling Wllama's createCompletion\n\n");
/*
export interface SamplingConfig {
// See sampling.h for more details
mirostat?: number, // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
mirostat_tau?: number,
temp?: number, // temperature
top_p?: number,
top_k?: number,
penalty_last_n?: number,
penalty_repeat?: number,
penalty_freq?: number,
penalty_present?: number,
penalize_nl?: boolean,
dynatemp_range?: number,
dynatemp_exponent?: number,
grammar?: string,
n_prev?: number,
n_probs?: number,
min_p?: number,
tfs_z?: number,
typical_p?: number,
logit_bias?: { token: number, bias: number }[],
};
*/
let sampling = generate_model_settings(task);
try{
//window.interrupt_wllama = false;
//let response_so_far = "";
window.currently_running_llm = task.assistant;
const outputText = await window.llama_cpp_app.createCompletion(total_prompt, {
//nPredict: 500,
allow_offline:true,
sampling: {
temp: temperature,
//top_k: top_k,//40,
//top_p: top_p, //0.9,
},
useCache: true,
onNewToken: (token, piece, currentText, { abortSignal }) => {
if (window.interrupt_wllama) {
console.log("sending interrupt signal to Wllama");
abortSignal();
window.interrupt_wllama = false;
}
else{
//console.log("wllama: onNewToken: token,piece,currentText:", token, piece, currentText);
let new_chunk = currentText.substr(response_so_far.length);
window.handle_chunk(my_task,response_so_far,new_chunk);
response_so_far = currentText;
}
},
});
//console.log("wllama: outputText: ", outputText);
if(typeof outputText == 'string' && outputText.length){
await window.handle_completed_task(my_task, outputText);
}
else if(typeof outputText == 'string' && outputText == ''){
console.error("wllama: output text was invalid. Empty string?: -->" + outputText + "<--");
window.flash_message(window.get_translation("The_AI_gave_an_empty_response"),3000,'fail');
await window.handle_completed_task(my_task, outputText, {'state':'failed'});
}
else{
console.error("wllama: output text was invalid, and not a string: ", outputText);
window.flash_message(window.get_translation("The_AI_gave_an_unexpected_response"),3000,'fail');
await window.handle_completed_task(my_task, '', {'state':'failed'});
}
response_so_far = '';
my_task = null;
window.llama_cpp_busy = false;
called_on_model_loaded = false;
}
catch(err){
console.error("caught error running Wllama: ", err);
if( ('' + err).indexOf('Received abort signal from llama.cpp') != -1){
window.add_chat_message(window.currently_loaded_llama_cpp_assistant,window.currently_loaded_llama_cpp_assistant,'it_seems_the_AI_has_crashed#setting---');
}
else if( ('' + err).indexOf('memory access out of bounds') != -1){
window.add_chat_message(window.currently_loaded_llama_cpp_assistant,window.currently_loaded_llama_cpp_assistant,'it_seems_the_AI_has_crashed#setting---');
}
message_downloads_container_el.innerHTML = '';
called_on_model_loaded = false;
window.llama_cpp_busy = true;
window.flash_message(window.get_translation("The_AI_has_crashed"));
setTimeout(() => {
//restart_llama_cpp(false);
console.error("wllama crash: 5 second passed");
repair_wllama();
},5000);
}
}
else{
console.error("wllama: onModelLoaded: invalid prompt: at the end total_prompt was still an empty string or null: ", total_prompt);
}
}
async function repair_wllama(){
console.error("in repair_wllama");
//console.log("it seems wllama crashed while loading the AI model");
if(my_task != null){
if(typeof my_task.parent_index == 'number'){
window.change_tasks_with_parent_index(my_task.parent_index);
}
console.warn("repair_wllama: candle handle_completed_task to set my_task to failed")
await window.handle_completed_task(my_task, '', {'state':'failed'});
my_task = null;
}
window.llama_cpp_busy = true;
called_on_model_loaded = false;
console.error("repair_wllama: calling restart_llama_cpp");
await restart_llama_cpp();
window.llama_cpp_busy = false;
}
//
// MODEL DOWNLOAD PROGRESS
//
// Is this still used?
const onMessage = (progression) => {
wllama_update_model_download_progress(progression);
};
let previous_percentage = 1;
let previous_time = 0;
async function wllama_update_model_download_progress(progression, assistant_id=null){
//console.log("LLAMA_CPP MODEL DOWNLOAD: PROGRESSION, window.llama_cpp_model_being_loaded: ", progression, window.llama_cpp_model_being_loaded, assistant_id);
if(assistant_id == null){
assistant_id = window.llama_cpp_model_being_loaded;
}
if(progression == 1){
if(typeof assistant_id == 'string'){
//console.log("llama_cpp model download complete: ", assistant_id);
//flash_message(window.get_translation("Download_complete"),2000);
if(window.settings.assistant == assistant_id){
window.add_body_class('model-loaded');
}
let progress_el = document.querySelector('#download-progress-' + assistant_id);
if(progress_el != null){
const message_el = progress_el.closest('.message');
if(message_el){
message_el.remove();
}
}
}
else{
console.error("llama_cpp model download complete, but no assistant id?");
const downloads_container_el = document.querySelector('#message-downloads-container');
if(downloads_container_el){
downloads_container_el.innerHTML = '';
}
}
await update_cached_files_list();
window.handle_download_complete(false); // TODO: delay this. This re-calculates the total used disk space. But in case of custom AI models it's called to early here, as we won't know their size until they have fully loaded.
}
if(assistant_id != null){
//console.log("a llama_cpp model is being loaded");
const percent = Math.floor(progression * 300);
//console.log("wllama_update_model_download_progress: percent: ", percent);
if(previous_percentage > percent){
previous_percentage = 0;
}
if(percent > previous_percentage){
//console.log("Wllama download percent: ", percent / 3);
let progress_el = document.getElementById('download-progress-' + assistant_id);
if(progress_el == null){
if(progression != 1){
//console.log("llama_cpp (down)load progress element is missing, adding it now: ", assistant_id, percent);
window.add_chat_message(assistant_id,assistant_id,"download_progress#setting---");
}
}
else{
//console.log("a llama_cpp model is being loaded: found the progress element");
progress_el.value = progression;
}
if(percent % 3 == 0 && percent != 300){
//console.log("doing remaining download time estimation. percent: ", percent);
const now_time = Date.now() / 300; // SIC
if(previous_time == 0){
previous_time = now_time;
//console.log("changed previous time to: ", previous_time);
}
else if(progress_el != null){
let delta = now_time - previous_time;
previous_time = now_time;
//console.log("it took this long to download the last percent: ", delta);
let time_remaining = ((300 - percent)/10) * delta;
let time_remaining_el = progress_el.parentNode.querySelector('.time-remaining'); // #download-progress-' + window.settings.assistant + ' +
if(time_remaining_el != null){
time_remaining_el.innerHTML = window.create_time_remaining_html(time_remaining);
}
else{
console.error("could not find time-remaining element")
}
}
}
previous_percentage = percent;
}
else{
//console.error("Download percentage is not greater: ", previous_percentage, percent);
}
}
else{
console.error("wllama download progress: assistant_id was null");
}
}
window.wllama_update_model_download_progress = wllama_update_model_download_progress;
function generate_model_settings(task){
let model_settings = {'allow_offline':true};//{'cache_type_k': 'q4_0'}; // save memory
//let model_settings = {};
let assistant_id = window.settings.assistant;
// window.currently_loaded_llama_cpp_assistant
if(typeof task.assistant == 'string'){
assistant_id = task.assistant;
}
let context = 1024;
model_settings['n_ctx'] = 1024;
if(typeof window.settings.assistants[assistant_id] != 'undefined' && typeof window.settings.assistants[assistant_id]['context'] == 'number'){
context = window.settings.assistants[assistant_id]['context'];
}
else if(typeof window.assistants[assistant_id] != 'undefined' && typeof window.assistants[assistant_id]['context'] == 'number'){
context = window.assistants[assistant_id]['context'];
}
if(typeof context == 'number' && context > 1024){
if(window.is_mobile){
//window.web_llm_app_config['context_window_size'] = 1024;
// 1024 is the default for mobile, unless there is tons of ram
if(window.ram > 6000 && context > 2048){
model_settings['n_ctx'] = 2048;
}
}
else{
model_settings['n_ctx'] = context;
}
}
//model_settings['n_seq_max'] = 1; //model_settings['n_ctx'];
//model_settings['n_batch'] = 1024; //2048;//model_settings['n_ctx'];
//model_settings['n_threads'] = 4;
if(typeof window.assistants[assistant_id]['cache_type_k'] == 'string'){
model_settings['cache_type_k'] = window.assistants[assistant_id]['cache_type_k']; //'q4_0'; = window.assistants[assistant_id]['context'];
}
model_settings['embeddings'] = false;
let downloads = {};
let file_chunk_count = 1;
if(typeof window.assistants[assistant_id] != 'undefined' && typeof window.assistants[assistant_id].download_url != 'undefined' && window.assistants[assistant_id].download_url != null && Array.isArray(window.assistants[assistant_id].download_url)){
file_chunk_count = window.assistants[assistant_id].download_url.length;
//console.log("wllama: downloading file in chunks: ", file_chunk_count);
}
model_settings['progressCallback'] = ({ loaded, total }) => {
//console.log(`Wllama: downloading... ${Math.round(loaded/total*100)}%`, loaded, total);
//console.log("percentage, loaded, total: ", Math.round(loaded/total*100) + '%', loaded, total);
if(total != 0 && loaded > 1000000){
//console.log("loaded, total: ", loaded, total);
wllama_update_model_download_progress(loaded / total, assistant_id);
}
}
let temperature = 0;
// Get custom temperature from task if it is set
if(typeof task.temperature == 'number'){
temperature = task.temperature;
}
// Get custom temperature if it is set
else if(typeof window.settings.assistants[assistant_id] != 'undefined' && typeof window.settings.assistants[assistant_id].temperature == 'number'){
temperature = window.assistants[assistant_id].temperature;
}
// Fall back to temperature in assistants dict if it exists
else if(typeof window.assistants[assistant_id] != 'undefined' && typeof window.assistants[assistant_id].temperature == 'number'){
temperature = window.assistants[assistant_id].temperature;
}
//console.log("wllama: window.llama_cpp_app: ", window.llama_cpp_app);
if(window.settings.settings_complexity == 'developer'){
console.warn("dev: wllama: temperature: ", temperature);
}
if(typeof temperature == 'number'){
model_settings['temp'] = temperature;
if(typeof window.settings.assistants[assistant_id] != 'undefined' && typeof window.settings.assistants[assistant_id].seed == 'number'){
model_settings['seed'] = window.settings.assistants[assistant_id].seed;
console.log("wllama: spotted seed preference, it is now: ", window.settings.assistants[assistant_id].seed);
}
else if(temperature == 0){
model_settings['seed'] = 42;
//console.log("wllama: temperature was 0, seed set to 42");
}
}
return model_settings
}
// This function returns immediately so that the main interval loop can continue
function do_llama_cpp(task=null, model_url=null, query=''){
//console.log("in do_llama_cpp. task,model_url,query: ", task,model_url,query);
if(query != ''){
//console.log("do_llama_cpp: also placing a string in the prompt input: ", query);
prompt_el.value = query;
}
if(task==null){
console.error("do_llama_cpp: task was null. Aborting.");
window.llama_cpp_busy = false;
return false
}
if(typeof window.settings.assistant != 'string'){
console.error("do_llama_cpp: no valid window.settings.assistant: ", window.settings.assistant); // need to know which model to load. Or could get that from the task?
window.llama_cpp_busy = false;
return false
}
let assistant_id = window.settings.assistant;
// window.currently_loaded_llama_cpp_assistant
if(typeof task.assistant == 'string'){
assistant_id = task.assistant;
}
else{
console.warn("do_llama_cpp: task had no assistant property: ", task);
}
if(typeof assistant_id != 'string'){
console.error("do_llama_cpp: no valid assistant_id");
window.llama_cpp_busy = false;
return false
}
if(typeof window.assistants[assistant_id]['do_not_load'] != 'undefined' && window.assistants[assistant_id]['do_not_load'] == true){ // for 'fake' assistants, such as Developer
console.warn("do_llama_cpp: aborting, as the assistant has do_not_load flag: ", assistant_id);
window.llama_cpp_busy = false;
return false
}
if(window.llama_cpp_busy){
console.error("in do_llama_cpp, but window.llama_cpp_busy was true? Aborting!");
return false
}
if(typeof window.settings.assistants[assistant_id] == 'undefined' || window.settings.assistants[task.assistant] == null){
console.error("do_llama_cpp: assistant_id not found in window.assistants: ", assistant_id);
window.llama_cpp_busy = false;
return false
}
window.llama_cpp_busy = true;
// NO AWAIT
really_do_llama_cpp(task, model_url, query);
return true
}
window.do_llama_cpp = do_llama_cpp;
async function really_do_llama_cpp(task=null, model_url=null, query=''){
//console.log("in really_do_llama_cpp. task: ", task);
//console.log("window.llama_cpp_app: ", window.llama_cpp_app);
window.llama_cpp_busy = true;
called_on_model_loaded = false;
if(task == null){
my_task = null;
}
else{
my_task = JSON.parse(JSON.stringify(task));
}
let assistant_id = window.settings.assistant;
// window.currently_loaded_llama_cpp_assistant
if(typeof my_task.assistant == 'string'){
assistant_id = my_task.assistant;
}
if(model_url == null){
//console.log("do_llama_cpp: assistant_id: ", assistant_id);
if(my_task != null && typeof assistant_id == 'string'){
if(typeof window.settings.assistants[assistant_id]['download_url'] == 'string'
&& (window.settings.assistants[assistant_id]['download_url'].startsWith('http') || window.settings.assistants[assistant_id]['download_url'].startsWith('/')) // || window.settings.assistants[task.assistant]['download_url'].startsWith('./')
){
model_url = window.settings.assistants[assistant_id]['download_url'];
//console.log("do_llama_cpp: getting CUSTOM model URL from window.settings: ", model_url);
}
else if(typeof window.settings.assistants[assistant_id]['download_url'] == 'string'
&& (window.settings.assistants[assistant_id]['download_url'].startsWith('[') && window.settings.assistants[assistant_id]['download_url'].endsWith(']')) // || window.settings.assistants[task.assistant]['download_url'].startsWith('./')
){
try{
model_url = JSON.parse(window.settings.assistants[assistant_id]['download_url']);
//console.log("getting CUSTOM model URL from window.settings: ", model_url);
}
catch(err){
console.error("do_llama_cpp: failed to parse what seemed like a custom model chunks array: ", window.settings.assistants[assistant_id]['download_url']);
}
}
if(model_url == null){
//console.log("do_llama_cpp: no custom model url, so will use the one from window.assistants (if it exists)");
if(typeof window.assistants[assistant_id] != 'undefined' && typeof window.assistants[assistant_id]['download_url'] != 'undefined' && window.assistants[assistant_id]['download_url'] != null){
model_url = window.assistants[assistant_id]['download_url'];
//console.log("do_llama_cpp: got model URL from assistants dict: ", model_url);
}
else{
// custom model, but still without a URL
// Although technically it could also be that the assistant key is invalid
//console.log("do_llama_cpp: ABORTING, NO DOWNLOAD_URL (likely custom assistant)");
window.add_chat_message(assistant_id,'developer',get_translation('Missing_AI_model_URL'));
window.llama_cpp_busy = false;
return false
}
}
}
else{
console.warn("do_llama_cpp: could not get a download URL from the task, as assistant_id was likely invalid: ", assistant_id, JSON.stringify(my_task,null,4));
}
// If the model_url is still an empty string, fall back to using the download URL of the currently visible assistant
/*
if(model_url == null){
console.warn("do_llama_cpp: could not get a model URL via/from the task itself, falling back to getting it based on the currently visible assistant");
if(typeof window.assistants[window.settings.assistant]['download_url'] == 'string'){
model_url = window.assistants[window.settings.assistant]['download_url'];
}
}
*/
// Turn relative model paths into absolute URL's
if(typeof model_url == 'string' && model_url != '' && !model_url.startsWith('http')){
let base_url = window.location.origin; //window.location.href;
//console.log("do_llama_cpp: base_url: ", base_url);
if(base_url.endsWith('/')){
base_url = base_url.substring(0, base_url.length - 1);
//console.log("do_llama_cpp: removing trailing slash base url: ", '' + base_url);
}
if(!model_url.startsWith('/')){
//console.log("do_llama_cpp: adding starting slash to model url: ", '' + model_url);
model_url = '/' + model_url;
}
model_url = base_url + model_url;
//console.log("do_llama_cpp: generated relative model url: ", model_url);
}
if(typeof model_url == 'string'){
//console.warn("do_llama_cpp: is it correct? model_url: ", model_url);
}
else if( Array.isArray(model_url) && model_url.length){
//console.warn("model_url is an array. First item is: ", model_url[0])
}
}
// If the URL is not a string, that's not good
if(model_url == null){
console.error("do_llama_cpp: model_url was null. Aborting.");
window.add_chat_message(assistant_id,'developer',get_translation('Missing_AI_model_URL'));
window.llama_cpp_busy = false;
return false
}
// If the URL is still an empty string, that's not good
if(typeof model_url == 'string' && model_url == ''){
console.error("\n\nERROR, model_url was an empty string. Adding error chat message and aborting.\n\n");
if(typeof assistant_id == 'string' && assistant_id.startsWith('custom')){
window.add_chat_message(assistant_id,'developer','Please_provide_the_URL_of_an_AI_model#setting---');
}
else{
window.add_chat_message(assistant_id,'developer',get_translation('Missing_AI_model_URL'));
}
await window.handle_completed_task(task,false,{'state':'failed'});
window.llama_cpp_busy = false;
return false
}
//console.log("do_llama_cpp: model_url is now: ", model_url);
if(typeof model_url == 'string'){
let check_for_gguf_extension = model_url.toLowerCase();
if(!check_for_gguf_extension.endsWith('.gguf')){
console.warning("\n\nWarning! MODEL URL DOES NOT SEEM TO END WITH .GGUF:\n" + model_url + "\n\n")
}
}
// THE FORK IN THE ROAD
//if (app && app.url == selectModel.value) {
if (window.llama_cpp_app && typeof window.currently_loaded_llama_cpp_assistant == 'string' && window.currently_loaded_llama_cpp_assistant == assistant_id) {
if(window.settings.settings_complexity == 'developer'){
console.warn("dev: do_llama_cpp: FORK: this model was already the loaded model. Jumping to onModelLoaded. currently_loaded_llama_cpp_assistant: ", window.currently_loaded_llama_cpp_assistant);
}
await onModelLoaded(task, false); // false indicates that the model was already loaded
return true;
}
else{
if(window.settings.settings_complexity == 'developer'){
console.warn("dev: really_do_llama_cpp: FORK: this model was NOT already the loaded model. Going to load model first, and then call onModelLoaded. assistant_id,window.currently_loaded_llama_cpp_assistant: ", assistant_id, window.currently_loaded_llama_cpp_assistant);
}
//console.log("- window.llama_cpp_app: ", window.llama_cpp_app);
//console.log("- window.currently_loaded_llama_cpp_assistant: ", window.currently_loaded_llama_cpp_assistant);
//window.add_chat_message(assistant_id,assistant_id,'download_progress#setting---');
}
if(window.settings.settings_complexity == 'developer'){
console.log("\n\ndo_llama_cpp: LOADING FIRST/DIFFERENT MODEL. assistant_id,model_url: ", assistant_id, model_url);
}
try{
window.add_chat_message(assistant_id,assistant_id,"download_progress#setting---");
if(window.llama_cpp_app == null){
console.warn("really_do_llama_cpp: still had to create window.llama_cpp_app");
create_wllama_object();
}
else{
try{
if(typeof window.currently_loaded_llama_cpp_assistant == 'string'){
console.log("really_do_llama_cpp: calling unload_llama_cpp first, to unload: window.currently_loaded_llama_cpp_assistant: ", window.currently_loaded_llama_cpp_assistant);
await unload_llama_cpp();
}
}
catch(err){
console.error("really_do_llama_cpp: caught error trying to call wllama's isModelLoaded: ", err);
//called_on_model_loaded = false;
}
}
if(window.llama_cpp_app == null){
console.warn("really_do_llama_cpp: still had to create window.llama_cpp_app (likely just unloaded the previous model)");
create_wllama_object();
}
//window.currently_loaded_llama_cpp_assistant = null;
previous_percentage = 1;
previous_time = 0;
if(window.llama_cpp_app != null && typeof window.llama_cpp_app.worker != 'undefined' && typeof window.llama_cpp_app.worker != null){
console.warn("Sreally_do_llama_cpp: terminated worker on existing app object before loading the new AI model (blocked)");
//window.llama_cpp_app.worker.terminate();
}
//window.assistants_loading_count++;
//window.busy_loading_assistant = true;
/*
export interface LoadModelConfig {
seed?: number,
n_ctx?: number,
n_batch?: number,
n_threads?: number,
embeddings?: boolean,
offload_kqv?: boolean,
n_seq_max?: number,
pooling_type?: 'LLAMA_POOLING_TYPE_UNSPECIFIED'
| 'LLAMA_POOLING_TYPE_NONE'
| 'LLAMA_POOLING_TYPE_MEAN'
| 'LLAMA_POOLING_TYPE_CLS',
// context extending
rope_scaling_type?: 'LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED'
| 'LLAMA_ROPE_SCALING_TYPE_NONE'
| 'LLAMA_ROPE_SCALING_TYPE_LINEAR'
| 'LLAMA_ROPE_SCALING_TYPE_YARN',
rope_freq_base?: number,
rope_freq_scale?: number,
yarn_ext_factor?: number,
yarn_attn_factor?: number,
yarn_beta_fast?: number,
yarn_beta_slow?: number,
yarn_orig_ctx?: number,
// TODO: add group attention
// optimizations
cache_type_k?: 'f16' | 'q8_0' | 'q4_0',
cache_type_v?: 'f16',
// download-specific params
n_download_parallel?: number,
*/
let model_settings = generate_model_settings(task);
// DEBUG
//model_settings = { temp: 0 };
// LOADING FROM URL
//window.llama_cpp_model_being_loaded = assistant_id;
//console.log("do_llama_cpp: calling loadModelFromUrl with: model_url,model_settings: ", model_url, model_settings);
//console.warn("do_llama_cpp: window.llama_cpp_app: ", window.llama_cpp_app);
//console.warn("do_llama_cpp: window.currently_loaded_llama_cpp_assistant: ", window.currently_loaded_llama_cpp_assistant);
/*
if(
typeof window.settings.assistants[assistant_id] != 'undefined'
&& typeof window.settings.assistants[assistant_id]['llama_cpp_general_name'] == 'string'
){
console.warn("really_do_llama_cpp: window.settings.assistants[assistant_id]['llama_cpp_general_name']: ", window.settings.assistants[assistant_id]['llama_cpp_general_name']);
}
if(
typeof window.llama_cpp_app.metadata != 'undefined'
&& typeof window.llama_cpp_app.metadata.meta != 'undefined'
&& typeof window.llama_cpp_app.metadata.meta['general.name'] == 'string'
){
console.warn("really_do_llama_cpp: window.llama_cpp_app.metadata.meta['general.name']: ", window.llama_cpp_app.metadata.meta['general.name']);
}
*/
if(
typeof assistant_id == 'string'
&& typeof window.settings.assistants[assistant_id] != 'undefined'
&& typeof window.settings.assistants[assistant_id]['llama_cpp_general_name'] == 'string'
&& window.llama_cpp_app != null
&& typeof window.llama_cpp_app.metadata != 'undefined'
&& typeof window.llama_cpp_app.metadata.meta != 'undefined'
&& typeof window.llama_cpp_app.metadata.meta['general.name'] == 'string'
){
if(window.llama_cpp_app.metadata.meta['general.name'] == window.settings.assistants[assistant_id]['llama_cpp_general_name']){
console.warn("really_do_llama_cpp: it seems this model is already loaded: ", assistant_id, ", a.k.a. ", window.settings.assistants[assistant_id]['llama_cpp_general_name']);
console.warn("really_do_llama_cpp: window.currently_loaded_llama_cpp_assistant: ", window.currently_loaded_llama_cpp_assistant);
}
else{
console.warn(" calling unload_llama_cpp.. again? Because general.name was not the same");
if(typeof window.llama_cpp_app.loadModelFromUrl != 'undefined'){
console.warn("really_do_llama_cpp: loadModelFromUrl was not undefined. first calling unload_llama_cpp.. again");
await unload_llama_cpp();
if(window.settings.settings_complexity == 'developer'){
console.warn("dev: really_load_llama_cpp: calling llama_cpp_app.loadModelFromUrl. model_url, model_settings: ", model_url, model_settings);
}
}
else{
console.error("really_load_llama_cpp: window.llama_cpp_app.loadModelFromUrl was undefined?", window.llama_cpp_app);
//console.log("window.llama_cpp_busy: ", window.llama_cpp_busy);
}
}
}
try{
if(window.llama_cpp_app == null){
console.error("really_do_llama_cpp: window.llama_cpp_app was still NULL?!");
create_wllama_object();
}
await window.llama_cpp_app.loadModelFromUrl(model_url, model_settings);
}
catch(err){
console.error("wllama: really_load_llama_cpp: caught loadModelFromUrl error: ", err);
//window.flash_message(window.get_translation('An_error_occured'),2000,'fail');
window.display_error(null, '' + err);
if(task != null && typeof task.index == 'number'){
await window.handle_completed_task(task,null,{'state':'failed'});
}
window.llama_cpp_busy = false;
window.interrupt_wllama = false;
window.doing_llama_cpp_refresh = false;
window.llama_cpp_model_being_loaded = null;
window.llama_cpp_model_being_downloaded = null;
window.currently_loaded_llama_cpp_assistant = null;
window.currently_loaded_llama_cpp_assistant_general_name = null;
return false
}
window.currently_loaded_llama_cpp_assistant = assistant_id;
//console.log("really_load_llama_cpp: window.currently_loaded_llama_cpp_assistant is now: ", window.currently_loaded_llama_cpp_assistant)
if(typeof window.llama_cpp_app.metadata != 'undefined' && typeof window.llama_cpp_app.metadata.meta != 'undefined' && typeof window.llama_cpp_app.metadata.meta['general.name'] == 'string'){
window.currently_loaded_llama_cpp_assistant_general_name = window.llama_cpp_app.metadata.meta['general.name'];
if(typeof window.settings.assistants[assistant_id] == 'undefined'){
window.settings.assistants[assistant_id] = {};
}
if(window.settings.settings_complexity == 'developer'){
console.warn("dev: wllama: really_load_llama_cpp: setting general.name: ", assistant_id, " -> ", window.llama_cpp_app.metadata.meta['general.name']);
}