-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathllm.js
More file actions
1579 lines (1345 loc) · 53.8 KB
/
Copy pathllm.js
File metadata and controls
1579 lines (1345 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Wllama } from "https://cdn.jsdelivr.net/npm/@wllama/wllama@3.1.1/esm/index.js";
const WASM_PATHS = {
default: "https://cdn.jsdelivr.net/npm/@wllama/wllama@3.1.1/esm/wasm/wllama.wasm"
};
const MODEL_REPO = "bartowski/Phi-3.5-mini-instruct-GGUF";
const MODEL_QUANT = "Q4_K_M";
const MODERATION_LIST_PATH = "./moderation/mod.txt";
const MODERATION_SAFE_RESPONSE = "I'm sorry. I can't help with that. Either your system instructions or user input included content that was flagged by the moderation system. If you think this was a mistake, please try rephrasing your input or instructions and try again.";
const WIKIPEDIA_MODEL_NAME = "Wikipedia API (Basic Chat)";
const STOPWORDS = new Set([
// Articles, prepositions, conjunctions
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from',
'in', 'is', 'it', 'its', 'of', 'on', 'that', 'the', 'to', 'with',
'or', 'but', 'if', 'than', 'then', 'so', 'yet',
'after', 'before', 'between', 'during', 'into', 'through', 'over',
'under', 'until', 'up', 'down', 'out', 'off', 'above', 'below',
// Pronouns
'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her',
'us', 'them', 'my', 'your', 'his', 'her', 'its', 'our', 'their', 'i\'m',
'you\'re', 'he\'s', 'she\'s', 'we\'re', 'they\'re',
// Determiners and quantifiers
'this', 'these', 'those', 'some', 'any', 'all', 'each', 'every',
'both', 'few', 'more', 'most', 'such', 'no', 'nor', 'not', 'only',
'own', 'same', 'other', 'another', 'much', 'many',
// Verbs (auxiliary, modal, and common generic)
'am', 'is', 'are', 'was', 'were', 'been', 'being', 'have', 'has',
'had', 'do', 'does', 'did', 'can', 'could', 'would', 'should',
'may', 'might', 'must', 'shall', 'ought', 'will',
'be', 'get', 'make', 'know', 'see', 'take', 'come', 'go', 'want',
'use', 'find', 'need', 'try', 'ask', 'work', 'help', 'like', 'seem',
'become', 'let', 'tell', 'show', 'give', 'provide', 'explain',
'describe', 'define',
// Question words
'what', 'when', 'where', 'who', 'how', 'why', 'which', 'whom',
'whose', 'whether', 'what\'s', 'whats', 'who\'s', 'whos', 'how\'s',
'hows',
// Common adverbs
'also', 'just', 'now', 'here', 'there', 'then', 'very', 'too',
'really', 'still', 'always', 'never', 'often', 'sometimes', 'maybe',
'perhaps', 'about',
// Other common words
'yes', 'no', 'thing', 'something', 'anything', 'nothing',
'everything', 'someone', 'anyone', 'everyone', 'understand', 'know',
'think', 'believe', 'feel', 'appear',
]);
function makeId(prefix) {
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function reverseWord(text) {
return text.split("").reverse().join("");
}
function shiftWord(text, amount) {
return text
.split("")
.map((char) => String.fromCharCode(char.charCodeAt(0) + amount))
.join("");
}
function roleToChatML(role) {
if (role === "developer" || role === "system") {
return "system";
}
if (role === "assistant") {
return "assistant";
}
return "user";
}
function isTextContentBlock(block) {
if (!block || typeof block !== "object") {
return false;
}
return ["input_text", "output_text", "text"].includes(String(block.type || ""));
}
function contentToText(content) {
if (typeof content === "string") {
return content;
}
if (Array.isArray(content)) {
return content
.map((block) => {
if (typeof block === "string") {
return block;
}
if (isTextContentBlock(block)) {
return String(block.text ?? "");
}
return "";
})
.filter((text) => text.length > 0)
.join("\n");
}
if (isTextContentBlock(content)) {
return String(content.text ?? "");
}
return String(content ?? "");
}
function extractLeadingSentences(text, maxSentences = 2) {
if (!text) {
return "";
}
let sentenceCount = 0;
let cutIndex = -1;
for (let i = 0; i < text.length; i += 1) {
const char = text[i];
if (char !== "." && char !== "!" && char !== "?") {
continue;
}
const prev = i > 0 ? text[i - 1] : "";
const next = i < text.length - 1 ? text[i + 1] : "";
// Ignore decimal separators such as 12.5.
if (char === "." && /\d/.test(prev) && /\d/.test(next)) {
continue;
}
sentenceCount += 1;
cutIndex = i + 1;
if (sentenceCount >= maxSentences) {
break;
}
}
if (cutIndex === -1) {
return text.trim();
}
return text.slice(0, cutIndex).trim();
}
function extractKeywords(text, excludedWords = null) {
const words = String(text || "")
.toLowerCase()
.replace(/[^\w\s]/g, "")
.split(/\s+/);
return words
.filter((word) => !STOPWORDS.has(word) && word.length > 0 && !(excludedWords && excludedWords.has(word)))
.join(" ");
}
function chunkTextForStreaming(text, minChunk = 12, maxChunk = 36) {
const source = String(text || "");
if (!source) {
return [];
}
const chunks = [];
let index = 0;
while (index < source.length) {
const remaining = source.length - index;
const target = Math.min(
remaining,
Math.max(minChunk, Math.floor(Math.random() * (maxChunk - minChunk + 1)) + minChunk)
);
let nextIndex = index + target;
// Prefer splitting on whitespace/punctuation boundaries for natural deltas.
if (nextIndex < source.length) {
const boundaryWindow = source.slice(index, Math.min(source.length, nextIndex + 10));
const boundaryOffset = boundaryWindow.search(/[\s,.!?;:)]/);
if (boundaryOffset > 0) {
nextIndex = index + boundaryOffset + 1;
}
}
chunks.push(source.slice(index, nextIndex));
index = nextIndex;
}
return chunks.filter((chunk) => chunk.length > 0);
}
function validateMessageContent(content, label) {
if (typeof content === "string") {
return;
}
if (!Array.isArray(content)) {
throw new Error(`${label} content must be a string or an array of content blocks.`);
}
for (const block of content) {
if (typeof block === "string") {
continue;
}
if (!block || typeof block !== "object") {
throw new Error(`${label} content blocks must be strings or objects.`);
}
if (!("type" in block)) {
throw new Error(`${label} content block objects must include a type.`);
}
if (isTextContentBlock(block) && typeof block.text !== "string") {
throw new Error(`${label} text content blocks must include a text string.`);
}
}
}
function validateMessages(messages, label = "messages") {
if (!Array.isArray(messages)) {
throw new Error(`${label} must be an array.`);
}
const allowedRoles = new Set(["developer", "system", "user", "assistant"]);
for (const message of messages) {
if (!message || typeof message !== "object") {
throw new Error(`${label} must contain objects with role and content.`);
}
if (!allowedRoles.has(message.role)) {
throw new Error("Message role must be developer, user, assistant, or system.");
}
validateMessageContent(message.content, label);
}
}
class ModelCoderLLM {
constructor() {
this.wllama = null; // wllama engine for Phi 3.5-mini
this.usingWllama = false; // Track if wllama is active
this.usingBasic = false; // Basic Chat Wikipedia mode
this.availableModes = { cpu: true, basic: true };
this.isReady = false;
this.isLoading = false;
this.statusCallback = null;
this.streamSessions = new Map();
this.responsesById = new Map();
this.sessionVersion = 0;
this.activeGenerationTasks = new Set();
this.activeRunId = 0;
this.moderationTerms = null;
this.moderationLoadPromise = null;
this.modelLoadingCancelled = false;
this.modelLoadingAbortController = null;
this.initSessionId = 0; // Track which init session we're in
this.gpuFailed = false; // True after a GPU inference failure; forces CPU-only on reload
this.wllamaUsedGPU = false; // True when the loaded model is using GPU acceleration
}
checkHardwareRequirements() {
const MIN_MEMORY_GB = 8;
const MIN_CORES = 8;
const deviceMemory = navigator.deviceMemory || 0;
const cores = navigator.hardwareConcurrency || 0;
console.log(`Hardware check: ${deviceMemory}GB RAM, ${cores} cores`);
console.log(`Requirements: ${MIN_MEMORY_GB}GB RAM, ${MIN_CORES} cores`);
if (deviceMemory < MIN_MEMORY_GB || cores < MIN_CORES) {
console.log(`Hardware below minimum requirements - disabling Phi 3.5-mini`);
return false;
}
return true;
}
async _ensureModerationTerms() {
if (Array.isArray(this.moderationTerms)) {
return this.moderationTerms;
}
if (this.moderationLoadPromise) {
return this.moderationLoadPromise;
}
this.moderationLoadPromise = (async () => {
const response = await fetch(MODERATION_LIST_PATH, { cache: "no-store" });
if (!response.ok) {
throw new Error("Failed to load moderation list.");
}
const text = await response.text();
const lines = text
.split(/\r?\n/)
.map((line) => line.trim().toLowerCase())
.filter((line) => line.length > 0);
this.moderationTerms = lines
.map((line) => shiftWord(reverseWord(line), 1))
.filter((line) => line.length > 0);
return this.moderationTerms;
})();
try {
return await this.moderationLoadPromise;
} finally {
this.moderationLoadPromise = null;
}
}
async _hasReversedModerationMatch(candidatePrompts) {
const prompts = Array.isArray(candidatePrompts)
? candidatePrompts.map((v) => String(v ?? "").toLowerCase())
: [];
if (prompts.length === 0) {
return false;
}
const terms = await this._ensureModerationTerms();
if (!Array.isArray(terms) || terms.length === 0) {
return false;
}
for (const prompt of prompts) {
for (const term of terms) {
if (term && prompt.includes(term)) {
return true;
}
}
}
return false;
}
_extractModeratedPromptsFromMessages(messages) {
if (!Array.isArray(messages)) {
return [];
}
return messages
.filter((message) => message && ["user", "system", "developer"].includes(String(message.role || "")))
.map((message) => contentToText(message.content));
}
_extractModeratedPromptsFromInput(input, instructions = "") {
const prompts = [];
if (instructions) {
prompts.push(String(instructions));
}
if (Array.isArray(input)) {
prompts.push(
...input
.filter((message) => message && ["user", "system", "developer"].includes(String(message.role || "user")))
.map((message) => contentToText(message.content))
);
return prompts;
}
prompts.push(contentToText(input));
return prompts;
}
_createSafeResponseStream(streamType, requestedRunId = null) {
const streamId = makeId("stream");
const responseId = makeId("resp");
const createdAtVersion = this.sessionVersion;
const session = {
queue: [],
done: true,
error: null,
responseId,
createdAtVersion,
requestedRunId: Number.isFinite(Number(requestedRunId)) ? Number(requestedRunId) : null,
};
if (streamType === "chat") {
session.queue.push({
object: "chat.completion.chunk",
choices: [
{
index: 0,
delta: {
content: MODERATION_SAFE_RESPONSE
}
}
]
});
session.queue.push({
object: "chat.completion.chunk",
choices: [
{
index: 0,
delta: {},
finish_reason: "stop"
}
]
});
} else {
session.queue.push({
type: "response.output_text.delta",
delta: MODERATION_SAFE_RESPONSE
});
session.queue.push({
type: "response.completed",
response: {
id: responseId,
output_text: MODERATION_SAFE_RESPONSE
}
});
}
this.responsesById.set(responseId, MODERATION_SAFE_RESPONSE);
this.streamSessions.set(streamId, session);
return { stream_id: streamId, response_id: responseId };
}
_createSafeChatResponse() {
const responseId = makeId("chatcmpl");
this.responsesById.set(responseId, MODERATION_SAFE_RESPONSE);
return {
id: responseId,
object: "chat.completion",
choices: [
{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: MODERATION_SAFE_RESPONSE
}
}
]
};
}
_createSafeResponsesResponse() {
const responseId = makeId("resp");
this.responsesById.set(responseId, MODERATION_SAFE_RESPONSE);
return {
id: responseId,
object: "response",
output_text: MODERATION_SAFE_RESPONSE,
output: [
{
type: "message",
role: "assistant",
content: [
{
type: "output_text",
text: MODERATION_SAFE_RESPONSE
}
]
}
]
};
}
setActiveRunId(runId) {
const numericRunId = Number(runId);
this.activeRunId = Number.isFinite(numericRunId) ? numericRunId : 0;
}
_ensureActiveRun(runId, context = "request") {
const numericRunId = Number(runId);
if (!Number.isFinite(numericRunId)) {
return;
}
if (numericRunId !== this.activeRunId) {
throw new Error(`Stale ${context} ignored for run ${numericRunId}. Active run is ${this.activeRunId}.`);
}
}
setStatusCallback(callback) {
this.statusCallback = callback;
}
cancelModelLoading() {
console.log('User requested to cancel model loading');
this.modelLoadingCancelled = true;
if (this.modelLoadingAbortController) {
this.modelLoadingAbortController.abort();
}
// Clean up any loading state
this.isLoading = false;
this.usingBasic = true;
this.usingWllama = false;
this.isReady = true;
this._status("ready", `${WIKIPEDIA_MODEL_NAME} ready (user cancelled loading)`);
console.log('Switched to Basic mode after cancellation');
}
async resetSession() {
console.log('[Model Reset] Soft reset - clearing conversation history only');
this.sessionVersion += 1;
this.streamSessions.clear();
this.responsesById.clear();
// Let in-flight generation loops observe the new sessionVersion and unwind.
if (this.activeGenerationTasks.size > 0) {
await Promise.race([
Promise.allSettled(Array.from(this.activeGenerationTasks)),
sleep(1500)
]);
}
// Note: KV cache clearing removed - not needed when doing hard resets
// and not supported in all wllama versions
}
async hardResetSession(options = {}) {
const { skipReinit = false } = options;
console.log('[Model Reset] Hard reset - reloading model');
// Clear any lingering status messages
this._status("loading", "Resetting model...");
await this.resetSession();
// Preserve availability information before reset
const preservedCpuAvailable = this.availableModes.cpu;
// Cancel any ongoing model loading only if actually loading
if (this.isLoading) {
this.modelLoadingCancelled = true;
if (this.modelLoadingAbortController) {
this.modelLoadingAbortController.abort();
}
// Give a moment for the cancellation to be observed
await sleep(100);
}
const currentWllama = this.wllama;
this.wllama = null;
this.isReady = false;
this.isLoading = false;
this.usingWllama = false;
this.usingBasic = false;
// Preserve mode availability knowledge
this.availableModes.cpu = preservedCpuAvailable;
// Clean up wllama
if (currentWllama) {
for (const methodName of ["dispose", "destroy", "unload", "unloadModel", "terminate", "exit"]) {
const method = currentWllama?.[methodName];
if (typeof method === "function") {
await Promise.resolve(method.call(currentWllama)).catch(() => { });
}
}
}
// Only reinitialize if not skipping (default behavior for backward compatibility)
if (!skipReinit) {
await this.initialize(2);
}
}
getCurrentMode() {
if (this.usingBasic) {
return "basic";
}
return "cpu";
}
getAvailableModes() {
return {
cpu: Boolean(this.availableModes.cpu),
basic: Boolean(this.availableModes.basic)
};
}
_activateBasicMode(reason = "Local model unavailable") {
this.usingBasic = true;
this.usingWllama = false;
this.availableModes.basic = true;
this._status("ready", `${WIKIPEDIA_MODEL_NAME} ready (${reason})`);
}
_status(kind, message) {
if (typeof this.statusCallback === "function") {
this.statusCallback({ kind, message });
}
}
async initialize(maxRetries = 3, options = {}) {
const { forceBasic = false } = options;
if (this.isReady) {
return;
}
if (this.isLoading) {
return;
}
this.modelLoadingCancelled = false;
this.modelLoadingAbortController = new AbortController();
this.isLoading = true;
this.initSessionId++;
console.log(`[Initialize] Session ID incremented to ${this.initSessionId}`);
this.availableModes = {
cpu: true,
basic: true
};
// Check hardware requirements before attempting to load model
if (!forceBasic && !this.checkHardwareRequirements()) {
this.availableModes.cpu = false;
this._activateBasicMode("AI model hardware requirements not met");
this.isReady = true;
this.isLoading = false;
return;
}
if (forceBasic) {
this._activateBasicMode("forced fallback mode");
this.isReady = true;
this.isLoading = false;
return;
}
this._status("loading", "Initializing Phi 3.5-mini...");
this.usingBasic = false;
try {
await this._loadWllama(maxRetries);
if (this.modelLoadingCancelled) {
console.log('Wllama loading was cancelled by user');
return;
}
this.usingWllama = true;
this.availableModes.cpu = true;
this.isReady = true;
this.isLoading = false;
} catch (wllamaError) {
if (this.modelLoadingCancelled || (wllamaError.message && wllamaError.message.includes('cancelled by user'))) {
console.log('Wllama loading was cancelled by user');
return;
}
console.error('Wllama initialization failed:', wllamaError);
this.availableModes.cpu = false;
this._activateBasicMode("AI model failed to load");
this.isReady = true;
this.isLoading = false;
}
}
async _loadWllama(maxRetries = 3) {
let lastError = null;
// Capture current session ID to detect stale loads
const currentSessionId = this.initSessionId;
for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
// Check if session changed
if (this.initSessionId !== currentSessionId) {
console.log('Wllama load aborted - session changed');
throw new Error('Session changed during loading');
}
// Check for cancellation before each attempt
if (this.modelLoadingCancelled) {
throw new Error('Loading cancelled by user');
}
try {
this._status("loading", `Loading local model (attempt ${attempt}/${maxRetries})...`);
await this._loadWllamaModel();
// Check if session changed after loading
if (this.initSessionId !== currentSessionId) {
console.log('Wllama load completed but session has changed - discarding result');
throw new Error('Session changed during loading');
}
// Check if cancelled after loading
if (this.modelLoadingCancelled) {
throw new Error('Loading cancelled by user');
}
this._status("ready", "Model ready: Phi 3.5-mini");
return;
} catch (error) {
// If cancelled, rethrow immediately
if (this.modelLoadingCancelled) {
throw error;
}
lastError = error;
this._status("error", `Model load failed on attempt ${attempt}: ${error.message}`);
if (attempt < maxRetries) {
await sleep(1200 * attempt);
}
}
}
throw lastError || new Error("Model initialization failed");
}
async _loadWllamaModel() {
this.wllamaUsedGPU = false;
// Detect GPU vendor and skip WebGPU for known-problematic GPUs
let gpuEnabled = !this.gpuFailed && !!navigator.gpu;
if (gpuEnabled) {
try {
const adapter = await navigator.gpu.requestAdapter();
if (adapter) {
const info = adapter.info ?? await adapter.requestAdapterInfo?.();
const vendor = (info?.vendor || '').toLowerCase();
if (vendor.includes('qualcomm') || vendor.includes('adreno')) {
// Open bug: ggml-org/llama.cpp#23558 — garbled output on Qualcomm WebGPU
console.warn('WebGPU disabled: Qualcomm/Adreno GPU detected. Using CPU.');
gpuEnabled = false;
} else if (vendor.includes('amd') || vendor.includes('advanced micro')) {
// Flashattention bug fixed in wllama 3.2.3+ (llama.cpp PR #23040); app uses 3.1.1
console.warn('WebGPU disabled: AMD GPU detected. Using CPU.');
gpuEnabled = false;
}
} else {
gpuEnabled = false;
}
} catch (e) {
console.warn('Could not query WebGPU adapter info:', e);
gpuEnabled = false;
}
}
const useMultiThread = window.crossOriginIsolated === true;
const availableThreads = navigator.hardwareConcurrency || 4;
const preferredThreads = useMultiThread ? Math.max(1, availableThreads - 2) : 1;
const progressCallback = ({ loaded, total }) => {
if (!total) {
this._status("loading", "Loading Phi 3.5-mini...");
return;
}
const pct = Math.round((loaded / total) * 100);
this._status("loading", `Downloading Phi 3.5-mini: ${pct}%`);
};
const modelRef = { repo: MODEL_REPO, quant: MODEL_QUANT };
const attemptLoad = async (n_gpu_layers, n_threads) => {
if (this.wllama) { try { await this.wllama.exit(); } catch (_) { } this.wllama = null; }
this.wllama = new Wllama(WASM_PATHS);
await this.wllama.loadModelFromHF(modelRef, { n_ctx: 712, n_gpu_layers, n_threads, progressCallback });
};
if (gpuEnabled) {
try {
console.log('Attempting GPU load (32 layers)...');
this._status("loading", "Loading with GPU acceleration...");
await attemptLoad(32, preferredThreads);
this.wllamaUsedGPU = true;
console.log('Model loaded with GPU acceleration.');
return;
} catch (gpuErr) {
console.warn('GPU load failed, falling back to CPU:', gpuErr);
this.wllamaUsedGPU = false;
}
}
if (preferredThreads > 1) {
try {
console.log('Attempting CPU load (multi-thread)...');
this._status("loading", "Loading with CPU (multi-thread)...");
await attemptLoad(0, preferredThreads);
return;
} catch (multiErr) {
console.warn('CPU multi-thread load failed, trying single-thread:', multiErr);
}
}
console.log('Attempting CPU load (single-thread)...');
this._status("loading", "Loading with CPU (single-thread)...");
await attemptLoad(0, 1);
}
/**
* Tears down wllama and reloads the model CPU-only.
* Called when GPU inference produces empty output at runtime.
*/
async _reloadOnCpu() {
console.warn('GPU produced empty response — reloading model on CPU.');
this.gpuFailed = true;
this.wllamaUsedGPU = false;
if (this.wllama) { try { await this.wllama.exit(); } catch (_) { } this.wllama = null; }
const useMultiThread = window.crossOriginIsolated === true;
const preferredThreads = useMultiThread ? Math.max(1, (navigator.hardwareConcurrency || 4) - 2) : 1;
const modelRef = { repo: MODEL_REPO, quant: MODEL_QUANT };
const tryLoad = async (n_threads) => {
if (this.wllama) { try { await this.wllama.exit(); } catch (_) { } this.wllama = null; }
this.wllama = new Wllama(WASM_PATHS);
await this.wllama.loadModelFromHF(modelRef, { n_ctx: 712, n_gpu_layers: 0, n_threads, progressCallback: () => { } });
};
if (preferredThreads > 1) {
try { await tryLoad(preferredThreads); } catch (_) { await tryLoad(1); }
} else {
await tryLoad(1);
}
}
_ensureClient(model) {
if (!this.isReady || (!this.usingBasic && !this.wllama)) {
throw new Error("Model is not ready yet.");
}
if (model !== "phi") {
throw new Error("The model parameter must be 'phi'.");
}
}
_toChatML(messages) {
let prompt = "";
for (const message of messages) {
const role = roleToChatML(message.role);
const content = contentToText(message.content);
prompt += `<|im_start|>${role}\n${content}\n<|im_end|>\n\n`;
}
prompt += "<|im_start|>assistant\n";
return prompt;
}
_buildResponsesMessages(input, instructions, previousResponseId) {
const messages = [];
if (instructions) {
messages.push({ role: "developer", content: String(instructions) });
}
if (previousResponseId && this.responsesById.has(previousResponseId)) {
messages.push({ role: "assistant", content: this.responsesById.get(previousResponseId) });
}
if (Array.isArray(input)) {
for (const message of input) {
messages.push({
role: String(message.role || "user"),
content: contentToText(message.content)
});
}
} else {
messages.push({ role: "user", content: contentToText(input) });
}
return messages;
}
async _complete(messagesOrPrompt, onDelta, expectedSessionVersion = this.sessionVersion) {
if (this.usingBasic) {
const messages = Array.isArray(messagesOrPrompt)
? messagesOrPrompt
: this._parseChatMLToMessages(messagesOrPrompt);
const userMessages = messages.filter((message) => String(message?.role || "") === "user");
const latestUserText = contentToText(userMessages[userMessages.length - 1]?.content || "");
const summary = await this._generateWithWikipedia(latestUserText);
if (summary && typeof onDelta === "function") {
onDelta(summary);
}
return String(summary || "").trim();
}
const messages = Array.isArray(messagesOrPrompt) ? messagesOrPrompt : this._parseChatMLToMessages(messagesOrPrompt);
return await this._completeWithWllama(messages, onDelta, expectedSessionVersion);
}
async _completeWithWllama(messages, onDelta, expectedSessionVersion = this.sessionVersion) {
const useStreaming = typeof onDelta === "function";
console.log(`[wllama] Phi 3.5-mini (${useStreaming ? "stream" : "sync"}):`, messages);
if (useStreaming) {
let fullText = "";
const completion = await this.wllama.createChatCompletion({
messages,
max_tokens: 512,
temperature: 0.2,
top_k: 30,
top_p: 0.85,
repeat_penalty: 1.1,
repeat_last_n: 64,
cache_prompt: false,
stream: true
});
for await (const chunk of completion) {
if (expectedSessionVersion !== this.sessionVersion) break;
const token = chunk.choices?.[0]?.delta?.content ?? '';
if (token) {
fullText += token;
onDelta(token);
}
}
const trimmed = fullText.trim();
if (!trimmed && this.wllamaUsedGPU && !this.gpuFailed) {
await this._reloadOnCpu();
return await this._completeWithWllama(messages, onDelta, expectedSessionVersion);
}
return trimmed;
}
// Non-streaming: single completion call, returns when fully generated
const result = await this.wllama.createChatCompletion({
messages,
max_tokens: 512,
temperature: 0.2,
top_k: 30,
top_p: 0.85,
repeat_penalty: 1.1,
repeat_last_n: 64,
cache_prompt: false,
stream: false
});
const text = String(result?.choices?.[0]?.message?.content ?? '').trim();
if (!text && this.wllamaUsedGPU && !this.gpuFailed) {
await this._reloadOnCpu();
return await this._completeWithWllama(messages, onDelta, expectedSessionVersion);
}
return text;
}
_parseChatMLToMessages(chatMLPrompt) {
// Simple parser to convert ChatML back to messages array
const messages = [];
const pattern = /<\|im_start\|>(system|user|assistant)\n([\s\S]*?)<\|im_end\|>/g;
let match;
while ((match = pattern.exec(chatMLPrompt)) !== null) {
const role = match[1];
const content = match[2].trim();
messages.push({ role, content });
}
return messages;
}
_extractPreviousAssistantFromMessages(messages) {
if (!Array.isArray(messages)) {
return "";
}
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (!message || String(message.role || "") !== "assistant") {
continue;
}
const text = contentToText(message.content).trim();
if (text) {
return text;
}
}
return "";
}
_appendPreviousResponseNote(outputText, previousText) {
const current = String(outputText || "").trim();
const priorRaw = String(previousText || "").trim();
const prior = this._stripPreviousResponseNote(priorRaw);
if (!current || !prior) {
return current;
}
return `${current}\n\n(Previous response: ${prior})`;
}
_stripPreviousResponseNote(text) {
const value = String(text || "");
if (!value) {
return "";
}
const marker = "\n(Previous response:";
const markerIndex = value.indexOf(marker);
if (markerIndex === -1) {
return value.trim();
}