diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 323f737c5..50629e30e 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,11 +1,9 @@ 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 { RootPathContextService } from "./context/RootPathContextService.js"; import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; @@ -13,12 +11,11 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; -import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -40,14 +37,13 @@ export type GetLspDefinitionsFunction = ( ) => Promise; export class CompletionProvider { - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = 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, @@ -57,11 +53,7 @@ export class CompletionProvider { private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); - this.importDefinitionsService = new ImportDefinitionsService(this.ide); - this.rootPathContextService = new RootPathContextService( - this.importDefinitionsService, - this.ide, - ); + this.contextRetrievalService = new ContextRetrievalService(this.ide); } private async _prepareLlm(): Promise { @@ -144,13 +136,18 @@ export class CompletionProvider { ): Promise { 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 options = await this._getAutocompleteOptions(); const helper = await HelperVars.create( input, options, @@ -162,11 +159,6 @@ export class CompletionProvider { return undefined; } - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } - // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( @@ -177,26 +169,15 @@ export class CompletionProvider { ////////// - // Construct full prefix/suffix (a few edge cases handled in here) - const { prefix: fullPrefix, suffix: fullSuffix } = - await constructInitialPrefixSuffix(helper.input, this.ide); - // 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, - fullPrefix, - fullSuffix, - ); + const extraSnippets = await this._getExtraSnippets(helper); let { prefix, suffix, completeMultiline, snippets } = await constructAutocompletePrompt( - fullPrefix, - fullSuffix, helper, extraSnippets, - this.importDefinitionsService, - this.rootPathContextService, + this.contextRetrievalService, ); // If prefix is manually passed @@ -301,15 +282,13 @@ export class CompletionProvider { private async _getExtraSnippets( helper: HelperVars, - fullPrefix: string, - fullSuffix: string, ): Promise { let extraSnippets = helper.options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( helper.input.filepath, - fullPrefix + fullSuffix, - fullPrefix.length, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, this.ide, helper.lang, ), diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 9dd56653d..2c9f0fe27 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -1,7 +1,9 @@ import { IDE, TabAutocompleteOptions } from ".."; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; import { languageForFilepath } from "./constructPrompt"; +import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; import { AutocompleteInput } from "./types"; +import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; /** * A collection of variables that are often accessed throughout the autocomplete pipeline @@ -9,8 +11,12 @@ import { AutocompleteInput } from "./types"; */ 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 constructor( public readonly input: AutocompleteInput, @@ -30,6 +36,21 @@ export class HelperVars { (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; + + 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( @@ -69,4 +90,22 @@ export class HelperVars { } 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; + } } diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 8bc5e5de4..d8df8aeb0 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,7 +1,7 @@ import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../HelperVars"; import { AutocompleteInput } from "../types"; -import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; @@ -10,23 +10,20 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean { } export async function shouldCompleteMultiline( - treePath: AstPath | undefined, - fullPrefix: string, - fullSuffix: string, - language: AutocompleteLanguageInfo, + helper: HelperVars, ): Promise { // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(fullPrefix, fullSuffix)) { + if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; } // Don't complete multi-line for single-line comments if ( - fullPrefix + helper.fullPrefix .split("\n") .slice(-1)[0] ?.trimStart() - .startsWith(language.singleLineComment) + .startsWith(helper.lang.singleLineComment) ) { return false; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index cbef4949b..c83e1b107 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -9,18 +9,14 @@ import { LANGUAGES, Typescript, } from "./constants/AutocompleteLanguageInfo.js"; -import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - getSymbolsForSnippet, rankSnippets, removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; -import { RootPathContextService } from "./context/RootPathContextService.js"; import { HelperVars } from "./HelperVars.js"; -import { findMatchingRange } from "./recentlyEdited.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( filepath: string, @@ -29,12 +25,9 @@ export function languageForFilepath( } export async function constructAutocompletePrompt( - fullPrefix: string, - fullSuffix: string, helper: HelperVars, extraSnippets: AutocompleteSnippet[], - importDefinitionsService: ImportDefinitionsService, - rootPathContextService: RootPathContextService, + contextRetrievalService: ContextRetrievalService, ): Promise<{ prefix: string; suffix: string; @@ -45,177 +38,84 @@ export async function constructAutocompletePrompt( // Construct basic prefix const maxPrefixTokens = helper.options.maxPromptTokens * helper.options.prefixPercentage; - const prefix = pruneLinesFromTop( - fullPrefix, + const prunedPrefix = pruneLinesFromTop( + helper.fullPrefix, maxPrefixTokens, helper.modelName, ); // Construct suffix const maxSuffixTokens = Math.min( - helper.options.maxPromptTokens - countTokens(prefix, helper.modelName), + helper.options.maxPromptTokens - + countTokens(prunedPrefix, helper.modelName), helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, ); - const suffix = pruneLinesFromBottom( - fullSuffix, + const prunedSuffix = pruneLinesFromBottom( + helper.fullSuffix, maxSuffixTokens, helper.modelName, ); - // Calculate AST Path - let treePath: AstPath | undefined; - try { - const ast = await getAst(helper.filepath, fullPrefix + fullSuffix); - if (ast) { - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } - } catch (e) { - console.error("Failed to parse AST", e); - } + let snippets = await contextRetrievalService.retrieve( + prunedPrefix, + helper, + extraSnippets, + ); - // Find external snippets - let snippets: AutocompleteSnippet[] = []; - - if (helper.options.useOtherFiles) { - snippets.push(...extraSnippets); - - const windowAroundCursor = - fullPrefix.slice( - -helper.options.slidingWindowSize * - helper.options.slidingWindowPrefixPercentage, - ) + - fullSuffix.slice( - helper.options.slidingWindowSize * - (1 - helper.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 (helper.options.useRecentlyEdited) { - const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if ( - currentLinePrefix?.length > - helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } - - // Use imports - if (helper.options.useImports) { - const importSnippets = []; - const fileInfo = importDefinitionsService.get(helper.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) => !helper.lang.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } - - if (helper.options.useRootPathContext && treePath) { - const ctx = await rootPathContextService.getContextForPath( - helper.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 = - helper.options.maxPromptTokens * helper.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: helper.pos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: helper.pos.line + suffixLines + buffer, - character: 0, - }, - }; - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - prefixSuffixRangeWithBuffer, + // Filter out empty snippets and ones that are already in the prefix/suffix + snippets = snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && + !(prunedPrefix + prunedSuffix).includes(s.contents.trim()), ); - // Filter snippets for those with best scores (must be above threshold) - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - finalSnippets = fillPromptWithSnippets( - scoredSnippets, - maxSnippetTokens, - helper.modelName, - ); + // Rank / order the snippets + const scoredSnippets = rankSnippets(snippets, helper); - snippets = finalSnippets; - } + // Fill maxSnippetTokens with snippets + const maxSnippetTokens = + helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; + + // Remove prefix range from snippets + const prefixLines = prunedPrefix.split("\n").length; + const suffixLines = prunedSuffix.split("\n").length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: helper.pos.line - prefixLines - buffer, + character: 0, + }, + end: { + line: helper.pos.line + suffixLines + buffer, + character: 0, + }, + }; + let finalSnippets = removeRangeFromSnippets( + scoredSnippets, + helper.filepath.split("://").slice(-1)[0], + prefixSuffixRangeWithBuffer, + ); + + // Filter snippets for those with best scores (must be above threshold) + finalSnippets = finalSnippets.filter( + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, + ); + finalSnippets = fillPromptWithSnippets( + scoredSnippets, + maxSnippetTokens, + helper.modelName, + ); + + snippets = finalSnippets; return { - prefix, - suffix, + prefix: prunedPrefix, + suffix: prunedSuffix, useFim: true, - completeMultiline: await shouldCompleteMultiline( - treePath, - fullPrefix, - fullSuffix, - helper.lang, - ), + completeMultiline: await shouldCompleteMultiline(helper), snippets, }; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts new file mode 100644 index 000000000..cdf5f2bcd --- /dev/null +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -0,0 +1,85 @@ +import { IDE } from "../.."; +import { HelperVars } from "../HelperVars"; +import { findMatchingRange } from "../recentlyEdited"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { RootPathContextService } from "./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 retrieve( + prunedPrefix: string, + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + ) { + // Find external snippets + let snippets: AutocompleteSnippet[] = []; + + if (helper.options.useOtherFiles) { + snippets.push(...extraSnippets); + + if (helper.options.useRecentlyEdited) { + const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + if ( + currentLinePrefix?.length > + helper.options.recentLinePrefixMatchMinLength + ) { + const matchingRange = findMatchingRange( + helper.input.recentlyEditedRanges, + currentLinePrefix, + ); + if (matchingRange) { + snippets.push({ + ...matchingRange, + contents: matchingRange.lines.join("\n"), + score: 0.8, + }); + } + } + } + + // Use imports + if (helper.options.useImports) { + 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); + } + } + } + snippets.push(...importSnippets); + } + + if (helper.options.useRootPathContext && helper.treePath) { + const ctx = await this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); + snippets.push(...ctx); + } + } + + return snippets; + } +} diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 4809901cd..119056ca8 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,6 +1,7 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; +import { HelperVars } from "../../HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; @@ -43,8 +44,18 @@ export function jaccardSimilarity(a: string, b: string): number { */ export function rankSnippets( ranges: AutocompleteSnippet[], - windowAroundCursor: string, + helper: HelperVars, ): Required[] { + const windowAroundCursor = + helper.fullPrefix.slice( + -helper.options.slidingWindowSize * + helper.options.slidingWindowPrefixPercentage, + ) + + helper.fullSuffix.slice( + helper.options.slidingWindowSize * + (1 - helper.options.slidingWindowPrefixPercentage), + ); + const snippets: Required[] = ranges.map((snippet) => ({ score: snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor),