Elffuss BraidHub

kikocis/continue public

7bdcbb7e117f · 5.3 KiBRawPermalink
1import {
2 ChatMessage,
3 DiffLine,
4 ILLM,
5 Prediction,
6 RuleWithSource,
7 ToolResultChatMessage,
8 UserChatMessage,
9} from "../";
10import {
11 filterCodeBlockLines,
12 filterEnglishLinesAtEnd,
13 filterEnglishLinesAtStart,
14 filterLeadingAndTrailingNewLineInsertion,
15 removeTrailingWhitespace,
16 skipLines,
17 stopAtLines,
18} from "../autocomplete/filtering/streamTransforms/lineStream";
19import { streamDiff } from "../diff/streamDiff";
20import { streamLines } from "../diff/util";
21import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
22import { gptEditPrompt } from "../llm/templates/edit";
23import { StreamAbortManager } from "../util/abortManager";
24import { findLast } from "../util/findLast";
25import { Telemetry } from "../util/posthog";
26import { recursiveStream } from "./recursiveStream";
27
28function constructEditPrompt(
29 prefix: string,
30 highlighted: string,
31 suffix: string,
32 llm: ILLM,
33 userInput: string,
34 language: string | undefined,
35): string | ChatMessage[] {
36 const template = llm.promptTemplates?.edit ?? gptEditPrompt;
37 return llm.renderPromptTemplate(template, [], {
38 userInput,
39 prefix,
40 codeToEdit: highlighted,
41 suffix,
42 language: language ?? "",
43 });
44}
45
46export async function* addIndentation(
47 diffLineGenerator: AsyncGenerator<DiffLine>,
48 indentation: string,
49): AsyncGenerator<DiffLine> {
50 for await (const diffLine of diffLineGenerator) {
51 yield {
52 ...diffLine,
53 line: indentation + diffLine.line,
54 };
55 }
56}
57
58function modelIsInept(model: string): boolean {
59 return !(model.includes("gpt") || model.includes("claude"));
60}
61
62export async function* streamDiffLines({
63 prefix,
64 highlighted,
65 suffix,
66 llm,
67 abortControllerId,
68 input,
69 language,
70 onlyOneInsertion,
71 overridePrompt,
72 rulesToInclude,
73}: {
74 prefix: string;
75 highlighted: string;
76 suffix: string;
77 llm: ILLM;
78 abortControllerId: string;
79 input: string;
80 language: string | undefined;
81 onlyOneInsertion: boolean;
82 overridePrompt: ChatMessage[] | undefined;
83 rulesToInclude: RuleWithSource[] | undefined;
84}): AsyncGenerator<DiffLine> {
85 const abortManager = StreamAbortManager.getInstance();
86 const abortController = abortManager.get(abortControllerId);
87 void Telemetry.capture(
88 "inlineEdit",
89 {
90 model: llm.model,
91 provider: llm.providerName,
92 },
93 true,
94 );
95
96 // Strip common indentation for the LLM, then add back after generation
97 let oldLines =
98 highlighted.length > 0
99 ? highlighted.split("\n")
100 : // When highlighted is empty, we need to combine last line of prefix and first line of suffix to determine the line being edited
101 [(prefix + suffix).split("\n")[prefix.split("\n").length - 1]];
102
103 // But if that line is empty, we can assume we are insertion-only
104 if (oldLines.length === 1 && oldLines[0].trim() === "") {
105 oldLines = [];
106 }
107
108 // Defaults to creating an edit prompt
109 // For apply can be overridden with simply apply prompt
110 let prompt =
111 overridePrompt ??
112 constructEditPrompt(prefix, highlighted, suffix, llm, input, language);
113
114 // Rules can be included with edit prompt
115 // If any rules are present this will result in using chat instead of legacy completion
116 const systemMessage = rulesToInclude
117 ? getSystemMessageWithRules({
118 rules: rulesToInclude,
119 userMessage:
120 typeof prompt === "string"
121 ? ({
122 role: "user",
123 content: prompt,
124 } as UserChatMessage)
125 : (findLast(
126 prompt,
127 (msg) => msg.role === "user" || msg.role === "tool",
128 ) as UserChatMessage | ToolResultChatMessage | undefined),
129 baseSystemMessage: undefined,
130 contextItems: [],
131 })
132 : undefined;
133
134 if (systemMessage) {
135 if (typeof prompt === "string") {
136 prompt = [
137 {
138 role: "system",
139 content: systemMessage,
140 },
141 {
142 role: "user",
143 content: prompt,
144 },
145 ];
146 } else {
147 const curSysMsg = prompt.find((msg) => msg.role === "system");
148 if (curSysMsg) {
149 curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content;
150 } else {
151 prompt.unshift({
152 role: "system",
153 content: systemMessage,
154 });
155 }
156 }
157 }
158
159 const inept = modelIsInept(llm.model);
160
161 const prediction: Prediction = {
162 type: "content",
163 content: highlighted,
164 };
165
166 const completion = recursiveStream(llm, abortController, prompt, prediction);
167
168 let lines = streamLines(completion);
169
170 lines = filterEnglishLinesAtStart(lines);
171 lines = filterCodeBlockLines(lines);
172 lines = stopAtLines(lines, () => {});
173 lines = skipLines(lines);
174 lines = removeTrailingWhitespace(lines);
175 if (inept) {
176 // lines = fixCodeLlamaFirstLineIndentation(lines);
177 lines = filterEnglishLinesAtEnd(lines);
178 }
179
180 let diffLines = streamDiff(oldLines, lines);
181 diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines);
182 if (highlighted.length === 0) {
183 const line = prefix.split("\n").slice(-1)[0];
184 const indentation = line.slice(0, line.length - line.trimStart().length);
185 diffLines = addIndentation(diffLines, indentation);
186 }
187
188 let seenGreen = false;
189 for await (const diffLine of diffLines) {
190 yield diffLine;
191 if (diffLine.type === "new") {
192 seenGreen = true;
193 } else if (onlyOneInsertion && seenGreen && diffLine.type === "same") {
194 break;
195 }
196 }
197}