| 1 | import { ConfigHandler } from "../config/ConfigHandler.js"; |
| 2 | import { IDE, ILLM } from "../index.js"; |
| 3 | import OpenAI from "../llm/llms/OpenAI.js"; |
| 4 | import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; |
| 5 | |
| 6 | import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; |
| 7 | import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; |
| 8 | |
| 9 | import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; |
| 10 | import { CompletionStreamer } from "./generation/CompletionStreamer.js"; |
| 11 | import { postprocessCompletion } from "./postprocessing/index.js"; |
| 12 | import { shouldPrefilter } from "./prefiltering/index.js"; |
| 13 | import { getAllSnippetsWithoutRace } from "./snippets/index.js"; |
| 14 | import { renderPrompt } from "./templating/index.js"; |
| 15 | import { GetLspDefinitionsFunction } from "./types.js"; |
| 16 | import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; |
| 17 | import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; |
| 18 | import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; |
| 19 | import { HelperVars } from "./util/HelperVars.js"; |
| 20 | import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js"; |
| 21 | |
| 22 | const autocompleteCache = AutocompleteLruCache.get(); |
| 23 | |
| 24 | // Errors that can be expected on occasion even during normal functioning should not be shown. |
| 25 | // Not worth disrupting the user to tell them that a single autocomplete request didn't go through |
| 26 | const ERRORS_TO_IGNORE = [ |
| 27 | // From Ollama |
| 28 | "unexpected server status", |
| 29 | "operation was aborted", |
| 30 | ]; |
| 31 | |
| 32 | export class CompletionProvider { |
| 33 | private autocompleteCache = AutocompleteLruCache.get(); |
| 34 | public errorsShown: Set<string> = new Set(); |
| 35 | private bracketMatchingService = new BracketMatchingService(); |
| 36 | private debouncer = new AutocompleteDebouncer(); |
| 37 | private completionStreamer: CompletionStreamer; |
| 38 | private loggingService = new AutocompleteLoggingService(); |
| 39 | private contextRetrievalService: ContextRetrievalService; |
| 40 | |
| 41 | constructor( |
| 42 | private readonly configHandler: ConfigHandler, |
| 43 | private readonly ide: IDE, |
| 44 | private readonly _injectedGetLlm: () => Promise<ILLM | undefined>, |
| 45 | private readonly _onError: (e: any) => void, |
| 46 | private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, |
| 47 | ) { |
| 48 | this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); |
| 49 | this.contextRetrievalService = new ContextRetrievalService(this.ide); |
| 50 | } |
| 51 | |
| 52 | private async _prepareLlm(): Promise<ILLM | undefined> { |
| 53 | const llm = await this._injectedGetLlm(); |
| 54 | |
| 55 | if (!llm) { |
| 56 | return undefined; |
| 57 | } |
| 58 | |
| 59 | // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022 |
| 60 | if (llm.model === undefined && llm.completionOptions?.model !== undefined) { |
| 61 | llm.model = llm.completionOptions.model; |
| 62 | } |
| 63 | |
| 64 | // Ignore empty API keys for Mistral since we currently write |
| 65 | // a template provider without one during onboarding |
| 66 | if (llm.providerName === "mistral" && llm.apiKey === "") { |
| 67 | return undefined; |
| 68 | } |
| 69 | |
| 70 | // Set temperature (but don't override) |
| 71 | if (llm.completionOptions.temperature === undefined) { |
| 72 | llm.completionOptions.temperature = 0.01; |
| 73 | } |
| 74 | |
| 75 | if (llm instanceof OpenAI) { |
| 76 | llm.useLegacyCompletionsEndpoint = true; |
| 77 | } |
| 78 | |
| 79 | return llm; |
| 80 | } |
| 81 | |
| 82 | private onError(e: any) { |
| 83 | if ( |
| 84 | ERRORS_TO_IGNORE.some((err) => |
| 85 | typeof e === "string" ? e.includes(err) : e?.message?.includes(err), |
| 86 | ) |
| 87 | ) { |
| 88 | return; |
| 89 | } |
| 90 | |
| 91 | console.warn("Error generating autocompletion: ", e); |
| 92 | if (!this.errorsShown.has(e.message)) { |
| 93 | this.errorsShown.add(e.message); |
| 94 | this._onError(e); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | public cancel() { |
| 99 | this.loggingService.cancel(); |
| 100 | } |
| 101 | |
| 102 | public accept(completionId: string) { |
| 103 | const outcome = this.loggingService.accept(completionId); |
| 104 | if (!outcome) { |
| 105 | return; |
| 106 | } |
| 107 | this.bracketMatchingService.handleAcceptedCompletion( |
| 108 | outcome.completion, |
| 109 | outcome.filepath, |
| 110 | ); |
| 111 | } |
| 112 | |
| 113 | public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { |
| 114 | this.loggingService.markDisplayed(completionId, outcome); |
| 115 | } |
| 116 | |
| 117 | private async _getAutocompleteOptions(llm: ILLM) { |
| 118 | const { config } = await this.configHandler.loadConfig(); |
| 119 | const options = { |
| 120 | ...DEFAULT_AUTOCOMPLETE_OPTS, |
| 121 | ...config?.tabAutocompleteOptions, |
| 122 | ...llm.autocompleteOptions, |
| 123 | }; |
| 124 | |
| 125 | // Enable static contextualization if defined. |
| 126 | if (config?.experimental?.enableStaticContextualization) { |
| 127 | options.experimental_enableStaticContextualization = true; |
| 128 | } |
| 129 | |
| 130 | return options; |
| 131 | } |
| 132 | |
| 133 | public async provideInlineCompletionItems( |
| 134 | input: AutocompleteInput, |
| 135 | token: AbortSignal | undefined, |
| 136 | force?: boolean, |
| 137 | ): Promise<AutocompleteOutcome | undefined> { |
| 138 | try { |
| 139 | // Create abort signal if not given |
| 140 | if (!token) { |
| 141 | const controller = this.loggingService.createAbortController( |
| 142 | input.completionId, |
| 143 | ); |
| 144 | token = controller.signal; |
| 145 | } |
| 146 | const startTime = Date.now(); |
| 147 | |
| 148 | const llm = await this._prepareLlm(); |
| 149 | if (!llm) { |
| 150 | return undefined; |
| 151 | } |
| 152 | |
| 153 | const options = await this._getAutocompleteOptions(llm); |
| 154 | |
| 155 | // Debounce |
| 156 | if (!force) { |
| 157 | if ( |
| 158 | await this.debouncer.delayAndShouldDebounce(options.debounceDelay) |
| 159 | ) { |
| 160 | return undefined; |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | if (llm.promptTemplates?.autocomplete) { |
| 165 | options.template = llm.promptTemplates.autocomplete as string; |
| 166 | } |
| 167 | |
| 168 | const helper = await HelperVars.create( |
| 169 | input, |
| 170 | options, |
| 171 | llm.model, |
| 172 | this.ide, |
| 173 | ); |
| 174 | |
| 175 | if (await shouldPrefilter(helper, this.ide)) { |
| 176 | return undefined; |
| 177 | } |
| 178 | |
| 179 | const [snippetPayload, workspaceDirs] = await Promise.all([ |
| 180 | getAllSnippetsWithoutRace({ |
| 181 | helper, |
| 182 | ide: this.ide, |
| 183 | getDefinitionsFromLsp: this.getDefinitionsFromLsp, |
| 184 | contextRetrievalService: this.contextRetrievalService, |
| 185 | }), |
| 186 | this.ide.getWorkspaceDirs(), |
| 187 | ]); |
| 188 | |
| 189 | const { prompt, prefix, suffix, completionOptions } = renderPrompt({ |
| 190 | snippetPayload, |
| 191 | workspaceDirs, |
| 192 | helper, |
| 193 | }); |
| 194 | |
| 195 | // Completion |
| 196 | let completion: string | undefined = ""; |
| 197 | |
| 198 | const cache = await autocompleteCache; |
| 199 | const cachedCompletion = helper.options.useCache |
| 200 | ? await cache.get(helper.prunedPrefix) |
| 201 | : undefined; |
| 202 | let cacheHit = false; |
| 203 | if (cachedCompletion) { |
| 204 | // Cache |
| 205 | cacheHit = true; |
| 206 | completion = cachedCompletion; |
| 207 | } else { |
| 208 | const multiline = |
| 209 | !helper.options.transform || shouldCompleteMultiline(helper); |
| 210 | |
| 211 | const completionStream = |
| 212 | this.completionStreamer.streamCompletionWithFilters( |
| 213 | token, |
| 214 | llm, |
| 215 | prefix, |
| 216 | suffix, |
| 217 | prompt, |
| 218 | multiline, |
| 219 | completionOptions, |
| 220 | helper, |
| 221 | ); |
| 222 | |
| 223 | for await (const update of completionStream) { |
| 224 | completion += update; |
| 225 | } |
| 226 | |
| 227 | // Don't postprocess if aborted |
| 228 | if (token.aborted) { |
| 229 | return undefined; |
| 230 | } |
| 231 | |
| 232 | const processedCompletion = helper.options.transform |
| 233 | ? postprocessCompletion({ |
| 234 | completion, |
| 235 | prefix: helper.prunedPrefix, |
| 236 | suffix: helper.prunedSuffix, |
| 237 | llm, |
| 238 | }) |
| 239 | : completion; |
| 240 | |
| 241 | completion = processedCompletion; |
| 242 | } |
| 243 | |
| 244 | if (!completion) { |
| 245 | return undefined; |
| 246 | } |
| 247 | |
| 248 | const outcome: AutocompleteOutcome = { |
| 249 | time: Date.now() - startTime, |
| 250 | completion, |
| 251 | prefix, |
| 252 | suffix, |
| 253 | prompt, |
| 254 | modelProvider: llm.underlyingProviderName, |
| 255 | modelName: llm.model, |
| 256 | completionOptions, |
| 257 | cacheHit, |
| 258 | filepath: helper.filepath, |
| 259 | numLines: completion.split("\n").length, |
| 260 | completionId: helper.input.completionId, |
| 261 | gitRepo: await this.ide.getRepoName(helper.filepath), |
| 262 | uniqueId: await this.ide.getUniqueId(), |
| 263 | timestamp: new Date().toISOString(), |
| 264 | ...helper.options, |
| 265 | }; |
| 266 | |
| 267 | if (options.experimental_enableStaticContextualization) { |
| 268 | outcome.enabledStaticContextualization = true; |
| 269 | } |
| 270 | |
| 271 | ////////// |
| 272 | |
| 273 | // Save to cache |
| 274 | if (!outcome.cacheHit && helper.options.useCache) { |
| 275 | (await this.autocompleteCache) |
| 276 | .put(outcome.prefix, outcome.completion) |
| 277 | .catch((e) => console.warn(`Failed to save to cache: ${e.message}`)); |
| 278 | } |
| 279 | |
| 280 | // When using the JetBrains extension, Mark as displayed |
| 281 | const ideType = (await this.ide.getIdeInfo()).ideType; |
| 282 | if (ideType === "jetbrains") { |
| 283 | this.markDisplayed(input.completionId, outcome); |
| 284 | } |
| 285 | |
| 286 | return outcome; |
| 287 | } catch (e: any) { |
| 288 | this.onError(e); |
| 289 | } finally { |
| 290 | this.loggingService.deleteAbortController(input.completionId); |
| 291 | } |
| 292 | } |
| 293 | } |