Elffuss BraidHub

kikocis/continue public

4940c71be2bf · 10.3 KiBRawPermalink
1import Handlebars from "handlebars";
2import { Position } from "../..";
3import { SnippetPayload } from "../../autocomplete/snippets";
4import { HelperVars } from "../../autocomplete/util/HelperVars";
5import {
6 CURRENT_FILE_CONTENT_CLOSE,
7 CURRENT_FILE_CONTENT_OPEN,
8 CURSOR,
9 EDIT_DIFF_HISTORY_CLOSE,
10 EDIT_DIFF_HISTORY_OPEN,
11 RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE,
12 RECENTLY_VIEWED_CODE_SNIPPETS_OPEN,
13 USER_CURSOR_IS_HERE_TOKEN,
14} from "../constants";
15import {
16 MercuryTemplateVars,
17 Model1TemplateVars,
18 NextEditTemplate,
19 PromptMetadata,
20 SystemPrompt,
21 TemplateVars,
22 UserPrompt,
23} from "../types";
24import {
25 currentFileContentBlock,
26 editHistoryBlock,
27 recentlyViewedCodeSnippetsBlock,
28} from "./mercuryCoderNextEdit";
29import {
30 insertCursorToken,
31 insertEditableRegionTokensWithStaticRange,
32} from "./utils";
33
34type TemplateRenderer = (vars: TemplateVars) => string;
35
36export type NextEditModelName =
37 | "mercury-coder-nextedit"
38 | "model-1"
39 | "this field is not used";
40
41const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
42 "mercury-coder-nextedit": {
43 template: `${RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${CURRENT_FILE_CONTENT_CLOSE}\n\n${EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at [CURRENT FILE PATH].\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`,
44 },
45 "model-1": {
46 template:
47 "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
48 },
49 "this field is not used": {
50 template: "NEXT_EDIT",
51 },
52};
53
54function templateRendererOfModel(
55 modelName: NextEditModelName,
56): TemplateRenderer {
57 let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
58 if (!template) {
59 throw new Error(`Model ${modelName} is not supported for next edit.`);
60 }
61
62 const compiledTemplate = Handlebars.compile(template.template);
63
64 return (vars: TemplateVars): string => {
65 return compiledTemplate(vars);
66 };
67}
68
69export async function renderPrompt(
70 helper: HelperVars,
71 ctx: any,
72): Promise<PromptMetadata> {
73 let modelName = helper.modelName as NextEditModelName;
74
75 if (modelName === "this field is not used") {
76 return {
77 prompt: {
78 role: "user",
79 content: "NEXT_EDIT",
80 },
81 userEdits: "",
82 userExcerpts: helper.fileContents,
83 };
84 }
85
86 // Validate that the modelName is actually a supported model.
87 if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
88 // Check if modelName includes any known model name as substring.
89 const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
90 modelName.includes(key),
91 );
92
93 if (matchingModel) {
94 modelName = matchingModel as NextEditModelName;
95 } else {
96 throw new Error(
97 `${helper.modelName} is not yet supported for next edit.`,
98 );
99 }
100 }
101
102 const renderer = templateRendererOfModel(modelName);
103 let userEdits = "";
104 let editedCodeWithTokens = "";
105 let tv: TemplateVars;
106
107 switch (modelName) {
108 case "mercury-coder-nextedit": {
109 userEdits = ctx.editDiffHistory;
110
111 editedCodeWithTokens = insertTokens(
112 helper.fileContents.split("\n"),
113 helper.pos,
114 CURSOR,
115 );
116
117 const mercuryCtx: MercuryTemplateVars = {
118 recentlyViewedCodeSnippets: recentlyViewedCodeSnippetsBlock(
119 ctx.recentlyViewedCodeSnippets,
120 ),
121 currentFileContent: currentFileContentBlock(
122 ctx.currentFileContent,
123 ctx.editableRegionStartLine,
124 ctx.editableRegionEndLine,
125 helper.pos,
126 ),
127 editDiffHistory: editHistoryBlock(ctx.editDiffHistory),
128 };
129
130 tv = mercuryCtx;
131
132 break;
133 }
134 case "model-1": {
135 userEdits = ctx.userEdits;
136
137 editedCodeWithTokens = insertTokens(
138 helper.fileContents.split("\n"),
139 helper.pos,
140 USER_CURSOR_IS_HERE_TOKEN,
141 );
142
143 const model1Ctx: Model1TemplateVars = {
144 userEdits: ctx.userEdits,
145 languageShorthand: ctx.languageShorthand,
146 userExcerpts: ctx.userExcerpts,
147 };
148
149 tv = model1Ctx;
150
151 break;
152 }
153 default:
154 tv = {};
155 break;
156 }
157
158 return {
159 prompt: {
160 role: "user",
161 content: renderer(tv),
162 },
163 userEdits,
164 userExcerpts: editedCodeWithTokens,
165 };
166}
167
168export function renderDefaultSystemPrompt(): SystemPrompt {
169 return {
170 role: "system",
171 content: [
172 /* Identity forming */
173 "You are an expert polyglot developer who is overseeing a junior developer write code in some language.",
174 "You are psychic as well, so you are an expert at reading minds just from what the junior has done.",
175 "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.",
176 /* Action crash course */
177 "An action is a change in code state that preserves the well-formedness of the code.",
178 "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.",
179 /* Input description */
180 // 'You will receive a prompt that includes an instruction, and a JSON of following format: { "language": string; "originalCode": string; "newCode": string }.',
181 // "language is the language the code is written in.",
182 // "originalCode is the code state before the junior has taken some edit action.",
183 // "editedCode is the code state after the junior has taken some edit action.",
184 // "If we put originalCode and editedCode on a timeline, originalCode lives in the past, and editedCode is the current code state.",
185 // "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.",
186 '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; }.',
187 "rootPathSnippet is all the code that is part of an AST path from the root node to the node at the current cursor.",
188 "recentlyEditedRange is the code that the junior has recently edited.",
189 "Do not guess what previous edit the junior has taken right before the request -- this is already given to you.",
190 "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.",
191 "The junior might want to add new code, delete existing code, or replace different parts of code.",
192 "The next edit action isn't strictly additive. It could be deleting existing code, or replacing parts of code.",
193 /* Output description */
194 'Reply with a JSON that has the following type: { "actionType": string; "newCode": string }.',
195 /* NOTE: Jacob -- try toggling between these two descriptions of actionType.*/
196 /* NOTE: Without reasoning, mercury tends to skew greatly towards not deleting things. */
197 "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.",
198 // "actionType is the type of action the junior has taken.",
199 "newCode is what the full code looks like after applying your nextEditContent.",
200 // "Make sure that newCode does not have errors. You are given the language, and you should know what the typescript compiler will complain about.",
201 "Given the above definition of an action, you should prioritize fixing the following:",
202 "- Patterns and repetition in code.",
203 "- Static errors that the compiler of the language may return.",
204 "- The junior's code style.",
205 "If the junior has deleted some code, there's a good chance that the next edit will also be deletions.",
206 "If the junior has added some code, there's a good chance that the next edit will also be additions.",
207 "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.",
208 "Careful of language intricacies.",
209 // "Always try deletion and replacements. Add code if there are no other valid or reasonable edit actions.",
210 "Do not reply in markdown.",
211 "Do not hallucinate.",
212 ].join(" "),
213 };
214}
215
216export function renderDefaultUserPrompt(
217 // originalCode: string,
218 // editedCode: string,
219 snippets: SnippetPayload,
220 helper: HelperVars,
221): UserPrompt {
222 const userEdit = {
223 language: helper.lang,
224 rootPathSnippets: snippets.rootPathSnippets,
225 importDefinitionSnippets: snippets.importDefinitionSnippets,
226 ideSnippets: snippets.ideSnippets,
227 recentlyEditedRangeSnippets: snippets.recentlyEditedRangeSnippets,
228 diffSnippets: snippets.diffSnippets,
229 clipboardSnippets: snippets.clipboardSnippets,
230 recentlyVisitedRangesSnippets: snippets.recentlyVisitedRangesSnippets,
231 };
232
233 return {
234 role: "user",
235 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?`,
236 };
237}
238
239function insertTokens(
240 lines: string[],
241 cursorPos: Position,
242 cursorToken: string,
243 editableRegionStart?: number,
244 editableRegionEnd?: number,
245) {
246 const a = insertCursorToken(lines, cursorPos, cursorToken);
247 const b = insertEditableRegionTokensWithStaticRange(
248 a,
249 cursorPos,
250 editableRegionStart,
251 editableRegionEnd,
252 );
253 return b.join("\n");
254}