Elffuss BraidHub

kikocis/continue public

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