Elffuss BraidHub

kikocis/continue public

2755bf5d2df4 · 8.4 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 { getAllSnippets } from "./snippets/index.js";
14import { renderPrompt } from "./templating/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 return options;
125 }
126
127 public async provideInlineCompletionItems(
128 input: AutocompleteInput,
129 token: AbortSignal | undefined,
130 force?: boolean,
131 ): Promise<AutocompleteOutcome | undefined> {
132 try {
133 // Create abort signal if not given
134 if (!token) {
135 const controller = this.loggingService.createAbortController(
136 input.completionId,
137 );
138 token = controller.signal;
139 }
140 const startTime = Date.now();
141
142 const llm = await this._prepareLlm();
143 if (!llm) {
144 return undefined;
145 }
146
147 const options = await this._getAutocompleteOptions(llm);
148
149 // Debounce
150 if (!force) {
151 if (
152 await this.debouncer.delayAndShouldDebounce(options.debounceDelay)
153 ) {
154 return undefined;
155 }
156 }
157
158 if (llm.promptTemplates?.autocomplete) {
159 options.template = llm.promptTemplates.autocomplete as string;
160 }
161
162 const helper = await HelperVars.create(
163 input,
164 options,
165 llm.model,
166 this.ide,
167 );
168
169 if (await shouldPrefilter(helper, this.ide)) {
170 return undefined;
171 }
172
173 const [snippetPayload, workspaceDirs] = await Promise.all([
174 getAllSnippets({
175 helper,
176 ide: this.ide,
177 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
178 contextRetrievalService: this.contextRetrievalService,
179 }),
180 this.ide.getWorkspaceDirs(),
181 ]);
182
183 const { prompt, prefix, suffix, completionOptions } = renderPrompt({
184 snippetPayload,
185 workspaceDirs,
186 helper,
187 });
188
189 // Completion
190 let completion: string | undefined = "";
191
192 const cache = await autocompleteCache;
193 const cachedCompletion = helper.options.useCache
194 ? await cache.get(helper.prunedPrefix)
195 : undefined;
196 let cacheHit = false;
197 if (cachedCompletion) {
198 // Cache
199 cacheHit = true;
200 completion = cachedCompletion;
201 } else {
202 const multiline =
203 !helper.options.transform || shouldCompleteMultiline(helper);
204
205 const completionStream =
206 this.completionStreamer.streamCompletionWithFilters(
207 token,
208 llm,
209 prefix,
210 suffix,
211 prompt,
212 multiline,
213 completionOptions,
214 helper,
215 );
216
217 for await (const update of completionStream) {
218 completion += update;
219 }
220
221 // Don't postprocess if aborted
222 if (token.aborted) {
223 return undefined;
224 }
225
226 const processedCompletion = helper.options.transform
227 ? postprocessCompletion({
228 completion,
229 prefix: helper.prunedPrefix,
230 suffix: helper.prunedSuffix,
231 llm,
232 })
233 : completion;
234
235 completion = processedCompletion;
236 }
237
238 if (!completion) {
239 return undefined;
240 }
241
242 const outcome: AutocompleteOutcome = {
243 time: Date.now() - startTime,
244 completion,
245 prefix,
246 suffix,
247 prompt,
248 modelProvider: llm.underlyingProviderName,
249 modelName: llm.model,
250 completionOptions,
251 cacheHit,
252 filepath: helper.filepath,
253 numLines: completion.split("\n").length,
254 completionId: helper.input.completionId,
255 gitRepo: await this.ide.getRepoName(helper.filepath),
256 uniqueId: await this.ide.getUniqueId(),
257 timestamp: new Date().toISOString(),
258 ...helper.options,
259 };
260
261 //////////
262
263 // Save to cache
264 if (!outcome.cacheHit && helper.options.useCache) {
265 (await this.autocompleteCache)
266 .put(outcome.prefix, outcome.completion)
267 .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
268 }
269
270 // When using the JetBrains extension, Mark as displayed
271 const ideType = (await this.ide.getIdeInfo()).ideType;
272 if (ideType === "jetbrains") {
273 this.markDisplayed(input.completionId, outcome);
274 }
275
276 return outcome;
277 } catch (e: any) {
278 this.onError(e);
279 } finally {
280 this.loggingService.deleteAbortController(input.completionId);
281 }
282 }
283}