-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebllm_setup.js
More file actions
277 lines (236 loc) · 8.63 KB
/
webllm_setup.js
File metadata and controls
277 lines (236 loc) · 8.63 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
// WebLLM Setup and Management
// This file handles the setup and management of WebLLM for browser-based AI
class WebLLMSetup {
constructor() {
this.engine = null;
this.initialized = false;
this.models = [
{
name: 'Llama-2-7b-chat-hf-q4f32_1',
size: '4.0GB',
description: 'Llama 2 7B Chat (Quantized)',
recommended: true
},
{
name: 'TinyLlama-1.1B-Chat-v0.4-q4f32_1',
size: '0.6GB',
description: 'TinyLlama 1.1B (Fast, smaller model)',
recommended: false
},
{
name: 'Mistral-7B-Instruct-v0.1-q4f32_1',
size: '4.0GB',
description: 'Mistral 7B Instruct',
recommended: false
}
];
}
async checkWebLLMSupport() {
// Check if browser supports WebLLM
const checks = {
webgpu: await this.checkWebGPU(),
wasmThreads: this.checkWasmThreads(),
sharedArrayBuffer: this.checkSharedArrayBuffer(),
bigInt64Array: this.checkBigInt64Array()
};
console.log('WebLLM Support Check:', checks);
return Object.values(checks).every(Boolean);
}
async checkWebGPU() {
if (!navigator.gpu) {
console.log('❌ WebGPU not supported');
return false;
}
try {
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
console.log('❌ WebGPU adapter not available');
return false;
}
console.log('✅ WebGPU supported');
return true;
} catch (error) {
console.log('❌ WebGPU error:', error);
return false;
}
}
checkWasmThreads() {
try {
return typeof SharedArrayBuffer !== 'undefined' &&
typeof WebAssembly.Memory !== 'undefined';
} catch (error) {
return false;
}
}
checkSharedArrayBuffer() {
return typeof SharedArrayBuffer !== 'undefined';
}
checkBigInt64Array() {
return typeof BigInt64Array !== 'undefined';
}
async initialize(modelName = null, onProgress = null) {
if (this.initialized) {
return this.engine;
}
const isSupported = await this.checkWebLLMSupport();
if (!isSupported) {
throw new Error('WebLLM not supported in this browser');
}
try {
// Use the recommended model if none specified
const selectedModel = modelName || this.getRecommendedModel();
console.log(`🧠 Initializing WebLLM with model: ${selectedModel}`);
// Import WebLLM
if (typeof window.webllm === 'undefined') {
await this.loadWebLLMScript();
}
const { CreateWebWorkerMLCEngine } = window.webllm;
// Create the engine
this.engine = await CreateWebWorkerMLCEngine(
new Worker(this.createWorkerBlob()),
selectedModel,
{
initProgressCallback: (progress) => {
const percent = Math.round(progress.progress * 100);
console.log(`WebLLM Loading: ${percent}% - ${progress.text}`);
if (onProgress) {
onProgress(percent, progress.text);
}
}
}
);
this.initialized = true;
console.log('✅ WebLLM initialized successfully');
return this.engine;
} catch (error) {
console.error('❌ WebLLM initialization failed:', error);
throw error;
}
}
async loadWebLLMScript() {
return new Promise((resolve, reject) => {
if (typeof window.webllm !== 'undefined') {
resolve();
return;
}
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.19/lib/index.js';
script.onload = resolve;
script.onerror = () => reject(new Error('Failed to load WebLLM script'));
document.head.appendChild(script);
});
}
createWorkerBlob() {
const workerCode = `
importScripts('https://cdn.jsdelivr.net/npm/@mlc-ai/web-llm@0.2.19/lib/webllm.min.js');
let engine;
self.addEventListener('message', async (event) => {
const { type, data } = event.data;
try {
switch (type) {
case 'init':
engine = new self.webllm.WebWorkerMLCEngine();
await engine.reload(data.modelId, data.chatConfig);
self.postMessage({ type: 'init_complete' });
break;
case 'chat':
if (!engine) {
throw new Error('Engine not initialized');
}
const response = await engine.chat.completions.create(data.messages);
self.postMessage({ type: 'chat_response', data: response });
break;
case 'generate':
if (!engine) {
throw new Error('Engine not initialized');
}
const generation = await engine.generate(data.prompt, data.options);
self.postMessage({ type: 'generate_response', data: generation });
break;
default:
throw new Error('Unknown message type: ' + type);
}
} catch (error) {
self.postMessage({ type: 'error', error: error.message });
}
});
`;
const blob = new Blob([workerCode], { type: 'application/javascript' });
return URL.createObjectURL(blob);
}
getRecommendedModel() {
const recommended = this.models.find(m => m.recommended);
return recommended ? recommended.name : this.models[0].name;
}
getAvailableModels() {
return this.models;
}
async generateText(prompt, options = {}) {
if (!this.engine) {
throw new Error('WebLLM not initialized');
}
const defaultOptions = {
max_tokens: 200,
temperature: 0.7,
top_p: 0.9,
...options
};
try {
const response = await this.engine.chat.completions.create({
messages: [
{ role: 'user', content: prompt }
],
...defaultOptions
});
return response.choices[0].message.content;
} catch (error) {
console.error('WebLLM generation error:', error);
throw error;
}
}
async generateChat(messages, options = {}) {
if (!this.engine) {
throw new Error('WebLLM not initialized');
}
const defaultOptions = {
max_tokens: 200,
temperature: 0.7,
...options
};
try {
const response = await this.engine.chat.completions.create({
messages,
...defaultOptions
});
return response.choices[0].message.content;
} catch (error) {
console.error('WebLLM chat error:', error);
throw error;
}
}
getStatus() {
return {
initialized: this.initialized,
engine: !!this.engine,
supported: true // We check this during initialization
};
}
async unload() {
if (this.engine) {
try {
await this.engine.unload();
this.engine = null;
this.initialized = false;
console.log('✅ WebLLM unloaded successfully');
} catch (error) {
console.error('❌ WebLLM unload error:', error);
}
}
}
}
// Export for use in main application
if (typeof module !== 'undefined' && module.exports) {
module.exports = WebLLMSetup;
} else {
window.WebLLMSetup = WebLLMSetup;
}