Elffuss BraidHub

kikocis/continue public

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