Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 11.9 KiBRawPermalink
1import * as path from "path";
2import { ConfigHandler } from "../config/ConfigHandler.js";
3import { ChatMessage, IDE, ILLM } from "../index.js";
4import OpenAI from "../llm/llms/OpenAI.js";
5import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
6
7import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
8
9import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
10import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
11import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
12import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
13import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
14import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
15import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
16import { HelperVars } from "../autocomplete/util/HelperVars.js";
17import { AutocompleteInput } from "../autocomplete/util/types.js";
18import { replaceEscapedCharacters } from "../util/text.js";
19import {
20 NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
21 NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
22} from "./constants.js";
23import { NextEditLoggingService } from "./NextEditLoggingService.js";
24import {
25 renderDefaultSystemPrompt,
26 renderDefaultUserPrompt,
27 renderPrompt,
28} from "./templating/NextEditPromptEngine.js";
29import { NextEditOutcome, Prompt, PromptMetadata } from "./types.js";
30// import { renderPrompt } from "./templating/NextEditPromptEngine.js";
31
32const autocompleteCache = AutocompleteLruCache.get();
33
34// Errors that can be expected on occasion even during normal functioning should not be shown.
35// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
36const ERRORS_TO_IGNORE = [
37 // From Ollama
38 "unexpected server status",
39 "operation was aborted",
40];
41
42export class NextEditProvider {
43 private static instance: NextEditProvider | null = null;
44
45 private autocompleteCache = AutocompleteLruCache.get();
46 public errorsShown: Set<string> = new Set();
47 private bracketMatchingService = new BracketMatchingService();
48 private debouncer = new AutocompleteDebouncer();
49 private completionStreamer: CompletionStreamer;
50 private loggingService: NextEditLoggingService;
51 private contextRetrievalService: ContextRetrievalService;
52 private endpointType: "default" | "fineTuned";
53 private diffContext: string = "";
54 private promptMetadata: PromptMetadata | null = null;
55
56 private constructor(
57 private readonly configHandler: ConfigHandler,
58 private readonly ide: IDE,
59 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
60 private readonly _onError: (e: any) => void,
61 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
62 endpointType: "default" | "fineTuned",
63 ) {
64 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
65 this.contextRetrievalService = new ContextRetrievalService(this.ide);
66 this.endpointType = endpointType;
67 this.loggingService = NextEditLoggingService.getInstance();
68 }
69
70 public static initialize(
71 configHandler: ConfigHandler,
72 ide: IDE,
73 injectedGetLlm: () => Promise<ILLM | undefined>,
74 onError: (e: any) => void,
75 getDefinitionsFromLsp: GetLspDefinitionsFunction,
76 endpointType: "default" | "fineTuned",
77 ): NextEditProvider {
78 if (!NextEditProvider.instance) {
79 NextEditProvider.instance = new NextEditProvider(
80 configHandler,
81 ide,
82 injectedGetLlm,
83 onError,
84 getDefinitionsFromLsp,
85 endpointType,
86 );
87 }
88 return NextEditProvider.instance;
89 }
90
91 public static getInstance(): NextEditProvider {
92 if (!NextEditProvider.instance) {
93 throw new Error(
94 "NextEditProvider has not been initialized. Call initialize() first.",
95 );
96 }
97 return NextEditProvider.instance;
98 }
99
100 public addDiffToContext(diff: string): void {
101 this.diffContext = diff;
102 }
103
104 private async _prepareLlm(): Promise<ILLM | undefined> {
105 const llm = await this._injectedGetLlm();
106
107 if (!llm) {
108 return undefined;
109 }
110
111 // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
112 if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
113 llm.model = llm.completionOptions.model;
114 }
115
116 // Ignore empty API keys for Mistral since we currently write
117 // a template provider without one during onboarding
118 if (llm.providerName === "mistral" && llm.apiKey === "") {
119 return undefined;
120 }
121
122 // Set temperature (but don't override)
123 if (llm.completionOptions.temperature === undefined) {
124 llm.completionOptions.temperature = 0.01;
125 }
126
127 if (llm instanceof OpenAI) {
128 llm.useLegacyCompletionsEndpoint = true;
129 }
130 // TODO: Resolve import error with TRIAL_FIM_MODEL
131 // else if (
132 // llm.providerName === "free-trial" &&
133 // llm.model !== TRIAL_FIM_MODEL
134 // ) {
135 // llm.model = TRIAL_FIM_MODEL;
136 // }
137
138 return llm;
139 }
140
141 private onError(e: any) {
142 if (
143 ERRORS_TO_IGNORE.some((err) =>
144 typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
145 )
146 ) {
147 return;
148 }
149
150 console.warn("Error generating autocompletion: ", e);
151 if (!this.errorsShown.has(e.message)) {
152 this.errorsShown.add(e.message);
153 this._onError(e);
154 }
155 }
156
157 public cancel() {
158 this.loggingService.cancel();
159 }
160
161 public accept(completionId: string) {
162 const outcome = this.loggingService.accept(completionId);
163 if (!outcome) {
164 return;
165 }
166 }
167
168 public reject(completionId: string) {
169 const outcome = this.loggingService.reject(completionId);
170 if (!outcome) {
171 return;
172 }
173 }
174
175 public markDisplayed(completionId: string, outcome: NextEditOutcome) {
176 this.loggingService.markDisplayed(completionId, outcome);
177 }
178
179 private async _getAutocompleteOptions() {
180 const { config } = await this.configHandler.loadConfig();
181 const options = {
182 ...DEFAULT_AUTOCOMPLETE_OPTS,
183 ...config?.tabAutocompleteOptions,
184 };
185 return options;
186 }
187
188 public async provideInlineCompletionItems(
189 input: AutocompleteInput,
190 token: AbortSignal | undefined,
191 ): Promise<NextEditOutcome | undefined> {
192 try {
193 // Create abort signal if not given
194 if (!token) {
195 const controller = this.loggingService.createAbortController(
196 input.completionId,
197 );
198 token = controller.signal;
199 }
200 const startTime = Date.now();
201 const options = await this._getAutocompleteOptions();
202
203 // Debounce
204 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
205 return undefined;
206 }
207
208 const llm = await this._prepareLlm();
209 if (!llm) {
210 return undefined;
211 }
212
213 if (llm.promptTemplates?.autocomplete) {
214 options.template = llm.promptTemplates.autocomplete as string;
215 }
216
217 const helper = await HelperVars.create(
218 input,
219 options,
220 llm.model,
221 this.ide,
222 );
223
224 if (await shouldPrefilter(helper, this.ide)) {
225 return undefined;
226 }
227
228 const [snippetPayload, workspaceDirs] = await Promise.all([
229 getAllSnippetsWithoutRace({
230 helper,
231 ide: this.ide,
232 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
233 contextRetrievalService: this.contextRetrievalService,
234 }),
235 this.ide.getWorkspaceDirs(),
236 ]);
237
238 // TODO: Toggle between the default endpoint and the finetuned endpoint.
239 const prompts: Prompt[] = [];
240 if (this.endpointType === "default") {
241 prompts.push(renderDefaultSystemPrompt());
242 prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
243 } else {
244 const promptMetadata = renderPrompt(helper, this.diffContext);
245 this.promptMetadata = promptMetadata;
246 prompts.push(promptMetadata.prompt);
247 }
248
249 if (this.endpointType === "default") {
250 const msg: ChatMessage = await llm.chat(prompts, token);
251 if (typeof msg.content === "string") {
252 const nextCompletion = JSON.parse(msg.content).newCode;
253 const outcomeNext: NextEditOutcome = {
254 elapsed: Date.now() - startTime,
255 modelProvider: llm.underlyingProviderName,
256 modelName: llm.model + ":zetaDataset",
257 completionOptions: null,
258 // filepath: helper.filepath,
259 completionId: helper.input.completionId,
260 gitRepo: await this.ide.getRepoName(helper.filepath),
261 uniqueId: await this.ide.getUniqueId(),
262 timestamp: Date.now(),
263 fileUri: helper.filepath,
264 workspaceDirUri:
265 helper.workspaceUris[0] ?? path.dirname(helper.filepath),
266 prompt: prompts.join("\n"),
267 userEdits: "",
268 userExcerpts: "",
269 originalEditableRange: "",
270 completion: nextCompletion,
271 cursorPosition: helper.pos,
272 ...helper.options,
273 };
274
275 // When using the JetBrains extension, mark as displayed.
276 // This helps us not need to make additional network calls just to mark as displayed.
277 const ideType = (await this.ide.getIdeInfo()).ideType;
278 if (ideType === "jetbrains") {
279 this.markDisplayed(input.completionId, outcomeNext);
280 }
281
282 return outcomeNext;
283 } else {
284 return undefined;
285 }
286 } else {
287 const msg: ChatMessage = await llm.chat(prompts, token);
288
289 if (typeof msg.content === "string") {
290 // NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
291 const nextCompletion = msg.content.split(
292 "<|editable_region_start|>\n",
293 )[1]
294 ? replaceEscapedCharacters(
295 msg.content.split("<|editable_region_start|>\n")[1],
296 ).replace(/\n$/, "")
297 : "";
298
299 const currCursorPos = helper.pos;
300 const editableRegionStartLine = Math.max(
301 currCursorPos.line - NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN,
302 0,
303 );
304 const editableRegionEndLine = Math.min(
305 currCursorPos.line + NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN,
306 helper.fileLines.length - 1,
307 );
308 const oldEditRangeSlice = helper.fileContents
309 .split("\n")
310 .slice(editableRegionStartLine, editableRegionEndLine + 1)
311 .join("\n");
312
313 const outcomeNext: NextEditOutcome = {
314 elapsed: Date.now() - startTime,
315 modelProvider: llm.underlyingProviderName,
316 modelName: llm.model + ":zetaDataset",
317 completionOptions: null,
318 // filepath: helper.filepath,
319 completionId: helper.input.completionId,
320 gitRepo: await this.ide.getRepoName(helper.filepath),
321 uniqueId: await this.ide.getUniqueId(),
322 timestamp: Date.now(),
323 fileUri: helper.filepath,
324 workspaceDirUri:
325 helper.workspaceUris[0] ?? path.dirname(helper.filepath),
326 prompt: this.promptMetadata!.prompt.content,
327 userEdits: this.promptMetadata!.userEdits,
328 userExcerpts: this.promptMetadata!.userExcerpts,
329 originalEditableRange: oldEditRangeSlice,
330 completion: nextCompletion,
331 cursorPosition: helper.pos,
332 ...helper.options,
333 };
334
335 // When using the JetBrains extension, mark as displayed.
336 // This helps us not need to make additional network calls just to mark as displayed.
337 const ideType = (await this.ide.getIdeInfo()).ideType;
338 if (ideType === "jetbrains") {
339 this.markDisplayed(input.completionId, outcomeNext);
340 }
341
342 return outcomeNext;
343 } else {
344 return undefined;
345 }
346 }
347 } catch (e: any) {
348 this.onError(e);
349 } finally {
350 this.loggingService.deleteAbortController(input.completionId);
351 }
352 }
353}