Elffuss BraidHub

kikocis/continue public

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