Elffuss BraidHub

kikocis/continue public

5fda066adb4e · 8.9 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 "./classification/shouldCompleteMultiline.js";
7import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
8
9import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
10import { CompletionStreamer } from "./generation/CompletionStreamer.js";
11import { postprocessCompletion } from "./postprocessing/index.js";
12import { shouldPrefilter } from "./prefiltering/index.js";
13import { renderPromptWithTokenLimit } from "./templating/index.js";
14import { getAllSnippetsWithoutRace } from "./snippets/index.js";
15import { GetLspDefinitionsFunction } from "./types.js";
16import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
17import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
18import AutocompleteLruCache from "./util/AutocompleteLruCache.js";
19import { HelperVars } from "./util/HelperVars.js";
20import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js";
21
22const 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
26const ERRORS_TO_IGNORE = [
27 // From Ollama
28 "unexpected server status",
29 "operation was aborted",
30];
31
32export 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 } =
190 renderPromptWithTokenLimit({
191 snippetPayload,
192 workspaceDirs,
193 helper,
194 llm,
195 });
196
197 // Completion
198 let completion: string | undefined = "";
199
200 const cache = await autocompleteCache;
201 const cachedCompletion = helper.options.useCache
202 ? await cache.get(helper.prunedPrefix)
203 : undefined;
204 let cacheHit = false;
205 if (cachedCompletion) {
206 // Cache
207 cacheHit = true;
208 completion = cachedCompletion;
209 } else {
210 const multiline =
211 !helper.options.transform || shouldCompleteMultiline(helper);
212
213 const rawGeneration = await llm.complete(
214 prompt,
215 token,
216 completionOptions,
217 );
218
219 const completionStream =
220 this.completionStreamer.streamCompletionWithFilters(
221 token,
222 llm,
223 prefix,
224 suffix,
225 prompt,
226 multiline,
227 completionOptions,
228 helper,
229 );
230
231 for await (const update of completionStream) {
232 completion += update;
233 }
234
235 // Don't postprocess if aborted
236 if (token.aborted) {
237 return undefined;
238 }
239
240 const processedCompletion = helper.options.transform
241 ? postprocessCompletion({
242 completion,
243 prefix: helper.prunedPrefix,
244 suffix: helper.prunedSuffix,
245 llm,
246 })
247 : completion;
248
249 completion = processedCompletion;
250 }
251
252 if (!completion) {
253 return undefined;
254 }
255
256 const outcome: AutocompleteOutcome = {
257 time: Date.now() - startTime,
258 completion,
259 prefix,
260 suffix,
261 prompt,
262 modelProvider: llm.underlyingProviderName,
263 modelName: llm.model,
264 completionOptions,
265 cacheHit,
266 filepath: helper.filepath,
267 numLines: completion.split("\n").length,
268 completionId: helper.input.completionId,
269 gitRepo: await this.ide.getRepoName(helper.filepath),
270 uniqueId: await this.ide.getUniqueId(),
271 timestamp: new Date().toISOString(),
272 ...helper.options,
273 };
274
275 if (options.experimental_enableStaticContextualization) {
276 outcome.enabledStaticContextualization = true;
277 }
278
279 //////////
280
281 // Save to cache
282 if (!outcome.cacheHit && helper.options.useCache) {
283 (await this.autocompleteCache)
284 .put(outcome.prefix, outcome.completion)
285 .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
286 }
287
288 // When using the JetBrains extension, Mark as displayed
289 const ideType = (await this.ide.getIdeInfo()).ideType;
290 if (ideType === "jetbrains") {
291 this.markDisplayed(input.completionId, outcome);
292 }
293
294 return outcome;
295 } catch (e: any) {
296 this.onError(e);
297 } finally {
298 this.loggingService.deleteAbortController(input.completionId);
299 }
300 }
301}