-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
CompletionStreamer.ts
69 lines (61 loc) · 2.06 KB
/
CompletionStreamer.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
import { CompletionOptions, ILLM } from "../..";
import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline";
import { HelperVars } from "../util/HelperVars";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
export class CompletionStreamer {
private streamTransformPipeline = new StreamTransformPipeline();
private generatorReuseManager: GeneratorReuseManager;
constructor(onError: (err: any) => void) {
this.generatorReuseManager = new GeneratorReuseManager(onError);
}
async *streamCompletionWithFilters(
token: AbortSignal,
llm: ILLM,
prefix: string,
suffix: string,
prompt: string,
multiline: boolean,
completionOptions: Partial<CompletionOptions> | undefined,
helper: HelperVars,
) {
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
prefix,
(abortSignal: AbortSignal) =>
llm.supportsFim()
? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
: llm.streamComplete(prompt, abortSignal, {
...completionOptions,
raw: true,
}),
multiline,
);
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
const fullStop = () =>
this.generatorReuseManager.currentGenerator?.cancel();
// LLM
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.aborted) {
return;
}
yield update;
}
};
const initialGenerator = generatorWithCancellation();
const transformedGenerator = helper.options.transform
? this.streamTransformPipeline.transform(
initialGenerator,
prefix,
suffix,
multiline,
completionOptions?.stop || [],
fullStop,
helper,
)
: initialGenerator;
for await (const update of transformedGenerator) {
yield update;
}
}
}