Elffuss BraidHub

kikocis/continue public

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