Elffuss BraidHub

kikocis/continue public

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