-
Notifications
You must be signed in to change notification settings - Fork 961
/
Copy pathchat_ui.ts
155 lines (145 loc) · 4.67 KB
/
chat_ui.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
import {
MLCEngineInterface,
ChatCompletionMessageParam,
CompletionUsage,
} from "@mlc-ai/web-llm";
export default class ChatUI {
private engine: MLCEngineInterface;
private chatLoaded = false;
private requestInProgress = false;
// We use a request chain to ensure that
// all requests send to chat are sequentialized
private chatRequestChain: Promise<void> = Promise.resolve();
private chatHistory: ChatCompletionMessageParam[] = [];
constructor(engine: MLCEngineInterface) {
this.engine = engine;
}
/**
* Push a task to the execution queue.
*
* @param task The task to be executed;
*/
private pushTask(task: () => Promise<void>) {
const lastEvent = this.chatRequestChain;
this.chatRequestChain = lastEvent.then(task);
}
// Event handlers
// all event handler pushes the tasks to a queue
// that get executed sequentially
// the tasks previous tasks, which causes them to early stop
// can be interrupted by chat.interruptGenerate
async onGenerate(
prompt: string,
messageUpdate: (kind: string, text: string, append: boolean) => void,
setRuntimeStats: (runtimeStats: string) => void,
) {
if (this.requestInProgress) {
return;
}
this.pushTask(async () => {
await this.asyncGenerate(prompt, messageUpdate, setRuntimeStats);
});
return this.chatRequestChain;
}
async onReset(clearMessages: () => void) {
if (this.requestInProgress) {
// interrupt previous generation if any
this.engine.interruptGenerate();
}
this.chatHistory = [];
// try reset after previous requests finishes
this.pushTask(async () => {
await this.engine.resetChat();
clearMessages();
});
return this.chatRequestChain;
}
async asyncInitChat(
messageUpdate: (kind: string, text: string, append: boolean) => void,
) {
if (this.chatLoaded) return;
this.requestInProgress = true;
messageUpdate("init", "", true);
const initProgressCallback = (report: { text: string }) => {
messageUpdate("init", report.text, false);
};
this.engine.setInitProgressCallback(initProgressCallback);
try {
const selectedModel = "Llama-3.1-8B-Instruct-q4f32_1-MLC";
// const selectedModel = "TinyLlama-1.1B-Chat-v0.4-q4f16_1-MLC-1k";
await this.engine.reload(selectedModel);
} catch (err: unknown) {
messageUpdate("error", "Init error, " + (err?.toString() ?? ""), true);
console.log(err);
await this.unloadChat();
this.requestInProgress = false;
return;
}
this.requestInProgress = false;
this.chatLoaded = true;
}
private async unloadChat() {
await this.engine.unload();
this.chatLoaded = false;
}
/**
* Run generate
*/
private async asyncGenerate(
prompt: string,
messageUpdate: (kind: string, text: string, append: boolean) => void,
setRuntimeStats: (runtimeStats: string) => void,
) {
await this.asyncInitChat(messageUpdate);
this.requestInProgress = true;
// const prompt = this.uiChatInput.value;
if (prompt == "") {
this.requestInProgress = false;
return;
}
messageUpdate("right", prompt, true);
// this.uiChatInput.value = "";
// this.uiChatInput.setAttribute("placeholder", "Generating...");
messageUpdate("left", "", true);
try {
this.chatHistory.push({ role: "user", content: prompt });
let curMessage = "";
let usage: CompletionUsage | undefined = undefined;
const completion = await this.engine.chat.completions.create({
stream: true,
messages: this.chatHistory,
stream_options: { include_usage: true },
});
for await (const chunk of completion) {
const curDelta = chunk.choices[0]?.delta.content;
if (curDelta) {
curMessage += curDelta;
}
messageUpdate("left", curMessage, false);
if (chunk.usage) {
usage = chunk.usage;
}
}
const output = await this.engine.getMessage();
this.chatHistory.push({ role: "assistant", content: output });
messageUpdate("left", output, false);
if (usage) {
const runtimeStats =
`prompt_tokens: ${usage.prompt_tokens}, ` +
`completion_tokens: ${usage.completion_tokens}, ` +
`prefill: ${usage.extra.prefill_tokens_per_s.toFixed(4)} tokens/sec, ` +
`decoding: ${usage.extra.decode_tokens_per_s.toFixed(4)} tokens/sec`;
setRuntimeStats(runtimeStats);
}
} catch (err: unknown) {
messageUpdate(
"error",
"Generate error, " + (err?.toString() ?? ""),
true,
);
console.log(err);
await this.unloadChat();
}
this.requestInProgress = false;
}
}