Elffuss BraidHub

kikocis/continue public

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