Merge branch 'dev' into nate/prompt-file-v2
This commit is contained in:
commit
c916791e8d
169 changed files with 4268 additions and 2921 deletions
4
.changes/unreleased/Added-20241108-113942.yaml
Normal file
4
.changes/unreleased/Added-20241108-113942.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: OpenAI predicted outputs support
|
||||
time: 2024-11-08T11:39:42.277047-08:00
|
||||
4
.changes/unreleased/Added-20241108-114100.yaml
Normal file
4
.changes/unreleased/Added-20241108-114100.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Improve codebase retrieval with BM25
|
||||
time: 2024-11-08T11:41:00.002716-08:00
|
||||
4
.changes/unreleased/Added-20241108-114423.yaml
Normal file
4
.changes/unreleased/Added-20241108-114423.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Support for Grok from xAI
|
||||
time: 2024-11-08T11:44:23.761084-08:00
|
||||
4
.changes/unreleased/Added-20241108-114437.yaml
Normal file
4
.changes/unreleased/Added-20241108-114437.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Chat enhancements including sticking input to bottom
|
||||
time: 2024-11-08T11:44:37.408176-08:00
|
||||
4
.changes/unreleased/Added-20241108-114450.yaml
Normal file
4
.changes/unreleased/Added-20241108-114450.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: New UI for cmd+I in sidebar
|
||||
time: 2024-11-08T11:44:50.682952-08:00
|
||||
4
.changes/unreleased/Added-20241108-114612.yaml
Normal file
4
.changes/unreleased/Added-20241108-114612.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Support for Nebius LLM provider
|
||||
time: 2024-11-08T11:46:12.94828-08:00
|
||||
4
.changes/unreleased/Added-20241108-114622.yaml
Normal file
4
.changes/unreleased/Added-20241108-114622.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Support for Ask Sage LLM provider
|
||||
time: 2024-11-08T11:46:22.626907-08:00
|
||||
4
.changes/unreleased/Added-20241108-114649.yaml
Normal file
4
.changes/unreleased/Added-20241108-114649.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Improved reference for config.json
|
||||
time: 2024-11-08T11:46:49.648545-08:00
|
||||
4
.changes/unreleased/Added-20241108-114753.yaml
Normal file
4
.changes/unreleased/Added-20241108-114753.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: New @web context provider
|
||||
time: 2024-11-08T11:47:53.447346-08:00
|
||||
4
.changes/unreleased/Added-20241108-114813.yaml
Normal file
4
.changes/unreleased/Added-20241108-114813.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Updates for llama3.2
|
||||
time: 2024-11-08T11:48:13.830692-08:00
|
||||
4
.changes/unreleased/Changed-20241108-114549.yaml
Normal file
4
.changes/unreleased/Changed-20241108-114549.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: Improved @docs crawler
|
||||
time: 2024-11-08T11:45:49.381554-08:00
|
||||
4
.changes/unreleased/Changed-20241108-114850.yaml
Normal file
4
.changes/unreleased/Changed-20241108-114850.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: Many improvements to make autocomplete more eager
|
||||
time: 2024-11-08T11:48:50.486502-08:00
|
||||
4
.changes/unreleased/Fixed-20241108-114322.yaml
Normal file
4
.changes/unreleased/Fixed-20241108-114322.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/intellij
|
||||
kind: Fixed
|
||||
body: OSR-related fixes for non-Mac users
|
||||
time: 2024-11-08T11:43:22.623155-08:00
|
||||
4
.changes/unreleased/Fixed-20241108-114707.yaml
Normal file
4
.changes/unreleased/Fixed-20241108-114707.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/intellij
|
||||
kind: Fixed
|
||||
body: Fixes for inline edit in JetBrains
|
||||
time: 2024-11-08T11:47:07.953304-08:00
|
||||
4
.changes/unreleased/Fixed-20241108-114905.yaml
Normal file
4
.changes/unreleased/Fixed-20241108-114905.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Fixed
|
||||
body: Brought back the Apply button for all code blocks
|
||||
time: 2024-11-08T11:49:05.021499-08:00
|
||||
304
core/autocomplete/CompletionProvider.ts
Normal file
304
core/autocomplete/CompletionProvider.ts
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js";
|
||||
import { constructAutocompletePrompt } from "./constructPrompt.js";
|
||||
import { AutocompleteSnippet } from "./context/ranking/index.js";
|
||||
import { postprocessCompletion } from "./postprocessing/index.js";
|
||||
// @prettier-ignore
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
|
||||
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
|
||||
import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
|
||||
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
|
||||
import { shouldPrefilter } from "./prefiltering/index.js";
|
||||
import { renderPrompt } from "./templating/index.js";
|
||||
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
|
||||
import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js";
|
||||
import AutocompleteLruCache from "./util/AutocompleteLruCache.js";
|
||||
import { HelperVars } from "./util/HelperVars.js";
|
||||
import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js";
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
// Errors that can be expected on occasion even during normal functioning should not be shown.
|
||||
// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
|
||||
const ERRORS_TO_IGNORE = [
|
||||
// From Ollama
|
||||
"unexpected server status",
|
||||
];
|
||||
|
||||
export type GetLspDefinitionsFunction = (
|
||||
filepath: string,
|
||||
contents: string,
|
||||
cursorIndex: number,
|
||||
ide: IDE,
|
||||
lang: AutocompleteLanguageInfo,
|
||||
) => Promise<AutocompleteSnippet[]>;
|
||||
|
||||
export class CompletionProvider {
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
private debouncer = new AutocompleteDebouncer();
|
||||
private completionStreamer: CompletionStreamer;
|
||||
private loggingService = new AutocompleteLoggingService();
|
||||
private contextRetrievalService: ContextRetrievalService;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
|
||||
private readonly _onError: (e: any) => void,
|
||||
private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
) {
|
||||
this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
|
||||
this.contextRetrievalService = new ContextRetrievalService(this.ide);
|
||||
}
|
||||
|
||||
private async _prepareLlm(): Promise<ILLM | undefined> {
|
||||
const llm = await this._injectedGetLlm();
|
||||
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Ignore empty API keys for Mistral since we currently write
|
||||
// a template provider without one during onboarding
|
||||
if (llm.providerName === "mistral" && llm.apiKey === "") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Set temperature (but don't override)
|
||||
if (llm.completionOptions.temperature === undefined) {
|
||||
llm.completionOptions.temperature = 0.01;
|
||||
}
|
||||
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
|
||||
return llm;
|
||||
}
|
||||
|
||||
private onError(e: any) {
|
||||
if (
|
||||
ERRORS_TO_IGNORE.some((err) =>
|
||||
typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (!this.errorsShown.has(e.message)) {
|
||||
this.errorsShown.add(e.message);
|
||||
this._onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this.loggingService.cancel();
|
||||
}
|
||||
|
||||
public accept(completionId: string) {
|
||||
const outcome = this.loggingService.accept(completionId);
|
||||
if (!outcome) {
|
||||
return;
|
||||
}
|
||||
this.bracketMatchingService.handleAcceptedCompletion(
|
||||
outcome.completion,
|
||||
outcome.filepath,
|
||||
);
|
||||
}
|
||||
|
||||
public markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
|
||||
this.loggingService.markDisplayed(completionId, outcome);
|
||||
}
|
||||
|
||||
private async _getAutocompleteOptions() {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config.tabAutocompleteOptions,
|
||||
};
|
||||
return options;
|
||||
}
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
// Debounce
|
||||
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const helper = await HelperVars.create(
|
||||
input,
|
||||
options,
|
||||
llm.model,
|
||||
this.ide,
|
||||
);
|
||||
|
||||
if (await shouldPrefilter(helper, this.ide)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = this.loggingService.createAbortController(
|
||||
input.completionId,
|
||||
);
|
||||
token = controller.signal;
|
||||
}
|
||||
|
||||
//////////
|
||||
|
||||
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
|
||||
// or they might separately track recently edited ranges)
|
||||
const extraSnippets = await this._getExtraSnippets(helper);
|
||||
|
||||
let snippets = await constructAutocompletePrompt(
|
||||
helper,
|
||||
extraSnippets,
|
||||
this.contextRetrievalService,
|
||||
);
|
||||
|
||||
const { prompt, prefix, suffix, completionOptions } = renderPrompt(
|
||||
snippets,
|
||||
await this.ide.getWorkspaceDirs(),
|
||||
helper,
|
||||
);
|
||||
|
||||
// Completion
|
||||
let completion: string | undefined = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = helper.options.useCache
|
||||
? await cache.get(helper.prunedPrefix)
|
||||
: undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
const multiline =
|
||||
!helper.options.transform || shouldCompleteMultiline(helper);
|
||||
|
||||
const completionStream =
|
||||
this.completionStreamer.streamCompletionWithFilters(
|
||||
token,
|
||||
llm,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
multiline,
|
||||
completionOptions,
|
||||
helper,
|
||||
);
|
||||
|
||||
for await (const update of completionStream) {
|
||||
completion += update;
|
||||
}
|
||||
|
||||
// Don't postprocess if aborted
|
||||
if (token.aborted) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const processedCompletion = helper.options.transform
|
||||
? postprocessCompletion({
|
||||
completion,
|
||||
prefix: helper.prunedPrefix,
|
||||
suffix: helper.prunedSuffix,
|
||||
llm,
|
||||
})
|
||||
: completion;
|
||||
|
||||
completion = processedCompletion;
|
||||
}
|
||||
|
||||
if (!completion) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const outcome: AutocompleteOutcome = {
|
||||
time: Date.now() - startTime,
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
filepath: helper.filepath,
|
||||
completionId: helper.input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(helper.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
...helper.options,
|
||||
};
|
||||
|
||||
//////////
|
||||
|
||||
// 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.prefix, completionToCache);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
return outcome;
|
||||
} catch (e: any) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
this.loggingService.deleteAbortController(input.completionId);
|
||||
}
|
||||
}
|
||||
|
||||
private async _getExtraSnippets(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
let extraSnippets = helper.options.useOtherFiles
|
||||
? ((await Promise.race([
|
||||
this.getDefinitionsFromLsp(
|
||||
helper.input.filepath,
|
||||
helper.fullPrefix + helper.fullSuffix,
|
||||
helper.fullPrefix.length,
|
||||
this.ide,
|
||||
helper.lang,
|
||||
),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
}),
|
||||
])) as AutocompleteSnippet[])
|
||||
: [];
|
||||
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
if (helper.options.onlyMyCode) {
|
||||
extraSnippets = extraSnippets.filter((snippet) => {
|
||||
return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir));
|
||||
});
|
||||
}
|
||||
|
||||
return extraSnippets;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
import { IDE, Location } from "../index.js";
|
||||
import { LANGUAGES } from "./languages.js";
|
||||
import { getSymbolsForSnippet } from "./ranking.js";
|
||||
|
||||
interface FileInfo {
|
||||
filepath: string;
|
||||
}
|
||||
|
||||
export class NearbyDefinitionsService {
|
||||
static N = 10;
|
||||
|
||||
constructor(private readonly ide: IDE) {}
|
||||
|
||||
async getDefinitionsForLine(filepath: string, line: number) {
|
||||
const lineContent = await this.ide.readRangeInFile(filepath, {
|
||||
start: {
|
||||
line,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: line + 1,
|
||||
character: 0,
|
||||
},
|
||||
});
|
||||
|
||||
// Remove keywords
|
||||
const lang = LANGUAGES[filepath.split(".").slice(-1)[0]];
|
||||
const symbols = Array.from(getSymbolsForSnippet(lineContent))
|
||||
.filter((s) => s.length > 0)
|
||||
.filter((s) => !(lang && lang?.stopWords?.includes(s)));
|
||||
|
||||
return Promise.all(
|
||||
symbols.map((s) => {
|
||||
const character = lineContent.indexOf(s);
|
||||
const pos: Location = {
|
||||
filepath,
|
||||
position: {
|
||||
line,
|
||||
character,
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
9
core/autocomplete/READEME.md
Normal file
9
core/autocomplete/READEME.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
TODO
|
||||
|
||||
- The generator reuse thing isn't working it seems
|
||||
|
||||
Tests for context:
|
||||
|
||||
- You need a static set of files to test. Ideally you don't have to rewrite the exact same files every time you want to make a new test.
|
||||
- So put some example files in a few folders. There should be a folder for each language I think.
|
||||
- You should definitely test each of the services separately
|
||||
53
core/autocomplete/classification/shouldCompleteMultiline.ts
Normal file
53
core/autocomplete/classification/shouldCompleteMultiline.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
function isMidlineCompletion(prefix: string, suffix: string): boolean {
|
||||
return !suffix.startsWith("\n");
|
||||
}
|
||||
|
||||
function shouldCompleteMultilineBasedOnLanguage(
|
||||
language: AutocompleteLanguageInfo,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
) {
|
||||
return language.useMultiline?.({ prefix, suffix }) ?? true;
|
||||
}
|
||||
|
||||
export function shouldCompleteMultiline(helper: HelperVars) {
|
||||
switch (helper.options.multilineCompletions) {
|
||||
case "always":
|
||||
return true;
|
||||
case "never":
|
||||
return false;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Always single-line if an intellisense option is selected
|
||||
if (helper.input.selectedCompletionInfo) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// // Don't complete multi-line if you are mid-line
|
||||
// if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// Don't complete multi-line for single-line comments
|
||||
if (
|
||||
helper.lang.singleLineComment &&
|
||||
helper.fullPrefix
|
||||
.split("\n")
|
||||
.slice(-1)[0]
|
||||
?.trimStart()
|
||||
.startsWith(helper.lang.singleLineComment)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return shouldCompleteMultilineBasedOnLanguage(
|
||||
helper.lang,
|
||||
helper.prunedPrefix,
|
||||
helper.prunedSuffix,
|
||||
);
|
||||
}
|
||||
|
|
@ -1,811 +0,0 @@
|
|||
import ignore from "ignore";
|
||||
import OpenAI from "openai";
|
||||
import path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import { streamLines } from "../diff/util.js";
|
||||
import {
|
||||
IDE,
|
||||
ILLM,
|
||||
ModelProvider,
|
||||
Position,
|
||||
Range,
|
||||
TabAutocompleteOptions,
|
||||
} from "../index.js";
|
||||
import { logDevData } from "../util/devdata.js";
|
||||
import { getBasename, getLastNPathParts } from "../util/index.js";
|
||||
import {
|
||||
COUNT_COMPLETION_REJECTED_AFTER,
|
||||
DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
} from "../util/parameters.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { getRangeInString } from "../util/ranges.js";
|
||||
|
||||
import AutocompleteLruCache from "./cache.js";
|
||||
import {
|
||||
constructAutocompletePrompt,
|
||||
languageForFilepath,
|
||||
} from "./constructPrompt.js";
|
||||
import { isOnlyWhitespace } from "./filter.js";
|
||||
import { AutocompleteLanguageInfo } from "./languages.js";
|
||||
import { postprocessCompletion } from "./postprocessing.js";
|
||||
import { AutocompleteSnippet } from "./ranking.js";
|
||||
import { RecentlyEditedRange } from "./recentlyEdited.js";
|
||||
import { RootPathContextService } from "./services/RootPathContextService.js";
|
||||
import {
|
||||
avoidPathLineAndEmptyComments,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
stopAtRepeatingLines,
|
||||
stopAtSimilarLine,
|
||||
streamWithNewLines,
|
||||
} from "./streamTransforms/lineStream.js";
|
||||
import { getTemplateForModel } from "./templates.js";
|
||||
import { GeneratorReuseManager } from "./util.js";
|
||||
// @prettier-ignore
|
||||
import Handlebars from "handlebars";
|
||||
import { getConfigJsonPath } from "../util/paths.js";
|
||||
import { BracketMatchingService } from "./services/BracketMatchingService.js";
|
||||
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
|
||||
import { stopAtStopTokens } from "./streamTransforms/charStream.js";
|
||||
|
||||
export interface AutocompleteInput {
|
||||
completionId: string;
|
||||
filepath: string;
|
||||
pos: Position;
|
||||
recentlyEditedFiles: RangeInFileWithContents[];
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
clipboardText: string;
|
||||
// Used for notebook files
|
||||
manuallyPassFileContents?: string;
|
||||
// Used for VS Code git commit input box
|
||||
manuallyPassPrefix?: string;
|
||||
selectedCompletionInfo?: {
|
||||
text: string;
|
||||
range: Range;
|
||||
};
|
||||
injectDetails?: string;
|
||||
}
|
||||
|
||||
export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
modelProvider: string;
|
||||
modelName: string;
|
||||
completionOptions: any;
|
||||
cacheHit: boolean;
|
||||
filepath: string;
|
||||
gitRepo?: string;
|
||||
completionId: string;
|
||||
uniqueId: string;
|
||||
}
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
const DOUBLE_NEWLINE = "\n\n";
|
||||
const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n";
|
||||
// TODO: Do we want to stop completions when reaching a `/src/` string?
|
||||
const SRC_DIRECTORY = "/src/";
|
||||
// Starcoder2 tends to output artifacts starting with the letter "t"
|
||||
const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
|
||||
const PYTHON_ENCODING = "#- coding: utf-8";
|
||||
const CODE_BLOCK_END = "```";
|
||||
|
||||
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.
|
||||
// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
|
||||
const ERRORS_TO_IGNORE = [
|
||||
// From Ollama
|
||||
"unexpected server status",
|
||||
];
|
||||
|
||||
const LOCAL_PROVIDERS: ModelProvider[] = [
|
||||
"ollama",
|
||||
"lmstudio",
|
||||
"llama.cpp",
|
||||
"llamafile",
|
||||
"text-gen-webui",
|
||||
];
|
||||
|
||||
function formatExternalSnippet(
|
||||
filepath: string,
|
||||
snippet: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
) {
|
||||
const comment = language.singleLineComment;
|
||||
const lines = [
|
||||
`${comment} Path: ${getBasename(filepath)}`,
|
||||
...snippet
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${comment} ${line}`),
|
||||
comment,
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export type GetLspDefinitionsFunction = (
|
||||
filepath: string,
|
||||
contents: string,
|
||||
cursorIndex: number,
|
||||
ide: IDE,
|
||||
lang: AutocompleteLanguageInfo,
|
||||
) => Promise<AutocompleteSnippet[]>;
|
||||
|
||||
export class CompletionProvider {
|
||||
private static debounceTimeout: NodeJS.Timeout | undefined = undefined;
|
||||
private static debouncing = 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: GetLspDefinitionsFunction,
|
||||
) {
|
||||
this.generatorReuseManager = new GeneratorReuseManager(
|
||||
this.onError.bind(this),
|
||||
);
|
||||
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
|
||||
this.rootPathContextService = new RootPathContextService(
|
||||
this.importDefinitionsService,
|
||||
this.ide,
|
||||
);
|
||||
}
|
||||
|
||||
private importDefinitionsService: ImportDefinitionsService;
|
||||
private rootPathContextService: RootPathContextService;
|
||||
private generatorReuseManager: GeneratorReuseManager;
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
// private nearbyDefinitionsService = new NearbyDefinitionsService();
|
||||
|
||||
private onError(e: any) {
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (
|
||||
ERRORS_TO_IGNORE.some((err) =>
|
||||
typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
// Key is completionId
|
||||
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);
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: outcome.accepted,
|
||||
modelName: outcome.modelName,
|
||||
modelProvider: outcome.modelProvider,
|
||||
time: outcome.time,
|
||||
cacheHit: outcome.cacheHit,
|
||||
},
|
||||
true,
|
||||
);
|
||||
this._outcomes.delete(completionId);
|
||||
|
||||
this.bracketMatchingService.handleAcceptedCompletion(
|
||||
outcome.completion,
|
||||
outcome.filepath,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
// Debounce
|
||||
const uuid = uuidv4();
|
||||
CompletionProvider.lastUUID = uuid;
|
||||
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config.tabAutocompleteOptions,
|
||||
};
|
||||
|
||||
// Check whether we're in the continue config.json file
|
||||
if (input.filepath === getConfigJsonPath()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
if (options.disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
let filepath = input.filepath;
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const relativePath = path.relative(workspaceDir, filepath);
|
||||
const relativePathBase = relativePath.split(path.sep).at(0);
|
||||
const isInWorkspace = !path.isAbsolute(relativePath) && relativePathBase !== "..";
|
||||
if (isInWorkspace) {
|
||||
filepath = path.relative(workspaceDir, filepath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Worst case we can check filetype glob patterns
|
||||
if (filepath === input.filepath) {
|
||||
filepath = getBasename(filepath);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(options.disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// Create abort signal if not given
|
||||
if (!token) {
|
||||
const controller = new AbortController();
|
||||
token = controller.signal;
|
||||
this._abortControllers.set(input.completionId, controller);
|
||||
}
|
||||
|
||||
// Allow disabling autocomplete from config.json
|
||||
if (options.disable) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Debounce
|
||||
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;
|
||||
}
|
||||
|
||||
// Ignore empty API keys for Mistral since we currently write
|
||||
// a template provider without one during onboarding
|
||||
if (llm.providerName === "mistral" && llm.apiKey === "") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Set temperature (but don't overrride)
|
||||
if (llm.completionOptions.temperature === undefined) {
|
||||
llm.completionOptions.temperature = 0.01;
|
||||
}
|
||||
|
||||
if (
|
||||
!config.tabAutocompleteOptions?.maxPromptTokens &&
|
||||
LOCAL_PROVIDERS.includes(llm.providerName)
|
||||
) {
|
||||
options.maxPromptTokens = 500;
|
||||
}
|
||||
|
||||
const outcome = await this.getTabCompletion(token, options, llm, input);
|
||||
|
||||
if (!outcome?.completion) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* This check is most likely not needed because we do trim the LLM output
|
||||
* elsewhere in the code. That said, I'm not yet confident enough to
|
||||
* remove this.
|
||||
*/
|
||||
if (options.transform && isOnlyWhitespace(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.prefix, completionToCache);
|
||||
}
|
||||
}, 100);
|
||||
|
||||
return outcome;
|
||||
} catch (e: any) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
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, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
useRootPathContext: restOfOutcome.useRootPathContext,
|
||||
},
|
||||
true,
|
||||
);
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
private isMultiline({
|
||||
language,
|
||||
prefix,
|
||||
suffix,
|
||||
selectedCompletionInfo,
|
||||
multilineCompletions,
|
||||
completeMultiline,
|
||||
}: {
|
||||
language: AutocompleteLanguageInfo;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"];
|
||||
multilineCompletions: TabAutocompleteOptions["multilineCompletions"];
|
||||
completeMultiline: boolean;
|
||||
}) {
|
||||
let langMultilineDecision = language.useMultiline?.({ prefix, suffix });
|
||||
if (langMultilineDecision) {
|
||||
return langMultilineDecision;
|
||||
} else {
|
||||
return (
|
||||
!selectedCompletionInfo && // Only ever single-line if using intellisense selected value
|
||||
multilineCompletions !== "never" &&
|
||||
(multilineCompletions === "always" || completeMultiline)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async getTabCompletion(
|
||||
token: AbortSignal,
|
||||
options: TabAutocompleteOptions,
|
||||
llm: ILLM,
|
||||
input: AutocompleteInput,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
const startTime = Date.now();
|
||||
|
||||
const {
|
||||
filepath,
|
||||
pos,
|
||||
recentlyEditedFiles,
|
||||
recentlyEditedRanges,
|
||||
clipboardText,
|
||||
manuallyPassFileContents,
|
||||
manuallyPassPrefix,
|
||||
} = input;
|
||||
const fileContents =
|
||||
manuallyPassFileContents ?? (await this.ide.readFile(filepath));
|
||||
const fileLines = fileContents.split("\n");
|
||||
|
||||
// Filter
|
||||
const lang = languageForFilepath(filepath);
|
||||
|
||||
if (options.transform) {
|
||||
const line = fileLines[pos.line] ?? "";
|
||||
for (const endOfLine of lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && pos.character >= line.length) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Model
|
||||
if (!llm) {
|
||||
return;
|
||||
}
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
|
||||
// Prompt
|
||||
let fullPrefix =
|
||||
getRangeInString(fileContents, {
|
||||
start: { line: 0, character: 0 },
|
||||
end: input.selectedCompletionInfo?.range.start ?? pos,
|
||||
}) + (input.selectedCompletionInfo?.text ?? "");
|
||||
|
||||
if (input.injectDetails) {
|
||||
const lines = fullPrefix.split("\n");
|
||||
fullPrefix = `${lines.slice(0, -1).join("\n")}\n${lang.singleLineComment
|
||||
} ${input.injectDetails
|
||||
.split("\n")
|
||||
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
|
||||
}
|
||||
|
||||
const fullSuffix = getRangeInString(fileContents, {
|
||||
start: pos,
|
||||
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
|
||||
});
|
||||
|
||||
// First non-whitespace line below the cursor
|
||||
let lineBelowCursor = "";
|
||||
let i = 1;
|
||||
while (
|
||||
lineBelowCursor.trim() === "" &&
|
||||
pos.line + i <= fileLines.length - 1
|
||||
) {
|
||||
lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)];
|
||||
i++;
|
||||
}
|
||||
|
||||
let extrasSnippets = options.useOtherFiles
|
||||
? ((await Promise.race([
|
||||
this.getDefinitionsFromLsp(
|
||||
filepath,
|
||||
fullPrefix + fullSuffix,
|
||||
fullPrefix.length,
|
||||
this.ide,
|
||||
lang,
|
||||
),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
}),
|
||||
])) as AutocompleteSnippet[])
|
||||
: [];
|
||||
|
||||
const workspaceDirs = await this.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,
|
||||
this.importDefinitionsService,
|
||||
this.rootPathContextService,
|
||||
);
|
||||
|
||||
// If prefix is manually passed
|
||||
if (manuallyPassPrefix) {
|
||||
prefix = manuallyPassPrefix;
|
||||
suffix = "";
|
||||
}
|
||||
|
||||
// Template prompt
|
||||
const {
|
||||
template,
|
||||
completionOptions,
|
||||
compilePrefixSuffix = undefined,
|
||||
} = options.template
|
||||
? { template: options.template, completionOptions: {} }
|
||||
: getTemplateForModel(llm.model);
|
||||
|
||||
let prompt: string;
|
||||
const filename = getBasename(filepath);
|
||||
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
|
||||
|
||||
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
|
||||
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
|
||||
if (compilePrefixSuffix) {
|
||||
[prefix, suffix] = compilePrefixSuffix(
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
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}`;
|
||||
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
|
||||
// If it's an empty file, include the file name as a comment
|
||||
prefix = `${lang.singleLineComment} ${getLastNPathParts(
|
||||
filepath,
|
||||
2,
|
||||
)}\n${prefix}`;
|
||||
}
|
||||
|
||||
prompt = compiledTemplate({
|
||||
prefix,
|
||||
suffix,
|
||||
filename,
|
||||
reponame,
|
||||
language: lang.name,
|
||||
});
|
||||
} else {
|
||||
// Let the template function format snippets
|
||||
prompt = template(
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
lang.name,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
// Completion
|
||||
let completion = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = options.useCache
|
||||
? await cache.get(prefix)
|
||||
: undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
const stop = [
|
||||
...(completionOptions?.stop || []),
|
||||
// ...multilineStops,
|
||||
...commonStops,
|
||||
...(llm.model.toLowerCase().includes("starcoder2")
|
||||
? STARCODER2_T_ARTIFACTS
|
||||
: []),
|
||||
...(lang.stopWords ?? []),
|
||||
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
|
||||
];
|
||||
|
||||
const multiline =
|
||||
!options.transform ||
|
||||
this.isMultiline({
|
||||
multilineCompletions: options.multilineCompletions,
|
||||
language: lang,
|
||||
selectedCompletionInfo: input.selectedCompletionInfo,
|
||||
prefix,
|
||||
suffix,
|
||||
completeMultiline,
|
||||
});
|
||||
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
const generator = this.generatorReuseManager.getGenerator(
|
||||
prefix,
|
||||
() =>
|
||||
llm.supportsFim()
|
||||
? llm.streamFim(prefix, suffix, {
|
||||
...completionOptions,
|
||||
stop,
|
||||
})
|
||||
: llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
raw: true,
|
||||
stop,
|
||||
}),
|
||||
multiline,
|
||||
);
|
||||
|
||||
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
|
||||
const fullStop = () =>
|
||||
this.generatorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
// LLM
|
||||
let cancelled = false;
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.aborted) {
|
||||
cancelled = true;
|
||||
return;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
let charGenerator = generatorWithCancellation();
|
||||
|
||||
if (options.transform) {
|
||||
// charGenerator = noFirstCharNewline(charGenerator);
|
||||
// charGenerator = onlyWhitespaceAfterEndOfLine(
|
||||
// charGenerator,
|
||||
// lang.endOfLine,
|
||||
// fullStop,
|
||||
// );
|
||||
charGenerator = stopAtStopTokens(charGenerator, stop);
|
||||
charGenerator =
|
||||
this.bracketMatchingService.stopOnUnmatchedClosingBracket(
|
||||
charGenerator,
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
multiline,
|
||||
);
|
||||
}
|
||||
|
||||
let lineGenerator = streamLines(charGenerator);
|
||||
if (options.transform) {
|
||||
lineGenerator = stopAtLines(lineGenerator, fullStop);
|
||||
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
|
||||
lineGenerator = avoidPathLineAndEmptyComments(
|
||||
lineGenerator,
|
||||
lang.singleLineComment,
|
||||
);
|
||||
lineGenerator = skipPrefixes(lineGenerator);
|
||||
|
||||
// lineGenerator = noTopLevelKeywordsMidline(
|
||||
// lineGenerator,
|
||||
// lang.topLevelKeywords,
|
||||
// fullStop,
|
||||
// );
|
||||
for (const lineFilter of lang.lineFilters ?? []) {
|
||||
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
|
||||
}
|
||||
|
||||
lineGenerator = stopAtSimilarLine(
|
||||
lineGenerator,
|
||||
lineBelowCursor,
|
||||
fullStop,
|
||||
);
|
||||
}
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
|
||||
try {
|
||||
for await (const update of finalGenerator) {
|
||||
completion += update;
|
||||
}
|
||||
} catch (e: any) {
|
||||
if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) {
|
||||
return undefined;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const processedCompletion = options.transform
|
||||
? postprocessCompletion({
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
llm,
|
||||
})
|
||||
: completion;
|
||||
|
||||
if (!processedCompletion) {
|
||||
return undefined;
|
||||
}
|
||||
completion = processedCompletion;
|
||||
}
|
||||
|
||||
const time = Date.now() - startTime;
|
||||
return {
|
||||
time,
|
||||
completion,
|
||||
prefix,
|
||||
suffix,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
filepath: input.filepath,
|
||||
completionId: input.completionId,
|
||||
gitRepo: await this.ide.getRepoName(input.filepath),
|
||||
uniqueId: await this.ide.getUniqueId(),
|
||||
...options,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,16 +1,18 @@
|
|||
import { LineFilter } from "./streamTransforms/lineStream";
|
||||
import { BracketMatchingService } from "../filtering/BracketMatchingService";
|
||||
import {
|
||||
CharacterFilter,
|
||||
LineFilter,
|
||||
} from "../filtering/streamTransforms/lineStream";
|
||||
|
||||
export interface AutocompleteLanguageInfo {
|
||||
name: string;
|
||||
topLevelKeywords: string[];
|
||||
singleLineComment: string;
|
||||
singleLineComment?: string;
|
||||
endOfLine: string[];
|
||||
stopWords?: string[];
|
||||
lineFilters?: LineFilter[];
|
||||
useMultiline?: (args: {
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
}) => boolean | undefined;
|
||||
charFilters?: CharacterFilter[];
|
||||
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
|
||||
}
|
||||
|
||||
// TypeScript
|
||||
|
|
@ -256,10 +258,8 @@ export const YAML: AutocompleteLanguageInfo = {
|
|||
} else {
|
||||
seenListItem = true;
|
||||
}
|
||||
yield line;
|
||||
} else {
|
||||
yield line;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
},
|
||||
// Don't allow consecutive lines of same key
|
||||
|
|
@ -268,18 +268,39 @@ export const YAML: AutocompleteLanguageInfo = {
|
|||
for await (const line of lines) {
|
||||
if (line.includes(":")) {
|
||||
const key = line.split(":")[0];
|
||||
if (key !== lastKey) {
|
||||
if (key === lastKey) {
|
||||
break;
|
||||
} else {
|
||||
yield line;
|
||||
lastKey = key;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const Json: AutocompleteLanguageInfo = {
|
||||
name: "JSON",
|
||||
topLevelKeywords: [],
|
||||
singleLineComment: "//",
|
||||
endOfLine: [",", "}", "]"],
|
||||
charFilters: [
|
||||
function matchBrackets({ chars, prefix, suffix, filepath, multiline }) {
|
||||
const bracketMatchingService = new BracketMatchingService();
|
||||
return bracketMatchingService.stopOnUnmatchedClosingBracket(
|
||||
chars,
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
multiline,
|
||||
);
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const Markdown: AutocompleteLanguageInfo = {
|
||||
name: "Markdown",
|
||||
topLevelKeywords: [],
|
||||
|
|
@ -289,7 +310,7 @@ export const Markdown: AutocompleteLanguageInfo = {
|
|||
const singleLineStarters = ["- ", "* ", /^\d+\. /, "> ", "```", /^#{1,6} /];
|
||||
let currentLine = prefix.split("\n").pop();
|
||||
if (!currentLine) {
|
||||
return undefined;
|
||||
return true;
|
||||
}
|
||||
currentLine = currentLine.trim();
|
||||
for (const starter of singleLineStarters) {
|
||||
|
|
@ -301,7 +322,7 @@ export const Markdown: AutocompleteLanguageInfo = {
|
|||
return false;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -309,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
ts: Typescript,
|
||||
js: Typescript,
|
||||
tsx: Typescript,
|
||||
json: Json,
|
||||
jsx: Typescript,
|
||||
ipynb: Python,
|
||||
py: Python,
|
||||
|
|
@ -346,3 +368,9 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
yml: YAML,
|
||||
md: Markdown,
|
||||
};
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string,
|
||||
): AutocompleteLanguageInfo {
|
||||
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
|
||||
}
|
||||
|
|
@ -1,215 +1,87 @@
|
|||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { TabAutocompleteOptions } from "../index.js";
|
||||
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
} from "../llm/countTokens.js";
|
||||
import { AstPath, getAst, getTreePathAtCursor } from "./ast.js";
|
||||
import {
|
||||
AutocompleteLanguageInfo,
|
||||
LANGUAGES,
|
||||
Typescript,
|
||||
} from "./languages.js";
|
||||
import { Position, Range } from "../index.js";
|
||||
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
|
||||
import {
|
||||
fillPromptWithSnippets,
|
||||
getSymbolsForSnippet,
|
||||
rankSnippets,
|
||||
rankAndOrderSnippets,
|
||||
removeRangeFromSnippets,
|
||||
type AutocompleteSnippet,
|
||||
} from "./ranking.js";
|
||||
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
|
||||
import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js";
|
||||
import { RootPathContextService } from "./services/RootPathContextService.js";
|
||||
import { shouldCompleteMultiline } from "./shouldCompleteMultiline.js";
|
||||
} from "./context/ranking/index.js";
|
||||
import { HelperVars } from "./util/HelperVars.js";
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string,
|
||||
): AutocompleteLanguageInfo {
|
||||
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
|
||||
function filterSnippetsAlreadyInCaretWindow(
|
||||
snippets: AutocompleteSnippet[],
|
||||
caretWindow: string,
|
||||
): AutocompleteSnippet[] {
|
||||
return snippets
|
||||
.map((snippet) => ({ ...snippet }))
|
||||
.filter(
|
||||
(s) =>
|
||||
s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()),
|
||||
);
|
||||
}
|
||||
|
||||
function getRangeOfPrefixAndSuffixWithBuffer(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
caretPos: Position,
|
||||
): Range {
|
||||
// Remove prefix range from snippets
|
||||
const prefixLines = prefix.split("\n").length;
|
||||
const suffixLines = suffix.split("\n").length;
|
||||
const buffer = 8;
|
||||
const prefixSuffixRangeWithBuffer = {
|
||||
start: {
|
||||
line: caretPos.line - prefixLines - buffer,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: caretPos.line + suffixLines + buffer,
|
||||
character: 0,
|
||||
},
|
||||
};
|
||||
|
||||
return prefixSuffixRangeWithBuffer;
|
||||
}
|
||||
|
||||
export async function constructAutocompletePrompt(
|
||||
filepath: string,
|
||||
cursorLine: number,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
clipboardText: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
options: TabAutocompleteOptions,
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
recentlyEditedFiles: RangeInFileWithContents[],
|
||||
modelName: string,
|
||||
helper: HelperVars,
|
||||
extraSnippets: AutocompleteSnippet[],
|
||||
importDefinitionsService: ImportDefinitionsService,
|
||||
rootPathContextService: RootPathContextService,
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
useFim: boolean;
|
||||
completeMultiline: boolean;
|
||||
snippets: AutocompleteSnippet[];
|
||||
}> {
|
||||
// Construct basic prefix
|
||||
const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage;
|
||||
const prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
|
||||
|
||||
// Construct suffix
|
||||
const maxSuffixTokens = Math.min(
|
||||
options.maxPromptTokens - countTokens(prefix, modelName),
|
||||
options.maxSuffixPercentage * options.maxPromptTokens,
|
||||
contextRetrievalService: ContextRetrievalService,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
let snippets = await contextRetrievalService.retrieveCandidateSnippets(
|
||||
helper,
|
||||
extraSnippets,
|
||||
);
|
||||
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
|
||||
|
||||
// Calculate AST Path
|
||||
let treePath: AstPath | undefined;
|
||||
try {
|
||||
const ast = await getAst(filepath, fullPrefix + fullSuffix);
|
||||
if (ast) {
|
||||
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse AST", e);
|
||||
}
|
||||
|
||||
// Find external snippets
|
||||
let snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
if (options.useOtherFiles) {
|
||||
snippets.push(...extraSnippets);
|
||||
|
||||
const windowAroundCursor =
|
||||
fullPrefix.slice(
|
||||
-options.slidingWindowSize * options.slidingWindowPrefixPercentage,
|
||||
) +
|
||||
fullSuffix.slice(
|
||||
options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage),
|
||||
);
|
||||
|
||||
// This was much too slow, and not super useful
|
||||
// const slidingWindowMatches = await slidingWindowMatcher(
|
||||
// recentlyEditedFiles,
|
||||
// windowAroundCursor,
|
||||
// 3,
|
||||
// options.slidingWindowSize,
|
||||
// );
|
||||
// snippets.push(...slidingWindowMatches);
|
||||
|
||||
// snippets.push(
|
||||
// ...recentlyEditedRanges.map((r) => ({
|
||||
// ...r,
|
||||
// contents: r.lines.join("\n"),
|
||||
// })),
|
||||
// );
|
||||
|
||||
if (options.useRecentlyEdited) {
|
||||
const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0];
|
||||
if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) {
|
||||
const matchingRange = findMatchingRange(
|
||||
recentlyEditedRanges,
|
||||
currentLinePrefix,
|
||||
);
|
||||
if (matchingRange) {
|
||||
snippets.push({
|
||||
...matchingRange,
|
||||
contents: matchingRange.lines.join("\n"),
|
||||
score: 0.8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Use imports
|
||||
if (options.useImports) {
|
||||
const importSnippets = [];
|
||||
const fileInfo = importDefinitionsService.get(filepath);
|
||||
if (fileInfo) {
|
||||
const { imports } = fileInfo;
|
||||
// Look for imports of any symbols around the current range
|
||||
const textAroundCursor =
|
||||
fullPrefix.split("\n").slice(-5).join("\n") +
|
||||
fullSuffix.split("\n").slice(0, 3).join("\n");
|
||||
const symbols = Array.from(
|
||||
getSymbolsForSnippet(textAroundCursor),
|
||||
).filter((symbol) => !language.topLevelKeywords.includes(symbol));
|
||||
for (const symbol of symbols) {
|
||||
const rifs = imports[symbol];
|
||||
if (Array.isArray(rifs)) {
|
||||
importSnippets.push(...rifs);
|
||||
}
|
||||
}
|
||||
}
|
||||
snippets.push(...importSnippets);
|
||||
}
|
||||
|
||||
if (options.useRootPathContext && treePath) {
|
||||
const ctx = await rootPathContextService.getContextForPath(
|
||||
filepath,
|
||||
treePath,
|
||||
);
|
||||
snippets.push(...ctx);
|
||||
}
|
||||
|
||||
// Filter out empty snippets and ones that are already in the prefix/suffix
|
||||
snippets = snippets
|
||||
.map((snippet) => ({ ...snippet }))
|
||||
.filter(
|
||||
(s) =>
|
||||
s.contents.trim() !== "" &&
|
||||
!(prefix + suffix).includes(s.contents.trim()),
|
||||
);
|
||||
|
||||
// Rank / order the snippets
|
||||
const scoredSnippets = rankSnippets(snippets, windowAroundCursor);
|
||||
|
||||
// Fill maxSnippetTokens with snippets
|
||||
const maxSnippetTokens =
|
||||
options.maxPromptTokens * options.maxSnippetPercentage;
|
||||
|
||||
// Remove prefix range from snippets
|
||||
const prefixLines = prefix.split("\n").length;
|
||||
const suffixLines = suffix.split("\n").length;
|
||||
const buffer = 8;
|
||||
const prefixSuffixRangeWithBuffer = {
|
||||
start: {
|
||||
line: cursorLine - prefixLines - buffer,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: cursorLine + suffixLines + buffer,
|
||||
character: 0,
|
||||
},
|
||||
};
|
||||
let finalSnippets = removeRangeFromSnippets(
|
||||
scoredSnippets,
|
||||
filepath.split("://").slice(-1)[0],
|
||||
prefixSuffixRangeWithBuffer,
|
||||
);
|
||||
|
||||
// Filter snippets for those with best scores (must be above threshold)
|
||||
finalSnippets = finalSnippets.filter(
|
||||
(snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold,
|
||||
);
|
||||
finalSnippets = fillPromptWithSnippets(
|
||||
scoredSnippets,
|
||||
maxSnippetTokens,
|
||||
modelName,
|
||||
);
|
||||
|
||||
snippets = finalSnippets;
|
||||
}
|
||||
|
||||
return {
|
||||
prefix,
|
||||
suffix,
|
||||
useFim: true,
|
||||
completeMultiline: await shouldCompleteMultiline(
|
||||
treePath,
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
language,
|
||||
),
|
||||
snippets = filterSnippetsAlreadyInCaretWindow(
|
||||
snippets,
|
||||
};
|
||||
helper.prunedCaretWindow,
|
||||
);
|
||||
|
||||
const scoredSnippets = rankAndOrderSnippets(snippets, helper);
|
||||
|
||||
// This might be redundant with filterSnippetsAlreadyInCaretWindow
|
||||
let finalSnippets = removeRangeFromSnippets(
|
||||
scoredSnippets,
|
||||
helper.filepath.split("://").slice(-1)[0],
|
||||
getRangeOfPrefixAndSuffixWithBuffer(
|
||||
helper.prunedPrefix,
|
||||
helper.prunedSuffix,
|
||||
helper.pos,
|
||||
),
|
||||
);
|
||||
|
||||
// Filter snippets below similarity threshold
|
||||
finalSnippets = finalSnippets.filter(
|
||||
(snippet) =>
|
||||
snippet.score >= helper.options.recentlyEditedSimilarityThreshold,
|
||||
);
|
||||
|
||||
finalSnippets = fillPromptWithSnippets(
|
||||
scoredSnippets,
|
||||
helper.maxSnippetTokens,
|
||||
helper.modelName,
|
||||
);
|
||||
|
||||
return finalSnippets;
|
||||
}
|
||||
|
|
|
|||
123
core/autocomplete/context/ContextRetrievalService.ts
Normal file
123
core/autocomplete/context/ContextRetrievalService.ts
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import { IDE } from "../..";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { RecentlyEditedRange } from "../util/types";
|
||||
import { ImportDefinitionsService } from "./ImportDefinitionsService";
|
||||
import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking";
|
||||
import { RootPathContextService } from "./root-path-context/RootPathContextService";
|
||||
|
||||
export class ContextRetrievalService {
|
||||
private importDefinitionsService: ImportDefinitionsService;
|
||||
private rootPathContextService: RootPathContextService;
|
||||
|
||||
constructor(private readonly ide: IDE) {
|
||||
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
|
||||
this.rootPathContextService = new RootPathContextService(
|
||||
this.importDefinitionsService,
|
||||
this.ide,
|
||||
);
|
||||
}
|
||||
|
||||
public async retrieveCandidateSnippets(
|
||||
helper: HelperVars,
|
||||
extraSnippets: AutocompleteSnippet[],
|
||||
) {
|
||||
if (helper.options.useOtherFiles === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
// Snippets injected by the IDE for IDE-specific reasons
|
||||
snippets.push(...extraSnippets);
|
||||
|
||||
// If a recently edited range has a line that is a perfect match with the start of the current line
|
||||
snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper));
|
||||
|
||||
// Import definitions of any symbols in near range of the caret
|
||||
snippets.push(...(await this.getSnippetsFromImportDefinitions(helper)));
|
||||
|
||||
// Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/
|
||||
if (helper.options.useRootPathContext && helper.treePath) {
|
||||
snippets.push(
|
||||
...(await this.rootPathContextService.getContextForPath(
|
||||
helper.filepath,
|
||||
helper.treePath,
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
return snippets;
|
||||
}
|
||||
|
||||
private getSnippetsFromRecentlyEditedRanges(
|
||||
helper: HelperVars,
|
||||
): AutocompleteSnippet[] {
|
||||
if (helper.options.useRecentlyEdited === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const currentLinePrefix = helper.prunedPrefix
|
||||
.trim()
|
||||
.split("\n")
|
||||
.slice(-1)[0];
|
||||
if (
|
||||
currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength
|
||||
) {
|
||||
const matchingRange = this.findMatchingRange(
|
||||
helper.input.recentlyEditedRanges,
|
||||
currentLinePrefix,
|
||||
);
|
||||
|
||||
if (matchingRange) {
|
||||
return [
|
||||
{
|
||||
...matchingRange,
|
||||
contents: matchingRange.lines.join("\n"),
|
||||
score: 0.8,
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private async getSnippetsFromImportDefinitions(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
if (helper.options.useImports === false) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const importSnippets = [];
|
||||
const fileInfo = this.importDefinitionsService.get(helper.filepath);
|
||||
if (fileInfo) {
|
||||
const { imports } = fileInfo;
|
||||
// Look for imports of any symbols around the current range
|
||||
const textAroundCursor =
|
||||
helper.fullPrefix.split("\n").slice(-5).join("\n") +
|
||||
helper.fullSuffix.split("\n").slice(0, 3).join("\n");
|
||||
const symbols = Array.from(getSymbolsForSnippet(textAroundCursor)).filter(
|
||||
(symbol) => !helper.lang.topLevelKeywords.includes(symbol),
|
||||
);
|
||||
for (const symbol of symbols) {
|
||||
const rifs = imports[symbol];
|
||||
if (Array.isArray(rifs)) {
|
||||
importSnippets.push(...rifs);
|
||||
}
|
||||
}
|
||||
}
|
||||
return importSnippets;
|
||||
}
|
||||
|
||||
findMatchingRange(
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
linePrefix: string,
|
||||
): RecentlyEditedRange | undefined {
|
||||
return recentlyEditedRanges.find((recentlyEditedRange) => {
|
||||
return recentlyEditedRange.lines.some((line) =>
|
||||
line.startsWith(linePrefix),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE, Location } from "../..";
|
||||
import { LANGUAGES } from "../languages";
|
||||
import { getSymbolsForSnippet } from "../ranking";
|
||||
import { LANGUAGES } from "../constants/AutocompleteLanguageInfo";
|
||||
import { getSymbolsForSnippet } from "./ranking";
|
||||
|
||||
interface FileInfo {
|
||||
filepath: string;
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { Range } from "../index.js";
|
||||
import { countTokens } from "../llm/countTokens.js";
|
||||
import { RangeInFileWithContents } from "../../../commands/util.js";
|
||||
import { Range } from "../../../index.js";
|
||||
import { countTokens } from "../../../llm/countTokens.js";
|
||||
import { HelperVars } from "../../util/HelperVars.js";
|
||||
|
||||
export type AutocompleteSnippet = RangeInFileWithContents & {
|
||||
score?: number;
|
||||
|
|
@ -41,10 +42,20 @@ export function jaccardSimilarity(a: string, b: string): number {
|
|||
/**
|
||||
* Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array.
|
||||
*/
|
||||
export function rankSnippets(
|
||||
export function rankAndOrderSnippets(
|
||||
ranges: AutocompleteSnippet[],
|
||||
windowAroundCursor: string,
|
||||
helper: HelperVars,
|
||||
): Required<AutocompleteSnippet>[] {
|
||||
const windowAroundCursor =
|
||||
helper.fullPrefix.slice(
|
||||
-helper.options.slidingWindowSize *
|
||||
helper.options.slidingWindowPrefixPercentage,
|
||||
) +
|
||||
helper.fullSuffix.slice(
|
||||
helper.options.slidingWindowSize *
|
||||
(1 - helper.options.slidingWindowPrefixPercentage),
|
||||
);
|
||||
|
||||
const snippets: Required<AutocompleteSnippet>[] = ranges.map((snippet) => ({
|
||||
score:
|
||||
snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor),
|
||||
|
|
@ -119,7 +130,8 @@ function mergeOverlappingRangeContents(
|
|||
}
|
||||
|
||||
/**
|
||||
* Fill the allowed space with snippets
|
||||
* Fill the allowed space with snippets.
|
||||
* It is assumed that the snippets are sorted by score.
|
||||
*/
|
||||
export function fillPromptWithSnippets(
|
||||
snippets: Required<AutocompleteSnippet>[],
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { AutocompleteSnippet, jaccardSimilarity } from "./ranking.js";
|
||||
import { RangeInFileWithContents } from "../../../commands/util.js";
|
||||
import { AutocompleteSnippet, jaccardSimilarity } from "./index.js";
|
||||
|
||||
function* slidingWindow(
|
||||
content: string,
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { Range } from "../../..";
|
||||
import { testIde } from "../../../test/util/fixtures";
|
||||
import { getAst, getTreePathAtCursor } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
import { RootPathContextService } from "./RootPathContextService";
|
||||
|
||||
function splitTextAtRange(fileContent: string, range: Range): [string, string] {
|
||||
const lines = fileContent.split("\n");
|
||||
let currentPos = 0;
|
||||
|
||||
if (range.start.line === range.end.line) {
|
||||
// If range is on the same line, calculate position once
|
||||
for (let i = 0; i < range.start.line; i++) {
|
||||
currentPos += lines[i].length + 1; // +1 for the newline character
|
||||
}
|
||||
const startPos = currentPos + range.start.character;
|
||||
const endPos = currentPos + range.end.character;
|
||||
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
|
||||
}
|
||||
|
||||
// Calculate position of range start
|
||||
for (let i = 0; i < range.start.line; i++) {
|
||||
currentPos += lines[i].length + 1;
|
||||
}
|
||||
const startPos = currentPos + range.start.character;
|
||||
|
||||
// Calculate position of range end
|
||||
currentPos = 0;
|
||||
for (let i = 0; i < range.end.line; i++) {
|
||||
currentPos += lines[i].length + 1;
|
||||
}
|
||||
const endPos = currentPos + range.end.character;
|
||||
|
||||
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
|
||||
}
|
||||
|
||||
export async function testRootPathContext(
|
||||
folderName: string,
|
||||
relativeFilepath: string,
|
||||
rangeToFill: Range,
|
||||
expectedSnippets: string[],
|
||||
) {
|
||||
const ide = testIde;
|
||||
const importDefinitionsService = new ImportDefinitionsService(ide);
|
||||
const service = new RootPathContextService(importDefinitionsService, ide);
|
||||
|
||||
// Copy the folder to the test directory
|
||||
const folderPath = path.join(
|
||||
__dirname,
|
||||
"autocomplete",
|
||||
"context",
|
||||
"root-path-context",
|
||||
"test",
|
||||
folderName,
|
||||
);
|
||||
const workspaceDir = (await ide.getWorkspaceDirs())[0];
|
||||
const testFolderPath = path.join(workspaceDir, folderName);
|
||||
fs.cpSync(folderPath, testFolderPath, {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
|
||||
// Get results of root path context
|
||||
const startPath = path.join(testFolderPath, relativeFilepath);
|
||||
const [prefix, suffix] = splitTextAtRange(
|
||||
fs.readFileSync(startPath, "utf8"),
|
||||
rangeToFill,
|
||||
);
|
||||
const fileContents = prefix + suffix;
|
||||
const ast = await getAst(startPath, fileContents);
|
||||
if (!ast) {
|
||||
throw new Error("AST is undefined");
|
||||
}
|
||||
|
||||
const treePath = await getTreePathAtCursor(ast, prefix.length);
|
||||
const snippets = await service.getContextForPath(startPath, treePath);
|
||||
|
||||
expectedSnippets.forEach((expectedSnippet) => {
|
||||
const found = snippets.find((snippet) =>
|
||||
snippet.contents.includes(expectedSnippet),
|
||||
);
|
||||
expect(found).toBeDefined();
|
||||
});
|
||||
}
|
||||
|
||||
describe("RootPathContextService", () => {
|
||||
it("should be true", async () => {
|
||||
await testRootPathContext(
|
||||
"typescript",
|
||||
"file1.ts",
|
||||
{ start: { line: 3, character: 2 }, end: { line: 3, character: 24 } },
|
||||
["export interface Person", "export interface Address"],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,11 +1,11 @@
|
|||
import { createHash } from "crypto";
|
||||
import { LRUCache } from "lru-cache";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { IDE } from "../..";
|
||||
import { getQueryForFile, TSQueryType } from "../../util/treeSitter";
|
||||
import { AstPath } from "../ast";
|
||||
import { IDE } from "../../..";
|
||||
import { getQueryForFile, TSQueryType } from "../../../util/treeSitter";
|
||||
import { AstPath } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
import { AutocompleteSnippet } from "../ranking";
|
||||
import { ImportDefinitionsService } from "./ImportDefinitionsService";
|
||||
|
||||
export class RootPathContextService {
|
||||
private cache = new LRUCache<string, AutocompleteSnippet[]>({
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import { Address, Person } from "./types";
|
||||
|
||||
function getAddress(person: Person): Address {
|
||||
return person.address;
|
||||
}
|
||||
|
||||
class Group {
|
||||
people: Person[];
|
||||
|
||||
constructor(people: Person[]) {
|
||||
this.people = people;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
export interface Person {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
age: number;
|
||||
address: Address;
|
||||
}
|
||||
|
||||
export interface Address {
|
||||
street: string;
|
||||
city: string;
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
export function isOnlyWhitespace(completion: string): boolean {
|
||||
const whitespaceRegex = /^[\s]+$/;
|
||||
return whitespaceRegex.test(completion);
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
import { streamLines } from "../../../diff/util";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters";
|
||||
import { HelperVars } from "../../util/HelperVars";
|
||||
import { stopAtStopTokens } from "./charStream";
|
||||
import {
|
||||
avoidEmptyComments,
|
||||
avoidPathLine,
|
||||
showWhateverWeHaveAtXMs,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
stopAtRepeatingLines,
|
||||
stopAtSimilarLine,
|
||||
streamWithNewLines,
|
||||
} from "./lineStream";
|
||||
|
||||
export class StreamTransformPipeline {
|
||||
async *transform(
|
||||
generator: AsyncGenerator<string>,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
multiline: boolean,
|
||||
stopTokens: string[],
|
||||
fullStop: () => void,
|
||||
helper: HelperVars,
|
||||
): AsyncGenerator<string> {
|
||||
let charGenerator = generator;
|
||||
|
||||
charGenerator = stopAtStopTokens(generator, stopTokens);
|
||||
for (const charFilter of helper.lang.charFilters ?? []) {
|
||||
charGenerator = charFilter({
|
||||
chars: charGenerator,
|
||||
prefix,
|
||||
suffix,
|
||||
filepath: helper.filepath,
|
||||
multiline,
|
||||
});
|
||||
}
|
||||
|
||||
let lineGenerator = streamLines(charGenerator);
|
||||
|
||||
lineGenerator = stopAtLines(lineGenerator, fullStop);
|
||||
lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop);
|
||||
lineGenerator = avoidEmptyComments(
|
||||
lineGenerator,
|
||||
helper.lang.singleLineComment,
|
||||
);
|
||||
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
|
||||
lineGenerator = skipPrefixes(lineGenerator);
|
||||
|
||||
for (const lineFilter of helper.lang.lineFilters ?? []) {
|
||||
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
|
||||
}
|
||||
|
||||
lineGenerator = stopAtSimilarLine(
|
||||
lineGenerator,
|
||||
this.getLineBelowCursor(helper),
|
||||
fullStop,
|
||||
);
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(
|
||||
lineGenerator,
|
||||
helper.options.showWhateverWeHaveAtXMs ??
|
||||
(DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number),
|
||||
);
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
for await (const update of finalGenerator) {
|
||||
yield update;
|
||||
}
|
||||
}
|
||||
|
||||
private getLineBelowCursor(helper: HelperVars): string {
|
||||
let lineBelowCursor = "";
|
||||
let i = 1;
|
||||
while (
|
||||
lineBelowCursor.trim() === "" &&
|
||||
helper.pos.line + i <= helper.fileLines.length - 1
|
||||
) {
|
||||
lineBelowCursor =
|
||||
helper.fileLines[
|
||||
Math.min(helper.pos.line + i, helper.fileLines.length - 1)
|
||||
];
|
||||
i++;
|
||||
}
|
||||
return lineBelowCursor;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { stopAtStopTokens } from "./streamTransforms/charStream";
|
||||
import { stopAtStopTokens } from "./charStream";
|
||||
|
||||
describe("stopAtStopTokens", () => {
|
||||
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import * as lineStream from "./streamTransforms/lineStream";
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
describe("lineStream", () => {
|
||||
let mockFullStop: jest.Mock;
|
||||
|
|
@ -31,21 +31,34 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
describe("avoidPathLine", () => {
|
||||
it("should filter out path lines and empty comments", async () => {
|
||||
it("should filter out path lines", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"// Path: src/index.ts",
|
||||
"const x = 5;",
|
||||
"//",
|
||||
"console.log(x);",
|
||||
]);
|
||||
|
||||
const result = lineStream.avoidPathLineAndEmptyComments(
|
||||
linesGenerator,
|
||||
"//",
|
||||
);
|
||||
const result = lineStream.avoidPathLine(linesGenerator, "//");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]);
|
||||
});
|
||||
});
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]);
|
||||
describe("avoidEmptyComments", () => {
|
||||
it("should filter out empty comments", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"// Path: src/index.ts",
|
||||
"const x = 5;",
|
||||
"//",
|
||||
"console.log(x);",
|
||||
]);
|
||||
const result = lineStream.avoidEmptyComments(linesGenerator, "//");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
expect(filteredLines).toEqual([
|
||||
"// Path: src/index.ts",
|
||||
"const x = 5;",
|
||||
"console.log(x);",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1,12 +1,20 @@
|
|||
import { distance } from "fastest-levenshtein";
|
||||
import { DiffLine } from "../..";
|
||||
import { LineStream } from "../../diff/util";
|
||||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
lines: LineStream;
|
||||
fullStop: () => void;
|
||||
}) => LineStream;
|
||||
|
||||
export type CharacterFilter = (args: {
|
||||
chars: AsyncGenerator<string>;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
filepath: string;
|
||||
multiline: boolean;
|
||||
}) => AsyncGenerator<string>;
|
||||
|
||||
function isBracketEnding(line: string): boolean {
|
||||
return line
|
||||
.trim()
|
||||
|
|
@ -14,14 +22,6 @@ function isBracketEnding(line: string): boolean {
|
|||
.some((char) => BRACKET_ENDING_CHARS.includes(char));
|
||||
}
|
||||
|
||||
function commonPrefixLength(a: string, b: string): number {
|
||||
let i = 0;
|
||||
while (i < a.length && i < b.length && a[i] === b[i]) {
|
||||
i++;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
function isEnglishFirstLine(line: string) {
|
||||
line = line.trim().toLowerCase();
|
||||
|
||||
|
|
@ -122,27 +122,45 @@ export async function* noTopLevelKeywordsMidline(
|
|||
}
|
||||
|
||||
/**
|
||||
* Filters out unwanted lines from a LineStream, specifically those starting with '// Path: <PATH>' or empty comments.
|
||||
* Filters out lines starting with '// Path: <PATH>' from a LineStream.
|
||||
*
|
||||
* @param {LineStream} stream - The input stream of lines to filter.
|
||||
* @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments).
|
||||
* @yields {string} The filtered lines, excluding unwanted path lines and empty comments.
|
||||
* @yields {string} The filtered lines, excluding unwanted path lines.
|
||||
*/
|
||||
export async function* avoidPathLineAndEmptyComments(
|
||||
export async function* avoidPathLine(
|
||||
stream: LineStream,
|
||||
comment: string,
|
||||
comment?: string,
|
||||
): LineStream {
|
||||
// Snippets are inserted as comments with a line at the start '// Path: <PATH>'.
|
||||
// Sometimes the model with copy this pattern, which is unwanted
|
||||
for await (const line of stream) {
|
||||
// Also filter lines that are empty comments
|
||||
if (line.startsWith(`${comment} Path: `) || line.trim() === comment) {
|
||||
if (line.startsWith(`${comment} Path: `)) {
|
||||
continue;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out empty comment lines from a LineStream.
|
||||
*
|
||||
* @param {LineStream} stream - The input stream of lines to filter.
|
||||
* @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments).
|
||||
* @yields {string} The filtered lines, excluding empty comments.
|
||||
*/
|
||||
export async function* avoidEmptyComments(
|
||||
stream: LineStream,
|
||||
comment?: string,
|
||||
): LineStream {
|
||||
// Filter lines that are empty comments
|
||||
for await (const line of stream) {
|
||||
if (!comment || line.trim() !== comment) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms a LineStream by adding newline characters between lines.
|
||||
*
|
||||
|
|
@ -168,9 +186,7 @@ export async function* streamWithNewLines(stream: LineStream): LineStream {
|
|||
* @returns {boolean} True if the lines are considered repeated, false otherwise.
|
||||
*
|
||||
* @description
|
||||
* This function checks if two lines are repeated or very similar based on two criteria:
|
||||
* 1. They have a common prefix longer than 12 characters.
|
||||
* 2. The Levenshtein distance between them is less than 10% of the length of the second line.
|
||||
* This function checks if the Levenshtein distance between them is less than 10% of the length of the second line.
|
||||
* Lines shorter than 5 characters are never considered repeated.
|
||||
*/
|
||||
export function lineIsRepeated(a: string, b: string): boolean {
|
||||
|
|
@ -180,10 +196,7 @@ export function lineIsRepeated(a: string, b: string): boolean {
|
|||
|
||||
const aTrim = a.trim();
|
||||
const bTrim = b.trim();
|
||||
return (
|
||||
commonPrefixLength(aTrim, bTrim) > 12 ||
|
||||
distance(aTrim, bTrim) / bTrim.length < 0.1
|
||||
);
|
||||
return distance(aTrim, bTrim) / bTrim.length < 0.05;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -210,9 +223,9 @@ export async function* stopAtSimilarLine(
|
|||
const lineIsBracketEnding = isBracketEnding(trimmedLine);
|
||||
|
||||
for await (const nextLine of stream) {
|
||||
if (nextLine === line) {
|
||||
fullStop();
|
||||
break;
|
||||
if (trimmedLine === "") {
|
||||
yield nextLine;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lineIsBracketEnding && trimmedLine.trim() === nextLine.trim()) {
|
||||
|
|
@ -220,6 +233,11 @@ export async function* stopAtSimilarLine(
|
|||
continue;
|
||||
}
|
||||
|
||||
if (nextLine === line) {
|
||||
fullStop();
|
||||
break;
|
||||
}
|
||||
|
||||
if (lineIsRepeated(nextLine, trimmedLine)) {
|
||||
fullStop();
|
||||
break;
|
||||
|
|
@ -510,3 +528,19 @@ export async function* logLines(
|
|||
}
|
||||
console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`);
|
||||
}
|
||||
|
||||
export async function* showWhateverWeHaveAtXMs(
|
||||
lines: LineStream,
|
||||
ms: number,
|
||||
): LineStream {
|
||||
const startTime = Date.now();
|
||||
for await (const line of lines) {
|
||||
// Always get at least one line
|
||||
yield line;
|
||||
|
||||
// But after that, soft break at X ms
|
||||
if (Date.now() - startTime > ms) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
##### Prompt #####
|
||||
{
|
||||
"active": true,
|
||||
"department": "Product Development",
|
||||
"location": {
|
||||
"country": "USA",
|
||||
"state": "California",
|
||||
"city": "San BERNARDINO",
|
||||
"coordinates": {
|
||||
<FIM>
|
||||
}
|
||||
},
|
||||
"employees": [
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"position": "Developer",
|
||||
"skills": ["JavaScript", "React", "Node.js"],
|
||||
"remote": false,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 95000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Jane Smith",
|
||||
"age": 25,
|
||||
"position": "Designer",
|
||||
"skills": ["Photoshop", "Illustrator"],
|
||||
"remote": true,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 70000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Emily Johnson",
|
||||
"age": 35,
|
||||
"position": "Manager",
|
||||
"teamSize": 8,
|
||||
"remote": true,
|
||||
"skills": ["Leadership", "Project Management"],==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
"latitude": 34.10834,
|
||||
"longitude": -117.28977
|
||||
}
|
||||
},
|
||||
"employeeCount": 2,
|
||||
"averageAge": 30,
|
||||
"remoteFriendly": true,
|
||||
"salaryRange": {
|
||||
"min": 70000,
|
||||
"max": 95000,
|
||||
"currency": "USD"
|
||||
},
|
||||
"skills": {
|
||||
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
|
||||
"optional": ["Photoshop", "Illustrator"]
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
##### Prompt #####
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Vue computed property",
|
||||
filename: "UserComponent.vue",
|
||||
input: `<template>
|
||||
<div>
|
||||
<p>User Full Name: {{ fullName }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
fullName<|fim|>
|
||||
},
|
||||
};
|
||||
</script>
|
||||
`,
|
||||
llmOutput: `() {
|
||||
return this.firstName + ' ' + this.lastName;
|
||||
}`,
|
||||
expectedCompletion: `() {
|
||||
return this.firstName + ' ' + this.lastName;
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Vue method using props",
|
||||
filename: "TodoItem.vue",
|
||||
input: `<template>
|
||||
<li>
|
||||
<p>{{ title }}</p>
|
||||
<button @click="completeTodo">Complete</button>
|
||||
</li>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
props: {
|
||||
title: String,
|
||||
completed: Boolean,
|
||||
},
|
||||
methods: {
|
||||
completeTodo() {
|
||||
<|fim|> = true;
|
||||
}
|
||||
},
|
||||
};
|
||||
</script>
|
||||
`,
|
||||
llmOutput: `this.completed`,
|
||||
expectedCompletion: `this.completed`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Svelte reactive statement",
|
||||
filename: "Counter.svelte",
|
||||
input: `
|
||||
<script>
|
||||
let count = 0;
|
||||
|
||||
$: <|fim|>
|
||||
|
||||
function handleClick() {
|
||||
count += 1;
|
||||
}
|
||||
</script>
|
||||
|
||||
<button on:click={handleClick}>
|
||||
Clicked {count} times
|
||||
</button>
|
||||
`,
|
||||
llmOutput: `doubledCount = count * 2`,
|
||||
expectedCompletion: `doubledCount = count * 2`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should autocomplete Svelte component inside HTML",
|
||||
filename: "NestedComponent.svelte",
|
||||
input: `
|
||||
<script>
|
||||
import ChildComponent from './ChildComponent.svelte';
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<h1>Hello Svelte</h1>
|
||||
<ChildComponent <|fim|> />
|
||||
</main>
|
||||
`,
|
||||
llmOutput: `name="World"`,
|
||||
expectedCompletion: `name="World"`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should handle autocomplete in Svelte each block",
|
||||
filename: "List.svelte",
|
||||
input: `
|
||||
<script>
|
||||
let items = ["Apple", "Banana", "Cherry"];
|
||||
</script>
|
||||
|
||||
<ul>
|
||||
{#each items as item}
|
||||
<li>{item}</li>
|
||||
{/each<|fim|>
|
||||
</ul>
|
||||
`,
|
||||
llmOutput: `}`,
|
||||
expectedCompletion: `}`,
|
||||
},
|
||||
<FIM>
|
||||
];
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
|
||||
|
||||
export default {
|
||||
components: {
|
||||
ChildComponent,
|
||||
},
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
##### Prompt #####
|
||||
{
|
||||
"employees": [
|
||||
{ "name": "John Doe", "age": 30, "position": "Developer" },
|
||||
{ "name": "Jane Smith", "age": 25, "position": "Designer" },
|
||||
{ "name": "Emily Johnson", "age": 35, "position": "Manager" }<FIM>
|
||||
],
|
||||
"active": true
|
||||
}
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
|
||||
}
|
||||
|
||||
{
|
||||
"employees": [
|
||||
{ "name": "John Doe", "age": 30 },
|
||||
{ "name": "Jane Smith", "age": 25 }
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
##### Prompt #####
|
||||
class Calculator:
|
||||
def __init__(self):
|
||||
self.result = 0
|
||||
|
||||
def add(self, number):
|
||||
self.result += number
|
||||
return self
|
||||
|
||||
def divid<FIM>
|
||||
|
||||
def subtract(self, number):
|
||||
self.result -= number
|
||||
return self
|
||||
|
||||
def reset(self):
|
||||
self.result = 0
|
||||
return self
|
||||
|
||||
def get_result(self):
|
||||
return self.result
|
||||
|
||||
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
self.result /= number
|
||||
return self
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
##### Prompt #####
|
||||
class Calculator
|
||||
attr_accessor :result
|
||||
|
||||
def initialize
|
||||
@result = 0
|
||||
end
|
||||
|
||||
def add(number)
|
||||
@result += number
|
||||
self
|
||||
end
|
||||
|
||||
def subtract(number)
|
||||
@result -= number
|
||||
self
|
||||
end
|
||||
|
||||
def power(ne<FIM>
|
||||
|
||||
def get_result
|
||||
@result
|
||||
end
|
||||
|
||||
def reset
|
||||
@result = 0
|
||||
self
|
||||
end
|
||||
end
|
||||
|
||||
calc = Calculator.new
|
||||
calc.add(5).subtract(3)
|
||||
puts "Result: #{calc.get_result}"
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
|
||||
@result ** number
|
||||
self
|
||||
end
|
||||
|
|
@ -0,0 +1,73 @@
|
|||
##### Prompt #####
|
||||
use std::io;
|
||||
|
||||
fn main() {
|
||||
println!("Welcome to the Calculator!");
|
||||
|
||||
loop {
|
||||
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
|
||||
let operator = read_input();
|
||||
|
||||
if operator == "q" {
|
||||
break;
|
||||
}
|
||||
|
||||
println!("Please enter the first number:");
|
||||
let num1 = read_input().parse::<f64>().unwrap();
|
||||
|
||||
println!("Please enter the second number:");
|
||||
let num2 = read_input().parse::<f64>().unwrap();
|
||||
|
||||
let result = match operator.as_str() {
|
||||
"+" => num1 + num2,
|
||||
"-" => num1 - num2,
|
||||
"*" => num1 * num2,
|
||||
"/" => num1 / num2,
|
||||
<FIM>
|
||||
_ => {
|
||||
println!("Invalid operator. Please try again.");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Result: {}", result);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_input() -> String {
|
||||
let mut input = String::new();
|
||||
io::stdin()
|
||||
.read_line(&mut input)
|
||||
.expect("Failed to read input");
|
||||
input.trim().to_string()
|
||||
}
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
=> {
|
||||
println!("Invalid operator. Please try again.");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Result: {}", result);
|
||||
}
|
||||
|
||||
println!("Goodbye!");
|
||||
}
|
||||
|
||||
|
||||
fn main2() {
|
||||
println!("Welcome to the Calculator!");
|
||||
|
||||
loop {
|
||||
println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
|
||||
let operator = read_input();
|
||||
|
||||
if operator == "q" {
|
||||
break;
|
||||
}
|
||||
|
||||
match operator.as_str() {
|
||||
"+" | "-" | "*" | "/" => (),
|
||||
49
core/autocomplete/filtering/test/filter.test.ts
Normal file
49
core/autocomplete/filtering/test/filter.test.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import {
|
||||
AutocompleteFileringTestInput,
|
||||
testAutocompleteFiltering,
|
||||
} from "./util";
|
||||
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
|
||||
import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir";
|
||||
|
||||
const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
|
||||
if (tests.some((test) => test.options?.only)) {
|
||||
return tests.filter((test) => test.options?.only);
|
||||
}
|
||||
|
||||
return tests;
|
||||
};
|
||||
|
||||
describe("llms/Mock", () => {
|
||||
beforeAll(async () => {
|
||||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
describe("Autocomplete Filtering Tests", () => {
|
||||
beforeEach(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
describe("Should return unmodified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Should return modified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,7 +1,243 @@
|
|||
import { dedent } from "../../util";
|
||||
import { dedent } from "../../../util";
|
||||
import { AutocompleteFileringTestInput } from "./util";
|
||||
|
||||
export const TEST_CASES: AutocompleteFileringTestInput[] = [
|
||||
export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [
|
||||
{
|
||||
description: "Should handle python multi-line string",
|
||||
filename: "test.py",
|
||||
input: `def create_greeting(name):
|
||||
greeting = """Hello, """ + name + """!
|
||||
Welcome to our community. We hope you have a great time here.
|
||||
If you have any questions, feel free to reach out."""
|
||||
return greeting
|
||||
|
||||
message = create_greeting("Alice")
|
||||
print(message)
|
||||
|
||||
multi_line_message = """<|fim|>
|
||||
print(multi_line_message)
|
||||
`,
|
||||
llmOutput: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""
|
||||
`,
|
||||
expectedCompletion: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust match arms",
|
||||
filename: "main.rs",
|
||||
input: `
|
||||
fn get_status_code_description(code: u16) -> &'static str {
|
||||
match code {
|
||||
200 => "OK",
|
||||
404 => "Not Found",
|
||||
500 => "Internal Server Error",
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
`,
|
||||
llmOutput: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",
|
||||
`,
|
||||
expectedCompletion: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",`,
|
||||
},
|
||||
{
|
||||
description: "Should complete a Markdown code block",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
Here is a sample JavaScript function:
|
||||
|
||||
\`\`\`javascript
|
||||
function sayHello() {
|
||||
console.log("Hello, <|fim|>
|
||||
}
|
||||
\`\`\`
|
||||
`,
|
||||
llmOutput: `world!");
|
||||
`,
|
||||
expectedCompletion: `world!");`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java when inside a block",
|
||||
filename: "Main.java",
|
||||
input: `
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (i % 2 == 0) {
|
||||
System.out.println("Even: " + i);
|
||||
} else {
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
llmOutput: `
|
||||
System.out.println("Odd: " + i);
|
||||
`,
|
||||
expectedCompletion: `
|
||||
System.out.println("Odd: " + i);`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete a Markdown heading and preserve formatting",
|
||||
filename: "test.md",
|
||||
input: `# My Document
|
||||
|
||||
## Introduction
|
||||
This is a sample document for testing.
|
||||
|
||||
## <|fim|>
|
||||
### Conclusion
|
||||
Thank you for reading.
|
||||
`,
|
||||
llmOutput: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
`,
|
||||
expectedCompletion: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Java method within a class",
|
||||
filename: "Calculator.java",
|
||||
input: `
|
||||
public class Calculator {
|
||||
private double result;
|
||||
|
||||
public Calculator() {
|
||||
this.result = 0.0;
|
||||
}
|
||||
|
||||
public void add(double number) {
|
||||
result += number;
|
||||
<|fim|>`,
|
||||
llmOutput: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}
|
||||
`,
|
||||
expectedCompletion: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should filter out consecutive, repeated YAML keys",
|
||||
filename: "test.yaml",
|
||||
input: `
|
||||
version: '3'
|
||||
services:
|
||||
db:
|
||||
image: postgres
|
||||
environment:
|
||||
POSTGRES_USER: user
|
||||
POSTGRES_PASSWORD: pass<|fim|>
|
||||
`,
|
||||
llmOutput: `
|
||||
POSTGRES_DB: mydb
|
||||
POSTGRES_DB: mydb
|
||||
`,
|
||||
expectedCompletion: `
|
||||
POSTGRES_DB: mydb
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Markdown list with nested items",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Subitem 1
|
||||
<|fim|>
|
||||
- Item 3
|
||||
`,
|
||||
llmOutput: ` - Subitem 2
|
||||
- Subitem 3
|
||||
`,
|
||||
expectedCompletion: ` - Subitem 2
|
||||
- Subitem 3`,
|
||||
},
|
||||
{
|
||||
description: "Should enforce bracket matching in JSON files",
|
||||
filename: "test.json",
|
||||
input: `{
|
||||
"active": true,
|
||||
"department": "Product Development",
|
||||
"location": {
|
||||
"country": "USA",
|
||||
"state": "California",
|
||||
"city": "San BERNARDINO",
|
||||
"coordinates": {
|
||||
<FIM>
|
||||
}
|
||||
},
|
||||
"employees": [
|
||||
{
|
||||
"name": "John Doe",
|
||||
"age": 30,
|
||||
"position": "Developer",
|
||||
"skills": ["JavaScript", "React", "Node.js"],
|
||||
"remote": false,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 95000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Jane Smith",
|
||||
"age": 25,
|
||||
"position": "Designer",
|
||||
"skills": ["Photoshop", "Illustrator"],
|
||||
"remote": true,
|
||||
"salary": {
|
||||
"currency": "USD",
|
||||
"amount": 70000
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Emily Johnson",
|
||||
"age": 35,
|
||||
"position": "Manager",
|
||||
"teamSize": 8,
|
||||
"remote": true,
|
||||
"skills": ["Leadership", "Project Management"],`,
|
||||
llmOutput: `"latitude": 34.10834,
|
||||
"longitude": -117.28977
|
||||
}
|
||||
},
|
||||
"employeeCount": 2,
|
||||
"averageAge": 30,
|
||||
"remoteFriendly": true,
|
||||
"salaryRange": {
|
||||
"min": 70000,
|
||||
"max": 95000,
|
||||
"currency": "USD"
|
||||
},
|
||||
"skills": {
|
||||
"required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"],
|
||||
"optional": ["Photoshop", "Illustrator"]`,
|
||||
expectedCompletion: `"latitude": 34.10834,
|
||||
"longitude": -117.28977
|
||||
`,
|
||||
},
|
||||
];
|
||||
|
||||
export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [
|
||||
{
|
||||
description: "should pass",
|
||||
filename: "test.js",
|
||||
|
|
@ -412,32 +648,6 @@ print(odd_squares)
|
|||
llmOutput: `x for x in squares if x % 2 != 0`,
|
||||
expectedCompletion: `x for x in squares if x % 2 != 0`,
|
||||
},
|
||||
{
|
||||
description: "Should handle python multi-line string",
|
||||
filename: "test.py",
|
||||
input: `def create_greeting(name):
|
||||
greeting = """Hello, """ + name + """!
|
||||
Welcome to our community. We hope you have a great time here.
|
||||
If you have any questions, feel free to reach out."""
|
||||
return greeting
|
||||
|
||||
message = create_greeting("Alice")
|
||||
print(message)
|
||||
|
||||
multi_line_message = """<|fim|>
|
||||
print(multi_line_message)
|
||||
`,
|
||||
llmOutput: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""
|
||||
`,
|
||||
expectedCompletion: `This is a multi-line message.
|
||||
It continues across multiple lines,
|
||||
which allows for easy reading and formatting.
|
||||
"""
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a simple Go function declaration",
|
||||
filename: "simpleFunction.go",
|
||||
|
|
@ -511,19 +721,6 @@ func main() {
|
|||
expectedCompletion: `
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with subquery and alias in SELECT clause",
|
||||
filename: "complex_query.sql",
|
||||
input: `SELECT u.id,
|
||||
u.name,
|
||||
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
|
||||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with nested functions and missing bracket",
|
||||
|
|
@ -536,6 +733,49 @@ func main() {
|
|||
llmOutput: `8.5)`,
|
||||
expectedCompletion: `8.5)`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL script with employee and product tables",
|
||||
filename: "database.sql",
|
||||
input: `
|
||||
CREATE TABLE employees (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
age INT NOT NULL,
|
||||
position VARCHAR(100)
|
||||
);
|
||||
|
||||
CREATE TABLE products (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(100),
|
||||
price DECIMAL(8,2) NOT NULL<FIM> '0.00',
|
||||
quantity INT NOT NULL DEFAULT '0'
|
||||
);
|
||||
|
||||
INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer');
|
||||
INSERT INTO products (name, price, quantity) VALUES ('Apple', '1.99', '47');
|
||||
|
||||
SELECT * FROM products ORDER BY name DESC LIMIT 3;
|
||||
SELECT * FROM products WHERE price > '0';
|
||||
SELECT * FROM products WHERE quantity > '100';
|
||||
SELECT * FROM employees WHERE age > 25;
|
||||
`,
|
||||
llmOutput: " DEFAULT",
|
||||
expectedCompletion: " DEFAULT",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete SQL query with subquery and alias in SELECT clause",
|
||||
filename: "complex_query.sql",
|
||||
input: `SELECT u.id,
|
||||
u.name,
|
||||
(SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count
|
||||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
expectedCompletion: ` AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete multi-line SQL query with CASE statements",
|
||||
|
|
@ -637,57 +877,6 @@ squared_numbers = numbers.<|fim|>
|
|||
expectedCompletion: `map { |n| n ** 2 }`,
|
||||
filename: "array_methods.rb",
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Java method within a class",
|
||||
filename: "Calculator.java",
|
||||
input: `
|
||||
public class Calculator {
|
||||
private double result;
|
||||
|
||||
public Calculator() {
|
||||
this.result = 0.0;
|
||||
}
|
||||
|
||||
public void add(double number) {
|
||||
result += number;
|
||||
<|fim|>`,
|
||||
llmOutput: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}
|
||||
`,
|
||||
expectedCompletion: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java when inside a block",
|
||||
filename: "Main.java",
|
||||
input: `
|
||||
public class Main {
|
||||
public static void main(String[] args) {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (i % 2 == 0) {
|
||||
System.out.println("Even: " + i);
|
||||
} else {
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
}
|
||||
}`,
|
||||
llmOutput: `
|
||||
System.out.println("Odd: " + i);
|
||||
`,
|
||||
expectedCompletion: `
|
||||
System.out.println("Odd: " + i);
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java within a string",
|
||||
filename: "App.java",
|
||||
|
|
@ -717,7 +906,6 @@ public class App {
|
|||
llmOutput: " int multiply(int a, int b);",
|
||||
expectedCompletion: " int multiply(int a, int b);",
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should autocomplete C++ for loop syntax",
|
||||
filename: "test.cpp",
|
||||
|
|
@ -730,64 +918,6 @@ public class App {
|
|||
llmOutput: "i++",
|
||||
expectedCompletion: "i++",
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete a Markdown list with nested items",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Subitem 1
|
||||
<|fim|>
|
||||
- Item 3
|
||||
`,
|
||||
llmOutput: ` - Subitem 2
|
||||
- Subitem 3
|
||||
`,
|
||||
expectedCompletion: ` - Subitem 2
|
||||
- Subitem 3
|
||||
`,
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Should autocomplete a Markdown heading and preserve formatting",
|
||||
filename: "test.md",
|
||||
input: `# My Document
|
||||
|
||||
## Introduction
|
||||
This is a sample document for testing.
|
||||
|
||||
## <|fim|>
|
||||
### Conclusion
|
||||
Thank you for reading.
|
||||
`,
|
||||
llmOutput: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
`,
|
||||
expectedCompletion: `Features
|
||||
Here is a list of features:
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should complete a Markdown code block",
|
||||
filename: "test.md",
|
||||
input: `
|
||||
Here is a sample JavaScript function:
|
||||
|
||||
\`\`\`javascript
|
||||
function sayHello() {
|
||||
console.log("Hello, <|fim|>
|
||||
}
|
||||
\`\`\`
|
||||
`,
|
||||
llmOutput: `world!");
|
||||
`,
|
||||
expectedCompletion: `world!");
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete JSON object inside an array",
|
||||
filename: "data.json",
|
||||
|
|
@ -801,40 +931,6 @@ function sayHello() {
|
|||
llmOutput: `, { "id": 3, "name": "Charlie" }`,
|
||||
expectedCompletion: `, { "id": 3, "name": "Charlie" }`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete nested JSON objects",
|
||||
filename: "config.json",
|
||||
input: `{
|
||||
"server": {
|
||||
"host": "localhost",
|
||||
"port": 8080,
|
||||
"features": {
|
||||
"enableLogging": true,
|
||||
"maxConnections": 100
|
||||
<|fim|>
|
||||
}
|
||||
}`,
|
||||
llmOutput: `,
|
||||
"timeout": 5000
|
||||
}`,
|
||||
expectedCompletion: `,
|
||||
"timeout": 5000
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete JSON object with missing bracket",
|
||||
filename: "settings.json",
|
||||
input: `{
|
||||
"theme": "dark",
|
||||
"language": "en"<|fim|>
|
||||
`,
|
||||
llmOutput: `,
|
||||
"notifications": true
|
||||
}`,
|
||||
expectedCompletion: `,
|
||||
"notifications": true
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete within a CSV record",
|
||||
filename: "test.csv",
|
||||
|
|
@ -986,28 +1082,6 @@ impl Calculator {
|
|||
println!("Cannot divide by zero.");
|
||||
}
|
||||
}`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust match arms",
|
||||
filename: "main.rs",
|
||||
input: `
|
||||
fn get_status_code_description(code: u16) -> &'static str {
|
||||
match code {
|
||||
200 => "OK",
|
||||
404 => "Not Found",
|
||||
500 => "Internal Server Error",
|
||||
<|fim|>
|
||||
}
|
||||
}
|
||||
`,
|
||||
llmOutput: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",
|
||||
`,
|
||||
expectedCompletion: `403 => "Forbidden",
|
||||
401 => "Unauthorized",
|
||||
_ => "Unknown Status",
|
||||
`,
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Rust struct definition",
|
||||
|
|
@ -1753,17 +1827,15 @@ let oddSquares = [<|fim|>]`,
|
|||
llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`,
|
||||
expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should complete an F# recursive function",
|
||||
filename: "recursiveFunctions.fs",
|
||||
input: `let rec factorial n =
|
||||
if n <= 1 then 1
|
||||
else n <|fim|> factorial (n - 1)`,
|
||||
llmOutput: ` * `,
|
||||
expectedCompletion: ` * `,
|
||||
llmOutput: `*`,
|
||||
expectedCompletion: `*`,
|
||||
},
|
||||
|
||||
{
|
||||
description: "Should complete F# member method inside a class type",
|
||||
filename: "bankAccount.fs",
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import Mock from "../../llm/llms/Mock";
|
||||
import { testConfigHandler, testIde } from "../../test/util/fixtures";
|
||||
import { AutocompleteInput, CompletionProvider } from "../completionProvider";
|
||||
import Mock from "../../../llm/llms/Mock";
|
||||
import { testConfigHandler, testIde } from "../../../test/util/fixtures";
|
||||
import { CompletionProvider } from "../../CompletionProvider";
|
||||
import { AutocompleteInput } from "../../util/types";
|
||||
|
||||
const FIM_DELIMITER = "<|fim|>";
|
||||
|
||||
68
core/autocomplete/generation/CompletionStreamer.ts
Normal file
68
core/autocomplete/generation/CompletionStreamer.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
import { CompletionOptions, ILLM } from "../..";
|
||||
import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { GeneratorReuseManager } from "./GeneratorReuseManager";
|
||||
|
||||
export class CompletionStreamer {
|
||||
private streamTransformPipeline = new StreamTransformPipeline();
|
||||
private generatorReuseManager: GeneratorReuseManager;
|
||||
|
||||
constructor(onError: (err: any) => void) {
|
||||
this.generatorReuseManager = new GeneratorReuseManager(onError);
|
||||
}
|
||||
|
||||
async *streamCompletionWithFilters(
|
||||
token: AbortSignal,
|
||||
llm: ILLM,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
prompt: string,
|
||||
multiline: boolean,
|
||||
completionOptions: Partial<CompletionOptions> | undefined,
|
||||
helper: HelperVars,
|
||||
) {
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
const generator = this.generatorReuseManager.getGenerator(
|
||||
prefix,
|
||||
() =>
|
||||
llm.supportsFim()
|
||||
? llm.streamFim(prefix, suffix, completionOptions)
|
||||
: llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
raw: true,
|
||||
}),
|
||||
multiline,
|
||||
);
|
||||
|
||||
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
|
||||
const fullStop = () =>
|
||||
this.generatorReuseManager.currentGenerator?.cancel();
|
||||
|
||||
// LLM
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.aborted) {
|
||||
return;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
|
||||
const initialGenerator = generatorWithCancellation();
|
||||
const transformedGenerator = helper.options.transform
|
||||
? this.streamTransformPipeline.transform(
|
||||
initialGenerator,
|
||||
prefix,
|
||||
suffix,
|
||||
multiline,
|
||||
completionOptions?.stop || [],
|
||||
fullStop,
|
||||
helper,
|
||||
)
|
||||
: initialGenerator;
|
||||
|
||||
for await (const update of transformedGenerator) {
|
||||
yield update;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,78 +1,4 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded = false;
|
||||
|
||||
constructor(
|
||||
source: AsyncGenerator<T>,
|
||||
private readonly onError: (e: any) => void,
|
||||
) {
|
||||
this._source = source;
|
||||
this._start();
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._isEnded = true;
|
||||
}
|
||||
|
||||
private async _start() {
|
||||
try {
|
||||
for await (const value of this._source) {
|
||||
if (this._isEnded) {
|
||||
break;
|
||||
}
|
||||
this._buffer.push(value);
|
||||
for (const listener of this._listeners) {
|
||||
listener(value);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
this._isEnded = true;
|
||||
for (const listener of this._listeners) {
|
||||
listener(null as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
listen(listener: (value: T) => void) {
|
||||
this._listeners.add(listener);
|
||||
for (const value of this._buffer) {
|
||||
listener(value);
|
||||
}
|
||||
if (this._isEnded) {
|
||||
listener(null as any);
|
||||
}
|
||||
}
|
||||
|
||||
async *tee(): AsyncGenerator<T> {
|
||||
try {
|
||||
let i = 0;
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
this._listeners.add(resolve!);
|
||||
});
|
||||
await promise;
|
||||
this._listeners.delete(resolve!);
|
||||
|
||||
// Possible timing caused something to slip in between
|
||||
// timers so we iterate over the buffer
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// this._listeners.delete(resolve!);
|
||||
}
|
||||
}
|
||||
}
|
||||
import { ListenableGenerator } from "./ListenableGenerator";
|
||||
|
||||
export class GeneratorReuseManager {
|
||||
currentGenerator: ListenableGenerator<string> | undefined;
|
||||
75
core/autocomplete/generation/ListenableGenerator.ts
Normal file
75
core/autocomplete/generation/ListenableGenerator.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded = false;
|
||||
|
||||
constructor(
|
||||
source: AsyncGenerator<T>,
|
||||
private readonly onError: (e: any) => void,
|
||||
) {
|
||||
this._source = source;
|
||||
this._start();
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._isEnded = true;
|
||||
}
|
||||
|
||||
private async _start() {
|
||||
try {
|
||||
for await (const value of this._source) {
|
||||
if (this._isEnded) {
|
||||
break;
|
||||
}
|
||||
this._buffer.push(value);
|
||||
for (const listener of this._listeners) {
|
||||
listener(value);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
this._isEnded = true;
|
||||
for (const listener of this._listeners) {
|
||||
listener(null as any);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
listen(listener: (value: T) => void) {
|
||||
this._listeners.add(listener);
|
||||
for (const value of this._buffer) {
|
||||
listener(value);
|
||||
}
|
||||
if (this._isEnded) {
|
||||
listener(null as any);
|
||||
}
|
||||
}
|
||||
|
||||
async *tee(): AsyncGenerator<T> {
|
||||
try {
|
||||
let i = 0;
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
this._listeners.add(resolve!);
|
||||
});
|
||||
await promise;
|
||||
this._listeners.delete(resolve!);
|
||||
|
||||
// Possible timing caused something to slip in between
|
||||
// timers so we iterate over the buffer
|
||||
while (i < this._buffer.length) {
|
||||
yield this._buffer[i++];
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// this._listeners.delete(resolve!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import type { ILLM } from "../index.js";
|
||||
import { longestCommonSubsequence } from "../util/lcs.js";
|
||||
import { lineIsRepeated } from "./streamTransforms/lineStream.js";
|
||||
import type { ILLM } from "../../index.js";
|
||||
import { longestCommonSubsequence } from "../../util/lcs.js";
|
||||
import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js";
|
||||
|
||||
function rewritesLineAbove(completion: string, prefix: string): boolean {
|
||||
const lineAbove = prefix
|
||||
|
|
@ -42,6 +42,10 @@ function isExtremeRepetition(completion: string): boolean {
|
|||
}
|
||||
return false;
|
||||
}
|
||||
export function isOnlyWhitespace(completion: string): boolean {
|
||||
const whitespaceRegex = /^[\s]+$/;
|
||||
return whitespaceRegex.test(completion);
|
||||
}
|
||||
|
||||
export function postprocessCompletion({
|
||||
completion,
|
||||
|
|
@ -55,7 +59,7 @@ export function postprocessCompletion({
|
|||
suffix: string;
|
||||
}): string | undefined {
|
||||
// Don't return empty
|
||||
if (completion.trim().length <= 0) {
|
||||
if (isOnlyWhitespace(completion)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
@ -69,9 +73,6 @@ export function postprocessCompletion({
|
|||
return undefined;
|
||||
}
|
||||
|
||||
// Remove trailing whitespace
|
||||
completion = completion.trimEnd();
|
||||
|
||||
if (llm.model.includes("codestral")) {
|
||||
// Codestral sometimes starts with an extra space
|
||||
if (completion[0] === " " && completion[1] !== " ") {
|
||||
|
|
@ -81,19 +82,23 @@ export function postprocessCompletion({
|
|||
}
|
||||
}
|
||||
|
||||
// If completion starts with multiple whitespaces, but the cursor is at the end of the line
|
||||
// then it should probably be on a new line
|
||||
if (
|
||||
(completion.startsWith(" ") || completion.startsWith("\t")) &&
|
||||
!prefix.endsWith("\n") &&
|
||||
(suffix.startsWith("\n") || suffix.trim().length === 0)
|
||||
) {
|
||||
// completion = "\n" + completion;
|
||||
return undefined;
|
||||
}
|
||||
// // If completion starts with multiple whitespaces, but the cursor is at the end of the line
|
||||
// // then it should probably be on a new line
|
||||
// if (
|
||||
// (completion.startsWith(" ") || completion.startsWith("\t")) &&
|
||||
// !prefix.endsWith("\n") &&
|
||||
// (suffix.startsWith("\n") || suffix.trim().length === 0)
|
||||
// ) {
|
||||
// completion = "\n" + completion;
|
||||
// }
|
||||
|
||||
// If prefix ends with space and so does completion, then remove the space from completion
|
||||
if (prefix.endsWith(" ") && completion.startsWith(" ")) {
|
||||
if (
|
||||
prefix.split("\n").pop()?.trim() !== "" &&
|
||||
prefix.endsWith(" ") &&
|
||||
completion.startsWith(" ")
|
||||
) {
|
||||
const test = prefix.split("\n").pop()?.trim() !== "";
|
||||
completion = completion.slice(1);
|
||||
}
|
||||
|
||||
78
core/autocomplete/prefiltering/index.ts
Normal file
78
core/autocomplete/prefiltering/index.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import path from "node:path";
|
||||
import { IDE } from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
import { getConfigJsonPath } from "../../util/paths";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
async function isDisabledForFile(
|
||||
currentFilepath: string,
|
||||
disableInFiles: string[] | undefined,
|
||||
ide: IDE,
|
||||
) {
|
||||
if (disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let filepath = currentFilepath;
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const relativePath = path.relative(workspaceDir, filepath);
|
||||
const relativePathBase = relativePath.split(path.sep).at(0);
|
||||
const isInWorkspace =
|
||||
!path.isAbsolute(relativePath) && relativePathBase !== "..";
|
||||
if (isInWorkspace) {
|
||||
filepath = path.relative(workspaceDir, filepath);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Worst case we can check filetype glob patterns
|
||||
if (filepath === currentFilepath) {
|
||||
filepath = getBasename(filepath);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(options.disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function shouldLanguageSpecificPrefilter(helper: HelperVars) {
|
||||
const line = helper.fileLines[helper.pos.line] ?? "";
|
||||
for (const endOfLine of helper.lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && helper.pos.character >= line.length) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function shouldPrefilter(
|
||||
helper: HelperVars,
|
||||
ide: IDE,
|
||||
): Promise<boolean> {
|
||||
// Allow disabling autocomplete from config.json
|
||||
if (helper.options.disable) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check whether we're in the continue config.json file
|
||||
if (helper.filepath === getConfigJsonPath()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
if (
|
||||
await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// if (
|
||||
// helper.options.transform &&
|
||||
// (await shouldLanguageSpecificPrefilter(helper))
|
||||
// ) {
|
||||
// return true;
|
||||
// }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
|
@ -1,18 +0,0 @@
|
|||
import { RangeInFile } from "../index.js";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
lines: string[];
|
||||
symbols: Set<string>;
|
||||
};
|
||||
|
||||
export function findMatchingRange(
|
||||
recentlyEditedRanges: RecentlyEditedRange[],
|
||||
linePrefix: string,
|
||||
): RecentlyEditedRange | undefined {
|
||||
return recentlyEditedRanges.find((recentlyEditedRange) => {
|
||||
return recentlyEditedRange.lines.some((line) =>
|
||||
line.startsWith(linePrefix),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
import { BranchAndDir, Chunk } from "../index.js";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js";
|
||||
|
||||
export async function fullTextRetrieve(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
indexTag: BranchAndDir,
|
||||
): Promise<Chunk[]> {
|
||||
const index = new FullTextSearchCodebaseIndex();
|
||||
const searchStrings = prefix.split("\n").slice(-3);
|
||||
const results: Chunk[] = [];
|
||||
searchStrings.forEach(async (searchString) => {
|
||||
const chunks = await index.retrieve(
|
||||
[indexTag],
|
||||
searchString,
|
||||
3,
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
results.push(...chunks);
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
import { AstPath } from "./ast";
|
||||
import { AutocompleteLanguageInfo } from "./languages";
|
||||
|
||||
const BLOCK_TYPES = ["body", "statement_block"];
|
||||
|
||||
function isMidlineCompletion(prefix: string, suffix: string): boolean {
|
||||
return !suffix.startsWith("\n");
|
||||
}
|
||||
|
||||
export async function shouldCompleteMultiline(
|
||||
treePath: AstPath | undefined,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
): Promise<boolean> {
|
||||
// Don't complete multi-line if you are mid-line
|
||||
if (isMidlineCompletion(fullPrefix, fullSuffix)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't complete multi-line for single-line comments
|
||||
if (
|
||||
fullPrefix
|
||||
.split("\n")
|
||||
.slice(-1)[0]
|
||||
?.trimStart()
|
||||
.startsWith(language.singleLineComment)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
|
@ -1,10 +1,10 @@
|
|||
// Fill in the middle prompts
|
||||
|
||||
import { CompletionOptions } from "../index.js";
|
||||
import { getLastNPathParts, shortestRelativePaths } from "../util/index.js";
|
||||
import { AutocompleteSnippet } from "./ranking.js";
|
||||
import { CompletionOptions } from "../../index.js";
|
||||
import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js";
|
||||
import { AutocompleteSnippet } from "../context/ranking/index.js";
|
||||
|
||||
interface AutocompleteTemplate {
|
||||
export interface AutocompleteTemplate {
|
||||
compilePrefixSuffix?: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
44
core/autocomplete/templating/constructPrefixSuffix.ts
Normal file
44
core/autocomplete/templating/constructPrefixSuffix.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { IDE } from "../..";
|
||||
import { getRangeInString } from "../../util/ranges";
|
||||
import { languageForFilepath } from "../constants/AutocompleteLanguageInfo";
|
||||
|
||||
import { AutocompleteInput } from "../util/types";
|
||||
|
||||
/**
|
||||
* We have to handle a few edge cases in getting the entire prefix/suffix for the current file.
|
||||
* This is entirely prior to finding snippets from other files
|
||||
*/
|
||||
export async function constructInitialPrefixSuffix(
|
||||
input: AutocompleteInput,
|
||||
ide: IDE,
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
}> {
|
||||
const lang = languageForFilepath(input.filepath);
|
||||
|
||||
const fileContents =
|
||||
input.manuallyPassFileContents ?? (await ide.readFile(input.filepath));
|
||||
const fileLines = fileContents.split("\n");
|
||||
let prefix =
|
||||
getRangeInString(fileContents, {
|
||||
start: { line: 0, character: 0 },
|
||||
end: input.selectedCompletionInfo?.range.start ?? input.pos,
|
||||
}) + (input.selectedCompletionInfo?.text ?? "");
|
||||
|
||||
if (input.injectDetails) {
|
||||
const lines = prefix.split("\n");
|
||||
prefix = `${lines.slice(0, -1).join("\n")}\n${
|
||||
lang.singleLineComment
|
||||
} ${input.injectDetails
|
||||
.split("\n")
|
||||
.join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`;
|
||||
}
|
||||
|
||||
const suffix = getRangeInString(fileContents, {
|
||||
start: input.pos,
|
||||
end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER },
|
||||
});
|
||||
|
||||
return { prefix, suffix };
|
||||
}
|
||||
33
core/autocomplete/templating/getStopTokens.ts
Normal file
33
core/autocomplete/templating/getStopTokens.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { CompletionOptions } from "../..";
|
||||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
|
||||
const DOUBLE_NEWLINE = "\n\n";
|
||||
const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n";
|
||||
// TODO: Do we want to stop completions when reaching a `/src/` string?
|
||||
const SRC_DIRECTORY = "/src/";
|
||||
// Starcoder2 tends to output artifacts starting with the letter "t"
|
||||
const STARCODER2_T_ARTIFACTS = ["t.", "\nt", "<file_sep>"];
|
||||
const PYTHON_ENCODING = "#- coding: utf-8";
|
||||
const CODE_BLOCK_END = "```";
|
||||
|
||||
const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE];
|
||||
const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END];
|
||||
|
||||
export function getStopTokens(
|
||||
completionOptions: Partial<CompletionOptions> | undefined,
|
||||
lang: AutocompleteLanguageInfo,
|
||||
model: string,
|
||||
): string[] {
|
||||
const stopTokens = [
|
||||
...(completionOptions?.stop || []),
|
||||
// ...multilineStops,
|
||||
...commonStops,
|
||||
...(model.toLowerCase().includes("starcoder2")
|
||||
? STARCODER2_T_ARTIFACTS
|
||||
: []),
|
||||
...(lang.stopWords ?? []),
|
||||
// ...lang.topLevelKeywords.map((word) => `\n${word}`),
|
||||
];
|
||||
|
||||
return stopTokens;
|
||||
}
|
||||
149
core/autocomplete/templating/index.ts
Normal file
149
core/autocomplete/templating/index.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { CompletionOptions } from "../..";
|
||||
import { getBasename, getLastNPathParts } from "../../util";
|
||||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
import { AutocompleteSnippet } from "../context/ranking";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import {
|
||||
AutocompleteTemplate,
|
||||
getTemplateForModel,
|
||||
} from "./AutocompleteTemplate";
|
||||
import { getStopTokens } from "./getStopTokens";
|
||||
|
||||
export function formatExternalSnippet(
|
||||
filepath: string,
|
||||
snippet: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
) {
|
||||
const comment = language.singleLineComment;
|
||||
const lines = [
|
||||
`${comment} Path: ${getBasename(filepath)}`,
|
||||
...snippet
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => `${comment} ${line}`),
|
||||
comment,
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
function renderStringTemplate(
|
||||
template: string,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
lang: AutocompleteLanguageInfo,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
) {
|
||||
const filename = getBasename(filepath);
|
||||
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}`;
|
||||
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
|
||||
// If it's an empty file, include the file name as a comment
|
||||
prefix = `${lang.singleLineComment} ${getLastNPathParts(
|
||||
filepath,
|
||||
2,
|
||||
)}\n${prefix}`;
|
||||
}
|
||||
|
||||
const prompt = compiledTemplate({
|
||||
prefix,
|
||||
suffix,
|
||||
filename,
|
||||
reponame,
|
||||
language: lang.name,
|
||||
});
|
||||
return prompt;
|
||||
}
|
||||
|
||||
function getTemplate(helper: HelperVars): AutocompleteTemplate {
|
||||
if (helper.options.template) {
|
||||
return {
|
||||
template: helper.options.template,
|
||||
completionOptions: {},
|
||||
compilePrefixSuffix: undefined,
|
||||
};
|
||||
}
|
||||
return getTemplateForModel(helper.modelName);
|
||||
}
|
||||
|
||||
export function renderPrompt(
|
||||
snippets: AutocompleteSnippet[],
|
||||
workspaceDirs: string[],
|
||||
helper: HelperVars,
|
||||
): {
|
||||
prompt: string;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
completionOptions: Partial<CompletionOptions> | undefined;
|
||||
} {
|
||||
// If prefix is manually passed
|
||||
let prefix = helper.prunedPrefix;
|
||||
let suffix = helper.prunedSuffix;
|
||||
|
||||
if (helper.input.manuallyPassPrefix) {
|
||||
prefix = helper.input.manuallyPassPrefix;
|
||||
suffix = "";
|
||||
}
|
||||
|
||||
let prompt: string;
|
||||
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
|
||||
|
||||
let { template, compilePrefixSuffix, completionOptions } =
|
||||
getTemplate(helper);
|
||||
|
||||
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
|
||||
// into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint
|
||||
if (compilePrefixSuffix) {
|
||||
[prefix, suffix] = compilePrefixSuffix(
|
||||
prefix,
|
||||
suffix,
|
||||
helper.filepath,
|
||||
reponame,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
// Templates can be passed as a Handlebars template string or a function
|
||||
if (typeof template === "string") {
|
||||
prompt = renderStringTemplate(
|
||||
template,
|
||||
prefix,
|
||||
suffix,
|
||||
snippets,
|
||||
helper.lang,
|
||||
helper.filepath,
|
||||
reponame,
|
||||
);
|
||||
} else {
|
||||
prompt = template(
|
||||
prefix,
|
||||
suffix,
|
||||
helper.filepath,
|
||||
reponame,
|
||||
helper.lang.name,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
const stopTokens = getStopTokens(
|
||||
completionOptions,
|
||||
helper.lang,
|
||||
helper.modelName,
|
||||
);
|
||||
|
||||
completionOptions = {
|
||||
...completionOptions,
|
||||
stop: stopTokens,
|
||||
};
|
||||
|
||||
return { prompt, prefix, suffix, completionOptions };
|
||||
}
|
||||
|
|
@ -1,51 +0,0 @@
|
|||
##### Prompt #####
|
||||
class Calculator {
|
||||
constructor() {
|
||||
this.result = 0;
|
||||
}
|
||||
|
||||
add(number) {
|
||||
this.result += number;
|
||||
return this;
|
||||
}
|
||||
|
||||
subtract(number) {
|
||||
this.result -= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
multiply(number) {
|
||||
this.result *= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
divide(number) {
|
||||
if (number === 0) {
|
||||
throw new Error("Cannot divide by zero");
|
||||
}
|
||||
|
||||
<FIM>
|
||||
|
||||
this.result /= number;
|
||||
return this;
|
||||
}
|
||||
|
||||
getResult() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.result = 0;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
==========================================================================
|
||||
==========================================================================
|
||||
Completion:
|
||||
|
||||
this.result /= number;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Calculator;
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
import {
|
||||
AutocompleteFileringTestInput,
|
||||
testAutocompleteFiltering,
|
||||
} from "./util";
|
||||
import { TEST_CASES } from "./testCases";
|
||||
|
||||
const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
|
||||
if (tests.some((test) => test.options?.only)) {
|
||||
return tests.filter((test) => test.options?.only);
|
||||
}
|
||||
|
||||
return tests;
|
||||
};
|
||||
|
||||
describe("llms/Mock", () => {
|
||||
describe("Autocomplete Filtering Tests", () => {
|
||||
beforeEach(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
describe("Should return unmodified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
});
|
||||
});
|
||||
|
||||
// TODO: Add test cases where modifying LLM output is desirable
|
||||
describe.skip("Should return modified LLM output", () => {});
|
||||
});
|
||||
});
|
||||
32
core/autocomplete/util/AutocompleteDebouncer.ts
Normal file
32
core/autocomplete/util/AutocompleteDebouncer.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
export class AutocompleteDebouncer {
|
||||
private debounceTimeout: NodeJS.Timeout | undefined = undefined;
|
||||
private debouncing = false;
|
||||
private lastUUID: string | undefined = undefined;
|
||||
|
||||
async delayAndShouldDebounce(debounceDelay: number): Promise<boolean> {
|
||||
// Debounce
|
||||
const uuid = uuidv4();
|
||||
this.lastUUID = uuid;
|
||||
|
||||
// Debounce
|
||||
if (this.debouncing) {
|
||||
this.debounceTimeout?.refresh();
|
||||
const lastUUID = await new Promise((resolve) =>
|
||||
setTimeout(() => {
|
||||
resolve(this.lastUUID);
|
||||
}, debounceDelay),
|
||||
);
|
||||
if (uuid !== lastUUID) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
this.debouncing = true;
|
||||
this.debounceTimeout = setTimeout(async () => {
|
||||
this.debouncing = false;
|
||||
}, debounceDelay);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
119
core/autocomplete/util/AutocompleteLoggingService.ts
Normal file
119
core/autocomplete/util/AutocompleteLoggingService.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { logDevData } from "../../util/devdata";
|
||||
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { AutocompleteOutcome } from "./types";
|
||||
|
||||
export class AutocompleteLoggingService {
|
||||
// Key is completionId
|
||||
private _abortControllers = new Map<string, AbortController>();
|
||||
private _logRejectionTimeouts = new Map<string, NodeJS.Timeout>();
|
||||
private _outcomes = new Map<string, AutocompleteOutcome>();
|
||||
_lastDisplayedCompletion: { id: string; displayedAt: number } | undefined =
|
||||
undefined;
|
||||
|
||||
public createAbortController(completionId: string): AbortController {
|
||||
const abortController = new AbortController();
|
||||
this._abortControllers.set(completionId, abortController);
|
||||
return abortController;
|
||||
}
|
||||
|
||||
public deleteAbortController(completionId: string) {
|
||||
this._abortControllers.delete(completionId);
|
||||
}
|
||||
|
||||
public cancel() {
|
||||
this._abortControllers.forEach((abortController, id) => {
|
||||
abortController.abort();
|
||||
});
|
||||
this._abortControllers.clear();
|
||||
}
|
||||
|
||||
public accept(completionId: string): AutocompleteOutcome | undefined {
|
||||
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)!;
|
||||
this.logAutocompleteOutcome(outcome);
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
|
||||
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 markDisplayed(completionId: string, outcome: AutocompleteOutcome) {
|
||||
const logRejectionTimeout = setTimeout(() => {
|
||||
// Wait 10 seconds, then assume it wasn't accepted
|
||||
outcome.accepted = false;
|
||||
this.logAutocompleteOutcome(outcome);
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
private logAutocompleteOutcome(outcome: AutocompleteOutcome) {
|
||||
outcome.accepted = true;
|
||||
logDevData("autocomplete", outcome);
|
||||
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0],
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
useRootPathContext: restOfOutcome.useRootPathContext,
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,17 @@
|
|||
import { Mutex } from "async-mutex";
|
||||
import { open } from "sqlite";
|
||||
import sqlite3 from "sqlite3";
|
||||
import { DatabaseConnection, truncateSqliteLikePattern } from "../indexing/refreshIndex.js";
|
||||
import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js";
|
||||
import {
|
||||
DatabaseConnection,
|
||||
truncateSqliteLikePattern,
|
||||
} from "../../indexing/refreshIndex.js";
|
||||
import { getTabAutocompleteCacheSqlitePath } from "../../util/paths.js";
|
||||
|
||||
export class AutocompleteLruCache {
|
||||
private static capacity = 1000;
|
||||
private mutex = new Mutex();
|
||||
|
||||
constructor(private db: DatabaseConnection) { }
|
||||
constructor(private db: DatabaseConnection) {}
|
||||
|
||||
static async get(): Promise<AutocompleteLruCache> {
|
||||
const db = await open({
|
||||
175
core/autocomplete/util/HelperVars.ts
Normal file
175
core/autocomplete/util/HelperVars.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { IDE, TabAutocompleteOptions } from "../..";
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
} from "../../llm/countTokens";
|
||||
import {
|
||||
AutocompleteLanguageInfo,
|
||||
languageForFilepath,
|
||||
} from "../constants/AutocompleteLanguageInfo";
|
||||
import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix";
|
||||
import { AstPath, getAst, getTreePathAtCursor } from "./ast";
|
||||
import { AutocompleteInput } from "./types";
|
||||
|
||||
/**
|
||||
* A collection of variables that are often accessed throughout the autocomplete pipeline
|
||||
* It's noisy to re-calculate all the time or inject them into each function
|
||||
*/
|
||||
export class HelperVars {
|
||||
lang: AutocompleteLanguageInfo;
|
||||
treePath: AstPath | undefined;
|
||||
|
||||
private _fileContents: string | undefined;
|
||||
private _fileLines: string[] | undefined;
|
||||
private _fullPrefix: string | undefined;
|
||||
private _fullSuffix: string | undefined;
|
||||
private _prunedPrefix: string | undefined;
|
||||
private _prunedSuffix: string | undefined;
|
||||
|
||||
private constructor(
|
||||
public readonly input: AutocompleteInput,
|
||||
public readonly options: TabAutocompleteOptions,
|
||||
public readonly modelName: string,
|
||||
private readonly ide: IDE,
|
||||
) {
|
||||
this.lang = languageForFilepath(input.filepath);
|
||||
}
|
||||
|
||||
private async init() {
|
||||
// Don't do anything if already initialized
|
||||
if (this._fileContents !== undefined) return;
|
||||
|
||||
this._fileContents =
|
||||
this.input.manuallyPassFileContents ??
|
||||
(await this.ide.readFile(this.filepath));
|
||||
|
||||
this._fileLines = this._fileContents.split("\n");
|
||||
|
||||
// Construct full prefix/suffix (a few edge cases handled in here)
|
||||
const { prefix: fullPrefix, suffix: fullSuffix } =
|
||||
await constructInitialPrefixSuffix(this.input, this.ide);
|
||||
this._fullPrefix = fullPrefix;
|
||||
this._fullSuffix = fullSuffix;
|
||||
|
||||
const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix();
|
||||
this._prunedPrefix = prunedPrefix;
|
||||
this._prunedSuffix = prunedSuffix;
|
||||
|
||||
try {
|
||||
const ast = await getAst(this.filepath, fullPrefix + fullSuffix);
|
||||
if (ast) {
|
||||
this.treePath = await getTreePathAtCursor(ast, fullPrefix.length);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to parse AST", e);
|
||||
}
|
||||
}
|
||||
|
||||
static async create(
|
||||
input: AutocompleteInput,
|
||||
options: TabAutocompleteOptions,
|
||||
modelName: string,
|
||||
ide: IDE,
|
||||
): Promise<HelperVars> {
|
||||
const instance = new HelperVars(input, options, modelName, ide);
|
||||
await instance.init();
|
||||
return instance;
|
||||
}
|
||||
|
||||
prunePrefixSuffix() {
|
||||
// Construct basic prefix
|
||||
const maxPrefixTokens =
|
||||
this.options.maxPromptTokens * this.options.prefixPercentage;
|
||||
const prunedPrefix = pruneLinesFromTop(
|
||||
this.fullPrefix,
|
||||
maxPrefixTokens,
|
||||
this.modelName,
|
||||
);
|
||||
|
||||
// Construct suffix
|
||||
const maxSuffixTokens = Math.min(
|
||||
this.options.maxPromptTokens - countTokens(prunedPrefix, this.modelName),
|
||||
this.options.maxSuffixPercentage * this.options.maxPromptTokens,
|
||||
);
|
||||
const prunedSuffix = pruneLinesFromBottom(
|
||||
this.fullSuffix,
|
||||
maxSuffixTokens,
|
||||
this.modelName,
|
||||
);
|
||||
|
||||
return {
|
||||
prunedPrefix,
|
||||
prunedSuffix,
|
||||
};
|
||||
}
|
||||
|
||||
// Fast access
|
||||
get filepath() {
|
||||
return this.input.filepath;
|
||||
}
|
||||
get pos() {
|
||||
return this.input.pos;
|
||||
}
|
||||
get maxSnippetTokens() {
|
||||
return this.options.maxPromptTokens * this.options.maxSnippetPercentage;
|
||||
}
|
||||
get prunedCaretWindow() {
|
||||
return this.prunedPrefix + this.prunedSuffix;
|
||||
}
|
||||
|
||||
// Getters for lazy access
|
||||
get fileContents(): string {
|
||||
if (this._fileContents === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fileContents",
|
||||
);
|
||||
}
|
||||
return this._fileContents;
|
||||
}
|
||||
|
||||
get fileLines(): string[] {
|
||||
if (this._fileLines === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fileLines",
|
||||
);
|
||||
}
|
||||
return this._fileLines;
|
||||
}
|
||||
|
||||
get fullPrefix(): string {
|
||||
if (this._fullPrefix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fullPrefix",
|
||||
);
|
||||
}
|
||||
return this._fullPrefix;
|
||||
}
|
||||
|
||||
get fullSuffix(): string {
|
||||
if (this._fullSuffix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing fullSuffix",
|
||||
);
|
||||
}
|
||||
return this._fullSuffix;
|
||||
}
|
||||
|
||||
get prunedPrefix(): string {
|
||||
if (this._prunedPrefix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing prunedPrefix",
|
||||
);
|
||||
}
|
||||
return this._prunedPrefix;
|
||||
}
|
||||
|
||||
get prunedSuffix(): string {
|
||||
if (this._prunedSuffix === undefined) {
|
||||
throw new Error(
|
||||
"HelperVars must be initialized before accessing prunedSuffix",
|
||||
);
|
||||
}
|
||||
return this._prunedSuffix;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { getParserForFile } from "../util/treeSitter.js";
|
||||
import { RangeInFileWithContents } from "../../commands/util.js";
|
||||
import { getParserForFile } from "../../util/treeSitter.js";
|
||||
|
||||
export type AstPath = Parser.SyntaxNode[];
|
||||
|
||||
43
core/autocomplete/util/types.ts
Normal file
43
core/autocomplete/util/types.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../..";
|
||||
import { RangeInFileWithContents } from "../../commands/util";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFile & {
|
||||
timestamp: number;
|
||||
lines: string[];
|
||||
symbols: Set<string>;
|
||||
};
|
||||
|
||||
export interface AutocompleteInput {
|
||||
completionId: string;
|
||||
filepath: string;
|
||||
pos: Position;
|
||||
recentlyEditedFiles: RangeInFileWithContents[];
|
||||
recentlyEditedRanges: RecentlyEditedRange[];
|
||||
clipboardText: string;
|
||||
// Used for notebook files
|
||||
manuallyPassFileContents?: string;
|
||||
// Used for VS Code git commit input box
|
||||
manuallyPassPrefix?: string;
|
||||
selectedCompletionInfo?: {
|
||||
text: string;
|
||||
range: Range;
|
||||
};
|
||||
injectDetails?: string;
|
||||
}
|
||||
|
||||
export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
prompt: string;
|
||||
completion: string;
|
||||
modelProvider: string;
|
||||
modelName: string;
|
||||
completionOptions: any;
|
||||
cacheHit: boolean;
|
||||
filepath: string;
|
||||
gitRepo?: string;
|
||||
completionId: string;
|
||||
uniqueId: string;
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
fixCodeLlamaFirstLineIndentation,
|
||||
stopAtLines,
|
||||
streamWithNewLines,
|
||||
} from "../../autocomplete/streamTransforms/lineStream";
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import GenerateTerminalCommand from "./cmd";
|
|||
import CommitMessageCommand from "./commit";
|
||||
import DraftIssueCommand from "./draftIssue";
|
||||
import HttpSlashCommand from "./http";
|
||||
import MultiFileEditSlashCommand from "./multifileEdit";
|
||||
import OnboardSlashCommand from "./onboard";
|
||||
import ReviewMessageCommand from "./review";
|
||||
import ShareSlashCommand from "./share";
|
||||
|
|
@ -14,4 +15,5 @@ export default [
|
|||
CommitMessageCommand,
|
||||
ReviewMessageCommand,
|
||||
OnboardSlashCommand,
|
||||
MultiFileEditSlashCommand,
|
||||
];
|
||||
|
|
|
|||
108
core/commands/slash/multifileEdit.ts
Normal file
108
core/commands/slash/multifileEdit.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { SlashCommand } from "../..";
|
||||
import { getFullyQualifiedPath } from "../../../extensions/vscode/src/util/util";
|
||||
import { VsCodeIde } from "../../../extensions/vscode/src/VsCodeIde";
|
||||
import { stripImages } from "../../llm/images";
|
||||
|
||||
const MultiFileEditSlashCommand: SlashCommand = {
|
||||
name: "multifile-edit",
|
||||
description: "Edit multiple files in the codebase at once",
|
||||
run: async function* ({ llm, contextItems, selectedCode, input, ide }) {
|
||||
const selectedCodeStr = (
|
||||
await Promise.all(
|
||||
selectedCode.map(async (item) => {
|
||||
// Split the range string from the filename, e.g. `filename.ts (1-2) -> [filename.ts, (1-2)]`
|
||||
const [filepath, rangeStr] = item.filepath.split(" ");
|
||||
const fullPath = getFullyQualifiedPath(ide as VsCodeIde, filepath);
|
||||
|
||||
if (!fullPath) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const codeStr = await ide.readRangeInFile(fullPath, item.range);
|
||||
|
||||
// Include the filepath so the model can map it correctly with codeblock outputs
|
||||
return `\`\`\`${fullPath} ${rangeStr}\n${codeStr}\`\`\``;
|
||||
}),
|
||||
)
|
||||
).join("\n");
|
||||
|
||||
const fileContextItemsStr = contextItems
|
||||
.filter((item) => item.uri?.type === "file")
|
||||
.map((item) => item.content)
|
||||
.join("\n");
|
||||
|
||||
const filesToEditStr = fileContextItemsStr + "\n" + selectedCodeStr;
|
||||
|
||||
const additionalContextStr = contextItems
|
||||
.filter((item) => item.uri?.type !== "file")
|
||||
.map((item) => `${item.description}: ${item.content}`)
|
||||
.join("\n");
|
||||
|
||||
const content = createPrompt(filesToEditStr, additionalContextStr, input);
|
||||
|
||||
for await (const chunk of llm.streamChat([{ role: "user", content }])) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
function createPrompt(
|
||||
filesToEditStr: string,
|
||||
additionalContextStr: string,
|
||||
input: string,
|
||||
): string {
|
||||
return `
|
||||
You are an AI assistant designed to help software engineers make multi-file edits in their codebase. Your task is to generate the necessary code changes for multiple files based on the engineer's request. Follow these guidelines:
|
||||
|
||||
1. Start with a brief introduction of the task you're about to perform. Do not start with any other preamble, such as "Certainly!"
|
||||
2. When providing instructions, if a user needs to interact with a CLI, walk them through each step
|
||||
2. Perform file edits in a logical, sequential ordering
|
||||
3. For each file edit, provide a brief explanation of the changes
|
||||
4. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
|
||||
a. When creating new files, also inlcude the filname in the language specifier of the code block.
|
||||
6. After providing all file changes, include a brief, sequential overview of the most important 3-5 edits
|
||||
|
||||
Remember to be concise and focus on the code changes and their impact.
|
||||
|
||||
Here's an example of how your response should be structured:
|
||||
|
||||
<example>
|
||||
I'll make the following changes to implement feature X:
|
||||
|
||||
1. First, I'll modify file1.js to add a new function:
|
||||
\`\`\`javascript /path/to/file1.js
|
||||
// Entire content of file1.js or changes to be made
|
||||
\`\`\`
|
||||
|
||||
2. Next, let's create a new test file:
|
||||
\`\`\`javascript /path/to/file1.test.js
|
||||
# Entire content of file2.py or changes to be made
|
||||
\`\`\`
|
||||
|
||||
Summary:
|
||||
- [Sequential overview of the most important 3-5 edits]
|
||||
</example>
|
||||
|
||||
Now, let's make the changes based on the engineer's request:
|
||||
|
||||
<input>
|
||||
${input}
|
||||
</input>
|
||||
|
||||
Here are the files to base your edits on:
|
||||
|
||||
<files>
|
||||
${filesToEditStr}
|
||||
</files>
|
||||
|
||||
And here is any additional context the engineer has provided:
|
||||
|
||||
<context>
|
||||
${additionalContextStr}
|
||||
</context>
|
||||
|
||||
Please provide the multi-file edit details based on the engineer's request.
|
||||
`;
|
||||
}
|
||||
|
||||
export default MultiFileEditSlashCommand;
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import * as fs from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import path from "path";
|
||||
import { languageForFilepath } from "../../autocomplete/constructPrompt.js";
|
||||
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,12 @@
|
|||
import Handlebars from "handlebars";
|
||||
import path from "path";
|
||||
import * as YAML from "yaml";
|
||||
import type { IDE, SlashCommand } from "..";
|
||||
import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from "..";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { stripImages } from "../llm/images";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { getBasename } from "../util/index";
|
||||
import { BaseContextProvider } from "../context";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
|
|
@ -147,28 +148,32 @@ function extractUserInput(input: string, commandName: string): string {
|
|||
return input;
|
||||
}
|
||||
|
||||
async function renderPrompt(prompt: string, context: any, userInput: string) {
|
||||
async function renderPrompt(prompt: string, context: ContinueSDK, userInput: string) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
const diff = await context.ide.getDiff(false);
|
||||
const currentFilePath = await context.ide.getCurrentFile();
|
||||
const currentFile = currentFilePath
|
||||
? await context.ide.readFile(currentFilePath)
|
||||
: undefined;
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
const inputData: Record<string, string> = {
|
||||
diff,
|
||||
input: userInput,
|
||||
};
|
||||
if (currentFile) {
|
||||
inputData.currentFile = currentFile.path;
|
||||
}
|
||||
|
||||
return renderTemplatedString(
|
||||
prompt,
|
||||
context.ide.readFile.bind(context.ide),
|
||||
{ diff, currentFile, input: userInput },
|
||||
inputData,
|
||||
helpers,
|
||||
);
|
||||
}
|
||||
|
||||
function getContextProviderHelpers(
|
||||
context: any,
|
||||
context: ContinueSDK,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: any) => [
|
||||
return context.config.contextProviders?.map((provider: IContextProvider) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
|
|
@ -182,16 +187,16 @@ function getContextProviderHelpers(
|
|||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item: any) =>
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
return items.map((item: any) => item.content).join("\n\n");
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function createContextItem(item: any, provider: any) {
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
|
|
@ -202,7 +207,7 @@ function createContextItem(item: any, provider: any) {
|
|||
}
|
||||
|
||||
function updateChatHistory(
|
||||
history: any[],
|
||||
history: ChatMessage[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessage?: string,
|
||||
|
|
|
|||
|
|
@ -463,7 +463,11 @@ declare global {
|
|||
stepIndex: number,
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getCurrentFile(): Promise<string | undefined>;
|
||||
getCurrentFile(): Promise<undefined | {
|
||||
isUntitled: boolean
|
||||
path: string
|
||||
contents: string
|
||||
}>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
|
|
@ -538,6 +542,7 @@ declare global {
|
|||
| "folder"
|
||||
| "jira"
|
||||
| "postgres"
|
||||
| "mssql"
|
||||
| "database"
|
||||
| "code"
|
||||
| "docs"
|
||||
|
|
@ -730,6 +735,7 @@ declare global {
|
|||
stop?: string[];
|
||||
maxTokens?: number;
|
||||
numThreads?: number;
|
||||
useMmap?: boolean;
|
||||
keepAlive?: number;
|
||||
raw?: boolean;
|
||||
stream?: boolean;
|
||||
|
|
|
|||
|
|
@ -24,17 +24,15 @@ class CurrentFileContextProvider extends BaseContextProvider {
|
|||
if (!currentFile) {
|
||||
return [];
|
||||
}
|
||||
const contents = await ide.readFile(currentFile);
|
||||
const baseName = getBasename(currentFile.path);
|
||||
return [
|
||||
{
|
||||
description: currentFile,
|
||||
content: `This is the currently open file:\n\n\`\`\`${getBasename(
|
||||
currentFile,
|
||||
)}\n${contents}\n\`\`\``,
|
||||
name: getBasename(currentFile),
|
||||
description: currentFile.path,
|
||||
content: `This is the currently open file:\n\n\`\`\`${baseName}\n${currentFile.contents}\n\`\`\``,
|
||||
name: baseName,
|
||||
uri: {
|
||||
type: "file",
|
||||
value: currentFile,
|
||||
value: currentFile.path,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,32 +0,0 @@
|
|||
import { BranchAndDir, Chunk } from "../../index.js";
|
||||
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js";
|
||||
|
||||
export async function retrieveFts(
|
||||
query: string,
|
||||
n: number,
|
||||
tags: BranchAndDir[],
|
||||
filterDirectory: string | undefined,
|
||||
): Promise<Chunk[]> {
|
||||
const ftsIndex = new FullTextSearchCodebaseIndex();
|
||||
|
||||
let ftsResults: Chunk[] = [];
|
||||
try {
|
||||
if (query.trim() !== "") {
|
||||
ftsResults = await ftsIndex.retrieve(
|
||||
tags,
|
||||
query
|
||||
.trim()
|
||||
.split(" ")
|
||||
.map((element) => `"${element}"`)
|
||||
.join(" OR "),
|
||||
n,
|
||||
filterDirectory,
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
return ftsResults;
|
||||
} catch (e) {
|
||||
console.warn("Error retrieving from FTS:", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,11 @@
|
|||
import {
|
||||
BranchAndDir,
|
||||
Chunk,
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
ILLM,
|
||||
} from "../../../index.js";
|
||||
import { chunkDocument } from "../../../indexing/chunk/chunk.js";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js";
|
||||
import { retrieveFts } from "../fullTextSearch.js";
|
||||
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
|
||||
// @ts-ignore
|
||||
import nlp from "wink-nlp-utils";
|
||||
|
||||
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
|
||||
import { chunkDocument } from "../../../indexing/chunk/chunk";
|
||||
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
|
||||
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
|
||||
|
||||
export interface RetrievalPipelineOptions {
|
||||
llm: ILLM;
|
||||
|
|
@ -23,11 +20,18 @@ export interface RetrievalPipelineOptions {
|
|||
includeEmbeddings?: boolean; // Used to handle JB w/o an embeddings model
|
||||
}
|
||||
|
||||
export interface RetrievalPipelineRunArguments {
|
||||
query: string;
|
||||
tags: BranchAndDir[];
|
||||
filterDirectory?: string;
|
||||
}
|
||||
|
||||
export interface IRetrievalPipeline {
|
||||
run(options: RetrievalPipelineOptions): Promise<Chunk[]>;
|
||||
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]>;
|
||||
}
|
||||
|
||||
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
||||
private ftsIndex = new FullTextSearchCodebaseIndex();
|
||||
private lanceDbIndex: LanceDbIndex;
|
||||
|
||||
constructor(protected readonly options: RetrievalPipelineOptions) {
|
||||
|
|
@ -38,6 +42,49 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
);
|
||||
}
|
||||
|
||||
private getCleanedTrigrams(
|
||||
query: RetrievalPipelineRunArguments["query"],
|
||||
): string[] {
|
||||
let text = nlp.string.removeExtraSpaces(query);
|
||||
text = nlp.string.stem(text);
|
||||
|
||||
let tokens = nlp.string
|
||||
.tokenize(text, true)
|
||||
.filter((token: any) => token.tag === "word")
|
||||
.map((token: any) => token.value);
|
||||
|
||||
tokens = nlp.tokens.removeWords(tokens);
|
||||
tokens = nlp.tokens.setOfWords(tokens);
|
||||
|
||||
const cleanedTokens = [...tokens].join(" ");
|
||||
const trigrams = nlp.string.ngram(cleanedTokens, 3);
|
||||
|
||||
return trigrams;
|
||||
}
|
||||
|
||||
protected async retrieveFts(
|
||||
args: RetrievalPipelineRunArguments,
|
||||
n: number,
|
||||
): Promise<Chunk[]> {
|
||||
try {
|
||||
if (args.query.trim() === "") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
|
||||
return await this.ftsIndex.retrieve({
|
||||
n,
|
||||
text: tokens,
|
||||
tags: args.tags,
|
||||
directory: args.filterDirectory,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("Error retrieving from FTS:", e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
protected async retrieveAndChunkRecentlyEditedFiles(
|
||||
n: number,
|
||||
): Promise<Chunk[]> {
|
||||
|
|
@ -75,15 +122,6 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
return chunks.slice(0, n);
|
||||
}
|
||||
|
||||
protected async retrieveFts(input: string, n: number): Promise<Chunk[]> {
|
||||
return retrieveFts(
|
||||
input,
|
||||
n,
|
||||
this.options.tags,
|
||||
this.options.filterDirectory,
|
||||
);
|
||||
}
|
||||
|
||||
protected async retrieveEmbeddings(
|
||||
input: string,
|
||||
n: number,
|
||||
|
|
@ -96,7 +134,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
);
|
||||
}
|
||||
|
||||
run(): Promise<Chunk[]> {
|
||||
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { Chunk } from "../../../index.js";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest.js";
|
||||
import { deduplicateChunks } from "../util.js";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
|
||||
import { Chunk } from "../../../";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest";
|
||||
import { deduplicateChunks } from "../util";
|
||||
|
||||
import BaseRetrievalPipeline, {
|
||||
RetrievalPipelineRunArguments,
|
||||
} from "./BaseRetrievalPipeline";
|
||||
|
||||
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
||||
async run(): Promise<Chunk[]> {
|
||||
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
|
||||
const { input, nFinal, filterDirectory, includeEmbeddings } = this.options;
|
||||
|
||||
// We give 1/4 weight to recently edited files, 1/4 to full text search,
|
||||
|
|
@ -15,7 +18,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
let retrievalResults: Chunk[] = [];
|
||||
|
||||
const ftsChunks = await this.retrieveFts(input, ftsNFinal);
|
||||
const ftsChunks = await this.retrieveFts(args, ftsNFinal);
|
||||
|
||||
const embeddingsChunks = includeEmbeddings
|
||||
? await this.retrieveEmbeddings(input, embeddingsNFinal)
|
||||
|
|
|
|||
|
|
@ -1,17 +1,22 @@
|
|||
import { Chunk } from "../../../index.js";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters.js";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest.js";
|
||||
import { deduplicateChunks } from "../util.js";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
|
||||
import { Chunk } from "../../..";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
|
||||
import { requestFilesFromRepoMap } from "../repoMapRequest";
|
||||
import { deduplicateChunks } from "../util";
|
||||
|
||||
import BaseRetrievalPipeline, {
|
||||
RetrievalPipelineRunArguments,
|
||||
} from "./BaseRetrievalPipeline";
|
||||
|
||||
export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
||||
private async _retrieveInitial(): Promise<Chunk[]> {
|
||||
private async _retrieveInitial(
|
||||
args: RetrievalPipelineRunArguments,
|
||||
): Promise<Chunk[]> {
|
||||
const { input, nRetrieve, filterDirectory, includeEmbeddings } =
|
||||
this.options;
|
||||
|
||||
let retrievalResults: Chunk[] = [];
|
||||
|
||||
const ftsChunks = await this.retrieveFts(input, nRetrieve);
|
||||
const ftsChunks = await this.retrieveFts(args, nRetrieve);
|
||||
const embeddingsChunks = includeEmbeddings
|
||||
? await this.retrieveEmbeddings(input, nRetrieve)
|
||||
: [];
|
||||
|
|
@ -104,9 +109,9 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
return results;
|
||||
}
|
||||
|
||||
async run(): Promise<Chunk[]> {
|
||||
const intialResults = await this._retrieveInitial();
|
||||
const rankedResults = await this._rerank(this.options.input, intialResults);
|
||||
async run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
|
||||
let results = await this._retrieveInitial(args);
|
||||
results = await this._rerank(args.query, results);
|
||||
|
||||
// // // Expand top reranked results
|
||||
// const expanded = await this._expandRankedResults(results);
|
||||
|
|
@ -120,7 +125,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
// TODO: stitch together results
|
||||
|
||||
return rankedResults;
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -93,7 +93,11 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
};
|
||||
|
||||
const pipeline = new pipelineType(pipelineOptions);
|
||||
const results = await pipeline.run();
|
||||
const results = await pipeline.run({
|
||||
tags,
|
||||
filterDirectory,
|
||||
query: extras.fullInput,
|
||||
});
|
||||
|
||||
if (results.length === 0) {
|
||||
throw new Error(
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ const modelDescriptionSchema = z.object({
|
|||
stop: z.array(z.string()).optional(),
|
||||
maxTokens: z.number().optional(),
|
||||
numThreads: z.number().optional(),
|
||||
useMmap: z.boolean().optional(),
|
||||
keepAlive: z.number().optional(),
|
||||
raw: z.boolean().optional(),
|
||||
stream: z.boolean().optional(),
|
||||
|
|
|
|||
21
core/core.ts
21
core/core.ts
|
|
@ -1,6 +1,8 @@
|
|||
import ignore from "ignore";
|
||||
import path from "path";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider";
|
||||
import { CompletionProvider } from "./autocomplete/CompletionProvider";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import {
|
||||
setupBestConfig,
|
||||
|
|
@ -16,6 +18,7 @@ import { ControlPlaneClient } from "./control-plane/client";
|
|||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
|
||||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { defaultIgnoreFile } from "./indexing/ignore.js";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
|
|
@ -77,7 +80,7 @@ export class Core {
|
|||
constructor(
|
||||
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
private readonly ide: IDE,
|
||||
private readonly onWrite: (text: string) => Promise<void> = async () => {},
|
||||
private readonly onWrite: (text: string) => Promise<void> = async () => { },
|
||||
) {
|
||||
// Ensure .continue directory is created
|
||||
setupInitialDotContinueDirectory();
|
||||
|
|
@ -168,7 +171,7 @@ export class Core {
|
|||
this.configHandler,
|
||||
ide,
|
||||
getLlm,
|
||||
(e) => {},
|
||||
(e) => { },
|
||||
(..._) => Promise.resolve([]),
|
||||
);
|
||||
|
||||
|
|
@ -398,6 +401,7 @@ export class Core {
|
|||
});
|
||||
break;
|
||||
}
|
||||
// @ts-ignore
|
||||
yield { content: next.value.content };
|
||||
next = await gen.next();
|
||||
}
|
||||
|
|
@ -677,7 +681,7 @@ export class Core {
|
|||
await codebaseIndexer.clearIndexes();
|
||||
}
|
||||
|
||||
const dirs = data?.dir ? [data.dir] : await this.ide.getWorkspaceDirs();
|
||||
const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs();
|
||||
await this.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
on("index/setPaused", (msg) => {
|
||||
|
|
@ -704,8 +708,13 @@ export class Core {
|
|||
return { url };
|
||||
});
|
||||
|
||||
on("didChangeActiveTextEditor", ({ data: { filepath } }) => {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
|
||||
const ignoreInstance = ignore().add(defaultIgnoreFile);
|
||||
let rootDirectory = await this.ide.getWorkspaceDirs();
|
||||
const relativeFilePath = path.relative(rootDirectory[0], filepath);
|
||||
if (!ignoreInstance.ignores(relativeFilePath)) {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { distance } from "fastest-levenshtein";
|
|||
import path from "path";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { DiffLine } from "../..";
|
||||
import { LANGUAGES } from "../../autocomplete/languages";
|
||||
import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo";
|
||||
import { myersDiff } from "../../diff/myers";
|
||||
import { getParserForFile } from "../../util/treeSitter";
|
||||
import { findInAst } from "./findInAst";
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { ILLM } from "../..";
|
|||
import {
|
||||
filterLeadingNewline,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/streamTransforms/lineStream";
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { dedent } from "../../util";
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import {
|
|||
filterLeadingAndTrailingNewLineInsertion,
|
||||
filterLeadingNewline,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/streamTransforms/lineStream";
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
|
||||
import { streamDiff } from "../../diff/streamDiff.js";
|
||||
import { LineStream, streamLines } from "../../diff/util.js";
|
||||
import { DiffLine, ILLM } from "../../index.js";
|
||||
|
|
@ -43,7 +43,7 @@ export async function* streamLazyApply(
|
|||
let lazyCompletionLines = streamLines(lazyCompletion, true);
|
||||
// Process line output
|
||||
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
|
||||
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => { }, ["```"]);
|
||||
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
|
||||
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
|
||||
|
||||
// Fill in unchanged code
|
||||
|
|
|
|||
|
|
@ -5,15 +5,10 @@ import {
|
|||
filterLeadingAndTrailingNewLineInsertion,
|
||||
skipLines,
|
||||
stopAtLines,
|
||||
} from "../autocomplete/streamTransforms/lineStream.js";
|
||||
} from "../autocomplete/filtering/streamTransforms/lineStream.js";
|
||||
import { streamDiff } from "../diff/streamDiff.js";
|
||||
import { streamLines } from "../diff/util.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
DiffLine,
|
||||
ILLM,
|
||||
LLMFullCompletionOptions,
|
||||
} from "../index.js";
|
||||
import { ChatMessage, DiffLine, ILLM, Prediction } from "../index.js";
|
||||
import { gptEditPrompt } from "../llm/templates/edit.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
|
||||
|
|
@ -94,10 +89,17 @@ export async function* streamDiffLines(
|
|||
);
|
||||
const inept = modelIsInept(llm.model);
|
||||
|
||||
const prediction: Prediction = {
|
||||
type: "content",
|
||||
content: highlighted,
|
||||
};
|
||||
|
||||
const completion =
|
||||
typeof prompt === "string"
|
||||
? llm.streamComplete(prompt, { raw: true })
|
||||
: llm.streamChat(prompt);
|
||||
? llm.streamComplete(prompt, { raw: true, prediction })
|
||||
: llm.streamChat(prompt, {
|
||||
prediction,
|
||||
});
|
||||
|
||||
let lines = streamLines(completion);
|
||||
|
||||
|
|
|
|||
30
core/index.d.ts
vendored
30
core/index.d.ts
vendored
|
|
@ -48,9 +48,9 @@ export interface IndexingProgressUpdate {
|
|||
export type PromptTemplate =
|
||||
| string
|
||||
| ((
|
||||
history: ChatMessage[],
|
||||
otherData: Record<string, string>,
|
||||
) => string | ChatMessage[]);
|
||||
history: ChatMessage[],
|
||||
otherData: Record<string, string>,
|
||||
) => string | ChatMessage[]);
|
||||
|
||||
export interface ILLM extends LLMOptions {
|
||||
get providerName(): ModelProvider;
|
||||
|
|
@ -494,7 +494,11 @@ export interface IDE {
|
|||
stepIndex: number,
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getCurrentFile(): Promise<string | undefined>;
|
||||
getCurrentFile(): Promise<undefined | {
|
||||
isUntitled: boolean
|
||||
path: string
|
||||
contents: string
|
||||
}>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string, cwd?: string): Promise<[string, string]>;
|
||||
|
|
@ -780,6 +784,14 @@ export interface CustomCommand {
|
|||
description: string;
|
||||
}
|
||||
|
||||
interface Prediction {
|
||||
type: "content"
|
||||
content: string | {
|
||||
type: "text"
|
||||
text: string
|
||||
}[]
|
||||
}
|
||||
|
||||
interface BaseCompletionOptions {
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
|
|
@ -791,9 +803,11 @@ interface BaseCompletionOptions {
|
|||
stop?: string[];
|
||||
maxTokens?: number;
|
||||
numThreads?: number;
|
||||
useMmap?: boolean;
|
||||
keepAlive?: number;
|
||||
raw?: boolean;
|
||||
stream?: boolean;
|
||||
prediction?: Prediction;
|
||||
}
|
||||
|
||||
export interface ModelCapability {
|
||||
|
|
@ -825,6 +839,7 @@ export type EmbeddingsProviderName =
|
|||
| "ollama"
|
||||
| "openai"
|
||||
| "cohere"
|
||||
| "lmstudio"
|
||||
| "free-trial"
|
||||
| "gemini"
|
||||
| "continue-proxy"
|
||||
|
|
@ -908,6 +923,7 @@ export interface TabAutocompleteOptions {
|
|||
disableInFiles?: string[];
|
||||
useImports?: boolean;
|
||||
useRootPathContext?: boolean;
|
||||
showWhateverWeHaveAtXMs?: number;
|
||||
}
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
|
|
@ -1057,9 +1073,9 @@ export interface Config {
|
|||
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
|
||||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?:
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
| CustomLLM
|
||||
| ModelDescription
|
||||
| (CustomLLM | ModelDescription)[];
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
/** UI styles customization */
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
|
||||
import { getBasename } from "../util/index";
|
||||
import { RETRIEVAL_PARAMS } from "../util/parameters";
|
||||
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
|
||||
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
|
||||
import {
|
||||
|
|
@ -10,10 +11,20 @@ import {
|
|||
type CodebaseIndex,
|
||||
} from "./types";
|
||||
|
||||
export interface RetrieveConfig {
|
||||
tags: BranchAndDir[];
|
||||
text: string;
|
||||
n: number;
|
||||
directory?: string;
|
||||
filterPaths?: string[];
|
||||
bm25Threshold?: number;
|
||||
}
|
||||
|
||||
export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
||||
relativeExpectedTime: number = 0.2;
|
||||
static artifactId = "sqliteFts";
|
||||
artifactId: string = FullTextSearchCodebaseIndex.artifactId;
|
||||
pathWeightMultiplier = 10.0;
|
||||
|
||||
private async _createTables(db: DatabaseConnection) {
|
||||
await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
|
||||
|
|
@ -71,17 +82,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
desc: `Indexing ${getBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
markComplete([item], IndexResultType.Compute);
|
||||
await markComplete([item], IndexResultType.Compute);
|
||||
}
|
||||
|
||||
// Add tag
|
||||
for (const item of results.addTag) {
|
||||
markComplete([item], IndexResultType.AddTag);
|
||||
await markComplete([item], IndexResultType.AddTag);
|
||||
}
|
||||
|
||||
// Remove tag
|
||||
for (const item of results.removeTag) {
|
||||
markComplete([item], IndexResultType.RemoveTag);
|
||||
await markComplete([item], IndexResultType.RemoveTag);
|
||||
}
|
||||
|
||||
// Delete
|
||||
|
|
@ -93,63 +104,81 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
await db.run("DELETE FROM fts WHERE path = ?", [item.path]);
|
||||
|
||||
markComplete([item], IndexResultType.Delete);
|
||||
await markComplete([item], IndexResultType.Delete);
|
||||
}
|
||||
}
|
||||
|
||||
async retrieve(
|
||||
tags: BranchAndDir[],
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined,
|
||||
filterPaths: string[] | undefined,
|
||||
bm25Threshold: number = RETRIEVAL_PARAMS.bm25Threshold,
|
||||
): Promise<Chunk[]> {
|
||||
async retrieve(config: RetrieveConfig): Promise<Chunk[]> {
|
||||
const db = await SqliteDb.get();
|
||||
|
||||
// Notice that the "chunks" artifactId is used because of linking between tables
|
||||
const tagStrings = tags.map((tag) => {
|
||||
return tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId });
|
||||
});
|
||||
const query = this.buildRetrieveQuery(config);
|
||||
const parameters = this.getRetrieveQueryParameters(config);
|
||||
|
||||
const query = `SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank
|
||||
FROM fts
|
||||
JOIN fts_metadata ON fts.rowid = fts_metadata.id
|
||||
JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId
|
||||
WHERE fts MATCH '${text.replace(
|
||||
/\?/g,
|
||||
"",
|
||||
)}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})
|
||||
${
|
||||
filterPaths
|
||||
? `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`
|
||||
: ""
|
||||
}
|
||||
ORDER BY rank
|
||||
LIMIT ?`;
|
||||
let results = await db.all(query, parameters);
|
||||
|
||||
let results = await db.all(query, [
|
||||
...tagStrings,
|
||||
...(filterPaths || []),
|
||||
Math.ceil(n),
|
||||
]);
|
||||
|
||||
results = results.filter((result) => result.rank <= bm25Threshold);
|
||||
results = results.filter(
|
||||
(result) =>
|
||||
result.rank <= (config.bm25Threshold ?? RETRIEVAL_PARAMS.bm25Threshold),
|
||||
);
|
||||
|
||||
const chunks = await db.all(
|
||||
`SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`,
|
||||
results.map((result) => result.chunkId),
|
||||
);
|
||||
|
||||
return chunks.map((chunk) => {
|
||||
return {
|
||||
filepath: chunk.path,
|
||||
index: chunk.index,
|
||||
startLine: chunk.startLine,
|
||||
endLine: chunk.endLine,
|
||||
content: chunk.content,
|
||||
digest: chunk.cacheKey,
|
||||
};
|
||||
});
|
||||
return chunks.map((chunk) => ({
|
||||
filepath: chunk.path,
|
||||
index: chunk.index,
|
||||
startLine: chunk.startLine,
|
||||
endLine: chunk.endLine,
|
||||
content: chunk.content,
|
||||
digest: chunk.cacheKey,
|
||||
}));
|
||||
}
|
||||
|
||||
private buildTagFilter(tags: BranchAndDir[]): string {
|
||||
const tagStrings = this.convertTags(tags);
|
||||
|
||||
return `AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})`;
|
||||
}
|
||||
|
||||
private buildPathFilter(filterPaths: string[] | undefined): string {
|
||||
if (!filterPaths || filterPaths.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return `AND fts_metadata.path IN (${filterPaths.map(() => "?").join(",")})`;
|
||||
}
|
||||
|
||||
private buildRetrieveQuery(config: RetrieveConfig): string {
|
||||
return `
|
||||
SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank
|
||||
FROM fts
|
||||
JOIN fts_metadata ON fts.rowid = fts_metadata.id
|
||||
JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId
|
||||
WHERE fts MATCH ?
|
||||
${this.buildTagFilter(config.tags)}
|
||||
${this.buildPathFilter(config.filterPaths)}
|
||||
ORDER BY bm25(fts, ${this.pathWeightMultiplier})
|
||||
LIMIT ?
|
||||
`;
|
||||
}
|
||||
|
||||
private getRetrieveQueryParameters(config: RetrieveConfig) {
|
||||
const { text, tags, filterPaths, n } = config;
|
||||
const tagStrings = this.convertTags(tags);
|
||||
|
||||
return [
|
||||
text.replace(/\?/g, ""),
|
||||
...tagStrings,
|
||||
...(filterPaths || []),
|
||||
Math.ceil(n),
|
||||
];
|
||||
}
|
||||
|
||||
private convertTags(tags: BranchAndDir[]): string[] {
|
||||
// Notice that the "chunks" artifactId is used because of linking between tables
|
||||
return tags.map((tag) =>
|
||||
tagToString({ ...tag, artifactId: ChunkCodebaseIndex.artifactId }),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
13
core/indexing/embeddings/LMStudio.ts
Normal file
13
core/indexing/embeddings/LMStudio.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { EmbeddingsProviderName, EmbedOptions } from "../..";
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
|
||||
|
||||
class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "lmstudio";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "http://localhost:1234/v1",
|
||||
model: "nomic-ai/nomic-embed-text-v1.5-GGUF",
|
||||
};
|
||||
}
|
||||
|
||||
export default LMStudioEmbeddingsProvider;
|
||||
|
|
@ -17,6 +17,7 @@ import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js";
|
|||
import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js";
|
||||
import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js";
|
||||
import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js";
|
||||
import LMStudioEmbeddingsProvider from "./LMStudio.js";
|
||||
|
||||
type EmbeddingsProviderConstructor = new (
|
||||
...args: any[]
|
||||
|
|
@ -42,5 +43,6 @@ export const allEmbeddingsProviders: Record<
|
|||
mistral: MistralEmbeddingsProvider,
|
||||
nebius: NebiusEmbeddingsProvider,
|
||||
vertexai: VertexEmbeddingsProvider,
|
||||
watsonx: WatsonxEmbeddingsProvider
|
||||
watsonx: WatsonxEmbeddingsProvider,
|
||||
lmstudio: LMStudioEmbeddingsProvider
|
||||
};
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ interface ModelFileParams {
|
|||
min_p?: number;
|
||||
// deprecated?
|
||||
num_thread?: number;
|
||||
use_mmap?: boolean;
|
||||
num_gqa?: number;
|
||||
num_gpu?: number;
|
||||
}
|
||||
|
|
@ -191,6 +192,7 @@ class Ollama extends BaseLLM {
|
|||
num_ctx: this.contextLength,
|
||||
mirostat: options.mirostat,
|
||||
num_thread: options.numThreads,
|
||||
use_mmap: options.useMmap,
|
||||
min_p: options.minP,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -95,7 +95,14 @@ class OpenAI extends BaseLLM {
|
|||
);
|
||||
}
|
||||
|
||||
protected _convertArgs(options: any, messages: ChatMessage[]) {
|
||||
private supportsPrediction(model: string): boolean {
|
||||
return [
|
||||
"gpt-4o-mini",
|
||||
"gpt-4o"
|
||||
].includes(model);
|
||||
}
|
||||
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) {
|
||||
const url = new URL(this.apiBase!);
|
||||
const finalOptions: any = {
|
||||
messages: messages.map(this._convertMessage),
|
||||
|
|
@ -135,6 +142,18 @@ class OpenAI extends BaseLLM {
|
|||
);
|
||||
}
|
||||
|
||||
if (options.prediction && this.supportsPrediction(options.model)) {
|
||||
if (finalOptions.presence_penalty) { // prediction doesn't support > 0
|
||||
finalOptions.presence_penalty = undefined;
|
||||
}
|
||||
if (finalOptions.frequency_penalty) { // prediction doesn't support > 0
|
||||
finalOptions.frequency_penalty = undefined;
|
||||
}
|
||||
finalOptions.max_completion_tokens = undefined;
|
||||
|
||||
finalOptions.prediction = options.prediction;
|
||||
}
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
|
|
|
|||
64
core/package-lock.json
generated
64
core/package-lock.json
generated
|
|
@ -64,6 +64,7 @@
|
|||
"vectordb": "^0.4.20",
|
||||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.23.8"
|
||||
|
|
@ -14850,6 +14851,69 @@
|
|||
"node": ">=4"
|
||||
}
|
||||
},
|
||||
"node_modules/wink-distance": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wink-distance/-/wink-distance-2.0.2.tgz",
|
||||
"integrity": "sha512-pyEhUB/OKFYcgOC4J6E+c+gwVA/8qg2s5n49mIcUsJZM5iDSa17uOxRQXR4rvfp+gbj55K/I08FwjFBwb6fq3g==",
|
||||
"dependencies": {
|
||||
"wink-helpers": "^2.0.0",
|
||||
"wink-jaro-distance": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wink-eng-lite-web-model": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/wink-eng-lite-web-model/-/wink-eng-lite-web-model-1.8.0.tgz",
|
||||
"integrity": "sha512-PlSaw2tzQ2SrKYEaH6AbxIUCFnQ9H7FeReVluV9O9VpgfYYa+urttUoAgzDrVujeMkJtACAIY8eFIkQgbEMpPg==",
|
||||
"engines": {
|
||||
"node": ">=16.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wink-helpers": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wink-helpers/-/wink-helpers-2.0.0.tgz",
|
||||
"integrity": "sha512-I/ZzXrHcNRXuoeFJmp2vMVqDI6UCK02Tds1WP4kSGAmx520gjL1BObVzF7d2ps24tyHIly9ngdB2jwhlFUjPvg=="
|
||||
},
|
||||
"node_modules/wink-jaro-distance": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wink-jaro-distance/-/wink-jaro-distance-2.0.0.tgz",
|
||||
"integrity": "sha512-9bcUaXCi9N8iYpGWbFkf83OsBkg17r4hEyxusEzl+nnReLRPqxhB9YNeRn3g54SYnVRNXP029lY3HDsbdxTAuA=="
|
||||
},
|
||||
"node_modules/wink-nlp": {
|
||||
"version": "1.14.3",
|
||||
"resolved": "https://registry.npmjs.org/wink-nlp/-/wink-nlp-1.14.3.tgz",
|
||||
"integrity": "sha512-lvY5iCs3T8I34F8WKS70+2P0U9dWLn3vdPf/Z+m2VK14N7OmqnPzmHfh3moHdusajoQ37Em39z0IZB9K4x/96A=="
|
||||
},
|
||||
"node_modules/wink-nlp-utils": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/wink-nlp-utils/-/wink-nlp-utils-2.1.0.tgz",
|
||||
"integrity": "sha512-b7PcRhEBNxQmsmht70jLOkwYUyie3da4/cgEXL+CumYO5b/nwV+W7fuMXToh5BtGq1RABznmc2TGTp1Qf/JUXg==",
|
||||
"dependencies": {
|
||||
"wink-distance": "^2.0.1",
|
||||
"wink-eng-lite-web-model": "^1.4.3",
|
||||
"wink-helpers": "^2.0.0",
|
||||
"wink-nlp": "^1.12.0",
|
||||
"wink-porter2-stemmer": "^2.0.1",
|
||||
"wink-tokenizer": "^5.2.3"
|
||||
}
|
||||
},
|
||||
"node_modules/wink-porter2-stemmer": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/wink-porter2-stemmer/-/wink-porter2-stemmer-2.0.1.tgz",
|
||||
"integrity": "sha512-0g+RkkqhRXFmSpJQStVXW5N/WsshWpJXsoDRW7DwVkGI2uDT6IBCoq3xdH5p6IHLaC6ygk7RWUsUx4alKxoagQ=="
|
||||
},
|
||||
"node_modules/wink-tokenizer": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/wink-tokenizer/-/wink-tokenizer-5.3.0.tgz",
|
||||
"integrity": "sha512-O/yAw0g3FmSgeeQuYAJJfP7fVPB4A6ay0018qASh79aWmIOyPYy4j4r9EQT8xBjicja6lCLvgRVAybmEBaATQA==",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^9.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wink-tokenizer/node_modules/emoji-regex": {
|
||||
"version": "9.2.2",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
|
||||
"integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="
|
||||
},
|
||||
"node_modules/word-wrap": {
|
||||
"version": "1.2.5",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
|
||||
|
|
|
|||
|
|
@ -95,6 +95,7 @@
|
|||
"vectordb": "^0.4.20",
|
||||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.23.8"
|
||||
|
|
|
|||
|
|
@ -71,7 +71,7 @@ export function registerHelpers(
|
|||
export async function prepareTemplateAndData(
|
||||
template: string,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
inputData: any,
|
||||
inputData: Record<string, string>,
|
||||
ctxProviderNames: string[],
|
||||
): Promise<[string, any]> {
|
||||
const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
|
||||
|
|
@ -95,7 +95,7 @@ export async function prepareTemplateAndData(
|
|||
return [newTemplate, data];
|
||||
}
|
||||
|
||||
export function compileAndRenderTemplate(template: string, data: any): string {
|
||||
export function compileAndRenderTemplate(template: string, data: Record<string, string>): string {
|
||||
const templateFn = Handlebars.compile(template);
|
||||
return templateFn(data);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import {
|
|||
export async function renderTemplatedString(
|
||||
template: string,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
inputData: any,
|
||||
inputData: Record<string, string>,
|
||||
availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
|
||||
): Promise<string> {
|
||||
const helperPromises = availableHelpers
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import * as YAML from "yaml";
|
||||
import { SlashCommand } from "../..";
|
||||
import { ContinueSDK, SlashCommand } from "../..";
|
||||
import { stripImages } from "../../llm/images";
|
||||
import { getBasename } from "../../util/index";
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
|
|
@ -37,18 +37,21 @@ export function extractUserInput(input: string, commandName: string): string {
|
|||
return input;
|
||||
}
|
||||
|
||||
export async function getDefaultVariables(context: any, userInput: string) {
|
||||
const currentFilePath = await context.ide.getCurrentFile();
|
||||
const currentFile = currentFilePath
|
||||
? await context.ide.readFile(currentFilePath)
|
||||
: undefined;
|
||||
|
||||
return { currentFile, input: userInput };
|
||||
export async function getDefaultVariables(
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
): Promise<Record<string, string>> {
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
const vars: Record<string, string> = { input: userInput };
|
||||
if (currentFile) {
|
||||
vars.currentFile = currentFile.path;
|
||||
}
|
||||
return vars;
|
||||
}
|
||||
|
||||
export async function renderPrompt(
|
||||
prompt: string,
|
||||
context: any,
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ import type {
|
|||
SessionInfo,
|
||||
SiteIndexingConfig,
|
||||
} from "../";
|
||||
import type { AutocompleteInput } from "../autocomplete/completionProvider";
|
||||
import { AutocompleteInput } from "../autocomplete/util/types";
|
||||
import { ProfileDescription } from "../config/ConfigHandler";
|
||||
|
||||
export type ProtocolGeneratorType<T> = AsyncGenerator<{
|
||||
|
|
@ -143,7 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"tts/kill": [undefined, void];
|
||||
"index/setPaused": [boolean, void];
|
||||
"index/forceReIndex": [
|
||||
undefined | { dir?: string; shouldClearIndexes?: boolean },
|
||||
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
|
||||
void,
|
||||
];
|
||||
"index/indexingProgressBarInitialized": [undefined, void];
|
||||
|
|
|
|||
|
|
@ -48,7 +48,11 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
];
|
||||
getProblems: [{ filepath: string }, Problem[]];
|
||||
getOpenFiles: [undefined, string[]];
|
||||
getCurrentFile: [undefined, string | undefined];
|
||||
getCurrentFile: [undefined, undefined | {
|
||||
isUntitled: boolean;
|
||||
path: string;
|
||||
contents: string;
|
||||
}];
|
||||
getPinnedFiles: [undefined, string[]];
|
||||
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
|
||||
readRangeInFile: [{ filepath: string; range: Range }, string];
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import type { RangeInFileWithContents } from "../commands/util.js";
|
||||
import type { ContextSubmenuItem, MessageContent } from "../index.js";
|
||||
import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js";
|
||||
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
|
||||
|
||||
import type { RangeInFileWithContents } from "../commands/util.js";
|
||||
import type { ContextSubmenuItem, MessageContent } from "../index.js";
|
||||
|
||||
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
||||
onLoad: [
|
||||
undefined,
|
||||
|
|
@ -17,8 +18,13 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
openUrl: [string, void];
|
||||
// We pass the `curSelectedModel` because we currently cannot access the
|
||||
// default model title in the GUI from JB
|
||||
applyToCurrentFile: [
|
||||
{ text: string; streamId: string; curSelectedModelTitle: string },
|
||||
applyToFile: [
|
||||
{
|
||||
text: string;
|
||||
streamId: string;
|
||||
curSelectedModelTitle: string;
|
||||
filepath: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
showTutorial: [undefined, void];
|
||||
|
|
@ -59,7 +65,6 @@ export interface ApplyState {
|
|||
|
||||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
setInactive: [undefined, void];
|
||||
setTTSActive: [boolean, void];
|
||||
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
|
||||
updateSubmenuItems: [
|
||||
{ provider: string; submenuItems: ContextSubmenuItem[] },
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue