Elffuss BraidHub

kikocis/continue public

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