Elffuss BraidHub

kikocis/continue public

main · 9.0 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 { isSecurityConcern } from "../indexing/ignore.js";
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 { getAllSnippetsWithoutRace } from "./snippets/index.js";
15import { renderPromptWithTokenLimit } 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 }
79
80 return llm;
81 }
82
83 private onError(e: any) {
84 if (
85 ERRORS_TO_IGNORE.some((err) =>
86 typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
87 )
88 ) {
89 return;
90 }
91
92 console.warn("Error generating autocompletion: ", e);
93 if (!this.errorsShown.has(e.message)) {
94 this.errorsShown.add(e.message);
95 this._onError(e);
96 }
97 }
98
99 public cancel() {
100 this.loggingService.cancel();
101 }
102
103 public accept(completionId: string) {
104 const outcome = this.loggingService.accept(completionId);
105 if (!outcome) {
106 return;
107 }
108 this.bracketMatchingService.handleAcceptedCompletion(
109 outcome.completion,
110 outcome.filepath,
111 );
112 }
113
114 public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
115 this.loggingService.markDisplayed(completionId, outcome);
116 }
117
118 private async _getAutocompleteOptions(llm: ILLM) {
119 const { config } = await this.configHandler.loadConfig();
120 const options = {
121 ...DEFAULT_AUTOCOMPLETE_OPTS,
122 ...config?.tabAutocompleteOptions,
123 ...llm.autocompleteOptions,
124 };
125
126 // Enable static contextualization if defined.
127 if (config?.experimental?.enableStaticContextualization) {
128 options.experimental_enableStaticContextualization = true;
129 }
130
131 return options;
132 }
133
134 public async provideInlineCompletionItems(
135 input: AutocompleteInput,
136 token: AbortSignal | undefined,
137 force?: boolean,
138 ): Promise<AutocompleteOutcome | undefined> {
139 try {
140 // Create abort signal if not given
141 if (!token) {
142 const controller = this.loggingService.createAbortController(
143 input.completionId,
144 );
145 token = controller.signal;
146 }
147 const startTime = Date.now();
148
149 const llm = await this._prepareLlm();
150 if (!llm) {
151 return undefined;
152 }
153
154 if (isSecurityConcern(input.filepath)) {
155 return undefined;
156 }
157
158 const options = await this._getAutocompleteOptions(llm);
159
160 // Debounce
161 if (!force) {
162 if (
163 await this.debouncer.delayAndShouldDebounce(options.debounceDelay)
164 ) {
165 return undefined;
166 }
167 }
168
169 if (llm.promptTemplates?.autocomplete) {
170 options.template = llm.promptTemplates.autocomplete as string;
171 }
172
173 const helper = await HelperVars.create(
174 input,
175 options,
176 llm.model,
177 this.ide,
178 );
179
180 if (await shouldPrefilter(helper, this.ide)) {
181 return undefined;
182 }
183
184 const [snippetPayload, workspaceDirs] = await Promise.all([
185 getAllSnippetsWithoutRace({
186 helper,
187 ide: this.ide,
188 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
189 contextRetrievalService: this.contextRetrievalService,
190 }),
191 this.ide.getWorkspaceDirs(),
192 ]);
193
194 const { prompt, prefix, suffix, completionOptions } =
195 renderPromptWithTokenLimit({
196 snippetPayload,
197 workspaceDirs,
198 helper,
199 llm,
200 });
201
202 // Completion
203 let completion: string | undefined = "";
204
205 const cache = await autocompleteCache;
206 const cachedCompletion = helper.options.useCache
207 ? await cache.get(helper.prunedPrefix)
208 : undefined;
209 let cacheHit = false;
210 if (cachedCompletion) {
211 // Cache
212 cacheHit = true;
213 completion = cachedCompletion;
214 } else {
215 const multiline =
216 !helper.options.transform || shouldCompleteMultiline(helper);
217
218 const completionStream =
219 this.completionStreamer.streamCompletionWithFilters(
220 token,
221 llm,
222 prefix,
223 suffix,
224 prompt,
225 multiline,
226 completionOptions,
227 helper,
228 );
229
230 for await (const update of completionStream) {
231 completion += update;
232 }
233
234 // Don't postprocess if aborted
235 if (token.aborted) {
236 return undefined;
237 }
238
239 const processedCompletion = helper.options.transform
240 ? postprocessCompletion({
241 completion,
242 prefix: helper.prunedPrefix,
243 suffix: helper.prunedSuffix,
244 llm,
245 })
246 : completion;
247
248 completion = processedCompletion;
249 }
250
251 if (!completion) {
252 return undefined;
253 }
254
255 const outcome: AutocompleteOutcome = {
256 time: Date.now() - startTime,
257 completion,
258 prefix,
259 suffix,
260 prompt,
261 modelProvider: llm.underlyingProviderName,
262 modelName: llm.model,
263 completionOptions,
264 cacheHit,
265 filepath: helper.filepath,
266 numLines: completion.split("\n").length,
267 completionId: helper.input.completionId,
268 gitRepo: await this.ide.getRepoName(helper.filepath),
269 uniqueId: await this.ide.getUniqueId(),
270 timestamp: new Date().toISOString(),
271 ...helper.options,
272 };
273
274 if (options.experimental_enableStaticContextualization) {
275 outcome.enabledStaticContextualization = true;
276 }
277
278 //////////
279
280 // Save to cache
281 if (!outcome.cacheHit && helper.options.useCache) {
282 (await this.autocompleteCache)
283 .put(outcome.prefix, outcome.completion)
284 .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
285 }
286
287 // When using the JetBrains extension, Mark as displayed
288 const ideType = (await this.ide.getIdeInfo()).ideType;
289 if (ideType === "jetbrains") {
290 this.markDisplayed(input.completionId, outcome);
291 }
292
293 return outcome;
294 } catch (e: any) {
295 this.onError(e);
296 } finally {
297 this.loggingService.deleteAbortController(input.completionId);
298 }
299 }
300}