Elffuss BraidHub

kikocis/continue public

b2d9c39b18ab · 15.2 KiBRawPermalink
1import { ConfigHandler } from "../config/ConfigHandler.js";
2import { ChatMessage, IDE, ILLM } from "../index.js";
3import OpenAI from "../llm/llms/OpenAI.js";
4import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
5
6import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
7
8import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
9import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
10import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
11import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
12import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
13import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
14import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
15import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
16import { HelperVars } from "../autocomplete/util/HelperVars.js";
17import {
18 AutocompleteInput,
19 AutocompleteOutcome,
20} from "../autocomplete/util/types.js";
21import { replaceEscapedCharacters } from "../util/text.js";
22import {
23 Prompt,
24 renderDefaultSystemPrompt,
25 renderDefaultUserPrompt,
26 renderPrompt,
27} from "./templating/NextEditPromptEngine.js";
28// import { renderPrompt } from "./templating/NextEditPromptEngine.js";
29
30const autocompleteCache = AutocompleteLruCache.get();
31
32// Errors that can be expected on occasion even during normal functioning should not be shown.
33// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
34const ERRORS_TO_IGNORE = [
35 // From Ollama
36 "unexpected server status",
37 "operation was aborted",
38];
39
40export class NextEditProvider {
41 private static instance: NextEditProvider | null = null;
42
43 private autocompleteCache = AutocompleteLruCache.get();
44 public errorsShown: Set<string> = new Set();
45 private bracketMatchingService = new BracketMatchingService();
46 private debouncer = new AutocompleteDebouncer();
47 private completionStreamer: CompletionStreamer;
48 private loggingService = new AutocompleteLoggingService();
49 private contextRetrievalService: ContextRetrievalService;
50 private endpointType: "default" | "fineTuned";
51 private diffContext: string = "";
52
53 private constructor(
54 private readonly configHandler: ConfigHandler,
55 private readonly ide: IDE,
56 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
57 private readonly _onError: (e: any) => void,
58 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
59 endpointType: "default" | "fineTuned",
60 ) {
61 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
62 this.contextRetrievalService = new ContextRetrievalService(this.ide);
63 this.endpointType = endpointType;
64 }
65
66 public static initialize(
67 configHandler: ConfigHandler,
68 ide: IDE,
69 injectedGetLlm: () => Promise<ILLM | undefined>,
70 onError: (e: any) => void,
71 getDefinitionsFromLsp: GetLspDefinitionsFunction,
72 endpointType: "default" | "fineTuned",
73 ): NextEditProvider {
74 if (!NextEditProvider.instance) {
75 NextEditProvider.instance = new NextEditProvider(
76 configHandler,
77 ide,
78 injectedGetLlm,
79 onError,
80 getDefinitionsFromLsp,
81 endpointType,
82 );
83 }
84 return NextEditProvider.instance;
85 }
86
87 public static getInstance(): NextEditProvider {
88 if (!NextEditProvider.instance) {
89 throw new Error(
90 "NextEditProvider has not been initialized. Call initialize() first.",
91 );
92 }
93 return NextEditProvider.instance;
94 }
95
96 public addDiffToContext(diff: string): void {
97 this.diffContext = diff;
98 }
99
100 private async _prepareLlm(): Promise<ILLM | undefined> {
101 const llm = await this._injectedGetLlm();
102
103 if (!llm) {
104 return undefined;
105 }
106
107 // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
108 if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
109 llm.model = llm.completionOptions.model;
110 }
111
112 // Ignore empty API keys for Mistral since we currently write
113 // a template provider without one during onboarding
114 if (llm.providerName === "mistral" && llm.apiKey === "") {
115 return undefined;
116 }
117
118 // Set temperature (but don't override)
119 if (llm.completionOptions.temperature === undefined) {
120 llm.completionOptions.temperature = 0.01;
121 }
122
123 if (llm instanceof OpenAI) {
124 llm.useLegacyCompletionsEndpoint = true;
125 }
126 // TODO: Resolve import error with TRIAL_FIM_MODEL
127 // else if (
128 // llm.providerName === "free-trial" &&
129 // llm.model !== TRIAL_FIM_MODEL
130 // ) {
131 // llm.model = TRIAL_FIM_MODEL;
132 // }
133
134 return llm;
135 }
136
137 private onError(e: any) {
138 if (
139 ERRORS_TO_IGNORE.some((err) =>
140 typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
141 )
142 ) {
143 return;
144 }
145
146 console.warn("Error generating autocompletion: ", e);
147 if (!this.errorsShown.has(e.message)) {
148 this.errorsShown.add(e.message);
149 this._onError(e);
150 }
151 }
152
153 public cancel() {
154 this.loggingService.cancel();
155 }
156
157 public accept(completionId: string) {
158 const outcome = this.loggingService.accept(completionId);
159 if (!outcome) {
160 return;
161 }
162 this.bracketMatchingService.handleAcceptedCompletion(
163 outcome.completion,
164 outcome.filepath,
165 );
166 }
167
168 public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
169 this.loggingService.markDisplayed(completionId, outcome);
170 }
171
172 private async _getAutocompleteOptions() {
173 const { config } = await this.configHandler.loadConfig();
174 const options = {
175 ...DEFAULT_AUTOCOMPLETE_OPTS,
176 ...config?.tabAutocompleteOptions,
177 };
178 return options;
179 }
180
181 public async provideInlineCompletionItems(
182 input: AutocompleteInput,
183 token: AbortSignal | undefined,
184 ): Promise<AutocompleteOutcome | undefined> {
185 try {
186 // Create abort signal if not given
187 if (!token) {
188 const controller = this.loggingService.createAbortController(
189 input.completionId,
190 );
191 token = controller.signal;
192 }
193 const startTime = Date.now();
194 const options = await this._getAutocompleteOptions();
195
196 // Debounce
197 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
198 return undefined;
199 }
200
201 const llm = await this._prepareLlm();
202 if (!llm) {
203 return undefined;
204 }
205
206 if (llm.promptTemplates?.autocomplete) {
207 options.template = llm.promptTemplates.autocomplete as string;
208 }
209
210 const helper = await HelperVars.create(
211 input,
212 options,
213 llm.model,
214 this.ide,
215 );
216
217 if (await shouldPrefilter(helper, this.ide)) {
218 return undefined;
219 }
220
221 const [snippetPayload, workspaceDirs] = await Promise.all([
222 getAllSnippetsWithoutRace({
223 helper,
224 ide: this.ide,
225 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
226 contextRetrievalService: this.contextRetrievalService,
227 }),
228 this.ide.getWorkspaceDirs(),
229 ]);
230
231 // TODO: Toggle between the default endpoint and the finetuned endpoint.
232 const prompts: Prompt[] = [];
233
234 if (this.endpointType === "default") {
235 prompts.push(renderDefaultSystemPrompt());
236 prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
237 } else {
238 prompts.push(
239 // await renderFineTunedUserPrompt(snippetPayload, this.ide, helper),
240 // await renderFineTunedBasicUserPrompt(
241 // snippetPayload,
242 // this.ide,
243 // helper,
244 // this.diffContext,
245 // ),
246 renderPrompt(helper, this.diffContext),
247 );
248 }
249
250 if (this.endpointType === "default") {
251 const msg: ChatMessage = await llm.chat(prompts, token);
252 if (typeof msg.content === "string") {
253 const nextCompletion = JSON.parse(msg.content).newCode;
254 const outcomeNext: AutocompleteOutcome = {
255 time: Date.now() - startTime,
256 completion: nextCompletion,
257 prefix: "",
258 suffix: "",
259 prompt: "",
260 modelProvider: llm.underlyingProviderName,
261 modelName: llm.model,
262 completionOptions: null,
263 cacheHit: false,
264 filepath: helper.filepath,
265 numLines: nextCompletion.split("\n").length,
266 completionId: helper.input.completionId,
267 gitRepo: await this.ide.getRepoName(helper.filepath),
268 uniqueId: await this.ide.getUniqueId(),
269 timestamp: Date.now(),
270 ...helper.options,
271 };
272 return outcomeNext;
273 } else {
274 return undefined;
275 }
276 // const body = {
277 // model: defaultModel,
278 // messages: prompts,
279 // // max_tokens: 15000,
280 // // stop: ["<|editable_region_end|>"],
281 // };
282 //
283 // const resp = await fetch(defaultEndpoint, {
284 // method: "POST",
285 // headers: {
286 // Authorization: `Bearer ${mercuryToken} `,
287 // "Content-Type": "application/json",
288 // },
289 // body: JSON.stringify(body),
290 // });
291 //
292 // const respJson = await resp.json();
293
294 // TODO: Do some zod schema validation here if needed.
295 } else {
296 // const testController = new AbortController();
297 // const msg: ChatMessage = await llm.chat(prompts, testController.signal);
298 // const testToken = testController.signal;
299 const msg: ChatMessage = await llm.chat(prompts, token);
300 if (typeof msg.content === "string") {
301 // TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
302 const nextCompletion = replaceEscapedCharacters(
303 msg.content.split("<|editable_region_start|>\n")[1],
304 ).replace(/\n$/, "");
305
306 // const diffLines = myersDiff(helper.fileContents, nextCompletion);
307
308 // const diff = getRenderableDiff(diffLines);
309 const outcomeNext: AutocompleteOutcome = {
310 time: Date.now() - startTime,
311 completion: nextCompletion,
312 prefix: "",
313 suffix: "",
314 prompt: "",
315 modelProvider: llm.underlyingProviderName,
316 modelName: llm.model,
317 completionOptions: null,
318 cacheHit: false,
319 filepath: helper.filepath,
320 numLines: nextCompletion.split("\n").length,
321 completionId: helper.input.completionId,
322 gitRepo: await this.ide.getRepoName(helper.filepath),
323 uniqueId: await this.ide.getUniqueId(),
324 timestamp: Date.now(),
325 ...helper.options,
326 };
327 return outcomeNext;
328 } else {
329 return undefined;
330 }
331 // const body = {
332 // model: fineTunedModel,
333 // messages: prompts,
334 // max_tokens: 15000,
335 // stop: ["<|editable_region_end|>"],
336 // };
337 //
338 // const resp = await fetch(fineTunedEndpoint, {
339 // method: "POST",
340 // headers: {
341 // Authorization: `Bearer ${mercuryToken} `,
342 // "Content-Type": "application/json",
343 // },
344 // body: JSON.stringify(body),
345 // });
346 //
347 // const respJson = await resp.json();
348 //
349 // const nextCompletion = respJson.choices[0].message.content
350 // .split("<|editable_region_start|>\n")[1]
351 // .split("<|editable_region_end|>")[0]
352 // .slice(1)
353 // .slice(0, -1)
354 // .replaceAll("\\n", "\n")
355 // .replaceAll('\\"', '"');
356 //
357 // const outcomeNext: AutocompleteOutcome = {
358 // time: Date.now() - startTime,
359 // completion: nextCompletion,
360 // prefix: "",
361 // suffix: "",
362 // prompt: "",
363 // modelProvider: llm.underlyingProviderName,
364 // modelName: llm.model,
365 // completionOptions: null,
366 // cacheHit: false,
367 // filepath: helper.filepath,
368 // numLines: nextCompletion.split("\n").length,
369 // completionId: helper.input.completionId,
370 // gitRepo: await this.ide.getRepoName(helper.filepath),
371 // uniqueId: await this.ide.getUniqueId(),
372 // timestamp: Date.now(),
373 // ...helper.options,
374 // };
375 // return outcomeNext;
376 }
377
378 // // Completion
379 // let completion: string | undefined = "";
380
381 // const cache = await autocompleteCache;
382 // const cachedCompletion = helper.options.useCache
383 // ? await cache.get(helper.prunedPrefix)
384 // : undefined;
385 // let cacheHit = false;
386 // if (cachedCompletion) {
387 // // Cache
388 // cacheHit = true;
389 // completion = cachedCompletion;
390 // } else {
391 // const multiline =
392 // !helper.options.transform || shouldCompleteMultiline(helper);
393
394 // const completionStream =
395 // this.completionStreamer.streamCompletionWithFilters(
396 // token,
397 // llm,
398 // prefix,
399 // suffix,
400 // prompt,
401 // multiline,
402 // completionOptions,
403 // helper,
404 // );
405
406 // for await (const update of completionStream) {
407 // completion += update;
408 // }
409
410 // // Don't postprocess if aborted
411 // if (token.aborted) {
412 // return undefined;
413 // }
414
415 // const processedCompletion = helper.options.transform
416 // ? postprocessCompletion({
417 // completion,
418 // prefix: helper.prunedPrefix,
419 // suffix: helper.prunedSuffix,
420 // llm,
421 // })
422 // : completion;
423
424 // completion = processedCompletion;
425 // }
426
427 // if (!completion) {
428 // return undefined;
429 // }
430
431 // const outcome: AutocompleteOutcome = {
432 // time: Date.now() - startTime,
433 // completion,
434 // prefix,
435 // suffix,
436 // prompt,
437 // modelProvider: llm.underlyingProviderName,
438 // modelName: llm.model,
439 // completionOptions,
440 // cacheHit,
441 // filepath: helper.filepath,
442 // numLines: completion.split("\n").length,
443 // completionId: helper.input.completionId,
444 // gitRepo: await this.ide.getRepoName(helper.filepath),
445 // uniqueId: await this.ide.getUniqueId(),
446 // timestamp: Date.now(),
447 // ...helper.options,
448 // };
449
450 // //////////
451
452 // // Save to cache
453 // if (!outcome.cacheHit && helper.options.useCache) {
454 // (await this.autocompleteCache)
455 // .put(outcome.prefix, outcome.completion)
456 // .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
457 // }
458
459 // // When using the JetBrains extension, Mark as displayed
460 // const ideType = (await this.ide.getIdeInfo()).ideType;
461 // if (ideType === "jetbrains") {
462 // this.markDisplayed(input.completionId, outcome);
463 // }
464
465 // return outcome;
466 } catch (e: any) {
467 this.onError(e);
468 } finally {
469 this.loggingService.deleteAbortController(input.completionId);
470 }
471 }
472}