diff --git a/core/autocomplete/cache.ts b/core/autocomplete/cache.ts index d157b88da..bad86ca38 100644 --- a/core/autocomplete/cache.ts +++ b/core/autocomplete/cache.ts @@ -30,6 +30,8 @@ export class AutocompleteLruCache { } async get(prefix: string): Promise { + // NOTE: Right now prompts with different suffixes will be considered the same + // If the query is "co" and we have "c" -> "ontinue" in the cache, // we should return "ntinue" as the completion. // Have to make sure we take the key with shortest length diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index b75559a27..af4c69ae6 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -16,7 +16,7 @@ import { } from "../index.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { logDevData } from "../util/devdata.js"; -import { getBasename } from "../util/index.js"; +import { getBasename, getLastNPathParts } from "../util/index.js"; import { COUNT_COMPLETION_REJECTED_AFTER, DEFAULT_AUTOCOMPLETE_OPTS, @@ -108,7 +108,7 @@ function formatExternalSnippet( snippet: string, language: AutocompleteLanguageInfo, ) { - const comment = language.comment; + const comment = language.singleLineComment; const lines = [ `${comment} Path: ${getBasename(filepath)}`, ...snippet @@ -204,8 +204,8 @@ export async function getTabCompletion( if (input.injectDetails) { const lines = fullPrefix.split("\n"); fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ - lang.comment - } ${input.injectDetails.split("\n").join(`\n${lang.comment} `)}\n${ + lang.singleLineComment + } ${input.injectDetails.split("\n").join(`\n${lang.singleLineComment} `)}\n${ lines[lines.length - 1] }`; } @@ -270,13 +270,30 @@ export async function getTabCompletion( } // Template prompt - const { template, completionOptions } = options.template + 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); @@ -288,6 +305,9 @@ export async function getTabCompletion( .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({ @@ -321,7 +341,8 @@ export async function getTabCompletion( ...(llm.model.toLowerCase().includes("starcoder2") ? STARCODER2_T_ARTIFACTS : []), - ...lang.stopWords.map((word) => `\n${word}`), + ...(lang.stopWords ?? []), + ...lang.topLevelKeywords.map((word) => `\n${word}`), ]; const multiline = @@ -369,8 +390,16 @@ export async function getTabCompletion( let lineGenerator = streamLines(charGenerator); lineGenerator = stopAtLines(lineGenerator); lineGenerator = stopAtRepeatingLines(lineGenerator); - lineGenerator = avoidPathLine(lineGenerator, lang.comment); - lineGenerator = noTopLevelKeywordsMidline(lineGenerator, lang.stopWords); + lineGenerator = avoidPathLine(lineGenerator, lang.singleLineComment); + lineGenerator = noTopLevelKeywordsMidline( + lineGenerator, + lang.topLevelKeywords, + ); + + for (const lineFilter of lang.lineFilters ?? []) { + lineGenerator = lineFilter(lineGenerator); + } + lineGenerator = streamWithNewLines(lineGenerator); const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor); diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index f6df874ab..299554e0d 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -68,7 +68,7 @@ async function shouldCompleteMultiline( .split("\n") .slice(-1)[0] ?.trimStart() - .startsWith(language.comment) + .startsWith(language.singleLineComment) ) { return false; } diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index 6f15fd55a..1fa501354 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -1,13 +1,17 @@ +import { LineFilter } from "./lineStream"; + export interface AutocompleteLanguageInfo { - stopWords: string[]; - comment: string; + topLevelKeywords: string[]; + singleLineComment: string; endOfLine: string[]; + stopWords?: string[]; + lineFilters?: LineFilter[]; } // TypeScript export const Typescript = { - stopWords: ["function", "class", "module", "export", "import"], - comment: "//", + topLevelKeywords: ["function", "class", "module", "export", "import"], + singleLineComment: "//", endOfLine: [";"], }; @@ -15,63 +19,63 @@ export const Typescript = { export const Python = { // """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks. // This stops the model from trying to complete the start of a new markdown block - stopWords: ["def", "class", "\"\"\"#"], - comment: "#", + topLevelKeywords: ["def", "class", '"""#'], + singleLineComment: "#", endOfLine: [], }; // Java export const Java = { - stopWords: ["class", "function"], - comment: "//", + topLevelKeywords: ["class", "function"], + singleLineComment: "//", endOfLine: [";"], }; // C++ export const Cpp = { - stopWords: ["class", "namespace", "template"], - comment: "//", + topLevelKeywords: ["class", "namespace", "template"], + singleLineComment: "//", endOfLine: [";"], }; // C# export const CSharp = { - stopWords: ["class", "namespace", "void"], - comment: "//", + topLevelKeywords: ["class", "namespace", "void"], + singleLineComment: "//", endOfLine: [";"], }; // C export const C = { - stopWords: ["if", "else", "while", "for", "switch", "case"], - comment: "//", + topLevelKeywords: ["if", "else", "while", "for", "switch", "case"], + singleLineComment: "//", endOfLine: [";"], }; // Scala export const Scala = { - stopWords: ["def", "val", "var", "class", "object", "trait"], - comment: "//", + topLevelKeywords: ["def", "val", "var", "class", "object", "trait"], + singleLineComment: "//", endOfLine: [";"], }; // Go export const Go = { - stopWords: ["func", "package", "import", "type"], - comment: "//", + topLevelKeywords: ["func", "package", "import", "type"], + singleLineComment: "//", endOfLine: [], }; // Rust export const Rust = { - stopWords: ["fn", "mod", "pub", "struct", "enum", "trait"], - comment: "//", + topLevelKeywords: ["fn", "mod", "pub", "struct", "enum", "trait"], + singleLineComment: "//", endOfLine: [";"], }; // Haskell export const Haskell = { - stopWords: [ + topLevelKeywords: [ "data", "type", "newtype", @@ -81,55 +85,55 @@ export const Haskell = { "in", "where", ], - comment: "--", + singleLineComment: "--", endOfLine: [], }; // PHP export const PHP = { - stopWords: ["function", "class", "namespace", "use"], - comment: "//", + topLevelKeywords: ["function", "class", "namespace", "use"], + singleLineComment: "//", endOfLine: [";"], }; // Ruby on Rails export const RubyOnRails = { - stopWords: ["def", "class", "module"], - comment: "#", + topLevelKeywords: ["def", "class", "module"], + singleLineComment: "#", endOfLine: [], }; // Swift export const Swift = { - stopWords: ["func", "class", "struct", "import"], - comment: "//", + topLevelKeywords: ["func", "class", "struct", "import"], + singleLineComment: "//", endOfLine: [";"], }; // Kotlin export const Kotlin = { - stopWords: ["fun", "class", "package", "import"], - comment: "//", + topLevelKeywords: ["fun", "class", "package", "import"], + singleLineComment: "//", endOfLine: [";"], }; // Ruby export const Ruby = { - stopWords: ["class", "module", "def"], - comment: "#", + topLevelKeywords: ["class", "module", "def"], + singleLineComment: "#", endOfLine: [], }; // Clojure export const Clojure = { - stopWords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"], - comment: ";", + topLevelKeywords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"], + singleLineComment: ";", endOfLine: [], }; // Julia export const Julia = { - stopWords: [ + topLevelKeywords: [ "function", "macro", "if", @@ -141,13 +145,13 @@ export const Julia = { "end", "module", ], - comment: "#", + singleLineComment: "#", endOfLine: [";"], }; // F# export const FSharp = { - stopWords: [ + topLevelKeywords: [ "let", "type", "module", @@ -159,13 +163,13 @@ export const FSharp = { "match", "with", ], - comment: "//", + singleLineComment: "//", endOfLine: [], }; // R export const R = { - stopWords: [ + topLevelKeywords: [ "function", "if", "else", @@ -175,20 +179,20 @@ export const R = { "library", "require", ], - comment: "#", + singleLineComment: "#", endOfLine: [], }; // Dart export const Dart = { - stopWords: ["class", "import", "void", "enum"], - comment: "//", + topLevelKeywords: ["class", "import", "void", "enum"], + singleLineComment: "//", endOfLine: [";"], }; // Solidity export const Solidity = { - stopWords: [ + topLevelKeywords: [ "contract", "event", "modifier", @@ -204,10 +208,50 @@ export const Solidity = { "enum", "type", ], - comment: "//", + singleLineComment: "//", endOfLine: [";"], }; +// YAML +export const YAML: AutocompleteLanguageInfo = { + topLevelKeywords: [], + singleLineComment: "#", + endOfLine: [], + lineFilters: [ + // Only display one list item at a time + async function* (lines) { + let seenListItem = false; + for await (const line of lines) { + if (line.trim().startsWith("- ")) { + if (seenListItem) { + break; + } else { + seenListItem = true; + } + yield line; + } else { + yield line; + } + } + }, + // Don't allow consecutive lines of same key + async function* (lines) { + let lastKey = undefined; + for await (const line of lines) { + if (line.includes(":")) { + const key = line.split(":")[0]; + if (key !== lastKey) { + yield line; + lastKey = key; + } else { + break; + } + } + } + }, + ], +}; + export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, js: Typescript, @@ -245,4 +289,5 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { R: R, dart: Dart, sol: Solidity, + yaml: YAML, }; diff --git a/core/autocomplete/lineStream.ts b/core/autocomplete/lineStream.ts index 8abdc556c..b1f6c4618 100644 --- a/core/autocomplete/lineStream.ts +++ b/core/autocomplete/lineStream.ts @@ -2,6 +2,8 @@ import { distance } from "fastest-levenshtein"; import { LineStream } from "../diff/util.js"; import { DiffLine } from "../index.js"; +export type LineFilter = (stream: LineStream) => LineStream; + export async function* noTopLevelKeywordsMidline( lines: LineStream, topLevelKeywords: string[], diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 615ce7ad5..f53620103 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -1,10 +1,17 @@ // Fill in the middle prompts import { CompletionOptions } from "../index.js"; -import { shortestRelativePaths } from "../util/index.js"; +import { getLastNPathParts, shortestRelativePaths } from "../util/index.js"; import { AutocompleteSnippet } from "./ranking.js"; interface AutocompleteTemplate { + compilePrefixSuffix?: ( + prefix: string, + suffix: string, + filepath: string, + reponame: string, + snippets: AutocompleteSnippet[], + ) => [string, string]; template: | string | (( @@ -33,15 +40,18 @@ const codestralFimTemplate: AutocompleteTemplate = { }; const codestralMultifileFimTemplate: AutocompleteTemplate = { - template: ( + compilePrefixSuffix: ( prefix: string, suffix: string, filepath: string, reponame: string, snippets: AutocompleteSnippet[], - ): string => { + ): [string, string] => { if (snippets.length === 0) { - return `[SUFFIX]${suffix}[PREFIX]${prefix}`; + if (suffix.trim().length === 0 && prefix.trim().length === 0) { + return [`+++++ ${getLastNPathParts(filepath, 2)}\n${prefix}`, suffix]; + } + return [prefix, suffix]; } const relativePaths = shortestRelativePaths([ ...snippets.map((snippet) => snippet.filepath), @@ -50,8 +60,19 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { const otherFiles = snippets .map((snippet, i) => `+++++ ${relativePaths[i]}\n${snippet.contents}`) .join("\n\n"); - const prompt = `[SUFFIX]${suffix}[PREFIX]${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`; - return prompt; + return [ + `${otherFiles}\n\n+++++ ${relativePaths[relativePaths.length - 1]}\n${prefix}`, + suffix, + ]; + }, + template: ( + prefix: string, + suffix: string, + filepath: string, + reponame: string, + snippets: AutocompleteSnippet[], + ): string => { + return `[SUFFIX]${suffix}[PREFIX]${prefix}`; }, completionOptions: { stop: ["[PREFIX]", "[SUFFIX]"], diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index 76b8e6dbf..1b52116a0 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -28,7 +28,7 @@ function reformatCodeBlocks(msgText: string): string { codeBlockFenceRegex, (match, metadata, filename, extension) => { const lang = languageForFilepath(filename); - return `\`\`\`${extension}\n${lang.comment} ${metadata}\n`; + return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`; }, ); // Appease the markdown linter diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 643278386..11a6a01bb 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -8,7 +8,7 @@ import type { IndexTag, IndexingProgressUpdate, } from "../index.js"; -import { getBasename } from "../util/index.js"; +import { getBasename, getLastNPathParts } from "../util/index.js"; import { getLanguageForFile, getParserForFile, @@ -194,7 +194,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return { name: row.title, - description: getBasename(row.path, 2), + description: getLastNPathParts(row.path, 2), content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, }; } @@ -214,7 +214,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return rows.map((row) => ({ title: row.title, - description: getBasename(row.path, 2), + description: getLastNPathParts(row.path, 2), id: row.id.toString(), })); } catch (e) { diff --git a/core/util/index.ts b/core/util/index.ts index 3fbefb736..8d506d34f 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -91,7 +91,7 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] { const SEP_REGEX = /[\\/]/; -export function getBasename(filepath: string, n = 1): string { +export function getBasename(filepath: string): string { return filepath.split(SEP_REGEX).pop() ?? ""; } @@ -137,7 +137,10 @@ export function shortestRelativePaths(paths: string[]): string[] { currentRelativePaths.forEach((x, i) => { if (x === firstDuplicatedPath) { currentNumParts[i] += 1; - currentRelativePaths[i] = getBasename(paths[i], currentNumParts[i]); + currentRelativePaths[i] = getLastNPathParts( + paths[i], + currentNumParts[i], + ); } }); diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 8d410986a..02441e965 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -283,7 +283,9 @@ export async function getDefinitionsForNode( ranges.push({ ...classDef, contents: `${ - classNameNode?.text ? `${lang.comment} ${classNameNode.text}:\n` : "" + classNameNode?.text + ? `${lang.singleLineComment} ${classNameNode.text}:\n` + : "" }${contents.trim()}`, });