Elffuss BraidHub

kikocis/continue public

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