Elffuss BraidHub

kikocis/continue public

60acd6c5ca13 · 3.1 KiBRawPermalink
1import { ChatMessage, ILLM, Prediction, PromptLog } from "..";
2import { DEFAULT_MAX_TOKENS } from "../llm/constants";
3import { countTokens } from "../llm/countTokens";
4import { renderChatMessage } from "../util/messageContent";
5
6const INFINITE_STREAM_SAFETY = 0.9;
7
8const DUD_PROMPT_LOG: PromptLog = {
9 modelTitle: "",
10 modelProvider: "",
11 completionOptions: { model: "" },
12 prompt: "",
13 completion: "",
14};
15
16const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
17
18export async function* recursiveStream(
19 llm: ILLM,
20 abortController: AbortController,
21 prompt: ChatMessage[] | string,
22 prediction: Prediction | undefined,
23 currentBuffer = "",
24 isContinuation = false,
25): AsyncGenerator<string | ChatMessage> {
26 const maxTokens = llm.completionOptions?.maxTokens ?? DEFAULT_MAX_TOKENS;
27 const safeTokens = maxTokens * INFINITE_STREAM_SAFETY;
28 let totalTokens = 0;
29 let buffer = currentBuffer;
30 // let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
31
32 if (typeof prompt === "string") {
33 const generator = llm.streamComplete(prompt, abortController.signal, {
34 raw: true,
35 prediction: undefined,
36 reasoning: false,
37 });
38
39 for await (const chunk of generator) {
40 yield chunk;
41 buffer += chunk;
42 totalTokens += countTokens(chunk);
43
44 if (totalTokens >= safeTokens) {
45 throw new Error(
46 "Token limit reached. File/range likely too large for this edit",
47 );
48 // const continuationPrompt = `${RECURSIVE_PROMPT}:\n\n${buffer}`;
49
50 // await generator.return(DUD_PROMPT_LOG); // kill the previous generator
51
52 // // TODO - Prediction capabilities lost because of partial input
53 // yield* recursiveStream(
54 // llm,
55 // abortController,
56 // continuationPrompt,
57 // undefined,
58 // buffer,
59 // true,
60 // ); // Recursively stream the continuation
61
62 // return;
63 }
64 }
65 } else {
66 const generator = llm.streamChat(prompt, abortController.signal, {
67 raw: true,
68 prediction: undefined,
69 reasoning: false,
70 });
71
72 for await (const chunk of generator) {
73 yield chunk;
74 const rendered = renderChatMessage(chunk);
75 buffer += rendered;
76 totalTokens += countTokens(chunk.content);
77
78 if (totalTokens >= safeTokens) {
79 throw new Error(
80 "Token limit reached. File/range likely too large for this edit",
81 );
82 // const continuationPrompt: ChatMessage[] = [
83 // ...(isContinuation ? prompt.slice(0, -2) : prompt),
84 // {
85 // role: "assistant",
86 // content: buffer,
87 // },
88 // {
89 // role: "user",
90 // content: RECURSIVE_PROMPT,
91 // },
92 // ];
93
94 // await generator.return(DUD_PROMPT_LOG);
95 // yield* recursiveStream(
96 // llm,
97 // abortController,
98 // continuationPrompt,
99 // undefined,
100 // buffer,
101 // true,
102 // );
103 // return;
104 }
105 }
106 }
107}