Elffuss BraidHub

kikocis/continue public

main · 18.5 KiBRawPermalink
1import { v4 as uuidv4 } from "uuid";
2import { ConfigHandler } from "../config/ConfigHandler.js";
3import { ChatMessage, IDE, ILLM, Range, RangeInFile } 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 { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
14import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
15import { getAst } from "../autocomplete/util/ast.js";
16import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
17import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
18import { HelperVars } from "../autocomplete/util/HelperVars.js";
19import { AutocompleteInput } from "../autocomplete/util/types.js";
20import { isSecurityConcern } from "../indexing/ignore.js";
21import { modelSupportsNextEdit } from "../llm/autodetect.js";
22import { localPathOrUriToPath } from "../util/pathToUri.js";
23import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
24import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
25import { NextEditLoggingService } from "./NextEditLoggingService.js";
26import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
27import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
28import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
29import {
30 ModelSpecificContext,
31 NextEditOutcome,
32 Prompt,
33 PromptMetadata,
34 RecentlyEditedRange,
35} from "./types.js";
36
37const autocompleteCache = AutocompleteLruCache.get();
38
39// Errors that can be expected on occasion even during normal functioning should not be shown.
40// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
41const ERRORS_TO_IGNORE = [
42 // From Ollama
43 "unexpected server status",
44 "operation was aborted",
45];
46
47/**
48 * This is the next edit analogue to autocomplete's CompletionProvider.
49 * You will see a lot of similar if not identical methods to CompletionProvider methods.
50 * All logic used to live inside this class, but that became untenable quickly.
51 * I moved a lot of the model-specific logic (prompt building, pre/post processing, etc.) to the BaseNextEditProvider and the children inheriting from it.
52 * Keeping this class around might be a good idea because it handles lots of delicate logic such as abort signals, chains, logging, etc.
53 * There being a singleton also gives a lot of guarantees about the state of the next edit state machine.
54 */
55export class NextEditProvider {
56 private static instance: NextEditProvider | null = null;
57
58 private autocompleteCache = AutocompleteLruCache.get();
59 public errorsShown: Set<string> = new Set();
60 private bracketMatchingService = new BracketMatchingService();
61 private debouncer = new AutocompleteDebouncer();
62 private completionStreamer: CompletionStreamer;
63 private loggingService: NextEditLoggingService;
64 private contextRetrievalService: ContextRetrievalService;
65 private endpointType: "default" | "fineTuned";
66 private diffContext: string[] = [];
67 private autocompleteContext: string = "";
68 private promptMetadata: PromptMetadata | null = null;
69 private currentEditChainId: string | null = null;
70 private previousRequest: AutocompleteInput | null = null;
71 private previousCompletions: NextEditOutcome[] = [];
72
73 // Model-specific provider instance.
74 private modelProvider: BaseNextEditModelProvider | null = null;
75
76 private constructor(
77 private readonly configHandler: ConfigHandler,
78 private readonly ide: IDE,
79 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
80 private readonly _onError: (e: any) => void,
81 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
82 endpointType: "default" | "fineTuned",
83 ) {
84 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
85 this.contextRetrievalService = new ContextRetrievalService(this.ide);
86 this.endpointType = endpointType;
87 this.loggingService = NextEditLoggingService.getInstance();
88 }
89
90 public static initialize(
91 configHandler: ConfigHandler,
92 ide: IDE,
93 injectedGetLlm: () => Promise<ILLM | undefined>,
94 onError: (e: any) => void,
95 getDefinitionsFromLsp: GetLspDefinitionsFunction,
96 endpointType: "default" | "fineTuned",
97 ): NextEditProvider {
98 if (!NextEditProvider.instance) {
99 NextEditProvider.instance = new NextEditProvider(
100 configHandler,
101 ide,
102 injectedGetLlm,
103 onError,
104 getDefinitionsFromLsp,
105 endpointType,
106 );
107 }
108 return NextEditProvider.instance;
109 }
110
111 public static getInstance(): NextEditProvider {
112 if (!NextEditProvider.instance) {
113 throw new Error(
114 "NextEditProvider has not been initialized. Call initialize() first.",
115 );
116 }
117 return NextEditProvider.instance;
118 }
119
120 public addDiffToContext(diff: string): void {
121 this.diffContext.push(diff);
122 if (this.diffContext.length > 5) {
123 this.diffContext.shift();
124 }
125 }
126
127 public addAutocompleteContext(ctx: string): void {
128 this.autocompleteContext = ctx;
129 }
130
131 private async _prepareLlm(): Promise<ILLM | undefined> {
132 const llm = await this._injectedGetLlm();
133
134 if (!llm) {
135 return undefined;
136 }
137
138 // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
139 if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
140 llm.model = llm.completionOptions.model;
141 }
142
143 // Ignore empty API keys for Mistral since we currently write
144 // a template provider without one during onboarding
145 if (llm.providerName === "mistral" && llm.apiKey === "") {
146 return undefined;
147 }
148
149 // Set temperature (but don't override)
150 if (llm.completionOptions.temperature === undefined) {
151 llm.completionOptions.temperature = 0.01;
152 }
153
154 if (llm instanceof OpenAI) {
155 llm.useLegacyCompletionsEndpoint = true;
156 }
157 // TODO: Resolve import error with TRIAL_FIM_MODEL
158 // else if (
159 // llm.providerName === "free-trial" &&
160 // llm.model !== TRIAL_FIM_MODEL
161 // ) {
162 // llm.model = TRIAL_FIM_MODEL;
163 // }
164
165 return llm;
166 }
167
168 private onError(e: any) {
169 if (
170 ERRORS_TO_IGNORE.some((err) =>
171 typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
172 )
173 ) {
174 return;
175 }
176
177 console.warn("Error generating autocompletion: ", e);
178 if (!this.errorsShown.has(e.message)) {
179 this.errorsShown.add(e.message);
180 this._onError(e);
181 }
182 }
183
184 public cancel() {
185 this.loggingService.cancel();
186 }
187
188 public accept(completionId: string) {
189 const outcome = this.loggingService.accept(completionId);
190 if (!outcome) {
191 return;
192 }
193 }
194
195 public reject(completionId: string) {
196 const outcome = this.loggingService.reject(completionId);
197 if (!outcome) {
198 return;
199 }
200 }
201
202 public markDisplayed(completionId: string, outcome: NextEditOutcome) {
203 this.loggingService.markDisplayed(completionId, outcome);
204 }
205
206 private async _getAutocompleteOptions() {
207 const { config } = await this.configHandler.loadConfig();
208 const options = {
209 ...DEFAULT_AUTOCOMPLETE_OPTS,
210 ...config?.tabAutocompleteOptions,
211 };
212 return options;
213 }
214
215 public chainExists(): boolean {
216 return this.currentEditChainId !== null;
217 }
218
219 public getChainLength(): number {
220 return this.previousCompletions.length;
221 }
222
223 public getPreviousCompletion(): NextEditOutcome | null {
224 return this.previousCompletions[0];
225 }
226
227 public async deleteChain(): Promise<void> {
228 PrefetchQueue.getInstance().abort();
229
230 this.currentEditChainId = null;
231 this.previousCompletions = [];
232
233 if (this.previousRequest) {
234 const fileContent = (
235 await this.ide.readFile(this.previousRequest.filepath)
236 ).toString();
237
238 const ast = await getAst(this.previousRequest.filepath, fileContent);
239
240 if (ast) {
241 DocumentHistoryTracker.getInstance().push(
242 localPathOrUriToPath(this.previousRequest.filepath),
243 fileContent,
244 ast,
245 );
246 }
247 }
248 }
249
250 public startChain(id?: string) {
251 this.currentEditChainId = id ?? uuidv4();
252 }
253
254 public getChain() {
255 return this.previousCompletions;
256 }
257
258 public isStartOfChain() {
259 return this.previousCompletions.length === 1;
260 }
261
262 /**
263 * This is the main entry point to this class.
264 */
265 public async provideInlineCompletionItems(
266 input: AutocompleteInput,
267 token: AbortSignal | undefined,
268 opts?: {
269 withChain: boolean;
270 usingFullFileDiff: boolean;
271 },
272 ): Promise<NextEditOutcome | undefined> {
273 if (isSecurityConcern(input.filepath)) {
274 return undefined;
275 }
276 try {
277 this.previousRequest = input;
278 const {
279 token: abortToken,
280 startTime,
281 helper,
282 } = await this._initializeCompletionRequest(input, token);
283 if (!helper) return undefined;
284
285 // Create model-specific provider based on the model name.
286 this.modelProvider = NextEditProviderFactory.createProvider(
287 helper.modelName,
288 );
289
290 const { editableRegionStartLine, editableRegionEndLine, prompts } =
291 await this._generatePrompts(helper, opts);
292
293 return await this._handleCompletion(
294 helper,
295 prompts,
296 abortToken,
297 startTime,
298 editableRegionStartLine,
299 editableRegionEndLine,
300 opts,
301 );
302 } catch (e: any) {
303 this.onError(e);
304 } finally {
305 this.loggingService.deleteAbortController(input.completionId);
306 }
307 }
308
309 private async _initializeCompletionRequest(
310 input: AutocompleteInput,
311 token: AbortSignal | undefined,
312 ): Promise<{
313 token: AbortSignal;
314 startTime: number;
315 helper: HelperVars | undefined;
316 }> {
317 // Create abort signal if not given
318 if (!token) {
319 const controller = this.loggingService.createAbortController(
320 input.completionId,
321 );
322 token = controller.signal;
323 } else {
324 // Token was provided externally, just track the completion.
325 this.loggingService.trackPendingCompletion(input.completionId);
326 }
327
328 const startTime = Date.now();
329 const options = await this._getAutocompleteOptions();
330
331 // Debounce
332 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
333 return { token, startTime, helper: undefined };
334 }
335
336 const llm = await this._prepareLlm();
337 if (!llm) {
338 return { token, startTime, helper: undefined };
339 }
340
341 // Update pending completion with model info.
342 this.loggingService.updatePendingCompletion(input.completionId, {
343 modelName: llm.model,
344 modelProvider: llm.providerName,
345 filepath: input.filepath,
346 });
347
348 // Check model capabilities
349 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
350 console.error(`${llm.model} is not capable of next edit.`);
351 return { token, startTime, helper: undefined };
352 }
353
354 if (llm.promptTemplates?.autocomplete) {
355 options.template = llm.promptTemplates.autocomplete as string;
356 }
357
358 const helper = await HelperVars.create(input, options, llm.model, this.ide);
359
360 if (await shouldPrefilter(helper, this.ide)) {
361 return { token, startTime, helper: undefined };
362 }
363
364 return { token, startTime, helper };
365 }
366
367 private async _generatePrompts(
368 helper: HelperVars,
369 opts?: {
370 withChain: boolean;
371 usingFullFileDiff: boolean;
372 },
373 ): Promise<{
374 editableRegionStartLine: number;
375 editableRegionEndLine: number;
376 prompts: Prompt[];
377 }> {
378 if (!this.modelProvider) {
379 throw new Error("Model provider not initialized");
380 }
381
382 // NOTE: getAllSnippetsWithoutRace doesn't seem to incur much performance penalties when compared to getAllSnippets.
383 // Use getAllSnippets if snippet gathering becomes noticably slow.
384 const [snippetPayload, workspaceDirs] = await Promise.all([
385 getAllSnippetsWithoutRace({
386 helper,
387 ide: this.ide,
388 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
389 contextRetrievalService: this.contextRetrievalService,
390 }),
391 this.ide.getWorkspaceDirs(),
392 ]);
393
394 // Calculate editable region based on model and options.
395 const { editableRegionStartLine, editableRegionEndLine } =
396 this.modelProvider.calculateEditableRegion(
397 helper,
398 opts?.usingFullFileDiff ?? false,
399 );
400
401 // Build context for model-specific prompt generation.
402 const context: ModelSpecificContext = {
403 helper,
404 snippetPayload,
405 editableRegionStartLine,
406 editableRegionEndLine,
407 diffContext: this.diffContext,
408 autocompleteContext: this.autocompleteContext,
409 historyDiff: createDiff({
410 beforeContent:
411 DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
412 localPathOrUriToPath(helper.filepath),
413 ) ?? "",
414 afterContent: helper.fileContents,
415 filePath: helper.filepath,
416 diffType: DiffFormatType.Unified,
417 contextLines: 3,
418 }),
419 };
420
421 const prompts = await this.modelProvider.generatePrompts(context);
422
423 this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
424
425 return { editableRegionStartLine, editableRegionEndLine, prompts };
426 }
427
428 private async _handleCompletion(
429 helper: HelperVars,
430 prompts: Prompt[],
431 token: AbortSignal,
432 startTime: number,
433 editableRegionStartLine: number,
434 editableRegionEndLine: number,
435 opts?: {
436 withChain: boolean;
437 usingFullFileDiff: boolean;
438 },
439 ): Promise<NextEditOutcome | undefined> {
440 if (!this.modelProvider) {
441 throw new Error("Model provider not initialized");
442 }
443
444 const llm = await this._prepareLlm();
445 if (!llm) return undefined;
446
447 // Inject unique token if needed (for Mercury models).
448 if (this.modelProvider.shouldInjectUniqueToken()) {
449 const uniqueToken = this.modelProvider.getUniqueToken();
450 if (uniqueToken) {
451 const lastPrompt = prompts[prompts.length - 1];
452 if (lastPrompt && typeof lastPrompt.content === "string") {
453 lastPrompt.content += uniqueToken;
454 }
455 }
456 }
457
458 // Send prompts to LLM (using only user prompt for fine-tuned models).
459 // prompts[1] extracts the user prompt from the system-user prompt pair.
460 // NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
461 // Mercury Coder currently does not support streaming.
462 const msg: ChatMessage = await llm.chat([prompts[1]], token, {
463 stream: false,
464 });
465
466 if (typeof msg.content !== "string") {
467 return undefined;
468 }
469
470 // Extract completion using model-specific logic.
471 const nextCompletion = this.modelProvider.extractCompletion(msg.content);
472
473 let outcome: NextEditOutcome | undefined;
474
475 // Handle based on diff type.
476 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
477 outcome = await this.modelProvider.handlePartialFileDiff(
478 helper,
479 editableRegionStartLine,
480 editableRegionEndLine,
481 startTime,
482 llm,
483 nextCompletion,
484 this.promptMetadata!,
485 this.ide,
486 );
487 } else {
488 outcome = await this.modelProvider.handleFullFileDiff(
489 helper,
490 editableRegionStartLine,
491 editableRegionEndLine,
492 startTime,
493 llm,
494 nextCompletion,
495 this.promptMetadata!,
496 this.ide,
497 );
498 }
499
500 if (outcome) {
501 // Handle NextEditProvider-specific state.
502 this.previousCompletions.push(outcome);
503
504 // Mark as displayed for JetBrains
505 await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
506 }
507
508 return outcome;
509 }
510
511 private async _markDisplayedIfJetBrains(
512 completionId: string,
513 outcome: NextEditOutcome,
514 ): Promise<void> {
515 const ideType = (await this.ide.getIdeInfo()).ideType;
516 if (ideType === "jetbrains") {
517 this.markDisplayed(completionId, outcome);
518 }
519 }
520
521 /**
522 * This is a wrapper around provideInlineCompletionItems.
523 * This is invoked when we call the model in the background using prefetch.
524 * It's not currently used anywhere (references are not used either), but I decided to keep it in case we actually need to use prefetch.
525 * You will see that calls to this method is made from NextEditPrefetchQueue.proecss(), which is wrapped in `if (!this.usingFullFileDiff)`.
526 */
527 public async provideInlineCompletionItemsWithChain(
528 ctx: {
529 completionId: string;
530 manuallyPassFileContents?: string;
531 manuallyPassPrefix?: string;
532 selectedCompletionInfo?: {
533 text: string;
534 range: Range;
535 };
536 isUntitledFile: boolean;
537 recentlyVisitedRanges: AutocompleteCodeSnippet[];
538 recentlyEditedRanges: RecentlyEditedRange[];
539 },
540 nextEditLocation: RangeInFile,
541 token: AbortSignal | undefined,
542 usingFullFileDiff: boolean,
543 ) {
544 try {
545 const previousOutcome = this.getPreviousCompletion();
546 if (!previousOutcome) {
547 console.log("previousOutcome is undefined");
548 return undefined;
549 }
550
551 // Use the frontmost RangeInFile to build an input.
552 const input = this.buildAutocompleteInputFromChain(
553 previousOutcome,
554 nextEditLocation,
555 ctx,
556 );
557 if (!input) {
558 console.log("input is undefined");
559 return undefined;
560 }
561
562 return await this.provideInlineCompletionItems(input, token, {
563 withChain: true,
564 usingFullFileDiff,
565 });
566 } catch (e: any) {
567 this.onError(e);
568 }
569 }
570
571 private buildAutocompleteInputFromChain(
572 previousOutcome: NextEditOutcome,
573 nextEditableRegion: RangeInFile,
574 ctx: {
575 completionId: string;
576 manuallyPassFileContents?: string;
577 manuallyPassPrefix?: string;
578 selectedCompletionInfo?: {
579 text: string;
580 range: Range;
581 };
582 isUntitledFile: boolean;
583 recentlyVisitedRanges: AutocompleteCodeSnippet[];
584 recentlyEditedRanges: RecentlyEditedRange[];
585 },
586 ): AutocompleteInput | undefined {
587 const input: AutocompleteInput = {
588 pos: {
589 line: nextEditableRegion.range.start.line,
590 character: nextEditableRegion.range.start.character,
591 },
592 filepath: previousOutcome.fileUri,
593 ...ctx,
594 };
595
596 return input;
597 }
598}