Elffuss BraidHub

kikocis/continue public

main · 1.8 KiBRawPermalink
1import path from "path";
2
3import workerpool from "workerpool";
4
5export interface AsyncEncoder {
6 encode(text: string): Promise<number[]>;
7 decode(tokens: number[]): Promise<string>;
8 close(): Promise<void>;
9}
10
11export class LlamaAsyncEncoder implements AsyncEncoder {
12 private workerPool: workerpool.Pool;
13
14 constructor() {
15 this.workerPool = workerpool.pool(
16 workerCodeFilePath("llamaTokenizerWorkerPool.mjs"),
17 );
18 }
19
20 async encode(text: string): Promise<number[]> {
21 return this.workerPool.exec("encode", [text]);
22 }
23
24 async decode(tokens: number[]): Promise<string> {
25 return this.workerPool.exec("decode", [tokens]);
26 }
27
28 // TODO: this should be called somewhere before exit or potentially with a shutdown hook
29 public async close(): Promise<void> {
30 await this.workerPool.terminate();
31 }
32}
33
34// this class does not yet do anything asynchronous
35export class GPTAsyncEncoder implements AsyncEncoder {
36 private workerPool: workerpool.Pool;
37
38 constructor() {
39 this.workerPool = workerpool.pool(
40 workerCodeFilePath("tiktokenWorkerPool.mjs"),
41 );
42 }
43
44 async encode(text: string): Promise<number[]> {
45 return this.workerPool.exec("encode", [text]);
46 }
47
48 async decode(tokens: number[]): Promise<string> {
49 return this.workerPool.exec("decode", [tokens]);
50 }
51
52 // TODO: this should be called somewhere before exit or potentially with a shutdown hook
53 public async close(): Promise<void> {
54 await this.workerPool.terminate();
55 }
56}
57
58function workerCodeFilePath(workerFileName: string): string {
59 if (process.env.NODE_ENV === "test") {
60 // `cross-env` seems to make it so __dirname is the root of the project and not the directory containing this file
61 return path.join(__dirname, "llm", workerFileName);
62 }
63 return path.join(__dirname, workerFileName);
64}