Elffuss BraidHub

kikocis/continue public

9da59f739c22 · 12.0 KiBRawPermalink
1import Handlebars from "handlebars";
2import { Position } from "../..";
3import { SnippetPayload } from "../../autocomplete/snippets";
4import { HelperVars } from "../../autocomplete/util/HelperVars";
5import {
6 EDITABLE_REGION_END_TOKEN,
7 EDITABLE_REGION_START_TOKEN,
8 NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
9 NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
10 USER_CURSOR_IS_HERE_TOKEN,
11} from "../constants";
12
13export type Prompt = SystemPrompt | UserPrompt;
14
15interface SystemPrompt {
16 role: "system";
17 content: string;
18}
19
20interface UserPrompt {
21 role: "user";
22 content: string;
23}
24
25export interface NextEditTemplate {
26 template: string;
27}
28
29export interface TemplateVars {
30 userEdits: string;
31 languageShorthand: string;
32 userExcerpts: string;
33}
34
35type TemplateRenderer = (vars: TemplateVars) => string;
36
37type NextEditModelName = "mercury-coder-nextedit" | "this field is not used";
38
39const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
40 "mercury-coder-nextedit": {
41 template:
42 "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{userExcerpts}}}\`\`\`",
43 },
44 "this field is not used": {
45 template: "NEXT_EDIT",
46 },
47};
48
49function templateRendererOfModel(
50 modelName: NextEditModelName,
51): TemplateRenderer {
52 let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
53 if (!template) {
54 // Check if modelName includes any known model name as substring.
55 const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
56 modelName.includes(key),
57 );
58
59 if (matchingModel) {
60 template = NEXT_EDIT_MODEL_TEMPLATES[matchingModel as NextEditModelName];
61 } else {
62 throw new Error(`Model ${modelName} is not supported for next edit.`);
63 }
64 }
65
66 const compiledTemplate = Handlebars.compile(template.template);
67
68 return (vars: TemplateVars): string => {
69 return compiledTemplate(vars);
70 };
71}
72
73export function renderPrompt(
74 helper: HelperVars,
75 userEdits: string,
76): UserPrompt {
77 const modelName = helper.modelName as NextEditModelName;
78
79 if (modelName === "this field is not used") {
80 return {
81 role: "user",
82 content: "NEXT_EDIT",
83 };
84 }
85
86 // Validate that the modelName is actually a supported model.
87 if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
88 throw new Error(`${helper.modelName} is not yet supported for next edit.`);
89 }
90
91 const renderer = templateRendererOfModel(modelName);
92 const editedCodeWithTokens = insertTokens(
93 helper.fileContents.split("\n"),
94 helper.pos,
95 );
96
97 const tv: TemplateVars = {
98 userEdits,
99 languageShorthand: helper.lang.name,
100 userExcerpts: editedCodeWithTokens,
101 };
102
103 return {
104 role: "user",
105 content: renderer(tv),
106 };
107}
108
109export function renderDefaultSystemPrompt(): SystemPrompt {
110 return {
111 role: "system",
112 content: [
113 /* Identity forming */
114 "You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
115 "You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
116 "As an expert, you know what the next edit of the junior is going to be, and you want to suggest it to save both of your's time.",
117 /* Action crash course */
118 "An action is a change in code state that preserves the well-formedness of the code.",
119 "Well-formedness means that given a cursor location, the local syntax tree that the cursor is in is syntactically correct, and the semantic correctness in the current cursor's character location - 1.",
120 /* Input description */
121 // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
122 // "language is the language the code is written in.",
123 // "originalCode is the code state before the junior has taken some edit action.",
124 // "editedCode is the code state after the junior has taken some edit action.",
125 // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
126 // "Measure the difference between the originalCode and editedCode inside the prompt, make your best understanding of what the junior wants to accomplish, and figure out what the junior will do next.",
127 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "rootPathSnippets": string; "importDefinitionSnippets": string; "ideSnippets": string; "recentlyEditedRangeSnippets": string; "diffSnippets": string; "clipboardSnippets": string; "recentlyVisitedRangesSnippets": string; }.',
128 "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
129 "recentlyEditedRange is the code that the junior has recently edited.",
130 "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
131 "The next edit action can happen any location, so do not default to where the junior left off. A potential next edit action can happen before or after the junior edit.",
132 "The junior might want to add new code, delete existing code, or replace different parts of code.",
133 "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
134 /* Output description */
135 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
136 /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
137 /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
138 "actionType is a four-sentence description of the type of action the junior has taken and the reason why you determined that to be the case. Actually analyze the given edit.",
139 // "actionType is the type of action the junior has taken.",
140 "newCode is what the full code looks like after applying your nextEditContent.",
141 // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
142 "Given the above definition of an action, you should prioritize fixing the following:",
143 "- Patterns and repetition in code.",
144 "- Static errors that the compiler of the language may return.",
145 "- The junior's code style.",
146 "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
147 "If the junior has added some code, there's a good chance that the next edit will also be additions.",
148 "If the junior has performed an action on some part of the code, and you see similar code remaining, there's a good chance that the next edit will also target these remaining similar code.",
149 "Careful of language intricacies.",
150 // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
151 "Do not reply in markdown.",
152 "Do not hallucinate.",
153 ].join(" "),
154 };
155}
156
157export function renderDefaultUserPrompt(
158 // originalCode: string,
159 // editedCode: string,
160 snippets: SnippetPayload,
161 helper: HelperVars,
162): UserPrompt {
163 const userEdit = {
164 language: helper.lang,
165 rootPathSnippets: snippets.rootPathSnippets,
166 importDefinitionSnippets: snippets.importDefinitionSnippets,
167 ideSnippets: snippets.ideSnippets,
168 recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
169 diffSnippets: snippets.diffSnippets,
170 clipboardSnippets: snippets.clipboardSnippets,
171 recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
172 };
173
174 return {
175 role: "user",
176 content: `Your junior made the following edit: ${JSON.stringify(userEdit)}. What is the most possible next edit your junior ${helper.lang.name} developer will make?`,
177 };
178}
179
180// export async function renderFineTunedUserPrompt(
181// snippets: SnippetPayload,
182// ide: IDE,
183// helper: HelperVars,
184// ): Promise<UserPrompt> {
185// const ideInfo = await ide.getIdeInfo();
186// switch (ideInfo.ideType) {
187// case "vscode":
188// const editedCodeWithPins = insertTokens(
189// helper.fileContents.split("\n"),
190// helper.pos,
191// );
192
193// return {
194// role: "user",
195// content: renderStringTemplate(
196// mercuryCoderTemplate,
197// snippets.diffSnippets.join("\n"),
198// helper.lang.name,
199// editedCodeWithPins,
200// ),
201// };
202
203// case "jetbrains":
204// return {
205// role: "user",
206// content: "",
207// };
208// }
209// }
210
211// export async function renderDefaultBasicUserPrompt(
212// snippets: SnippetPayload,
213// ide: IDE,
214// helper: HelperVars,
215// ): Promise<UserPrompt> {
216// const ideInfo = await ide.getIdeInfo();
217// switch (ideInfo.ideType) {
218// case "vscode":
219// const editedCodeWithPins = insertTokens(
220// helper.fileContents.split("\n"),
221// helper.pos,
222// );
223
224// return {
225// role: "user",
226// content: renderStringTemplate(
227// mercuryCoderTemplate,
228// JSON.stringify(snippets),
229// helper.lang.name,
230// editedCodeWithPins,
231// ),
232// };
233
234// case "jetbrains":
235// return {
236// role: "user",
237// content: "",
238// };
239// }
240// }
241
242// export async function renderFineTunedBasicUserPrompt(
243// snippets: SnippetPayload,
244// ide: IDE,
245// helper: HelperVars,
246// diffContext: string,
247// ): Promise<UserPrompt> {
248// const ideInfo = await ide.getIdeInfo();
249// switch (ideInfo.ideType) {
250// case "vscode":
251// const lines = helper.fileContents.split("\n");
252// const editedCodeWithPins = insertTokens(lines, helper.pos);
253
254// return {
255// role: "user",
256// content: renderStringTemplate(
257// mercuryCoderTemplate,
258// diffContext,
259// helper.lang.name,
260// editedCodeWithPins,
261// ),
262// };
263
264// case "jetbrains":
265// return {
266// role: "user",
267// content: "",
268// };
269// }
270// }
271
272function insertTokens(lines: string[], cursorPos: Position) {
273 const a = insertCursorToken(lines, cursorPos);
274 const b = insertEditableRegionTokensWithStaticRange(a, cursorPos);
275 return b.join("\n");
276}
277
278function insertCursorToken(lines: string[], cursorPos: Position) {
279 if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
280 return lines;
281 }
282
283 // Ensure character position is within bounds or at the end of the line.
284 const lineLength = lines[cursorPos.line].length;
285 const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
286
287 lines[cursorPos.line] =
288 lines[cursorPos.line].slice(0, charPos) +
289 USER_CURSOR_IS_HERE_TOKEN +
290 lines[cursorPos.line].slice(charPos);
291
292 return lines;
293}
294
295function insertEditableRegionTokensWithStaticRange(
296 lines: string[],
297 cursorPos: Position,
298) {
299 if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
300 return lines;
301 }
302
303 // Ensure editable regions are within bounds.
304 const editableRegionStart = Math.max(
305 cursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
306 0,
307 );
308 const editableRegionEnd = Math.min(
309 cursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
310 lines.length - 1, // Line numbers should be zero-indexed.
311 );
312
313 const instrumentedLines = [
314 ...lines.slice(0, editableRegionStart),
315 EDITABLE_REGION_START_TOKEN,
316 ...lines.slice(editableRegionStart, editableRegionEnd + 1),
317 EDITABLE_REGION_END_TOKEN,
318 ...lines.slice(editableRegionEnd + 1),
319 ];
320
321 return instrumentedLines;
322}
323
324function insertEditableRegionTokensWithAst(
325 lines: string[],
326 cursorPos: Position,
327) {
328 if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
329 return lines;
330 }
331
332 // Ensure character position is within bounds or at the end of the line.
333 const lineLength = lines[cursorPos.line].length;
334 const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
335
336 (lines[cursorPos.line] =
337 lines[cursorPos.line].slice(0, charPos) + USER_CURSOR_IS_HERE_TOKEN),
338 lines[cursorPos.line].slice(charPos);
339
340 return lines;
341}