File size: 8,935 Bytes
1d3f990
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * WebLLM Engine

 * Browser-native model inference with WebGPU acceleration

 */

class WebLLMEngine {
    constructor(options = {}) {
        this.status = 'OFFLINE';
        this.model = options.model || 'TinyLlama-1.1B-Chat-v0.4-q4f16_1-1k';
        this.temperature = options.temperature || 0.2;
        this.topP = options.topP || 0.9;
        this.maxTokens = options.maxTokens || 256;

        this.engine = null;
        this.isLoading = false;
        this.isGenerating = false;
        this.abortController = null;

        this.supportedModels = [
            { id: 'TinyLlama-1.1B-Chat-v0.4-q4f16_1-1k', name: 'TinyLlama 1.1B' },
            { id: 'Mistral-7B-Instruct-v0.2-q4f16_1-MLC', name: 'Mistral 7B' },
            { id: 'Llama-2-7b-chat-hf-q4f32_1-MLC', name: 'Llama 2 7B' },
        ];

        this.conversationHistory = [];
        this.maxHistoryLength = 10;
    }

    /**

     * Initialize WebLLM engine

     */
    async initialize() {
        if (this.status === 'READY' || this.isLoading) {
            return;
        }

        this.isLoading = true;
        this.status = 'LOADING';
        this.emit('statusChanged', 'LOADING');

        try {
            // Check WebLLM availability
            if (typeof window.webllm === 'undefined') {
                throw new Error('WebLLM not loaded. Include @mlc-ai/web-llm script.');
            }

            // Detect WebGPU support
            const hasWebGPU = !!(navigator.gpu);
            console.log(`WebGPU available: ${hasWebGPU}`);

            // Initialize engine
            const webllm = window.webllm;
            this.engine = new webllm.Engine({
                model: this.model,
                useWebGPU: hasWebGPU,
                maxSequenceLength: 4096,
            });

            await this.engine.forward('');

            this.status = 'READY';
            this.isLoading = false;
            this.emit('statusChanged', 'READY');
            console.log(`WebLLM engine initialized: ${this.model}`);
        } catch (error) {
            this.status = 'ERROR';
            this.isLoading = false;
            this.emit('statusChanged', 'ERROR');
            this.emit('error', error.message);
            console.error('WebLLM initialization failed:', error);
            throw error;
        }
    }

    /**

     * Generate response with streaming

     */
    async generateResponse(userMessage, systemPrompt = '') {
        if (this.status !== 'READY' || !this.engine) {
            throw new Error('Engine not ready');
        }

        if (this.isGenerating) {
            throw new Error('Generation already in progress');
        }

        this.isGenerating = true;
        this.status = 'GENERATING';
        this.emit('statusChanged', 'GENERATING');
        this.emit('generationStart');

        this.abortController = new AbortController();
        let fullResponse = '';

        try {
            // Build conversation
            const messages = this.buildConversation(userMessage, systemPrompt);

            // Stream generation
            const generator = await this.engine.generate(messages, {
                temperature: this.temperature,
                top_p: this.topP,
                max_new_tokens: this.maxTokens,
            });

            for await (const token of generator) {
                if (this.abortController.signal.aborted) {
                    break;
                }

                fullResponse += token;
                this.emit('token', token);
            }

            // Add to conversation history
            this.addToHistory({
                role: 'user',
                content: userMessage,
            });

            this.addToHistory({
                role: 'assistant',
                content: fullResponse,
            });

            this.status = 'READY';
            this.emit('statusChanged', 'READY');
            this.emit('generationComplete', fullResponse);

            return fullResponse;
        } catch (error) {
            if (error.name !== 'AbortError') {
                this.status = 'ERROR';
                this.emit('statusChanged', 'ERROR');
                this.emit('error', error.message);
                console.error('Generation failed:', error);
                throw error;
            }
        } finally {
            this.isGenerating = false;
        }
    }

    /**

     * Build conversation history for API

     */
    buildConversation(userMessage, systemPrompt) {
        const messages = [];

        if (systemPrompt) {
            messages.push({
                role: 'system',
                content: systemPrompt,
            });
        }

        // Add conversation history (bounded)
        for (const msg of this.conversationHistory.slice(-this.maxHistoryLength)) {
            messages.push(msg);
        }

        // Add current message
        messages.push({
            role: 'user',
            content: userMessage,
        });

        return messages;
    }

    /**

     * Add message to history

     */
    addToHistory(message) {
        this.conversationHistory.push(message);

        // Trim history to max length
        if (this.conversationHistory.length > this.maxHistoryLength * 2) {
            this.conversationHistory = this.conversationHistory.slice(-this.maxHistoryLength);
        }
    }

    /**

     * Stop current generation

     */
    stopGeneration() {
        if (this.abortController) {
            this.abortController.abort();
            this.isGenerating = false;
            this.status = 'READY';
            this.emit('statusChanged', 'READY');
            this.emit('generationStopped');
        }
    }

    /**

     * Clear conversation history

     */
    clearHistory() {
        this.conversationHistory = [];
        this.emit('historyCleared');
    }

    /**

     * Change temperature

     */
    setTemperature(temp) {
        this.temperature = Math.max(0, Math.min(2, temp));
    }

    /**

     * Change top-p

     */
    setTopP(p) {
        this.topP = Math.max(0, Math.min(1, p));
    }

    /**

     * Change max tokens

     */
    setMaxTokens(tokens) {
        this.maxTokens = Math.max(1, Math.min(2048, tokens));
    }

    /**

     * Get current settings

     */
    getSettings() {
        return {
            model: this.model,
            temperature: this.temperature,
            topP: this.topP,
            maxTokens: this.maxTokens,
            status: this.status,
        };
    }

    /**

     * Get supported models

     */
    getSupportedModels() {
        return this.supportedModels;
    }

    /**

     * Switch model

     */
    async switchModel(modelId) {
        if (this.isGenerating) {
            throw new Error('Cannot switch model while generating');
        }

        const supported = this.supportedModels.some(m => m.id === modelId);
        if (!supported) {
            throw new Error(`Model not supported: ${modelId}`);
        }

        this.model = modelId;
        this.status = 'OFFLINE';

        // Reset engine to force re-initialization
        this.engine = null;
        this.emit('statusChanged', 'OFFLINE');
    }

    /**

     * Event emitter

     */
    listeners = {};

    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
    }

    off(event, callback) {
        if (this.listeners[event]) {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        }
    }

    emit(event, data) {
        if (this.listeners[event]) {
            for (const callback of this.listeners[event]) {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`Error in listener for ${event}:`, error);
                }
            }
        }
    }

    /**

     * Check WebGPU support

     */
    static hasWebGPU() {
        return !!navigator.gpu;
    }

    /**

     * Check WebLLM availability

     */
    static hasWebLLM() {
        return typeof window.webllm !== 'undefined';
    }

    /**

     * Estimate download size

     */
    estimateModelSize(modelId) {
        const sizes = {
            'TinyLlama-1.1B-Chat-v0.4-q4f16_1-1k': '600MB',
            'Mistral-7B-Instruct-v0.2-q4f16_1-MLC': '4GB',
            'Llama-2-7b-chat-hf-q4f32_1-MLC': '8GB',
        };
        return sizes[modelId] || 'Unknown';
    }
}

// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = WebLLMEngine;
}