forked from mlc-ai/web-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb_worker.ts
842 lines (800 loc) · 26 KB
/
web_worker.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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
import { AppConfig, ChatOptions, MLCEngineConfig } from "./config";
import {
MLCEngineInterface,
InitProgressCallback,
InitProgressReport,
LogLevel,
LogitProcessor,
} from "./types";
import {
ChatCompletionRequest,
ChatCompletionRequestBase,
ChatCompletionRequestStreaming,
ChatCompletionRequestNonStreaming,
ChatCompletion,
ChatCompletionChunk,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CompletionCreateParamsBase,
CompletionCreateParams,
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "./openai_api_protocols/index";
import * as API from "./openai_api_protocols/index";
import {
MessageContent,
ReloadParams,
ForwardTokensAndSampleParams,
ChatCompletionNonStreamingParams,
ChatCompletionStreamInitParams,
ResetChatParams,
WorkerResponse,
WorkerRequest,
CompletionNonStreamingParams,
EmbeddingParams,
CompletionStreamInitParams,
GetMessageParams,
RuntimeStatsTextParams,
CompletionStreamNextChunkParams,
} from "./message";
import log from "loglevel";
import { MLCEngine } from "./engine";
import {
UnknownMessageKindError,
WorkerEngineModelNotLoadedError,
} from "./error";
import { areArraysEqual } from "./utils";
import { getModelIdToUse } from "./support";
/**
* Worker handler that can be used in a WebWorker
*
* @example
*
* // setup a chat worker handler that routes
* // requests to the chat
* const engine = new MLCEngine();
* cont handler = new WebWorkerMLCEngineHandler(engine);
* onmessage = handler.onmessage;
*/
export class WebWorkerMLCEngineHandler {
/**
* The modelId and chatOpts that the underlying engine (backend) is currently loaded with.
* An engine can be loaded with multiple models, so modelId and chatOpts are lists.
*
* TODO(webllm-team): This is always in-sync with `this.engine` unless device is lost due to
* unexpected reason. Therefore, we should get it from `this.engine` directly and make handler
* stateless. Besides, consider if we should add appConfig, or use engine's API to find the
* corresponding model record rather than relying on just the modelId.
*/
modelId?: string[];
chatOpts?: ChatOptions[];
public engine: MLCEngine;
/** ChatCompletion and Completion share the same chunk generator. Each loaded model has its own. */
protected loadedModelIdToAsyncGenerator: Map<
string,
AsyncGenerator<ChatCompletionChunk | Completion, void, void>
>;
/**
* @param engine A concrete implementation of MLCEngineInterface
*/
constructor() {
this.engine = new MLCEngine();
this.loadedModelIdToAsyncGenerator = new Map<
string,
AsyncGenerator<ChatCompletionChunk | Completion, void, void>
>();
this.engine.setInitProgressCallback((report: InitProgressReport) => {
const msg: WorkerResponse = {
kind: "initProgressCallback",
uuid: "",
content: report,
};
this.postMessage(msg);
});
}
postMessage(msg: any) {
// Use Web Worker DOM Message API
postMessage(msg);
}
setLogitProcessorRegistry(
logitProcessorRegistry?: Map<string, LogitProcessor>,
) {
this.engine.setLogitProcessorRegistry(logitProcessorRegistry);
}
async handleTask<T extends MessageContent>(
uuid: string,
task: () => Promise<T>,
) {
try {
const res = await task();
const msg: WorkerResponse = {
kind: "return",
uuid: uuid,
content: res,
};
this.postMessage(msg);
} catch (err) {
const errStr = (err as object).toString();
const msg: WorkerResponse = {
kind: "throw",
uuid: uuid,
content: errStr,
};
this.postMessage(msg);
}
}
onmessage(
event: any,
onComplete?: (value: any) => void,
onError?: () => void,
) {
let msg: WorkerRequest;
if (event instanceof MessageEvent) {
msg = event.data as WorkerRequest;
} else {
msg = event as WorkerRequest;
}
switch (msg.kind) {
case "reload": {
this.handleTask(msg.uuid, async () => {
const params = msg.content as ReloadParams;
await this.engine.reload(params.modelId, params.chatOpts);
this.modelId = params.modelId;
this.chatOpts = params.chatOpts;
onComplete?.(null);
return null;
});
return;
}
case "forwardTokensAndSample": {
this.handleTask(msg.uuid, async () => {
const params = msg.content as ForwardTokensAndSampleParams;
const res = await this.engine.forwardTokensAndSample(
params.inputIds,
params.isPrefill,
params.modelId,
);
onComplete?.(res);
return res;
});
return;
}
// For engine.chat.completions.create()
case "chatCompletionNonStreaming": {
// Directly return the ChatCompletion response
this.handleTask(msg.uuid, async () => {
const params = msg.content as ChatCompletionNonStreamingParams;
await this.reloadIfUnmatched(params.modelId, params.chatOpts);
const res = await this.engine.chatCompletion(params.request);
onComplete?.(res);
return res;
});
return;
}
case "chatCompletionStreamInit": {
// One-time set up that instantiates the chunk generator in worker
this.handleTask(msg.uuid, async () => {
const params = msg.content as ChatCompletionStreamInitParams;
// Also ensures params.selectedModelId will match what this.engine selects
await this.reloadIfUnmatched(params.modelId, params.chatOpts);
// Register new async generator for this new request of the model
const curGenerator = (await this.engine.chatCompletion(
params.request,
)) as AsyncGenerator<ChatCompletionChunk, void, void>;
this.loadedModelIdToAsyncGenerator.set(
params.selectedModelId,
curGenerator,
);
onComplete?.(null);
return null;
});
return;
}
// For engine.completions.create()
case "completionNonStreaming": {
// Directly return the ChatCompletion response
this.handleTask(msg.uuid, async () => {
const params = msg.content as CompletionNonStreamingParams;
await this.reloadIfUnmatched(params.modelId, params.chatOpts);
const res = await this.engine.completion(params.request);
onComplete?.(res);
return res;
});
return;
}
case "completionStreamInit": {
// One-time set up that instantiates the chunk generator in worker
this.handleTask(msg.uuid, async () => {
const params = msg.content as CompletionStreamInitParams;
// Also ensures params.selectedModelId will match what this.engine selects
await this.reloadIfUnmatched(params.modelId, params.chatOpts);
// Register new async generator for this new request of the model
const curGenerator = (await this.engine.completion(
params.request,
)) as AsyncGenerator<Completion, void, void>;
this.loadedModelIdToAsyncGenerator.set(
params.selectedModelId,
curGenerator,
);
onComplete?.(null);
return null;
});
return;
}
// Shared by engine.chat.completions.create() and engine.completions.create()
case "completionStreamNextChunk": {
// Note: ChatCompletion and Completion share the same chunk generator.
// For any subsequent request, we return whatever `next()` yields
this.handleTask(msg.uuid, async () => {
const params = msg.content as CompletionStreamNextChunkParams;
const curGenerator = this.loadedModelIdToAsyncGenerator.get(
params.selectedModelId,
);
if (curGenerator === undefined) {
throw Error(
"InternalError: Chunk generator in worker should be instantiated by now.",
);
}
// Yield the next chunk
const { value } = await curGenerator.next();
onComplete?.(value);
return value;
});
return;
}
// For engine.embeddings.create()
case "embedding": {
// Directly return the Embeddings response
this.handleTask(msg.uuid, async () => {
const params = msg.content as EmbeddingParams;
await this.reloadIfUnmatched(params.modelId, params.chatOpts);
const res = await this.engine.embedding(params.request);
onComplete?.(res);
return res;
});
return;
}
case "runtimeStatsText": {
this.handleTask(msg.uuid, async () => {
const params = msg.content as RuntimeStatsTextParams;
const res = await this.engine.runtimeStatsText(params.modelId);
onComplete?.(res);
return res;
});
return;
}
case "interruptGenerate": {
this.handleTask(msg.uuid, async () => {
this.engine.interruptGenerate();
onComplete?.(null);
return null;
});
return;
}
case "unload": {
// Unset modelId and chatOpts since backend unloads the model
this.handleTask(msg.uuid, async () => {
await this.engine.unload();
this.modelId = undefined;
this.chatOpts = undefined;
// This may not be cleaned properly when one asyncGenerator finishes.
// We only clear at unload(), which may not be called upon reload().
// However, service_worker may skip reload(). Will leave as is for now.
this.loadedModelIdToAsyncGenerator.clear();
onComplete?.(null);
return null;
});
return;
}
case "resetChat": {
this.handleTask(msg.uuid, async () => {
const params = msg.content as ResetChatParams;
await this.engine.resetChat(params.keepStats, params.modelId);
onComplete?.(null);
return null;
});
return;
}
case "getMaxStorageBufferBindingSize": {
this.handleTask(msg.uuid, async () => {
const res = await this.engine.getMaxStorageBufferBindingSize();
onComplete?.(res);
return res;
});
return;
}
case "getGPUVendor": {
this.handleTask(msg.uuid, async () => {
const res = await this.engine.getGPUVendor();
onComplete?.(res);
return res;
});
return;
}
case "getMessage": {
this.handleTask(msg.uuid, async () => {
const params = msg.content as GetMessageParams;
const res = await this.engine.getMessage(params.modelId);
onComplete?.(res);
return res;
});
return;
}
case "setLogLevel": {
const logLevel = msg.content as LogLevel;
this.engine.setLogLevel(logLevel);
log.setLevel(logLevel);
onComplete?.(null);
return;
}
case "setAppConfig": {
const appConfig = msg.content as AppConfig;
this.engine.setAppConfig(appConfig);
onComplete?.(null);
return;
}
case "customRequest": {
onComplete?.(null);
return;
}
default: {
if (msg.kind && msg.content) {
onError?.();
throw new UnknownMessageKindError(msg.kind, msg.content);
} else {
// Ignore irrelavent events
onComplete?.(null);
}
}
}
}
/** Check whether frontend expectation matches with backend (modelId and chatOpts). If not (due
* to possibly killed service worker), we reload here.
* For more, see https://github.com/mlc-ai/web-llm/pull/533
*/
async reloadIfUnmatched(
expectedModelId: string[],
expectedChatOpts?: ChatOptions[],
) {
// TODO: should we also check expectedChatOpts here?
if (!areArraysEqual(this.modelId, expectedModelId)) {
log.warn(
"WebWorkerMLCEngine expects model is loaded in WebWorkerMLCEngineHandler, " +
"but it is not. This may due to web/service worker is unexpectedly killed.\n" +
"Reloading engine in WebWorkerMLCEngineHandler.",
);
await this.engine.reload(expectedModelId, expectedChatOpts);
}
}
}
export interface ChatWorker {
onmessage: any;
postMessage: (message: any) => void;
}
/**
* Creates `WebWorkerMLCEngine`, a client that holds the same interface as `MLCEngine`.
*
* Equivalent to `new webllm.WebWorkerMLCEngine(worker).reload(...)`.
*
* @param worker The worker that holds the actual MLCEngine, initialized with `new Worker()`.
* @param modelId model_id of the model to load, either string or string[]. When multiple models
* are provided, we load all models sequentially. Each modelId needs to either be in
* `webllm.prebuiltAppConfig`, or in `engineCOnfig.appConfig`.
* @param engineConfig Optionally configures the engine, see `webllm.MLCEngineConfig` for more.
* @param chatOpts Extra options to optionally override the `mlc-chat-config.json` of `modelId`.
* The size of which needs to match that of `modelId`; chatOpts[i] will be used for modelId[i].
* @returns An initialized `WebLLM.WebWorkerMLCEngine` with `modelId` loaded.
*
* @note engineConfig.logitProcessorRegistry is ignored for `CreateWebWorkMLCEngine()`.
*/
export async function CreateWebWorkerMLCEngine(
worker: any,
modelId: string | string[],
engineConfig?: MLCEngineConfig,
chatOpts?: ChatOptions | ChatOptions[],
): Promise<WebWorkerMLCEngine> {
const webWorkerMLCEngine = new WebWorkerMLCEngine(worker, engineConfig);
await webWorkerMLCEngine.reload(modelId, chatOpts);
return webWorkerMLCEngine;
}
/**
* A client of MLCEngine that exposes the same interface
*
* @example
*
* const chat = new webllm.WebWorkerMLCEngine(new Worker(
* new URL('./worker.ts', import.meta.url),
* {type: 'module'}
* ));
*/
export class WebWorkerMLCEngine implements MLCEngineInterface {
public worker: ChatWorker;
/** For chat.completions.create() */
public chat: API.Chat;
/** For completions.create() */
public completions: API.Completions;
/** For embeddings.create() */
public embeddings: API.Embeddings;
/**
* The modelId and chatOpts that the frontend expects the backend engine is currently loaded
* with. Needed for service worker. It is the backend and handler's job to match up with the
* expectation despite the web/service worker possibly being killed.
* Since an engine can load multiple models, both modelId and chatOpts are lists.
*/
modelId?: string[];
chatOpts?: ChatOptions[];
private initProgressCallback?: InitProgressCallback;
private pendingPromise = new Map<string, (msg: WorkerResponse) => void>();
constructor(worker: ChatWorker, engineConfig?: MLCEngineConfig) {
this.worker = worker;
worker.onmessage = (event: any) => {
this.onmessage.bind(this)(event);
};
if (engineConfig?.appConfig) {
this.setAppConfig(engineConfig?.appConfig);
}
if (engineConfig?.logLevel) {
this.setLogLevel(engineConfig?.logLevel);
}
this.setInitProgressCallback(engineConfig?.initProgressCallback);
if (engineConfig?.logitProcessorRegistry) {
if (engineConfig?.logitProcessorRegistry) {
log.warn(
"Warning: The `logitProcessorRegistry` property in `engineConfig` will be ignored when using the WebWorkerMLCEngine constructor. To set `logitProcessorRegistry`, use the engine constructor within the worker script instead.",
);
}
}
this.chat = new API.Chat(this);
this.completions = new API.Completions(this);
this.embeddings = new API.Embeddings(this);
}
setInitProgressCallback(initProgressCallback?: InitProgressCallback) {
this.initProgressCallback = initProgressCallback;
}
getInitProgressCallback(): InitProgressCallback | undefined {
return this.initProgressCallback;
}
setAppConfig(appConfig: AppConfig) {
const msg: WorkerRequest = {
kind: "setAppConfig",
uuid: crypto.randomUUID(),
content: appConfig,
};
this.worker.postMessage(msg);
}
setLogLevel(logLevel: LogLevel) {
log.setLevel(logLevel);
const msg: WorkerRequest = {
kind: "setLogLevel",
uuid: crypto.randomUUID(),
content: logLevel,
};
this.worker.postMessage(msg);
}
protected getPromise<T extends MessageContent>(
msg: WorkerRequest,
): Promise<T> {
const uuid = msg.uuid;
const executor = (
resolve: (arg: T) => void,
reject: (arg: any) => void,
) => {
const cb = (msg: WorkerResponse) => {
if (msg.kind == "return") {
resolve(msg.content as T);
} else {
if (msg.kind != "throw") {
reject("Uknown msg kind " + msg.kind);
} else {
reject(msg.content);
}
}
};
this.pendingPromise.set(uuid, cb);
};
const promise = new Promise<T>(executor);
this.worker.postMessage(msg);
return promise;
}
async reload(
modelId: string | string[],
chatOpts?: ChatOptions | ChatOptions[],
): Promise<void> {
// Always convert modelId and chatOpts to lists internally for ease of manipulation
if (!Array.isArray(modelId)) {
modelId = [modelId];
}
if (chatOpts !== undefined && !Array.isArray(chatOpts)) {
chatOpts = [chatOpts];
}
const msg: WorkerRequest = {
kind: "reload",
uuid: crypto.randomUUID(),
content: {
modelId: modelId,
chatOpts: chatOpts,
},
};
await this.getPromise<null>(msg);
this.modelId = modelId;
this.chatOpts = chatOpts;
}
async getMaxStorageBufferBindingSize(): Promise<number> {
const msg: WorkerRequest = {
kind: "getMaxStorageBufferBindingSize",
uuid: crypto.randomUUID(),
content: null,
};
return await this.getPromise<number>(msg);
}
async getGPUVendor(): Promise<string> {
const msg: WorkerRequest = {
kind: "getGPUVendor",
uuid: crypto.randomUUID(),
content: null,
};
return await this.getPromise<string>(msg);
}
async getMessage(modelId?: string): Promise<string> {
const msg: WorkerRequest = {
kind: "getMessage",
uuid: crypto.randomUUID(),
content: {
modelId: modelId,
},
};
return await this.getPromise<string>(msg);
}
async runtimeStatsText(modelId?: string): Promise<string> {
const msg: WorkerRequest = {
kind: "runtimeStatsText",
uuid: crypto.randomUUID(),
content: {
modelId: modelId,
},
};
return await this.getPromise<string>(msg);
}
interruptGenerate(): void {
const msg: WorkerRequest = {
kind: "interruptGenerate",
uuid: crypto.randomUUID(),
content: null,
};
this.getPromise<null>(msg);
}
async unload(): Promise<void> {
const msg: WorkerRequest = {
kind: "unload",
uuid: crypto.randomUUID(),
content: null,
};
await this.getPromise<null>(msg);
this.modelId = undefined;
this.chatOpts = undefined;
}
async resetChat(keepStats = false, modelId?: string): Promise<void> {
const msg: WorkerRequest = {
kind: "resetChat",
uuid: crypto.randomUUID(),
content: {
keepStats: keepStats,
modelId: modelId,
},
};
await this.getPromise<null>(msg);
}
async forwardTokensAndSample(
inputIds: Array<number>,
isPrefill: boolean,
modelId?: string,
): Promise<number> {
const msg: WorkerRequest = {
kind: "forwardTokensAndSample",
uuid: crypto.randomUUID(),
content: {
inputIds: inputIds,
isPrefill: isPrefill,
modelId: modelId,
},
};
return await this.getPromise<number>(msg);
}
/**
* Every time the generator is called, we post a message to the worker asking it to
* decode one step, and we expect to receive a message of `ChatCompletionChunk` from
* the worker which we yield. The last message is `void`, meaning the generator has nothing
* to yield anymore.
*
* @param selectedModelId: The model of whose async generator to call next() to get next chunk.
* Needed because an engine can load multiple models.
*
* @note ChatCompletion and Completion share the same chunk generator.
*/
async *asyncGenerate(
selectedModelId: string,
): AsyncGenerator<ChatCompletionChunk | Completion, void, void> {
// Every time it gets called, sends message to worker, asking for the next chunk
while (true) {
const msg: WorkerRequest = {
kind: "completionStreamNextChunk",
uuid: crypto.randomUUID(),
content: {
selectedModelId: selectedModelId,
} as CompletionStreamNextChunkParams,
};
const ret = await this.getPromise<ChatCompletionChunk>(msg);
// If the worker's generator reached the end, it would return a `void`
if (typeof ret !== "object") {
break;
}
yield ret;
}
}
async chatCompletion(
request: ChatCompletionRequestNonStreaming,
): Promise<ChatCompletion>;
async chatCompletion(
request: ChatCompletionRequestStreaming,
): Promise<AsyncIterable<ChatCompletionChunk>>;
async chatCompletion(
request: ChatCompletionRequestBase,
): Promise<AsyncIterable<ChatCompletionChunk> | ChatCompletion>;
async chatCompletion(
request: ChatCompletionRequest,
): Promise<AsyncIterable<ChatCompletionChunk> | ChatCompletion> {
if (this.modelId === undefined) {
throw new WorkerEngineModelNotLoadedError(this.constructor.name);
}
// Needed for the streaming case. Consolidate model id to specify
// which model's asyncGenerator to instantiate or call next() on.
// Since handler can maintain multiple generators concurrently
const selectedModelId = getModelIdToUse(
this.modelId ? this.modelId : [],
request.model,
"ChatCompletionRequest",
);
if (request.stream) {
// First let worker instantiate a generator
const msg: WorkerRequest = {
kind: "chatCompletionStreamInit",
uuid: crypto.randomUUID(),
content: {
request: request,
selectedModelId: selectedModelId,
modelId: this.modelId,
chatOpts: this.chatOpts,
},
};
await this.getPromise<null>(msg);
// Then return an async chunk generator that resides on the client side
return this.asyncGenerate(selectedModelId) as AsyncGenerator<
ChatCompletionChunk,
void,
void
>;
}
// Non streaming case is more straightforward
const msg: WorkerRequest = {
kind: "chatCompletionNonStreaming",
uuid: crypto.randomUUID(),
content: {
request: request,
modelId: this.modelId,
chatOpts: this.chatOpts,
},
};
return await this.getPromise<ChatCompletion>(msg);
}
async completion(
request: CompletionCreateParamsNonStreaming,
): Promise<Completion>;
async completion(
request: CompletionCreateParamsStreaming,
): Promise<AsyncIterable<Completion>>;
async completion(
request: CompletionCreateParamsBase,
): Promise<AsyncIterable<Completion> | Completion>;
async completion(
request: CompletionCreateParams,
): Promise<AsyncIterable<Completion> | Completion> {
if (this.modelId === undefined) {
throw new WorkerEngineModelNotLoadedError(this.constructor.name);
}
// Needed for the streaming case. Consolidate model id to specify
// which model's asyncGenerator to instantiate or call next() on.
// Since handler can maintain multiple generators concurrently
const selectedModelId = getModelIdToUse(
this.modelId ? this.modelId : [],
request.model,
"CompletionCreateParams",
);
if (request.stream) {
// First let worker instantiate a generator
const msg: WorkerRequest = {
kind: "completionStreamInit",
uuid: crypto.randomUUID(),
content: {
request: request,
selectedModelId: selectedModelId,
modelId: this.modelId,
chatOpts: this.chatOpts,
},
};
await this.getPromise<null>(msg);
// Then return an async chunk generator that resides on the client side
return this.asyncGenerate(selectedModelId) as AsyncGenerator<
Completion,
void,
void
>;
}
// Non streaming case is more straightforward
const msg: WorkerRequest = {
kind: "completionNonStreaming",
uuid: crypto.randomUUID(),
content: {
request: request,
modelId: this.modelId,
chatOpts: this.chatOpts,
},
};
return await this.getPromise<Completion>(msg);
}
async embedding(
request: EmbeddingCreateParams,
): Promise<CreateEmbeddingResponse> {
if (this.modelId === undefined) {
throw new WorkerEngineModelNotLoadedError(this.constructor.name);
}
const msg: WorkerRequest = {
kind: "embedding",
uuid: crypto.randomUUID(),
content: {
request: request,
modelId: this.modelId,
chatOpts: this.chatOpts,
},
};
return await this.getPromise<CreateEmbeddingResponse>(msg);
}
onmessage(event: any) {
let msg: WorkerResponse;
if (event instanceof MessageEvent) {
msg = event.data as WorkerResponse;
} else {
msg = event as WorkerResponse;
}
switch (msg.kind) {
case "initProgressCallback": {
if (this.initProgressCallback !== undefined) {
this.initProgressCallback(msg.content as InitProgressReport);
}
return;
}
case "return": {
const cb = this.pendingPromise.get(msg.uuid);
if (cb === undefined) {
throw Error("return from a unknown uuid msg=" + msg.uuid);
}
this.pendingPromise.delete(msg.uuid);
cb(msg);
return;
}
case "throw": {
const cb = this.pendingPromise.get(msg.uuid);
if (cb === undefined) {
throw Error("return from a unknown uuid, msg=" + msg);
}
this.pendingPromise.delete(msg.uuid);
cb(msg);
return;
}
default: {
const unknownMsg = msg as any;
throw new UnknownMessageKindError(unknownMsg.kind, unknownMsg.content);
}
}
}
}