Elffuss BraidHub

kikocis/continue public

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