Elffuss BraidHub

kikocis/continue public

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