Elffuss BraidHub

kikocis/continue public

9d8db5fc402e · 2.1 KiBRawPermalink
1import { CompletionOptions, ILLM } from "../..";
2import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline";
3import { HelperVars } from "../util/HelperVars";
4
5import { GeneratorReuseManager } from "./GeneratorReuseManager";
6
7export class CompletionStreamer {
8 private streamTransformPipeline = new StreamTransformPipeline();
9 private generatorReuseManager: GeneratorReuseManager;
10
11 constructor(onError: (err: any) => void) {
12 this.generatorReuseManager = new GeneratorReuseManager(onError);
13 }
14
15 async *streamCompletionWithFilters(
16 token: AbortSignal,
17 llm: ILLM,
18 prefix: string,
19 suffix: string,
20 prompt: string,
21 multiline: boolean,
22 completionOptions: Partial<CompletionOptions> | undefined,
23 helper: HelperVars,
24 ) {
25 // Try to reuse pending requests if what the user typed matches start of completion
26 const generator = this.generatorReuseManager.getGenerator(
27 prefix,
28 (abortSignal: AbortSignal) =>
29 llm.supportsFim()
30 ? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
31 : llm.streamComplete(prompt, abortSignal, {
32 ...completionOptions,
33 raw: true,
34 }),
35 multiline,
36 );
37
38 // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
39 const fullStop = () =>
40 this.generatorReuseManager.currentGenerator?.cancel();
41
42 // LLM
43 const generatorWithCancellation = async function* () {
44 for await (const update of generator) {
45 if (token.aborted) {
46 return;
47 }
48 yield update;
49 }
50 };
51
52 const initialGenerator = generatorWithCancellation();
53 const transformedGenerator = helper.options.transform
54 ? this.streamTransformPipeline.transform(
55 initialGenerator,
56 prefix,
57 suffix,
58 multiline,
59 completionOptions?.stop || [],
60 fullStop,
61 helper,
62 )
63 : initialGenerator;
64
65 for await (const update of transformedGenerator) {
66 yield update;
67 }
68 }
69}