Nate/autocomplete-metrics (#1230)

* ⚡️ use context.selectedCompletionInfo, deduplicate logs

* ⚡️ don't reject if user keeps typing same as completion

* ⚡️ vscode autocomplete edge cases

* 🚧 WIP on vscode autocomplete

* ⚡️ better bracket handlng

* ⚡️ improved multi-line detection
This commit is contained in:
Nate Sesti 2024-05-03 21:32:53 -07:00 • committed by GitHub
parent 2fa3885bf8
commit 98f6145caa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 333 additions and 81 deletions

View file

@ -35,3 +35,42 @@ export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
yield char;
}
}
const BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" };
const BRACKETS_REVERSE: { [key: string]: string } = {
")": "(",
"}": "{",
"]": "[",
};
export async function* stopOnUnmatchedClosingBracket(
stream: AsyncGenerator<string>,
suffix: string,
): AsyncGenerator<string> {
const stack: string[] = [];
for (let i = 0; i < suffix.length; i++) {
if (suffix[i] === " ") continue;
const openBracket = BRACKETS_REVERSE[suffix[i]];
if (!openBracket) break;
stack.unshift(openBracket);
}
let all = "";
for await (let chunk of stream) {
all += chunk;
for (let i = 0; i < chunk.length; i++) {
const char = chunk[i];
if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
// If the stack is empty or the top of the stack doesn't match the current closing bracket
yield chunk.slice(0, i);
return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream
}
} else if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
}
}
yield chunk;
}
}

View file

@ -2,18 +2,25 @@ import Handlebars from "handlebars";
import ignore from "ignore";
import path from "path";
import { v4 as uuidv4 } from "uuid";
import { IDE, ILLM, Position, TabAutocompleteOptions } from "..";
import { IDE, ILLM, Position, Range, 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 { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters";
import {
COUNT_COMPLETION_REJECTED_AFTER,
DEFAULT_AUTOCOMPLETE_OPTS,
} from "../util/parameters";
import { Telemetry } from "../util/posthog";
import { getRangeInString } from "../util/ranges";
import AutocompleteLruCache from "./cache";
import { noFirstCharNewline, onlyWhitespaceAfterEndOfLine } from "./charStream";
import {
noFirstCharNewline,
onlyWhitespaceAfterEndOfLine,
stopOnUnmatchedClosingBracket,
} from "./charStream";
import {
constructAutocompletePrompt,
languageForFilepath,
@ -42,6 +49,10 @@ export interface AutocompleteInput {
manuallyPassFileContents?: string;
// Used for VS Code git commit input box
manuallyPassPrefix?: string;
selectedCompletionInfo?: {
text: string;
range: Range;
};
}
export interface AutocompleteOutcome extends TabAutocompleteOptions {
@ -53,6 +64,7 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
modelName: string;
completionOptions: any;
cacheHit: boolean;
filepath: string;
}
const autocompleteCache = AutocompleteLruCache.get();
@ -65,7 +77,7 @@ const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
const PYTHON_ENCODING = "#- coding: utf-8";
const CODE_BLOCK_END = "```";
const multilineStops = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
const multilineStops: string[] = []; // [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
// Errors that can be expected on occasion even during normal functioning should not be shown.
@ -156,10 +168,12 @@ export async function getTabCompletion(
}
// Prompt
const fullPrefix = getRangeInString(fileContents, {
start: { line: 0, character: 0 },
end: pos,
});
const fullPrefix =
getRangeInString(fileContents, {
start: { line: 0, character: 0 },
end: input.selectedCompletionInfo?.range.start ?? pos,
}) + (input.selectedCompletionInfo?.text ?? "");
const fullSuffix = getRangeInString(fileContents, {
start: pos,
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
@ -292,6 +306,7 @@ export async function getTabCompletion(
let charGenerator = generatorWithCancellation();
charGenerator = noFirstCharNewline(charGenerator);
charGenerator = onlyWhitespaceAfterEndOfLine(charGenerator, lang.endOfLine);
charGenerator = stopOnUnmatchedClosingBracket(charGenerator, suffix);
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator);
@ -335,6 +350,7 @@ export async function getTabCompletion(
modelName: llm.model,
completionOptions,
cacheHit,
filepath: input.filepath,
...options,
};
}
@ -380,6 +396,7 @@ export class CompletionProvider {
this._abortControllers.clear();
}
// Key is completionId
private _abortControllers = new Map<string, AbortController>();
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
private _outcomes = new Map<string, AutocompleteOutcome>();
@ -405,6 +422,17 @@ export class CompletionProvider {
}
}
public cancelRejectionTimeout(completionId: string) {
if (this._logRejectionTimeouts.has(completionId)) {
clearTimeout(this._logRejectionTimeouts.get(completionId)!);
this._logRejectionTimeouts.delete(completionId);
}
if (this._outcomes.has(completionId)) {
this._outcomes.delete(completionId);
}
}
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined,
@ -492,32 +520,19 @@ export class CompletionProvider {
input,
this.getDefinitionsFromLsp,
);
const completion = outcome?.completion;
if (!completion) {
if (!outcome?.completion) {
return undefined;
}
// Do some stuff later so as not to block return. Latency matters
const completionToCache = outcome.completion;
setTimeout(async () => {
if (!outcome.cacheHit) {
(await this.autocompleteCache).put(outcome.prompt, completion);
(await this.autocompleteCache).put(outcome.prompt, completionToCache);
}
}, 100);
outcome.accepted = false;
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
logDevData("autocomplete", outcome);
const { prompt, completion, ...restOfOutcome } = outcome;
Telemetry.capture("autocomplete", {
...restOfOutcome,
});
this._logRejectionTimeouts.delete(input.completionId);
}, 10_000);
this._outcomes.set(input.completionId, outcome);
this._logRejectionTimeouts.set(input.completionId, logRejectionTimeout);
return outcome;
} catch (e: any) {
this.onError(e);
@ -525,4 +540,50 @@ export class CompletionProvider {
this._abortControllers.delete(input.completionId);
}
}
_lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
undefined;
markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
outcome.accepted = false;
logDevData("autocomplete", outcome);
const { prompt, completion, ...restOfOutcome } = outcome;
Telemetry.capture("autocomplete", {
...restOfOutcome,
});
this._logRejectionTimeouts.delete(completionId);
}, COUNT_COMPLETION_REJECTED_AFTER);
this._outcomes.set(completionId, outcome);
this._logRejectionTimeouts.set(completionId, logRejectionTimeout);
// If the previously displayed completion is still waiting for rejection,
// and this one is a continuation of that (the outcome.completion is the same modulo prefix)
// then we should cancel the rejection timeout
const previous = this._lastDisplayedCompletion;
const now = Date.now();
if (previous && this._logRejectionTimeouts.has(previous.id)) {
const previousOutcome = this._outcomes.get(previous.id);
const c1 = previousOutcome?.completion.split("\n")[0] ?? "";
const c2 = outcome.completion.split("\n")[0];
if (
previousOutcome &&
(c1.endsWith(c2) ||
c2.endsWith(c1) ||
c1.startsWith(c2) ||
c2.startsWith(c1))
) {
this.cancelRejectionTimeout(previous.id);
} else if (now - previous.displayedAt < 500) {
// If a completion isn't shown for more than
this.cancelRejectionTimeout(previous.id);
}
}
this._lastDisplayedCompletion = {
id: completionId,
displayedAt: now,
};
}
}

View file

@ -57,6 +57,15 @@ async function shouldCompleteMultiline(
fullPrefix: string,
fullSuffix: string,
): Promise<boolean> {
// First, if the line before ends with an opening bracket, then assume multi-line
if (
["{", "(", "["].includes(
fullPrefix.split("\n").slice(-2)[0]?.trim().slice(-1)[0],
)
) {
return true;
}
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {

View file

@ -44,26 +44,27 @@ export async function* streamWithNewLines(stream: LineStream): LineStream {
}
}
const brackets = ["(", "[", "{", "`", '"""'];
const bracketsReverse = [")", "]", "}", "`", '"""'];
const bracketEnding = [")", "]", "}", ";"];
function isBracketEnding(line: string): boolean {
return line
.trim()
.split("")
.some((char) => bracketEnding.includes(char));
}
export async function* stopAtSimilarLine(
stream: LineStream,
line: string,
): AsyncGenerator<string> {
line = line.trim();
const lineIsBracketEnding = isBracketEnding(line);
for await (const nextLine of stream) {
if (
bracketsReverse.includes(nextLine.trim()) &&
bracketsReverse.includes(line.trim()) &&
line.trim() === nextLine.trim()
) {
if (lineIsBracketEnding && line.trim() === nextLine.trim()) {
yield nextLine;
continue;
}
const dist = distance(nextLine.trim(), line);
let lineQualifies = nextLine.length > 4 && line.length > 4;
if (lineQualifies && dist / line.length < 0.1) {
if (lineQualifies && distance(nextLine.trim(), line) / line.length < 0.1) {
break;
}
yield nextLine;

View file

@ -19,6 +19,9 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
disableInFiles: undefined,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;
export const DO_NOT_COUNT_REJECTED_BEFORE = 250;
export const RETRIEVAL_PARAMS = {
rerankThreshold: 0.3,
nFinal: 10,

View file

@ -1,4 +1,4 @@
import { Range } from "..";
import { Position, Range } from "..";
export function getRangeInString(content: string, range: Range): string {
const lines = content.split("\n");
@ -23,3 +23,71 @@ export function getRangeInString(content: string, range: Range): string {
return [firstLine, ...middleLines, lastLine].join("\n");
}
export function intersection(a: Range, b: Range): Range | null {
const startLine = Math.max(a.start.line, b.start.line);
const endLine = Math.min(a.end.line, b.end.line);
if (startLine > endLine) {
return null;
}
if (startLine === endLine) {
const startCharacter = Math.max(a.start.character, b.start.character);
const endCharacter = Math.min(a.end.character, b.end.character);
if (startCharacter > endCharacter) {
return null;
}
return {
start: { line: startLine, character: startCharacter },
end: { line: endLine, character: endCharacter },
};
}
const startCharacter =
startLine === a.start.line ? a.start.character : b.start.character;
const endCharacter =
endLine === a.end.line ? a.end.character : b.end.character;
return {
start: { line: startLine, character: startCharacter },
end: { line: endLine, character: endCharacter },
};
}
export function union(a: Range, b: Range): Range {
const startLine = Math.min(a.start.line, b.start.line);
const endLine = Math.max(a.end.line, b.end.line);
const startCharacter =
startLine === a.start.line ? a.start.character : b.start.character;
const endCharacter =
endLine === a.end.line ? a.end.character : b.end.character;
return {
start: { line: startLine, character: startCharacter },
end: { line: endLine, character: endCharacter },
};
}
export function maxPosition(a: Position, b: Position): Position {
if (a.line > b.line) {
return a;
} else if (a.line < b.line) {
return b;
} else {
return a.character > b.character ? a : b;
}
}
export function minPosition(a: Position, b: Position): Position {
if (a.line < b.line) {
return a;
} else if (a.line > b.line) {
return b;
} else {
return a.character < b.character ? a : b;
}
}

View file

@ -1,17 +1,22 @@
import { IDE } from "core";
import {
AutocompleteInput,
AutocompleteOutcome,
CompletionProvider,
} from "core/autocomplete/completionProvider";
import { ConfigHandler } from "core/config/handler";
import { logDevData } from "core/util/devdata";
import { Telemetry } from "core/util/posthog";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
import { getDefinitionsFromLsp } from "./lsp";
import { setupStatusBar, stopStatusBarLoading } from "./statusBar";
interface VsCodeCompletionInput {
document: vscode.TextDocument;
position: vscode.Position;
context: vscode.InlineCompletionContext;
}
export class ContinueCompletionProvider
implements vscode.InlineCompletionItemProvider
{
@ -47,8 +52,18 @@ export class ContinueCompletionProvider
this.onError.bind(this),
getDefinitionsFromLsp,
);
vscode.workspace.onDidChangeTextDocument((event) => {
if (event.document.uri.fsPath === this._lastShownCompletion?.filepath) {
// console.log("updating completion");
}
});
}
_lastShownCompletion: AutocompleteOutcome | undefined;
_lastVsCodeCompletionInput: VsCodeCompletionInput | undefined;
public async provideInlineCompletionItems(
document: vscode.TextDocument,
position: vscode.Position,
@ -61,9 +76,30 @@ export class ContinueCompletionProvider
.getConfiguration("continue")
.get<boolean>("enableTabAutocomplete") || false;
if (token.isCancellationRequested || !enableTabAutocomplete) {
return [];
return null;
}
// If the text at the range isn't a prefix of the intellisense text,
// no completion will be displayed, regardless of what we return
if (
context.selectedCompletionInfo &&
!context.selectedCompletionInfo.text.startsWith(
document.getText(context.selectedCompletionInfo.range),
)
) {
return null;
}
// The first time intellisense dropdown shows up, and the first choice is selected,
// we should not consider this. Only once user explicitly moves down the list
const newVsCodeInput = {
context,
document,
position,
};
const selectedCompletionInfo = context.selectedCompletionInfo;
this._lastVsCodeCompletionInput = newVsCodeInput;
try {
const abortController = new AbortController();
const signal = abortController.signal;
@ -111,7 +147,7 @@ export class ContinueCompletionProvider
// Handle commit message input box
let manuallyPassPrefix: string | undefined = undefined;
if (document.uri.scheme === "vscode-scm") {
return [];
return null;
// let diff = await this.ide.getDiff();
// diff = diff.split("\n").splice(-150).join("\n");
// manuallyPassPrefix = `${diff}\n\nCommit message: `;
@ -126,6 +162,7 @@ export class ContinueCompletionProvider
clipboardText: clipboardText,
manuallyPassFileContents,
manuallyPassPrefix,
selectedCompletionInfo,
};
setupStatusBar(true, true);
@ -136,38 +173,83 @@ export class ContinueCompletionProvider
);
if (!outcome || !outcome.completion) {
return [];
return null;
}
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
outcome.accepted = false;
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
}, 10_000);
// VS Code displays dependent on selectedCompletionInfo (their docstring below)
// We should first always make sure we have a valid completion, but if it goes wrong we
// want telemetry to be correct
/**
* Provides information about the currently selected item in the autocomplete widget if it is visible.
*
* If set, provided inline completions must extend the text of the selected item
* and use the same range, otherwise they are not shown as preview.
* As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
* the inline completion must also replace `.` and start with `.log`, for example `.log()`.
*
* Inline completion providers are requested again whenever the selected item changes.
*/
if (selectedCompletionInfo) {
outcome.completion = selectedCompletionInfo.text + outcome.completion;
}
const willDisplay = this.willDisplay(
document,
selectedCompletionInfo,
signal,
outcome,
);
if (!willDisplay) {
return null;
}
return [
new vscode.InlineCompletionItem(
outcome.completion,
new vscode.Range(
position,
position.translate(0, outcome.completion.length),
),
{
title: "Log Autocomplete Outcome",
command: "continue.logAutocompleteOutcome",
arguments: [outcome, logRejectionTimeout],
},
),
];
// Mark displayed
this.completionProvider.markDisplayed(input.completionId, outcome);
this._lastShownCompletion = outcome;
// Construct the range/text to show
const startPos = selectedCompletionInfo?.range.start ?? position;
const completionRange = new vscode.Range(
startPos,
startPos.translate(0, outcome.completion.length),
);
const completionItem = new vscode.InlineCompletionItem(
outcome.completion,
completionRange,
{
title: "Log Autocomplete Outcome",
command: "continue.logAutocompleteOutcome",
arguments: [input.completionId, this.completionProvider],
},
);
(completionItem as any).completeBracketPairs = true;
return [completionItem];
} finally {
stopStatusBarLoading();
}
}
willDisplay(
document: vscode.TextDocument,
selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined,
abortSignal: AbortSignal,
outcome: AutocompleteOutcome,
): boolean {
if (selectedCompletionInfo) {
const { text, range } = selectedCompletionInfo;
if (!outcome.completion.startsWith(text)) {
console.log(
`Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
range,
);
return false;
}
}
if (abortSignal.aborted) {
return false;
}
return true;
}
}

View file

@ -4,12 +4,10 @@ import * as path from "path";
import * as vscode from "vscode";
import { ContextMenuConfig, IDE } from "core";
import { AutocompleteOutcome } from "core/autocomplete/completionProvider";
import { CompletionProvider } from "core/autocomplete/completionProvider";
import { ConfigHandler } from "core/config/handler";
import { logDevData } from "core/util/devdata";
import { fetchwithRequestOptions } from "core/util/fetchWithOptions";
import { getConfigJsonPath } from "core/util/paths";
import { Telemetry } from "core/util/posthog";
import { ContinueGUIWebviewViewProvider } from "./debugPanel";
import { DiffManager } from "./diff/horizontal";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
@ -511,19 +509,10 @@ const commandsMap: (
);
},
"continue.logAutocompleteOutcome": (
outcome: AutocompleteOutcome,
logRejectionTimeout: NodeJS.Timeout,
completionId: string,
completionProvider: CompletionProvider,
) => {
clearTimeout(logRejectionTimeout);
outcome.accepted = true;
logDevData("autocomplete", outcome);
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
});
completionProvider.accept(completionId);
},
"continue.toggleTabAutocompleteEnabled": () => {
const config = vscode.workspace.getConfiguration("continue");