continue-custom/core/autocomplete/constructPrompt.ts
Nate Sesti 04c08c7159
dev (#1542)
* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
2024-06-28 16:21:36 -07:00

279 lines
7.7 KiB
TypeScript

import Parser from "web-tree-sitter";
import { RangeInFileWithContents } from "../commands/util.js";
import { TabAutocompleteOptions } from "../index.js";
import {
countTokens,
pruneLinesFromBottom,
pruneLinesFromTop,
} from "../llm/countTokens.js";
import { ImportDefinitionsService } from "./ImportDefinitionsService.js";
import { getAst, getTreePathAtCursor } from "./ast.js";
import {
AutocompleteLanguageInfo,
LANGUAGES,
Typescript,
} from "./languages.js";
import {
fillPromptWithSnippets,
getSymbolsForSnippet,
rankSnippets,
removeRangeFromSnippets,
type AutocompleteSnippet,
} from "./ranking.js";
import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js";
export function languageForFilepath(
filepath: string,
): AutocompleteLanguageInfo {
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
}
const BLOCK_TYPES = ["body", "statement_block"];
function shouldCompleteMultilineAst(
treePath: Parser.SyntaxNode[],
cursorLine: number,
): boolean {
// If at the base of the file, do multiline
if (treePath.length === 1) {
return true;
}
// If at the first line of an otherwise empty funtion body, do multiline
for (let i = treePath.length - 1; i >= 0; i--) {
const node = treePath[i];
if (
BLOCK_TYPES.includes(node.type) &&
Math.abs(node.startPosition.row - cursorLine) <= 1
) {
let text = node.text;
text = text.slice(text.indexOf("{") + 1);
text = text.slice(0, text.lastIndexOf("}"));
text = text.trim();
return text.split("\n").length === 1;
}
}
return false;
}
function isMidlineCompletion(prefix: string, suffix: string): boolean {
return !suffix.startsWith("\n");
}
async function shouldCompleteMultiline(
filepath: string,
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;
}
// First, if the line before ends with an opening bracket, then assume multi-line
if (
["{", "(", "["].includes(
fullPrefix.split("\n").slice(-2)[0]?.trim().slice(-1)[0],
)
) {
return true;
}
// Use AST to determine whether to complete multiline
let treePath: Parser.SyntaxNode[] | undefined;
try {
const ast = await getAst(filepath, fullPrefix + fullSuffix);
if (!ast) {
return true;
}
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
} catch (e) {
console.error("Failed to parse AST", e);
}
let completeMultiline = false;
if (treePath) {
const cursorLine = fullPrefix.split("\n").length - 1;
completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine);
}
return completeMultiline;
}
export async function constructAutocompletePrompt(
filepath: string,
cursorLine: number,
fullPrefix: string,
fullSuffix: string,
clipboardText: string,
language: AutocompleteLanguageInfo,
options: TabAutocompleteOptions,
recentlyEditedRanges: RecentlyEditedRange[],
recentlyEditedFiles: RangeInFileWithContents[],
modelName: string,
extraSnippets: AutocompleteSnippet[],
importDefinitionsService: ImportDefinitionsService,
): 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,
);
const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
// 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);
}
// 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(
filepath,
fullPrefix,
fullSuffix,
language,
),
snippets,
};
}