Elffuss BraidHub

kikocis/continue public

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