Elffuss BraidHub

kikocis/continue public

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