-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwebllm-service.js
More file actions
54 lines (44 loc) · 1.32 KB
/
Copy pathwebllm-service.js
File metadata and controls
54 lines (44 loc) · 1.32 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
import * as webllm from "@mlc-ai/web-llm";
export class WebLLMService {
constructor() {
this.engine = null;
// User requested "qwen3.5 0.8b".
// Available MLC models for Qwen2.5 include 0.5B and 1.5B.
// Qwen2.5-0.5B-Instruct-q4f16_1-MLC is the most efficient and reliable choice for this context.
this.selectedModel = "Qwen2.5-0.5B-Instruct-q4f16_1-MLC";
}
async init(onProgress) {
if (this.engine) return;
this.engine = await webllm.CreateMLCEngine(this.selectedModel, {
initProgressCallback: onProgress,
});
}
async chat(messages, options = {}) {
if (!this.engine) {
await this.init();
}
const completion = await this.engine.chat.completions.create({
messages,
...options,
});
return completion.choices[0].message.content;
}
async chatStream(messages, onChunk, options = {}) {
if (!this.engine) {
await this.init();
}
const chunks = await this.engine.chat.completions.create({
messages,
stream: true,
...options,
});
let fullAnswer = "";
for await (const chunk of chunks) {
const content = chunk.choices[0]?.delta?.content || "";
fullAnswer += content;
if (onChunk) onChunk(content, fullAnswer);
}
return fullAnswer;
}
}
export const webLLMService = new WebLLMService();