diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts new file mode 100644 index 000000000..9e0dc1cd8 --- /dev/null +++ b/core/nextEdit/NextEditProvider.ts @@ -0,0 +1,282 @@ +import { ConfigHandler } from "../config/ConfigHandler.js"; +import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; +import { IDE, ILLM } from "../index.js"; +import OpenAI from "../llm/llms/OpenAI.js"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; + +import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js"; +import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js"; + +import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js"; +import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js"; +import { postprocessCompletion } from "../autocomplete/postprocessing/index.js"; +import { shouldPrefilter } from "../autocomplete/prefiltering/index.js"; +import { getAllSnippets } from "../autocomplete/snippets/index.js"; +import { renderPrompt } from "../autocomplete/templating/index.js"; +import { GetLspDefinitionsFunction } from "../autocomplete/types.js"; +import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js"; +import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js"; +import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; +import { HelperVars } from "../autocomplete/util/HelperVars.js"; +import { AutocompleteInput, AutocompleteOutcome } from "../autocomplete/util/types.js"; + +const autocompleteCache = AutocompleteLruCache.get(); + +// Errors that can be expected on occasion even during normal functioning should not be shown. +// Not worth disrupting the user to tell them that a single autocomplete request didn't go through +const ERRORS_TO_IGNORE = [ + // From Ollama + "unexpected server status", + "operation was aborted", +]; + +export class NextEditProvider { + private autocompleteCache = AutocompleteLruCache.get(); + public errorsShown: Set = new Set(); + private bracketMatchingService = new BracketMatchingService(); + private debouncer = new AutocompleteDebouncer(); + private completionStreamer: CompletionStreamer; + private loggingService = new AutocompleteLoggingService(); + private contextRetrievalService: ContextRetrievalService; + + constructor( + private readonly configHandler: ConfigHandler, + private readonly ide: IDE, + private readonly _injectedGetLlm: () => Promise, + private readonly _onError: (e: any) => void, + private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, + ) { + this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); + this.contextRetrievalService = new ContextRetrievalService(this.ide); + } + + private async _prepareLlm(): Promise { + const llm = await this._injectedGetLlm(); + + if (!llm) { + return undefined; + } + + // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022 + if (llm.model === undefined && llm.completionOptions?.model !== undefined) { + llm.model = llm.completionOptions.model; + } + + // Ignore empty API keys for Mistral since we currently write + // a template provider without one during onboarding + if (llm.providerName === "mistral" && llm.apiKey === "") { + return undefined; + } + + // Set temperature (but don't override) + if (llm.completionOptions.temperature === undefined) { + llm.completionOptions.temperature = 0.01; + } + + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } else if ( + llm.providerName === "free-trial" && + llm.model !== TRIAL_FIM_MODEL + ) { + llm.model = TRIAL_FIM_MODEL; + } + + return llm; + } + + private onError(e: any) { + if ( + ERRORS_TO_IGNORE.some((err) => + typeof e === "string" ? e.includes(err) : e?.message?.includes(err), + ) + ) { + return; + } + + console.warn("Error generating autocompletion: ", e); + if (!this.errorsShown.has(e.message)) { + this.errorsShown.add(e.message); + this._onError(e); + } + } + + public cancel() { + this.loggingService.cancel(); + } + + public accept(completionId: string) { + const outcome = this.loggingService.accept(completionId); + if (!outcome) { + return; + } + this.bracketMatchingService.handleAcceptedCompletion( + outcome.completion, + outcome.filepath, + ); + } + + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + this.loggingService.markDisplayed(completionId, outcome); + } + + private async _getAutocompleteOptions() { + const { config } = await this.configHandler.loadConfig(); + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config?.tabAutocompleteOptions, + }; + return options; + } + + public async provideInlineCompletionItems( + input: AutocompleteInput, + token: AbortSignal | undefined, + ): Promise { + try { + // Create abort signal if not given + if (!token) { + const controller = this.loggingService.createAbortController( + input.completionId, + ); + token = controller.signal; + } + const startTime = Date.now(); + const options = await this._getAutocompleteOptions(); + + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; + } + + const llm = await this._prepareLlm(); + if (!llm) { + return undefined; + } + + if (llm.promptTemplates?.autocomplete) { + options.template = llm.promptTemplates.autocomplete as string; + } + + const helper = await HelperVars.create( + input, + options, + llm.model, + this.ide, + ); + + if (await shouldPrefilter(helper, this.ide)) { + return undefined; + } + + const [snippetPayload, workspaceDirs] = await Promise.all([ + getAllSnippets({ + helper, + ide: this.ide, + getDefinitionsFromLsp: this.getDefinitionsFromLsp, + contextRetrievalService: this.contextRetrievalService, + }), + this.ide.getWorkspaceDirs(), + ]); + + const { prompt, prefix, suffix, completionOptions } = renderPrompt({ + snippetPayload, + workspaceDirs, + helper, + }); + + // Completion + let completion: string | undefined = ""; + + const cache = await autocompleteCache; + const cachedCompletion = helper.options.useCache + ? await cache.get(helper.prunedPrefix) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + const multiline = + !helper.options.transform || shouldCompleteMultiline(helper); + + const completionStream = + this.completionStreamer.streamCompletionWithFilters( + token, + llm, + prefix, + suffix, + prompt, + multiline, + completionOptions, + helper, + ); + + for await (const update of completionStream) { + completion += update; + } + + // Don't postprocess if aborted + if (token.aborted) { + return undefined; + } + + const processedCompletion = helper.options.transform + ? postprocessCompletion({ + completion, + prefix: helper.prunedPrefix, + suffix: helper.prunedSuffix, + llm, + }) + : completion; + + completion = processedCompletion; + } + + if (!completion) { + return undefined; + } + + const outcome: AutocompleteOutcome = { + time: Date.now() - startTime, + completion, + prefix, + suffix, + prompt, + modelProvider: llm.underlyingProviderName, + modelName: llm.model, + completionOptions, + cacheHit, + filepath: helper.filepath, + numLines: completion.split("\n").length, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + timestamp: Date.now(), + ...helper.options, + }; + + ////////// + + // Save to cache + if (!outcome.cacheHit && helper.options.useCache) { + (await this.autocompleteCache) + .put(outcome.prefix, outcome.completion) + .catch((e) => console.warn(`Failed to save to cache: ${e.message}`)); + } + + // When using the JetBrains extension, Mark as displayed + const ideType = (await this.ide.getIdeInfo()).ideType; + if (ideType === "jetbrains") { + this.markDisplayed(input.completionId, outcome); + } + + return outcome; + } catch (e: any) { + this.onError(e); + } finally { + this.loggingService.deleteAbortController(input.completionId); + } + } +} diff --git a/core/nextEdit/constants.ts b/core/nextEdit/constants.ts new file mode 100644 index 000000000..317a3dcf7 --- /dev/null +++ b/core/nextEdit/constants.ts @@ -0,0 +1 @@ +export const IS_NEXT_EDIT_ACTIVE = false; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index a2688d886..432e3d8af 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,6 +5,8 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; +import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; +import { NextEditProvider } from "core/nextEdit/NextEditProvider"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; @@ -59,6 +61,7 @@ export class ContinueCompletionProvider } private completionProvider: CompletionProvider; + private nextEditProvider: NextEditProvider | undefined; private recentlyVisitedRanges: RecentlyVisitedRangesService; private recentlyEditedTracker: RecentlyEditedTracker; @@ -83,12 +86,21 @@ export class ContinueCompletionProvider this.onError.bind(this), getDefinitionsFromLsp, ); + // NOTE: Only turn it on locally when testing (for review purposes). + if (IS_NEXT_EDIT_ACTIVE) { + this.nextEditProvider = new NextEditProvider( + this.configHandler, + this.ide, + getAutocompleteModel, + this.onError.bind(this), + getDefinitionsFromLsp, + ); + } this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); } _lastShownCompletion: AutocompleteOutcome | undefined; - public async provideInlineCompletionItems( document: vscode.TextDocument, position: vscode.Position, @@ -209,6 +221,17 @@ export class ContinueCompletionProvider return null; } + // NOTE: This is a very rudimentary check to see if we can call the next edit service. + // In the future we will have to figure out how to call this more gracefully. + if (this.nextEditProvider) { + const nextEditOutcome = + await this.nextEditProvider?.provideInlineCompletionItems(input, signal); + + if (nextEditOutcome && nextEditOutcome.completion) { + outcome.completion = nextEditOutcome.completion; + } + } + // VS Code displays dependent on selectedCompletionInfo (their docstring below) // We should first always make sure we have a valid completion, but if it goes wrong we // want telemetry to be correct @@ -254,7 +277,7 @@ export class ContinueCompletionProvider const result = processSingleLineCompletion( lastLineOfCompletionText, currentText, - startPos.character + startPos.character, ); if (result === undefined) { @@ -265,10 +288,9 @@ export class ContinueCompletionProvider if (result.range) { range = new vscode.Range( new vscode.Position(startPos.line, result.range.start), - new vscode.Position(startPos.line, result.range.end) + new vscode.Position(startPos.line, result.range.end), ); } - } else { // Extend the range to the end of the line for multiline completions range = new vscode.Range(startPos, document.lineAt(startPos).range.end);