continue-custom/core/autocomplete/completionProvider.ts
Nate Sesti 3bd9c8996c
💫 Preview (#996)
* feat: add fixed version of the nodejs

* revert accidentally committed files

* add: unified version of the Node.js that is used locally and on Github Actions

* Set itemType for querySubmenuItem

This is necessary before calling props.command the same way we do it for non-query item types. Otherwise we receive an 'Unknow provider...' error message in the 'getContextItems' case in the 'panel.webview.onDidReceiveMessage, callback.

* include @vscode node module folder

we need the @vscode folder containing ripgrep in the distribution.

* Amended path for ripgrep executable

We have to preprend the 'out' folder in order to find the ripgrep executable in the distribution.
Prepending 'out' during development is not necessary. We need a way to distinguish in 'ideProtocol'?

* implemented locals context provider

* normal to submenu(select thread) for the locals provider

* added code context from the call stack

* use parameter for callstack retrieving

* added thread filtering and handle a edge case

* revert accidentally committed file

* temporary fix to use refreshSubmenuItems

* added updateSubmenuItems request

* refactor: changed the interface of threads

* polished format and file reading

* added a little doc

* typo

* revert accidentally committed file

* ✨ UI for JetBrains autocomplete

* 🎨 decouple autocomplete from VS Code extension

* ✨ autocomplete in core protocol

* 🚧 jetbrains autocomplete fixes

* 🐛 successfully get responses for jetbrains autocomplete

* Refactored web crawling code for document indexing. The updated code uses a breadth-first search, filters out specific paths, and ensures that websites are not downloaded twice.

* update hasDocs to use new pattern

* feat: add gitlab context class

* feat: update to work as normal context provider

* fix: add context provider

* feat: add code that comment is based on

* docs: add documentation

* feat: enable comment filtering

* 🐛 fix autocomplete with azure

* ✨ jetbrains multiline completions

* 🐛 fix file reading in autocomplete

* ✨ option to disable jetbrains autocomplete

* 📌 update package-lock files

* 🐛 fix localhost ollama bug with jetbrains binary

* 🔥 disable apply to file in jetbrains for now

* 🚸 fix constant re-rendering of code vision in jetbrains

* 🔖 update package.json versiojn

* 🐛 don't override user temperature value for tab autocomplete model

* Fix chat msg formatting in Output for image models (#971)

* 📝 tweak docs for "locals" ctx provider

* 🩹 small tweak to link filtering logic

* Add more C++ extensions for AST parser (#972)

* 🔥 remove ruby example file

* add claude3 to free trial

* 🐛 fix codelens in tutorial

* 🧱 change server url

* 🐛 don't send image_url if not image type

* 🔧 update config schemas

* 📌 update npm version to v20.11.0

* 📈 Locally track tokens generated and show stats (#987)

* ✨ log tokens generated locally

* 💄 UI for usage stats

* 🔥 delete unused test file

* 🚚 rename core package for publishing on npm

* Remove duplicate itemType property (#986)

* 🔒️ add .env to .gitignore for npm package

* Add SystemContextProvider to context providers so that users can use … (#988)

* Add SystemContextProvider to context providers so that users can use their own system cpu and os for a resource

* change to OSContextProvider

* update descriptor

* 🎨 export transformers.js

* 🐛 fix /edit for anthropic

* 🚑 fix autocomplete by binding function

---------

Co-authored-by: my8bit <mail@my8bit.name>
Co-authored-by: Ihor Pavlenko <my8bit@users.noreply.github.com>
Co-authored-by: Lars Pagh <lp@airsupport.dk>
Co-authored-by: commandblock2 <tony_hu@live.com>
Co-authored-by: Jason Jacobs <nerfnerd@gmail.com>
Co-authored-by: Ben Force <benforce@gmail.com>
Co-authored-by: Peter Zaback <pzaback@gmail.com>
Co-authored-by: SR_team <sr_team@sr.team>
2024-03-19 10:35:28 -07:00

437 lines
12 KiB
TypeScript

import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
import { IDE, ILLM, Position, TabAutocompleteOptions } from "..";
import { RangeInFileWithContents } from "../commands/util";
import { ConfigHandler } from "../config/handler";
import { streamLines } from "../diff/util";
import OpenAI from "../llm/llms/OpenAI";
import { getBasename } from "../util";
import { logDevData } from "../util/devdata";
import { Telemetry } from "../util/posthog";
import { getRangeInString } from "../util/ranges";
import AutocompleteLruCache from "./cache";
import { noFirstCharNewline, onlyWhitespaceAfterEndOfLine } from "./charStream";
import {
constructAutocompletePrompt,
languageForFilepath,
} from "./constructPrompt";
import { AutocompleteLanguageInfo } from "./languages";
import {
avoidPathLine,
stopAtLines,
stopAtRepeatingLines,
stopAtSimilarLine,
streamWithNewLines,
} from "./lineStream";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "./parameters";
import { AutocompleteSnippet } from "./ranking";
import { getTemplateForModel } from "./templates";
import { GeneratorReuseManager } from "./util";
export interface AutocompleteInput {
completionId: string;
filepath: string;
pos: Position;
recentlyEditedFiles: RangeInFileWithContents[];
recentlyEditedRanges: RangeInFileWithContents[];
clipboardText: string;
}
export interface AutocompleteOutcome {
accepted?: boolean;
time: number;
prompt: string;
completion: string;
modelProvider: string;
modelName: string;
completionOptions: any;
cacheHit: boolean;
}
const autocompleteCache = AutocompleteLruCache.get();
function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo,
) {
const comment = language.comment;
const lines = [
comment + " Path: " + getBasename(filepath),
...snippet
.trim()
.split("\n")
.map((line) => comment + " " + line),
comment,
];
return lines.join("\n");
}
export async function getTabCompletion(
token: AbortSignal,
options: TabAutocompleteOptions,
llm: ILLM,
ide: IDE,
generatorReuseManager: GeneratorReuseManager,
input: AutocompleteInput,
getDefinitionsFromLsp: (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
) => Promise<AutocompleteSnippet[]>,
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
const {
filepath,
pos,
recentlyEditedFiles,
recentlyEditedRanges,
clipboardText,
} = input;
const fileContents = await ide.readFile(filepath);
const fileLines = fileContents.split("\n");
// Filter
const lang = languageForFilepath(filepath);
const line = fileLines[pos.line] ?? "";
for (const endOfLine of lang.endOfLine) {
if (line.endsWith(endOfLine) && pos.character >= line.length) {
return undefined;
}
}
// Model
if (llm instanceof OpenAI) {
llm.useLegacyCompletionsEndpoint = true;
}
if (!llm) return;
// Prompt
const fullPrefix = getRangeInString(fileContents, {
start: { line: 0, character: 0 },
end: pos,
});
const fullSuffix = getRangeInString(fileContents, {
start: pos,
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
});
const lineBelowCursor =
fileLines[Math.min(pos.line + 1, fileLines.length - 1)];
let extrasSnippets = (await Promise.race([
getDefinitionsFromLsp(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
ide,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
}),
])) as AutocompleteSnippet[];
const workspaceDirs = await ide.getWorkspaceDirs();
if (options.onlyMyCode) {
extrasSnippets = extrasSnippets.filter((snippet) => {
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
});
}
let { prefix, suffix, completeMultiline, snippets } =
await constructAutocompletePrompt(
filepath,
pos.line,
fullPrefix,
fullSuffix,
clipboardText,
lang,
options,
recentlyEditedRanges,
recentlyEditedFiles,
llm.model,
extrasSnippets,
);
// Template prompt
const { template, completionOptions } = options.template
? { template: options.template, completionOptions: {} }
: getTemplateForModel(llm.model);
let prompt: string;
const filename = getBasename(filepath);
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
if (typeof template === "string") {
const compiledTemplate = Handlebars.compile(template);
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = formattedSnippets + "\n\n" + prefix;
}
prompt = compiledTemplate({
prefix,
suffix,
filename,
reponame,
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filename, reponame, snippets);
}
// Completion
let completion = "";
const cache = await autocompleteCache;
const cachedCompletion = options.useCache
? await cache.get(prompt)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
} else {
// Try to reuse pending requests if what the user typed matches start of completion
let stop = [
...(completionOptions?.stop || []),
"\n\n",
"/src/",
"```",
...lang.stopWords,
];
const multiline =
options.multilineCompletions !== "never" &&
(options.multilineCompletions === "always" || completeMultiline);
let generator = generatorReuseManager.getGenerator(
prefix,
() =>
llm.streamComplete(prompt, {
...completionOptions,
raw: true,
stop,
}),
multiline,
);
// LLM
let cancelled = false;
const generatorWithCancellation = async function* () {
for await (const update of generator) {
if (token.aborted) {
cancelled = true;
return undefined;
}
yield update;
}
};
let chars = generatorWithCancellation();
const gen2 = onlyWhitespaceAfterEndOfLine(
noFirstCharNewline(chars),
lang.endOfLine,
);
const lineGenerator = streamWithNewLines(
avoidPathLine(
stopAtRepeatingLines(stopAtLines(streamLines(gen2))),
lang.comment,
),
);
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
for await (const update of finalGenerator) {
completion += update;
}
if (cancelled) {
return undefined;
}
// Don't return empty
if (completion.trim().length <= 0) {
return undefined;
}
// Post-processing
completion = completion.trimEnd();
}
const time = Date.now() - startTime;
return {
time,
completion,
prompt,
modelProvider: llm.providerName,
modelName: llm.model,
completionOptions,
cacheHit,
};
}
export class CompletionProvider {
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
private static debouncing: boolean = false;
private static lastUUID: string | undefined = undefined;
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly getLlm: () => Promise<ILLM | undefined>,
private readonly _onError: (e: any) => void,
private readonly getDefinitionsFromLsp: (
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE,
) => Promise<AutocompleteSnippet[]>,
) {
this.generatorReuseManager = new GeneratorReuseManager(
this.onError.bind(this),
);
}
private generatorReuseManager: GeneratorReuseManager;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
private onError(e: any) {
console.warn("Error generating autocompletion: ", e);
if (!this.errorsShown.has(e.message)) {
this.errorsShown.add(e.message);
this._onError(e);
}
}
public cancel() {
this._abortControllers.forEach((abortController, id) => {
abortController.abort();
});
this._abortControllers.clear();
}
private _abortControllers = new Map<string, AbortController>();
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
private _outcomes = new Map<string, AutocompleteOutcome>();
public accept(completionId: string) {
if (this._logRejectionTimeouts.has(completionId)) {
clearTimeout(this._logRejectionTimeouts.get(completionId));
this._logRejectionTimeouts.delete(completionId);
}
if (this._outcomes.has(completionId)) {
const outcome = this._outcomes.get(completionId)!;
outcome.accepted = true;
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
this._outcomes.delete(completionId);
}
}
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
// Create abort signal if not given
if (!token) {
const controller = new AbortController();
token = controller.signal;
this._abortControllers.set(input.completionId, controller);
}
try {
// Debounce
const uuid = uuidv4();
CompletionProvider.lastUUID = uuid;
const config = await this.configHandler.loadConfig();
const options = {
...DEFAULT_AUTOCOMPLETE_OPTS,
...config.tabAutocompleteOptions,
};
if (CompletionProvider.debouncing) {
CompletionProvider.debounceTimeout?.refresh();
const lastUUID = await new Promise((resolve) =>
setTimeout(() => {
resolve(CompletionProvider.lastUUID);
}, options.debounceDelay),
);
if (uuid !== lastUUID) {
return undefined;
}
} else {
CompletionProvider.debouncing = true;
CompletionProvider.debounceTimeout = setTimeout(async () => {
CompletionProvider.debouncing = false;
}, options.debounceDelay);
}
// Get completion
const llm = await this.getLlm();
if (!llm) {
return undefined;
}
// Set temperature (but don't overrride)
if (llm.completionOptions.temperature === undefined) {
llm.completionOptions.temperature = 0.0;
}
const outcome = await getTabCompletion(
token,
options,
llm,
this.ide,
this.generatorReuseManager,
input,
this.getDefinitionsFromLsp,
);
const completion = outcome?.completion;
if (!completion) {
return undefined;
}
// Do some stuff later so as not to block return. Latency matters
setTimeout(async () => {
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prompt, completion);
}
}, 100);
outcome.accepted = false;
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
this._logRejectionTimeouts.delete(input.completionId);
}, 10_000);
this._outcomes.set(input.completionId, outcome);
this._logRejectionTimeouts.set(input.completionId, logRejectionTimeout);
return outcome;
} finally {
this._abortControllers.delete(input.completionId);
}
}
}