-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathwebllm.ts
224 lines (201 loc) · 6.07 KB
/
webllm.ts
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
"use client";
import log from "loglevel";
import { createContext } from "react";
import {
InitProgressReport,
prebuiltAppConfig,
ChatCompletionMessageParam,
ServiceWorkerMLCEngine,
ChatCompletionChunk,
ChatCompletion,
WebWorkerMLCEngine,
CompletionUsage,
ChatCompletionFinishReason,
} from "@mlc-ai/web-llm";
import { ChatOptions, LLMApi, LLMConfig, RequestMessage } from "./api";
import { LogLevel } from "@mlc-ai/web-llm";
import { fixMessage } from "../utils";
import { DEFAULT_MODELS } from "../constant";
const KEEP_ALIVE_INTERVAL = 5_000;
type ServiceWorkerWebLLMHandler = {
type: "serviceWorker";
engine: ServiceWorkerMLCEngine;
};
type WebWorkerWebLLMHandler = {
type: "webWorker";
engine: WebWorkerMLCEngine;
};
type WebLLMHandler = ServiceWorkerWebLLMHandler | WebWorkerWebLLMHandler;
export class WebLLMApi implements LLMApi {
private llmConfig?: LLMConfig;
private initialized = false;
webllm: WebLLMHandler;
constructor(
type: "serviceWorker" | "webWorker",
logLevel: LogLevel = "WARN",
) {
const engineConfig = {
appConfig: {
...prebuiltAppConfig,
useIndexedDBCache: this.llmConfig?.cache === "index_db",
},
logLevel,
};
if (type === "serviceWorker") {
log.info("Create ServiceWorkerMLCEngine");
this.webllm = {
type: "serviceWorker",
engine: new ServiceWorkerMLCEngine(engineConfig, KEEP_ALIVE_INTERVAL),
};
} else {
log.info("Create WebWorkerMLCEngine");
this.webllm = {
type: "webWorker",
engine: new WebWorkerMLCEngine(
new Worker(new URL("../worker/web-worker.ts", import.meta.url), {
type: "module",
}),
engineConfig,
),
};
}
}
private async initModel(onUpdate?: (message: string, chunk: string) => void) {
if (!this.llmConfig) {
throw Error("llmConfig is undefined");
}
this.webllm.engine.setInitProgressCallback((report: InitProgressReport) => {
onUpdate?.(report.text, report.text);
});
await this.webllm.engine.reload(this.llmConfig.model, this.llmConfig);
this.initialized = true;
}
async chat(options: ChatOptions): Promise<void> {
if (!this.initialized || this.isDifferentConfig(options.config)) {
this.llmConfig = { ...(this.llmConfig || {}), ...options.config };
try {
await this.initModel(options.onUpdate);
} catch (err: any) {
let errorMessage = err.message || err.toString() || "";
if (errorMessage === "[object Object]") {
errorMessage = JSON.stringify(err);
}
console.error("Error while initializing the model", errorMessage);
options?.onError?.(errorMessage);
return;
}
}
let reply: string | null = "";
let stopReason: ChatCompletionFinishReason | undefined;
let usage: CompletionUsage | undefined;
try {
const completion = await this.chatCompletion(
!!options.config.stream,
options.messages,
options.onUpdate,
);
reply = completion.content;
stopReason = completion.stopReason;
usage = completion.usage;
} catch (err: any) {
let errorMessage = err.message || err.toString() || "";
if (errorMessage === "[object Object]") {
log.error(JSON.stringify(err));
errorMessage = JSON.stringify(err);
}
console.error("Error in chatCompletion", errorMessage);
if (
errorMessage.includes("WebGPU") &&
errorMessage.includes("compatibility chart")
) {
// Add WebGPU compatibility chart link
errorMessage = errorMessage.replace(
"compatibility chart",
"[compatibility chart](https://caniuse.com/webgpu)",
);
}
options.onError?.(errorMessage);
return;
}
if (reply) {
reply = fixMessage(reply);
options.onFinish(reply, stopReason, usage);
} else {
options.onError?.(new Error("Empty response generated by LLM"));
}
}
async abort() {
await this.webllm.engine?.interruptGenerate();
}
private isDifferentConfig(config: LLMConfig): boolean {
if (!this.llmConfig) {
return true;
}
// Compare required fields
if (this.llmConfig.model !== config.model) {
return true;
}
// Compare optional fields
const optionalFields: (keyof LLMConfig)[] = [
"temperature",
"context_window_size",
"top_p",
"stream",
"presence_penalty",
"frequency_penalty",
];
for (const field of optionalFields) {
if (
this.llmConfig[field] !== undefined &&
config[field] !== undefined &&
config[field] !== config[field]
) {
return true;
}
}
return false;
}
async chatCompletion(
stream: boolean,
messages: RequestMessage[],
onUpdate?: (
message: string,
chunk: string,
usage?: CompletionUsage,
) => void,
) {
const completion = await this.webllm.engine.chatCompletion({
stream: stream,
messages: messages as ChatCompletionMessageParam[],
...(stream ? { stream_options: { include_usage: true } } : {}),
});
if (stream) {
let content: string | null = "";
let stopReason: ChatCompletionFinishReason | undefined;
let usage: CompletionUsage | undefined;
const asyncGenerator = completion as AsyncIterable<ChatCompletionChunk>;
for await (const chunk of asyncGenerator) {
if (chunk.choices[0]?.delta.content) {
content += chunk.choices[0].delta.content;
onUpdate?.(content, chunk.choices[0].delta.content);
}
if (chunk.usage) {
usage = chunk.usage;
}
if (chunk.choices[0]?.finish_reason) {
stopReason = chunk.choices[0].finish_reason;
}
}
return { content, stopReason, usage };
}
const chatCompletion = completion as ChatCompletion;
return {
content: chatCompletion.choices[0].message.content,
stopReason: chatCompletion.choices[0].finish_reason,
usage: chatCompletion.usage,
};
}
async models() {
return DEFAULT_MODELS;
}
}