1
1
import appConfig from "./app-config" ;
2
- import { ChatModule , ModelRecord } from "@mlc-ai/web-llm" ;
2
+ import { ChatInterface , ChatModule , ChatWorkerClient , ModelRecord } from "@mlc-ai/web-llm" ;
3
3
4
4
function getElementAndCheck ( id : string ) : HTMLElement {
5
5
const element = document . getElementById ( id ) ;
@@ -18,7 +18,7 @@ class ChatUI {
18
18
private uiChat : HTMLElement ;
19
19
private uiChatInput : HTMLInputElement ;
20
20
private uiChatInfoLabel : HTMLLabelElement ;
21
- private chat : ChatModule ;
21
+ private chat : ChatInterface ;
22
22
private config : AppConfig = appConfig ;
23
23
private selectedModel : string ;
24
24
private chatLoaded = false ;
@@ -27,8 +27,9 @@ class ChatUI {
27
27
// all requests send to chat are sequentialized
28
28
private chatRequestChain : Promise < void > = Promise . resolve ( ) ;
29
29
30
- constructor ( ) {
31
- this . chat = new ChatModule ( ) ;
30
+ constructor ( chat : ChatInterface ) {
31
+ // use web worker to run chat generation in background
32
+ this . chat = chat ;
32
33
// get the elements
33
34
this . uiChat = getElementAndCheck ( "chatui-chat" ) ;
34
35
this . uiChatInput = getElementAndCheck ( "chatui-input" ) as HTMLInputElement ;
@@ -156,9 +157,10 @@ class ChatUI {
156
157
private resetChatHistory ( ) {
157
158
const clearTags = [ "left" , "right" , "init" , "error" ] ;
158
159
for ( const tag of clearTags ) {
159
- const matches = this . uiChat . getElementsByClassName ( `msg ${ tag } -msg` ) ;
160
+ // need to unpack to list so the iterator don't get affected by mutation
161
+ const matches = [ ...this . uiChat . getElementsByClassName ( `msg ${ tag } -msg` ) ] ;
160
162
for ( const item of matches ) {
161
- item . remove ( ) ;
163
+ this . uiChat . removeChild ( item ) ;
162
164
}
163
165
}
164
166
if ( this . uiChatInfoLabel !== undefined ) {
@@ -211,11 +213,6 @@ class ChatUI {
211
213
212
214
this . appendMessage ( "left" , "" ) ;
213
215
const callbackUpdateResponse = ( step , msg ) => {
214
- if ( msg . endsWith ( "##" ) ) {
215
- msg = msg . substring ( 0 , msg . length - 2 ) ;
216
- } else if ( msg . endsWith ( "#" ) ) {
217
- msg = msg . substring ( 0 , msg . length - 1 ) ;
218
- }
219
216
this . updateLastMessage ( "left" , msg ) ;
220
217
} ;
221
218
@@ -233,4 +230,15 @@ class ChatUI {
233
230
}
234
231
}
235
232
236
- new ChatUI ( ) ;
233
+ const useWebWorker = appConfig . use_web_worker ;
234
+ let chat : ChatInterface ;
235
+
236
+ if ( useWebWorker ) {
237
+ chat = new ChatWorkerClient ( new Worker (
238
+ new URL ( './worker.ts' , import . meta. url ) ,
239
+ { type : 'module' }
240
+ ) ) ;
241
+ } else {
242
+ chat = new ChatModule ( ) ;
243
+ }
244
+ new ChatUI ( chat ) ;
0 commit comments