Elffuss BraidHub

kikocis/continue public

796feb88992e · 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 completionOptions: { model: "" },
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 prediction,
67 reasoning: false,
68 });
69
70 for await (const chunk of generator) {
71 yield chunk;
72 const rendered = renderChatMessage(chunk);
73 buffer += rendered;
74 totalTokens += countTokens(chunk.content);
75
76 if (totalTokens >= safeTokens) {
77 throw new Error(
78 "Token limit reached. File/range likely too large for this edit",
79 );
80 // const continuationPrompt: ChatMessage[] = [
81 // ...(isContinuation ? prompt.slice(0, -2) : prompt),
82 // {
83 // role: "assistant",
84 // content: buffer,
85 // },
86 // {
87 // role: "user",
88 // content: RECURSIVE_PROMPT,
89 // },
90 // ];
91
92 // await generator.return(DUD_PROMPT_LOG);
93 // yield* recursiveStream(
94 // llm,
95 // abortController,
96 // continuationPrompt,
97 // undefined,
98 // buffer,
99 // true,
100 // );
101 // return;
102 }
103 }
104 }
105}