Elffuss BraidHub

kikocis/continue public

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