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