-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebllm-engine.ts
More file actions
255 lines (219 loc) Β· 7.39 KB
/
webllm-engine.ts
File metadata and controls
255 lines (219 loc) Β· 7.39 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
// WebLLM Engine - Local AI inference in the browser
// Supports WebGPU (fast) with automatic fallback to CPU/WASM (slower)
import * as webllm from '@mlc-ai/web-llm';
import { probeActualLimits, getWebGPUConfig } from './gpu-limits';
/**
* Get all available model IDs from the current WebLLM version
*/
export function getAvailableModelIds(): string[] {
try {
const models = webllm.prebuiltAppConfig.model_list.map((model) => model.model_id);
console.log('π Available WebLLM models:', models);
return models;
} catch (error) {
console.error('Failed to get available models:', error);
return [];
}
}
export interface GenerationOptions {
temperature?: number;
maxTokens?: number;
topP?: number;
onStream?: (chunk: string) => void;
}
export interface ProgressCallback {
(progress: number, status: string): void;
}
/**
* WebLLM Engine for local AI inference
* Automatically uses WebGPU if available, falls back to WASM/CPU
*/
export class WebLLMEngine {
private engine: webllm.MLCEngine | null = null;
private modelName: string = '';
private isInitialized: boolean = false;
private backend: 'webgpu' | 'wasm' = 'wasm';
constructor() {
console.log('π€ WebLLM Engine created');
}
/**
* Initialize the WebLLM engine with a specific model
* IMPORTANT: WebLLM 0.2.80 REQUIRES WebGPU - no CPU/WASM fallback
* This will throw an error if WebGPU is not available
*/
async initialize(
modelName: string,
onProgress?: ProgressCallback
): Promise<void> {
if (this.isInitialized && this.modelName === modelName) {
console.log('β
WebLLM already initialized with', modelName);
return;
}
try {
console.log('π Initializing WebLLM with model:', modelName);
onProgress?.(0, 'Inicializando WebLLM...');
// Probe actual GPU limits
const gpuLimits = await probeActualLimits();
if (!gpuLimits) {
throw new Error('WebGPU is required for WebLLM but is not available');
}
this.backend = 'webgpu';
console.log('β
WebGPU available, using GPU backend');
console.log(`π― GPU Tier: ${gpuLimits.tier.toUpperCase()}`);
onProgress?.(10, 'Usando backend: GPU (WebGPU)');
// Get optimal WebGPU configuration based on GPU tier
const webgpuConfig = getWebGPUConfig(gpuLimits.tier);
console.log('βοΈ WebGPU config:', webgpuConfig);
// Create MLCEngine instance - requires WebGPU
this.engine = new webllm.MLCEngine();
onProgress?.(20, `Cargando modelo ${modelName}...`);
// Load the model with optimized configuration
console.log(`π₯ Downloading WebLLM model: ${modelName}`);
await this.engine.reload(modelName, {
context_window_size: webgpuConfig.max_window_size,
// @ts-ignore - advanced options
max_batch_size: webgpuConfig.max_batch_size,
// @ts-ignore - initProgressCallback exists but might not be in types
initProgressCallback: (report: webllm.InitProgressReport) => {
const progress = Math.round(report.progress * 70) + 20; // 20-90%
const status = report.text || 'Cargando...';
onProgress?.(progress, status);
console.log(`[WebLLM] ${Math.round(report.progress * 100)}% - ${status}`);
},
});
console.log('β
WebLLM model loaded successfully');
// WARM-UP: Generate 1 token to initialize GPU pipeline
console.log('π₯ Warming up GPU pipeline...');
onProgress?.(95, 'Calentando modelo...');
await this.engine.chat.completions.create({
messages: [{ role: 'user', content: 'Hi' }],
max_tokens: 1,
temperature: 0.7,
});
console.log('β
Model warmed up, ready for inference');
this.modelName = modelName;
this.isInitialized = true;
console.log(`β
WebLLM initialized successfully with ${this.backend.toUpperCase()}`);
onProgress?.(100, 'Modelo listo (GPU)');
} catch (error) {
console.error('β Failed to initialize WebLLM:', error);
this.isInitialized = false;
throw new Error(
`Failed to initialize WebLLM: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/**
* Generate embeddings for a text (for semantic search)
* NOTE: WebLLM doesn't support embeddings
* This method should NOT be called - use WllamaEngine instead
*/
async generateEmbedding(text: string): Promise<number[]> {
throw new Error(
'WebLLM does not support embeddings. Use WllamaEngine for embeddings instead.'
);
}
/**
* Generate text response using WebLLM
* Supports streaming for better UX
*/
async generateText(
prompt: string,
options: GenerationOptions = {}
): Promise<string> {
if (!this.isInitialized || !this.engine) {
throw new Error('WebLLM engine not initialized');
}
const {
temperature = 0.7,
maxTokens = 512,
topP = 0.95,
onStream,
} = options;
try {
console.log('π¬ Generating text with WebLLM...');
if (onStream) {
// Streaming mode
let fullResponse = '';
const completion = await this.engine.chat.completions.create({
messages: [{ role: 'user', content: prompt }],
temperature,
max_tokens: maxTokens,
top_p: topP,
stream: true,
});
for await (const chunk of completion) {
const content = chunk.choices[0]?.delta?.content || '';
if (content) {
fullResponse += content;
onStream(content);
}
}
console.log('β
Generated', fullResponse.length, 'characters');
return fullResponse;
} else {
// Non-streaming mode
const response = await this.engine.chat.completions.create({
messages: [{ role: 'user', content: prompt }],
temperature,
max_tokens: maxTokens,
top_p: topP,
stream: false,
});
const generatedText = response.choices[0]?.message?.content || '';
console.log('β
Generated', generatedText.length, 'characters');
return generatedText;
}
} catch (error) {
console.error('β Text generation failed:', error);
throw new Error(
`Failed to generate text: ${error instanceof Error ? error.message : 'Unknown error'}`
);
}
}
/**
* Get the current backend being used
*/
getBackend(): 'webgpu' | 'wasm' {
return this.backend;
}
/**
* Check if the engine is initialized
*/
isReady(): boolean {
return this.isInitialized && this.engine !== null;
}
/**
* Get the current model name
*/
getModelName(): string {
return this.modelName;
}
/**
* Reset/unload the model (free memory)
*/
async reset(): Promise<void> {
if (this.engine) {
console.log('π Resetting WebLLM engine...');
// WebLLM doesn't have an explicit unload, but we can recreate the engine
this.engine = null;
this.isInitialized = false;
this.modelName = '';
console.log('β
WebLLM engine reset');
}
}
/**
* Get runtime statistics (if available)
*/
async getRuntimeStats(): Promise<any> {
if (!this.engine) return null;
try {
// @ts-ignore - runtimeStatsText might not be in types
const stats = await this.engine.runtimeStatsText?.();
return stats;
} catch (error) {
console.warn('Could not get runtime stats:', error);
return null;
}
}
}