Merge branch 'preview'
This commit is contained in:
commit
e1f9ef6e78
272 changed files with 31245 additions and 10034 deletions
8
.changes/extensions/intellij/0.0.34.md
Normal file
8
.changes/extensions/intellij/0.0.34.md
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
## 0.0.34 - 2024-03-03
|
||||
### Added
|
||||
* diff context provider
|
||||
### Changed
|
||||
* Allow LLM servers to handle templating
|
||||
### Fixed
|
||||
* Fix a few context providers / slash commands
|
||||
* Fixed issues preventing proper extension startup
|
||||
10
.changes/extensions/vscode/0.8.14.md
Normal file
10
.changes/extensions/vscode/0.8.14.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
## 0.8.14 - 2024-03-03
|
||||
### Added
|
||||
* Image support
|
||||
* Full-text search index for retrieval
|
||||
* Docs context provider
|
||||
* CodeLlama-70b support
|
||||
### Changed
|
||||
* config.ts only runs in NodeJS, not browser
|
||||
### Fixed
|
||||
* Fixed proxy setting in config.json
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/intellij
|
||||
kind: Added
|
||||
body: diff context provider
|
||||
time: 2023-12-29T10:58:15.432508-05:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Image support
|
||||
time: 2024-01-24T22:29:04.193864-08:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Full-text search index for retrieval
|
||||
time: 2024-01-29T21:05:50.216548-08:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Docs context provider
|
||||
time: 2024-01-30T12:31:43.521306-08:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: CodeLlama-70b support
|
||||
time: 2024-01-30T13:03:32.287428-08:00
|
||||
4
.changes/unreleased/Added-20240303-190039.yaml
Normal file
4
.changes/unreleased/Added-20240303-190039.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Tab-autocomplete in beta
|
||||
time: 2024-03-03T19:00:39.909292-05:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/intellij
|
||||
kind: Changed
|
||||
body: Allow LLM servers to handle templating
|
||||
time: 2024-01-03T11:33:41.535094-05:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: config.ts only runs in NodeJS, not browser
|
||||
time: 2024-02-03T16:33:43.006333-08:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/intellij
|
||||
kind: Fixed
|
||||
body: Fix a few context providers / slash commands
|
||||
time: 2024-01-03T01:52:17.592331-05:00
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
project: extensions/vscode
|
||||
kind: Fixed
|
||||
body: Fixed proxy setting in config.json
|
||||
time: 2024-01-30T13:03:15.8294-08:00
|
||||
4
.prettierrc
Normal file
4
.prettierrc
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
}
|
||||
12
.vscode/launch.json
vendored
12
.vscode/launch.json
vendored
|
|
@ -5,6 +5,18 @@
|
|||
"version": "0.2.0",
|
||||
"compounds": [],
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Core Binary",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"program": "${workspaceFolder}/pkg/out/index.js",
|
||||
"preLaunchTask": "pkg:esbuild",
|
||||
"outFiles": ["${workspaceFolder}/pkg/out/**/*.js"],
|
||||
"sourceMaps": true,
|
||||
"smartStep": true,
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
|
|
|
|||
22
.vscode/tasks.json
vendored
22
.vscode/tasks.json
vendored
|
|
@ -22,8 +22,9 @@
|
|||
{
|
||||
"label": "vscode-extension:esbuild",
|
||||
"type": "npm",
|
||||
"script": "esbuild",
|
||||
"script": "esbuild-watch",
|
||||
"path": "extensions/vscode",
|
||||
"isBackground": true,
|
||||
"problemMatcher": [
|
||||
{
|
||||
"pattern": [
|
||||
|
|
@ -35,7 +36,12 @@
|
|||
"severity": 4,
|
||||
"message": 5
|
||||
}
|
||||
]
|
||||
],
|
||||
"background": {
|
||||
"activeOnStart": true,
|
||||
"beginsPattern": ">",
|
||||
"endsPattern": ">"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
|
@ -136,6 +142,18 @@
|
|||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
//
|
||||
// esbuild for the core binary
|
||||
{
|
||||
"label": "pkg:esbuild",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "esbuild"],
|
||||
"problemMatcher": [],
|
||||
"options": {
|
||||
"cwd": "pkg"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
89
core/autocomplete/ast.ts
Normal file
89
core/autocomplete/ast.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { getParserForFile } from "../util/treeSitter";
|
||||
|
||||
export async function getAst(
|
||||
filepath: string,
|
||||
fileContents: string,
|
||||
): Promise<Parser.Tree | undefined> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
|
||||
if (!parser) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ast = parser.parse(fileContents);
|
||||
return ast;
|
||||
}
|
||||
|
||||
export async function getTreePathAtCursor(
|
||||
ast: Parser.Tree,
|
||||
cursorIndex: number,
|
||||
): Promise<Parser.SyntaxNode[] | undefined> {
|
||||
const path = [ast.rootNode];
|
||||
while (path[path.length - 1].childCount > 0) {
|
||||
let foundChild = false;
|
||||
for (let child of path[path.length - 1].children) {
|
||||
if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) {
|
||||
path.push(child);
|
||||
foundChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundChild) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
export async function getScopeAroundRange(
|
||||
range: RangeInFileWithContents,
|
||||
): Promise<RangeInFileWithContents | undefined> {
|
||||
const ast = await getAst(range.filepath, range.contents);
|
||||
if (!ast) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { start: s, end: e } = range.range;
|
||||
const lines = range.contents.split("\n");
|
||||
const startIndex =
|
||||
lines.slice(0, s.line).join("\n").length +
|
||||
(lines[s.line]?.slice(s.character).length ?? 0);
|
||||
const endIndex =
|
||||
lines.slice(0, e.line).join("\n").length +
|
||||
(lines[e.line]?.slice(0, e.character).length ?? 0);
|
||||
|
||||
let node = ast.rootNode;
|
||||
while (node.childCount > 0) {
|
||||
let foundChild = false;
|
||||
for (let child of node.children) {
|
||||
if (child.startIndex < startIndex && child.endIndex > endIndex) {
|
||||
node = child;
|
||||
foundChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundChild) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
contents: node.text,
|
||||
filepath: range.filepath,
|
||||
range: {
|
||||
start: {
|
||||
line: node.startPosition.row,
|
||||
character: node.startPosition.column,
|
||||
},
|
||||
end: {
|
||||
line: node.endPosition.row,
|
||||
character: node.endPosition.column,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -32,14 +32,14 @@ export class AutocompleteLruCache {
|
|||
async get(key: string): Promise<string | undefined> {
|
||||
const result = await this.db.get(
|
||||
"SELECT value FROM cache WHERE key = ?",
|
||||
key
|
||||
key,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET timestamp = ? WHERE key = ?",
|
||||
Date.now(),
|
||||
key
|
||||
key,
|
||||
);
|
||||
return result.value;
|
||||
}
|
||||
|
|
@ -50,7 +50,7 @@ export class AutocompleteLruCache {
|
|||
async put(key: string, value: string) {
|
||||
const result = await this.db.get(
|
||||
"SELECT key FROM cache WHERE key = ?",
|
||||
key
|
||||
key,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
|
|
@ -58,14 +58,14 @@ export class AutocompleteLruCache {
|
|||
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
|
||||
value,
|
||||
Date.now(),
|
||||
key
|
||||
key,
|
||||
);
|
||||
} else {
|
||||
const count = await this.db.get("SELECT COUNT(*) as count FROM cache");
|
||||
|
||||
if (count.count >= AutocompleteLruCache.capacity) {
|
||||
await this.db.run(
|
||||
"DELETE FROM cache WHERE key = (SELECT key FROM cache ORDER BY timestamp ASC LIMIT 1)"
|
||||
"DELETE FROM cache WHERE key = (SELECT key FROM cache ORDER BY timestamp ASC LIMIT 1)",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -73,7 +73,7 @@ export class AutocompleteLruCache {
|
|||
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
|
||||
key,
|
||||
value,
|
||||
Date.now()
|
||||
Date.now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,16 @@
|
|||
export async function* onlyWhitespaceAfterEndOfLine(
|
||||
stream: AsyncGenerator<string>,
|
||||
endOfLine: string[]
|
||||
endOfLine: string[],
|
||||
): AsyncGenerator<string> {
|
||||
let pending = "";
|
||||
for await (let chunk of stream) {
|
||||
chunk = pending + chunk;
|
||||
pending = "";
|
||||
for (let i = 0; i < chunk.length - 1; i++) {
|
||||
if (endOfLine.includes(chunk[i]) && chunk[i + 1] === " ") {
|
||||
if (
|
||||
endOfLine.includes(chunk[i]) &&
|
||||
chunk[i + 1].trim() === chunk[i + 1]
|
||||
) {
|
||||
yield chunk.slice(0, i + 1);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,25 @@
|
|||
import Parser from "web-tree-sitter";
|
||||
import { TabAutocompleteOptions } from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
} from "../llm/countTokens";
|
||||
import { getBasename } from "../util";
|
||||
import { getParserForFile } from "../util/treeSitter";
|
||||
|
||||
import { getAst, getTreePathAtCursor } from "./ast";
|
||||
import { AutocompleteLanguageInfo, LANGUAGES, Typescript } from "./languages";
|
||||
import {
|
||||
AutocompleteSnippet,
|
||||
fillPromptWithSnippets,
|
||||
rankSnippets,
|
||||
removeRangeFromSnippets,
|
||||
} from "./ranking";
|
||||
import { slidingWindowMatcher } from "./slidingWindow";
|
||||
|
||||
export function languageForFilepath(
|
||||
filepath: string
|
||||
filepath: string,
|
||||
): AutocompleteLanguageInfo {
|
||||
return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript;
|
||||
}
|
||||
|
|
@ -18,120 +27,188 @@ export function languageForFilepath(
|
|||
function formatExternalSnippet(
|
||||
filepath: string,
|
||||
snippet: string,
|
||||
language: AutocompleteLanguageInfo
|
||||
language: AutocompleteLanguageInfo,
|
||||
) {
|
||||
const comment = language.comment;
|
||||
const lines = [
|
||||
comment + " Path: " + getBasename(filepath),
|
||||
...snippet.split("\n").map((line) => comment + " " + line),
|
||||
...snippet
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => comment + " " + line),
|
||||
comment,
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function getTreePathAtCursor(
|
||||
filepath: string,
|
||||
fileContents: string,
|
||||
cursorIndex: number
|
||||
): Promise<Parser.SyntaxNode[] | undefined> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
const BLOCK_TYPES = ["body", "statement_block"];
|
||||
|
||||
if (!parser) {
|
||||
return undefined;
|
||||
function shouldCompleteMultilineAst(
|
||||
treePath: Parser.SyntaxNode[],
|
||||
cursorLine: number,
|
||||
): boolean {
|
||||
// If at the base of the file, do multiline
|
||||
if (treePath.length === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ast = parser.parse(fileContents);
|
||||
const path = [ast.rootNode];
|
||||
while (path[path.length - 1].childCount > 0) {
|
||||
let foundChild = false;
|
||||
for (let child of path[path.length - 1].children) {
|
||||
if (child.startIndex <= cursorIndex && child.endIndex >= cursorIndex) {
|
||||
path.push(child);
|
||||
foundChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!foundChild) {
|
||||
break;
|
||||
// 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 path;
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface AutocompleteSnippet {
|
||||
filepath: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export async function constructAutocompletePrompt(
|
||||
async function shouldCompleteMultiline(
|
||||
filepath: string,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
clipboardText: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
getDefinition: (
|
||||
filepath: string,
|
||||
line: number,
|
||||
character: number
|
||||
) => Promise<AutocompleteSnippet | undefined>,
|
||||
options: TabAutocompleteOptions
|
||||
): Promise<{ prefix: string; suffix: string; useFim: boolean }> {
|
||||
// Find external snippets
|
||||
const snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
let treePath;
|
||||
): Promise<boolean> {
|
||||
// Use AST to determine whether to complete multiline
|
||||
let treePath: Parser.SyntaxNode[] | undefined;
|
||||
try {
|
||||
treePath = await getTreePathAtCursor(
|
||||
filepath,
|
||||
fullPrefix + fullSuffix,
|
||||
fullPrefix.length
|
||||
);
|
||||
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);
|
||||
}
|
||||
|
||||
// Get function def when inside call expression
|
||||
let completeMultiline = false;
|
||||
if (treePath) {
|
||||
let callExpression = undefined;
|
||||
for (let node of treePath.reverse()) {
|
||||
if (node.type === "call_expression") {
|
||||
callExpression = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (callExpression) {
|
||||
const definition = await getDefinition(
|
||||
filepath,
|
||||
callExpression.startPosition.row,
|
||||
callExpression.startPosition.column
|
||||
);
|
||||
if (definition) {
|
||||
snippets.push(definition);
|
||||
}
|
||||
}
|
||||
let cursorLine = fullPrefix.split("\n").length - 1;
|
||||
completeMultiline = shouldCompleteMultilineAst(treePath, cursorLine);
|
||||
}
|
||||
return completeMultiline;
|
||||
}
|
||||
|
||||
// Construct basic prefix / suffix
|
||||
const formattedSnippets = snippets
|
||||
export async function constructAutocompletePrompt(
|
||||
filepath: string,
|
||||
cursorLine: number,
|
||||
fullPrefix: string,
|
||||
fullSuffix: string,
|
||||
clipboardText: string,
|
||||
language: AutocompleteLanguageInfo,
|
||||
options: TabAutocompleteOptions,
|
||||
recentlyEditedRanges: RangeInFileWithContents[],
|
||||
recentlyEditedDocuments: RangeInFileWithContents[],
|
||||
modelName: string,
|
||||
extraSnippets: AutocompleteSnippet[],
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
useFim: boolean;
|
||||
completeMultiline: boolean;
|
||||
}> {
|
||||
// Find external snippets
|
||||
let snippets: RangeInFileWithContents[] = extraSnippets;
|
||||
|
||||
const windowAroundCursor =
|
||||
fullPrefix.slice(
|
||||
-options.slidingWindowSize * options.slidingWindowPrefixPercentage,
|
||||
) +
|
||||
fullSuffix.slice(
|
||||
options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage),
|
||||
);
|
||||
|
||||
const slidingWindowMatches = await slidingWindowMatcher(
|
||||
recentlyEditedDocuments,
|
||||
windowAroundCursor,
|
||||
3,
|
||||
options.slidingWindowSize,
|
||||
);
|
||||
snippets.push(...slidingWindowMatches);
|
||||
|
||||
const recentlyEdited = (
|
||||
await Promise.all(
|
||||
recentlyEditedRanges.map(async (r) => {
|
||||
return r;
|
||||
// return await getScopeAroundRange(r);
|
||||
}),
|
||||
)
|
||||
).filter((s) => !!s);
|
||||
snippets.push(...(recentlyEdited as any));
|
||||
|
||||
// Rank / order the snippets
|
||||
const scoredSnippets = rankSnippets(snippets, windowAroundCursor);
|
||||
|
||||
// Fill maxSnippetTokens with snippets
|
||||
const maxSnippetTokens =
|
||||
options.maxPromptTokens * options.maxSnippetPercentage;
|
||||
|
||||
// Construct basic prefix
|
||||
const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage;
|
||||
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
|
||||
|
||||
// Construct suffix
|
||||
const maxSuffixTokens = Math.min(
|
||||
options.maxPromptTokens - countTokens(prefix, modelName),
|
||||
options.maxSuffixPercentage * options.maxPromptTokens,
|
||||
);
|
||||
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
|
||||
|
||||
// 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,
|
||||
);
|
||||
|
||||
// Format snippets as comments and prepend to prefix
|
||||
const formattedSnippets = finalSnippets
|
||||
.map((snippet) =>
|
||||
formatExternalSnippet(snippet.filepath, snippet.content, language)
|
||||
formatExternalSnippet(snippet.filepath, snippet.contents, language),
|
||||
)
|
||||
.join("\n");
|
||||
const maxPrefixTokens =
|
||||
options.maxPromptTokens * options.prefixPercentage -
|
||||
countTokens(formattedSnippets, "gpt-4");
|
||||
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens);
|
||||
if (formattedSnippets.length > 0) {
|
||||
prefix = formattedSnippets + "\n" + prefix;
|
||||
prefix = formattedSnippets + "\n\n" + prefix;
|
||||
}
|
||||
|
||||
const maxSuffixTokens = Math.min(
|
||||
options.maxPromptTokens - countTokens(prefix, "gpt-4"),
|
||||
options.maxSuffixPercentage * options.maxPromptTokens
|
||||
);
|
||||
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens);
|
||||
|
||||
return { prefix, suffix, useFim: true };
|
||||
return {
|
||||
prefix,
|
||||
suffix,
|
||||
useFim: true,
|
||||
completeMultiline: await shouldCompleteMultiline(
|
||||
filepath,
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export const Scala = {
|
|||
export const Go = {
|
||||
stopWords: ["func", "package", "import", "type"],
|
||||
comment: "//",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Rust
|
||||
|
|
@ -69,9 +69,18 @@ export const Rust = {
|
|||
|
||||
// Haskell
|
||||
export const Haskell = {
|
||||
stopWords: ["data", "type", "newtype", "class", "instance", "let", "in", "where"],
|
||||
stopWords: [
|
||||
"data",
|
||||
"type",
|
||||
"newtype",
|
||||
"class",
|
||||
"instance",
|
||||
"let",
|
||||
"in",
|
||||
"where",
|
||||
],
|
||||
comment: "--",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// PHP
|
||||
|
|
@ -85,7 +94,7 @@ export const PHP = {
|
|||
export const RubyOnRails = {
|
||||
stopWords: ["def", "class", "module"],
|
||||
comment: "#",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Swift
|
||||
|
|
@ -106,35 +115,66 @@ export const Kotlin = {
|
|||
export const Ruby = {
|
||||
stopWords: ["class", "module", "def"],
|
||||
comment: "#",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Clojure
|
||||
export const Clojure = {
|
||||
stopWords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"],
|
||||
comment: ";",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Julia
|
||||
export const Julia = {
|
||||
stopWords: ["function", "macro", "if", "else", "elseif", "while", "for", "begin", "end", "module"],
|
||||
stopWords: [
|
||||
"function",
|
||||
"macro",
|
||||
"if",
|
||||
"else",
|
||||
"elseif",
|
||||
"while",
|
||||
"for",
|
||||
"begin",
|
||||
"end",
|
||||
"module",
|
||||
],
|
||||
comment: "#",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// F#
|
||||
export const FSharp = {
|
||||
stopWords: ["let", "type", "module", "namespace", "open", "if", "then", "else", "match", "with"],
|
||||
stopWords: [
|
||||
"let",
|
||||
"type",
|
||||
"module",
|
||||
"namespace",
|
||||
"open",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"match",
|
||||
"with",
|
||||
],
|
||||
comment: "//",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// R
|
||||
export const R = {
|
||||
stopWords: ["function", "if", "else", "for", "while", "repeat", "library", "require"],
|
||||
stopWords: [
|
||||
"function",
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"repeat",
|
||||
"library",
|
||||
"require",
|
||||
],
|
||||
comment: "#",
|
||||
endOfLine: [""],
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Dart
|
||||
|
|
@ -154,7 +194,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
java: Java,
|
||||
cpp: Cpp,
|
||||
cxx: Cpp,
|
||||
h: Cpp,
|
||||
h: Cpp,
|
||||
hpp: Cpp,
|
||||
cs: CSharp,
|
||||
c: C,
|
||||
|
|
@ -172,11 +212,11 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
cljs: Clojure,
|
||||
cljc: Clojure,
|
||||
jl: Julia,
|
||||
fs: FSharp,
|
||||
fsi: FSharp,
|
||||
fsx: FSharp,
|
||||
fs: FSharp,
|
||||
fsi: FSharp,
|
||||
fsx: FSharp,
|
||||
fsscript: FSharp,
|
||||
r: R,
|
||||
R: R,
|
||||
dart: Dart,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,20 @@ import { distance } from "fastest-levenshtein";
|
|||
import { DiffLine } from "..";
|
||||
import { LineStream } from "../diff/util";
|
||||
|
||||
export async function* avoidPathLine(
|
||||
stream: LineStream,
|
||||
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) {
|
||||
if (line.startsWith(comment + " Path: ")) {
|
||||
continue;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
export async function* streamWithNewLines(stream: LineStream): LineStream {
|
||||
let firstLine = true;
|
||||
for await (const nextLine of stream) {
|
||||
|
|
@ -18,7 +32,7 @@ const bracketsReverse = [")", "]", "}", "`", '"""'];
|
|||
|
||||
export async function* stopAtSimilarLine(
|
||||
stream: LineStream,
|
||||
line: string
|
||||
line: string,
|
||||
): AsyncGenerator<string> {
|
||||
line = line.trim();
|
||||
for await (const nextLine of stream) {
|
||||
|
|
@ -39,6 +53,17 @@ export async function* stopAtSimilarLine(
|
|||
}
|
||||
}
|
||||
|
||||
const LINES_TO_STOP_AT = ["# End of file."];
|
||||
|
||||
export async function* stopAtLines(stream: LineStream): LineStream {
|
||||
for await (const line of stream) {
|
||||
if (LINES_TO_STOP_AT.includes(line)) {
|
||||
break;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
|
||||
function shouldRemoveLineBeforeStart(line: string): boolean {
|
||||
return (
|
||||
line.trimStart().startsWith("```") ||
|
||||
|
|
@ -171,7 +196,7 @@ function isUselessLine(line: string): boolean {
|
|||
}
|
||||
|
||||
export async function* filterLeadingAndTrailingNewLineInsertion(
|
||||
diffLines: AsyncGenerator<DiffLine>
|
||||
diffLines: AsyncGenerator<DiffLine>,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
let isFirst = true;
|
||||
let buffer: DiffLine[] = [];
|
||||
|
|
@ -198,3 +223,28 @@ export async function* filterLeadingAndTrailingNewLineInsertion(
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function* stopAtRepeatingLines(lines: LineStream): LineStream {
|
||||
const repeatedLines: string[] = [];
|
||||
for await (const line of lines) {
|
||||
if (repeatedLines.length === 0) {
|
||||
repeatedLines.push(line);
|
||||
} else if (repeatedLines.length < 3) {
|
||||
if (repeatedLines[repeatedLines.length - 1] === line) {
|
||||
repeatedLines.push(line);
|
||||
} else {
|
||||
while (repeatedLines.length > 0) {
|
||||
yield repeatedLines.shift()!;
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
} else {
|
||||
yield repeatedLines[0];
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
while (repeatedLines.length > 0) {
|
||||
yield repeatedLines.shift()!;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,15 @@ import { TabAutocompleteOptions } from "..";
|
|||
export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
||||
useCopyBuffer: true,
|
||||
useSuffix: true,
|
||||
maxPromptTokens: 650,
|
||||
maxPromptTokens: 500,
|
||||
prefixPercentage: 0.85,
|
||||
maxSuffixPercentage: 0.25,
|
||||
debounceDelay: 350,
|
||||
multilineCompletions: "auto",
|
||||
slidingWindowPrefixPercentage: 0.75,
|
||||
slidingWindowSize: 500,
|
||||
maxSnippetPercentage: 0.6,
|
||||
recentlyEditedSimilarityThreshold: 0.3,
|
||||
useCache: true,
|
||||
onlyMyCode: true,
|
||||
};
|
||||
|
|
|
|||
242
core/autocomplete/ranking.ts
Normal file
242
core/autocomplete/ranking.ts
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
import { Range } from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { countTokens } from "../llm/countTokens";
|
||||
|
||||
export type AutocompleteSnippet = RangeInFileWithContents & {
|
||||
score: number;
|
||||
};
|
||||
|
||||
const rx = /[\s.,\/#!$%\^&\*;:{}=\-_`~()\[\]]/g;
|
||||
function getSymbolsForSnippet(snippet: string): Set<string> {
|
||||
const symbols = snippet
|
||||
.split(rx)
|
||||
.map((s) => s.trim())
|
||||
.filter((s) => s !== "");
|
||||
return new Set(symbols);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate similarity as number of shared symbols divided by total number of unique symbols between both.
|
||||
*/
|
||||
export function jaccardSimilarity(a: string, b: string): number {
|
||||
const aSet = getSymbolsForSnippet(a);
|
||||
const bSet = getSymbolsForSnippet(b);
|
||||
const union = new Set([...aSet, ...bSet]).size;
|
||||
|
||||
// Avoid division by zero
|
||||
if (union === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let intersection = 0;
|
||||
for (const symbol of aSet) {
|
||||
if (bSet.has(symbol)) {
|
||||
intersection++;
|
||||
}
|
||||
}
|
||||
|
||||
return intersection / union;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array.
|
||||
*/
|
||||
export function rankSnippets(
|
||||
ranges: RangeInFileWithContents[],
|
||||
windowAroundCursor: string,
|
||||
): AutocompleteSnippet[] {
|
||||
const snippets = ranges.map((snippet) => ({
|
||||
score: jaccardSimilarity(snippet.contents, windowAroundCursor),
|
||||
...snippet,
|
||||
}));
|
||||
const uniqueSnippets = deduplicateSnippets(snippets);
|
||||
return uniqueSnippets.sort((a, b) => a.score - b.score);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deduplicate code snippets by merging overlapping ranges into a single range.
|
||||
*/
|
||||
export function deduplicateSnippets(
|
||||
snippets: AutocompleteSnippet[],
|
||||
): AutocompleteSnippet[] {
|
||||
// Group by file
|
||||
const fileGroups: { [key: string]: AutocompleteSnippet[] } = {};
|
||||
for (const snippet of snippets) {
|
||||
if (!fileGroups[snippet.filepath]) {
|
||||
fileGroups[snippet.filepath] = [];
|
||||
}
|
||||
fileGroups[snippet.filepath].push(snippet);
|
||||
}
|
||||
|
||||
// Merge overlapping ranges
|
||||
const allRanges = [];
|
||||
for (const file of Object.keys(fileGroups)) {
|
||||
allRanges.push(...mergeSnippetsByRange(fileGroups[file]));
|
||||
}
|
||||
return allRanges;
|
||||
}
|
||||
|
||||
function mergeSnippetsByRange(
|
||||
snippets: AutocompleteSnippet[],
|
||||
): AutocompleteSnippet[] {
|
||||
if (snippets.length === 0) {
|
||||
return snippets;
|
||||
}
|
||||
|
||||
const sorted = snippets.sort(
|
||||
(a, b) => a.range.start.line - b.range.start.line,
|
||||
);
|
||||
const merged: AutocompleteSnippet[] = [];
|
||||
|
||||
while (sorted.length > 0) {
|
||||
const next = sorted.shift()!;
|
||||
const last = merged[merged.length - 1];
|
||||
if (merged.length > 0 && last.range.end.line >= next.range.start.line) {
|
||||
// Merge with previous snippet
|
||||
last.score = Math.max(last.score, next.score);
|
||||
try {
|
||||
last.range.end = next.range.end;
|
||||
} catch (e) {
|
||||
console.log("Error merging ranges", e);
|
||||
}
|
||||
last.contents = mergeOverlappingRangeContents(last, next);
|
||||
} else {
|
||||
merged.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
return merged;
|
||||
}
|
||||
|
||||
function mergeOverlappingRangeContents(
|
||||
first: RangeInFileWithContents,
|
||||
second: RangeInFileWithContents,
|
||||
): string {
|
||||
const firstLines = first.contents.split("\n");
|
||||
const numOverlapping = first.range.end.line - second.range.start.line;
|
||||
return firstLines.slice(-numOverlapping).join("\n") + "\n" + second.contents;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill the allowed space with snippets
|
||||
*/
|
||||
export function fillPromptWithSnippets(
|
||||
snippets: AutocompleteSnippet[],
|
||||
maxSnippetTokens: number,
|
||||
modelName: string,
|
||||
): AutocompleteSnippet[] {
|
||||
let tokensRemaining = maxSnippetTokens;
|
||||
const keptSnippets: AutocompleteSnippet[] = [];
|
||||
for (let i = 0; i < snippets.length; i++) {
|
||||
const snippet = snippets[i];
|
||||
const tokenCount = countTokens(snippet.contents, modelName);
|
||||
if (tokensRemaining - tokenCount >= 0) {
|
||||
tokensRemaining -= tokenCount;
|
||||
keptSnippets.push(snippet);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return keptSnippets;
|
||||
}
|
||||
|
||||
function rangeIntersectionByLines(a: Range, b: Range): Range | null {
|
||||
const startLine = Math.max(a.start.line, b.start.line);
|
||||
const endLine = Math.min(a.end.line, b.end.line);
|
||||
if (startLine >= endLine) {
|
||||
return null;
|
||||
} else {
|
||||
return {
|
||||
start: {
|
||||
line: startLine,
|
||||
character: 0,
|
||||
},
|
||||
end: {
|
||||
line: endLine,
|
||||
character: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove one range from another range, which may lead to returning two disjoint ranges
|
||||
*/
|
||||
function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
|
||||
if (
|
||||
orig.start.line >= remove.start.line &&
|
||||
orig.end.line <= remove.end.line
|
||||
) {
|
||||
// / | | /
|
||||
return [];
|
||||
} else if (
|
||||
orig.start.line <= remove.start.line &&
|
||||
orig.end.line >= remove.end.line
|
||||
) {
|
||||
// | / / |
|
||||
// Splits the range
|
||||
return [
|
||||
{
|
||||
start: orig.start,
|
||||
end: remove.start,
|
||||
},
|
||||
{
|
||||
start: remove.end,
|
||||
end: orig.end,
|
||||
},
|
||||
];
|
||||
} else if (
|
||||
orig.start.line >= remove.start.line &&
|
||||
orig.end.line >= remove.end.line
|
||||
) {
|
||||
// \ | / |
|
||||
return [
|
||||
{
|
||||
start: remove.end,
|
||||
end: orig.end,
|
||||
},
|
||||
];
|
||||
} else if (
|
||||
orig.start.line <= remove.start.line &&
|
||||
orig.end.line <= remove.end.line
|
||||
) {
|
||||
// | / | /
|
||||
return [
|
||||
{
|
||||
start: orig.start,
|
||||
end: remove.start,
|
||||
},
|
||||
];
|
||||
} else {
|
||||
return [orig];
|
||||
}
|
||||
}
|
||||
|
||||
export function removeRangeFromSnippets(
|
||||
snippets: AutocompleteSnippet[],
|
||||
filepath: string,
|
||||
range: Range,
|
||||
): AutocompleteSnippet[] {
|
||||
const finalSnippets: AutocompleteSnippet[] = [];
|
||||
for (let snippet of snippets) {
|
||||
if (snippet.filepath !== filepath) {
|
||||
finalSnippets.push(snippet);
|
||||
continue;
|
||||
}
|
||||
|
||||
const intersection = rangeIntersectionByLines(range, snippet.range);
|
||||
if (!intersection) {
|
||||
finalSnippets.push(snippet);
|
||||
} else {
|
||||
finalSnippets.push(
|
||||
...rangeDifferenceByLines(snippet.range, intersection).map((range) => ({
|
||||
...snippet,
|
||||
range,
|
||||
})),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return finalSnippets;
|
||||
}
|
||||
5
core/autocomplete/recentlyEdited.ts
Normal file
5
core/autocomplete/recentlyEdited.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
import { RangeInFileWithContents } from "../commands/util";
|
||||
|
||||
export type RecentlyEditedRange = RangeInFileWithContents & {
|
||||
timestamp: number;
|
||||
};
|
||||
24
core/autocomplete/retrieval.ts
Normal file
24
core/autocomplete/retrieval.ts
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { Chunk } from "..";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
|
||||
import { IndexTag } from "../indexing/types";
|
||||
|
||||
export async function fullTextRetrieve(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
indexTag: IndexTag,
|
||||
): 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;
|
||||
}
|
||||
59
core/autocomplete/slidingWindow.ts
Normal file
59
core/autocomplete/slidingWindow.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { AutocompleteSnippet, jaccardSimilarity } from "./ranking";
|
||||
|
||||
function* slidingWindow(
|
||||
content: string,
|
||||
windowSize: number,
|
||||
): Generator<string> {
|
||||
const lines = content.split("\n");
|
||||
|
||||
let charCount = 0;
|
||||
let currWindowLines: string[] = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (charCount + lines[i].length >= windowSize) {
|
||||
yield currWindowLines.join("\n");
|
||||
currWindowLines = [lines[i]];
|
||||
charCount = 0;
|
||||
} else {
|
||||
currWindowLines.push(lines[i]);
|
||||
}
|
||||
charCount += lines[i].length;
|
||||
}
|
||||
|
||||
if (currWindowLines.length > 0) {
|
||||
yield currWindowLines.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Match by similarity over sliding windows of recent documents.
|
||||
* @param recentDocuments
|
||||
* @param prefix
|
||||
* @param suffix
|
||||
*/
|
||||
export async function slidingWindowMatcher(
|
||||
recentDocuments: RangeInFileWithContents[],
|
||||
windowAroundCursor: string,
|
||||
topN: number,
|
||||
windowSize: number,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
// Sorted lowest similarity to highest
|
||||
const topMatches: AutocompleteSnippet[] = [];
|
||||
|
||||
for (const { filepath, contents, range } of recentDocuments) {
|
||||
for (const window of slidingWindow(contents, windowSize)) {
|
||||
const score = jaccardSimilarity(window, windowAroundCursor);
|
||||
|
||||
// Insertion sort
|
||||
let i = -1;
|
||||
while (++i < topMatches.length && score > topMatches[i].score) {}
|
||||
topMatches.splice(i + 1, 0, { filepath, contents, score, range });
|
||||
if (topMatches.length > topN) {
|
||||
topMatches.shift();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: convert the arbitrary window frame to some whole AST node?
|
||||
return topMatches;
|
||||
}
|
||||
|
|
@ -17,7 +17,7 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
|
|||
|
||||
const codeLlamaFimTemplate: AutocompleteTemplate = {
|
||||
template: "<PRE> {{{prefix}}} <SUF>{{{suffix}}} <MID>",
|
||||
completionOptions: { stop: ["<PRE>", "<SUF>", "<MID>"] },
|
||||
completionOptions: { stop: ["<PRE>", "<SUF>", "<MID>", "<EOT>"] },
|
||||
};
|
||||
|
||||
// https://huggingface.co/deepseek-ai/deepseek-coder-1.3b-base
|
||||
|
|
|
|||
137
core/autocomplete/util.ts
Normal file
137
core/autocomplete/util.ts
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
export class ListenableGenerator<T> {
|
||||
private _source: AsyncGenerator<T>;
|
||||
private _buffer: T[] = [];
|
||||
private _listeners: Set<(value: T) => void> = new Set();
|
||||
private _isEnded: boolean = 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 {
|
||||
for (const value of this._buffer) {
|
||||
yield value;
|
||||
}
|
||||
while (!this._isEnded) {
|
||||
let resolve: (value: any) => void;
|
||||
let promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
this._listeners.add(resolve!);
|
||||
});
|
||||
const value = await promise;
|
||||
this._listeners.delete(resolve!);
|
||||
|
||||
yield value;
|
||||
}
|
||||
} finally {
|
||||
// this._listeners.delete(resolve!);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class GeneratorReuseManager {
|
||||
currentGenerator: ListenableGenerator<string> | undefined;
|
||||
pendingGeneratorPrefix: string | undefined;
|
||||
pendingCompletion: string = "";
|
||||
|
||||
constructor(private readonly onError: (err: any) => void) {}
|
||||
|
||||
private _createListenableGenerator(
|
||||
gen: AsyncGenerator<string>,
|
||||
prefix: string,
|
||||
) {
|
||||
this.currentGenerator?.cancel();
|
||||
|
||||
const listenableGen = new ListenableGenerator(gen, this.onError);
|
||||
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
|
||||
|
||||
this.pendingGeneratorPrefix = prefix;
|
||||
this.pendingCompletion = "";
|
||||
this.currentGenerator = listenableGen;
|
||||
}
|
||||
|
||||
async *getGenerator(
|
||||
prefix: string,
|
||||
newGenerator: () => AsyncGenerator<string>,
|
||||
multiline: boolean,
|
||||
): AsyncGenerator<string> {
|
||||
// Check if current can be reused
|
||||
if (
|
||||
!(
|
||||
this.currentGenerator &&
|
||||
this.pendingGeneratorPrefix &&
|
||||
(this.pendingGeneratorPrefix + this.pendingCompletion).startsWith(
|
||||
prefix,
|
||||
) &&
|
||||
// for e.g. backspace
|
||||
this.pendingGeneratorPrefix?.length <= prefix?.length
|
||||
)
|
||||
) {
|
||||
// Create a wrapper over the current generator to fix the prompt
|
||||
this._createListenableGenerator(newGenerator(), prefix);
|
||||
}
|
||||
|
||||
let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || "";
|
||||
for await (let chunk of this.currentGenerator!.tee()) {
|
||||
if (!chunk) {
|
||||
continue;
|
||||
}
|
||||
while (chunk.length && alreadyTyped.length) {
|
||||
if (chunk[0] === alreadyTyped[0]) {
|
||||
alreadyTyped = alreadyTyped.slice(1);
|
||||
chunk = chunk.slice(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const newLineIndex = chunk.indexOf("\n");
|
||||
if (multiline || newLineIndex === -1) {
|
||||
yield chunk;
|
||||
} else {
|
||||
yield chunk.slice(0, newLineIndex);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import { stripImages } from "../llm/countTokens";
|
|||
import SlashCommands from "./slash";
|
||||
|
||||
export function slashFromCustomCommand(
|
||||
customCommand: CustomCommand
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommand {
|
||||
return {
|
||||
name: customCommand.name,
|
||||
|
|
@ -30,7 +30,7 @@ export function slashFromCustomCommand(
|
|||
}
|
||||
|
||||
export function slashCommandFromDescription(
|
||||
desc: SlashCommandDescription
|
||||
desc: SlashCommandDescription,
|
||||
): SlashCommand | undefined {
|
||||
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
|
||||
if (!cmd) {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { removeQuotesAndEscapes } from "../../util";
|
|||
|
||||
const PROMPT = (
|
||||
input: string,
|
||||
title: string
|
||||
title: string,
|
||||
) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules:
|
||||
- Be descriptive but do not make up details
|
||||
- If the the user request includes any code snippets that are relevant, reference them in code blocks
|
||||
|
|
@ -31,7 +31,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
}
|
||||
let title = await llm.complete(
|
||||
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
|
||||
{ maxTokens: 20 }
|
||||
{ maxTokens: 20 },
|
||||
);
|
||||
|
||||
title = removeQuotesAndEscapes(title.trim()) + "\n\n";
|
||||
|
|
@ -49,7 +49,7 @@ const DraftIssueCommand: SlashCommand = {
|
|||
}
|
||||
|
||||
const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(
|
||||
title
|
||||
title,
|
||||
)}&body=${encodeURIComponent(body)}`;
|
||||
yield `\n\n[Link to draft of issue](${url})`;
|
||||
},
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ export async function getPromptParts(
|
|||
fullFileContents: string,
|
||||
model: ILLM,
|
||||
input: string,
|
||||
tokenLimit: number | undefined
|
||||
tokenLimit: number | undefined,
|
||||
) {
|
||||
let maxTokens = Math.floor(model.contextLength / 2);
|
||||
|
||||
|
|
@ -119,7 +119,7 @@ export async function getPromptParts(
|
|||
fileSuffix = lastLine + fileSuffix;
|
||||
rif.contents = rif.contents.substring(
|
||||
0,
|
||||
rif.contents.length - lastLine.length
|
||||
rif.contents.length - lastLine.length,
|
||||
);
|
||||
lines = rif.contents.split(/\r?\n/);
|
||||
lastLine = lines[lines.length - 1] || null;
|
||||
|
|
@ -141,7 +141,7 @@ function compilePrompt(
|
|||
filePrefix: string,
|
||||
contents: string,
|
||||
fileSuffix: string,
|
||||
input: string
|
||||
input: string,
|
||||
): string {
|
||||
if (contents.trim() == "") {
|
||||
// Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file
|
||||
|
|
@ -216,11 +216,11 @@ const EditSlashCommand: SlashCommand = {
|
|||
run: async function* ({ ide, llm, input, history, contextItems, params }) {
|
||||
let contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) =>
|
||||
item.editing && item.id.providerTitle === "code"
|
||||
item.editing && item.id.providerTitle === "code",
|
||||
);
|
||||
if (!contextItemToEdit) {
|
||||
contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) => item.id.providerTitle === "code"
|
||||
(item: ContextItemWithId) => item.id.providerTitle === "code",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -230,13 +230,18 @@ const EditSlashCommand: SlashCommand = {
|
|||
}
|
||||
|
||||
// Strip unecessary parts of the input (the fact that you have to do this is suboptimal, should be refactored away)
|
||||
input = input.replace(
|
||||
`\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`,
|
||||
""
|
||||
);
|
||||
if (input.startsWith("/edit")) {
|
||||
input = input.replace("/edit", "").trimStart();
|
||||
let content = history[history.length - 1].content;
|
||||
if (typeof content !== "string") {
|
||||
content.forEach((part) => {
|
||||
if (part.text && part.text.startsWith("/edit")) {
|
||||
part.text = part.text.replace("/edit", "").trimStart();
|
||||
}
|
||||
});
|
||||
}
|
||||
let userInput = stripImages(content).replace(
|
||||
`\`\`\`${contextItemToEdit.name}\n${contextItemToEdit.content}\n\`\`\`\n`,
|
||||
"",
|
||||
);
|
||||
|
||||
const rif: RangeInFileWithContents =
|
||||
contextItemToRangeInFileWithContents(contextItemToEdit);
|
||||
|
|
@ -248,18 +253,18 @@ const EditSlashCommand: SlashCommand = {
|
|||
rif,
|
||||
fullFileContents,
|
||||
llm,
|
||||
input,
|
||||
params?.tokenLimit
|
||||
userInput,
|
||||
params?.tokenLimit,
|
||||
);
|
||||
const [dedentedContents, commonWhitespace] =
|
||||
dedentAndGetCommonWhitespace(contents);
|
||||
contents = dedentedContents;
|
||||
|
||||
let prompt = compilePrompt(filePrefix, contents, fileSuffix, input);
|
||||
let prompt = compilePrompt(filePrefix, contents, fileSuffix, userInput);
|
||||
let fullFileContentsLines = fullFileContents.split("\n");
|
||||
let fullPrefixLines = fullFileContentsLines.slice(
|
||||
0,
|
||||
Math.max(0, rif.range.start.line - 1)
|
||||
Math.max(0, rif.range.start.line - 1),
|
||||
);
|
||||
let fullSuffixLines = fullFileContentsLines.slice(rif.range.end.line);
|
||||
|
||||
|
|
@ -421,14 +426,14 @@ const EditSlashCommand: SlashCommand = {
|
|||
|
||||
// Make sure they are sorted by index
|
||||
indicesOfLastMatchedLines = indicesOfLastMatchedLines.sort(
|
||||
(a, b) => a[0] - b[0]
|
||||
(a, b) => a[0] - b[0],
|
||||
);
|
||||
|
||||
currentBlockLines.push(line);
|
||||
}
|
||||
|
||||
let messages = history;
|
||||
messages.push({ role: "user", content: prompt });
|
||||
messages[messages.length - 1] = { role: "user", content: prompt };
|
||||
|
||||
let linesOfPrefixCopied = 0;
|
||||
let lines = [];
|
||||
|
|
@ -447,12 +452,12 @@ const EditSlashCommand: SlashCommand = {
|
|||
messages.slice(0, messages.length - 1),
|
||||
{
|
||||
codeToEdit: rif.contents,
|
||||
userInput: input,
|
||||
userInput,
|
||||
filePrefix: filePrefix,
|
||||
fileSuffix: fileSuffix,
|
||||
systemMessage: llm.systemMessage || "",
|
||||
// "contextItems": (await sdk.getContextItemChatMessages()).map(x => x.content || "").join("\n\n"),
|
||||
}
|
||||
},
|
||||
);
|
||||
if (typeof rendered === "string") {
|
||||
messages = [
|
||||
|
|
@ -476,7 +481,7 @@ const EditSlashCommand: SlashCommand = {
|
|||
lineStream = filterEnglishLinesAtEnd(filterCodeBlockLines(lineStream));
|
||||
|
||||
generator = streamWithNewLines(
|
||||
fixCodeLlamaFirstLineIndentation(lineStream)
|
||||
fixCodeLlamaFirstLineIndentation(lineStream),
|
||||
);
|
||||
} else {
|
||||
async function* gen() {
|
||||
|
|
@ -485,7 +490,7 @@ const EditSlashCommand: SlashCommand = {
|
|||
maxTokens: Math.min(
|
||||
maxTokens,
|
||||
Math.floor(llm.contextLength / 2),
|
||||
4096
|
||||
4096,
|
||||
),
|
||||
})) {
|
||||
yield stripImages(chunk.content);
|
||||
|
|
@ -562,7 +567,7 @@ const EditSlashCommand: SlashCommand = {
|
|||
unfinishedLine?.startsWith("<")
|
||||
? commonWhitespace
|
||||
: commonWhitespace + unfinishedLine,
|
||||
])
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import EditSlashCommand from "./edit";
|
|||
import HttpSlashCommand from "./http";
|
||||
import ShareSlashCommand from "./share";
|
||||
import StackOverflowSlashCommand from "./stackOverflow";
|
||||
import VerticalEditSlashCommand from "./verticalEdit";
|
||||
|
||||
export default [
|
||||
DraftIssueCommand,
|
||||
|
|
@ -17,5 +16,4 @@ export default [
|
|||
CommentSlashCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
VerticalEditSlashCommand,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { pruneStringFromBottom, stripImages } from "../../llm/countTokens";
|
|||
|
||||
const SERVER_URL = "https://proxy-server-l6vsfbzhba-uw.a.run.app";
|
||||
const PROMPT = (
|
||||
input: string
|
||||
input: string,
|
||||
) => `The above sources are excerpts from related StackOverflow questions. Use them to help answer the below question from our user. Provide links to the sources in markdown whenever possible:
|
||||
|
||||
${input}
|
||||
|
|
@ -82,7 +82,7 @@ const StackOverflowSlashCommand: SlashCommand = {
|
|||
sources[sources.length - 1] = pruneStringFromBottom(
|
||||
llm.model,
|
||||
contextLength - (totalTokens - newTokens),
|
||||
sources[sources.length - 1]
|
||||
sources[sources.length - 1],
|
||||
);
|
||||
shouldBreak = true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,124 +0,0 @@
|
|||
import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../..";
|
||||
import {
|
||||
filterCodeBlockLines,
|
||||
filterEnglishLinesAtEnd,
|
||||
filterEnglishLinesAtStart,
|
||||
filterLeadingAndTrailingNewLineInsertion,
|
||||
fixCodeLlamaFirstLineIndentation,
|
||||
} from "../../autocomplete/lineStream";
|
||||
import { streamDiff } from "../../diff/streamDiff";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { stripImages } from "../../llm/countTokens";
|
||||
import { gptEditPrompt } from "../../llm/templates/edit";
|
||||
import {
|
||||
dedentAndGetCommonWhitespace,
|
||||
getMarkdownLanguageTagForFile,
|
||||
renderPromptTemplate,
|
||||
} from "../../util";
|
||||
import {
|
||||
RangeInFileWithContents,
|
||||
contextItemToRangeInFileWithContents,
|
||||
} from "../util";
|
||||
|
||||
function constructPrompt(
|
||||
codeToEdit: string,
|
||||
llm: ILLM,
|
||||
userInput: string,
|
||||
language: string | undefined
|
||||
): string {
|
||||
const template = llm.promptTemplates?.edit ?? gptEditPrompt;
|
||||
const rendered = renderPromptTemplate(template, [], {
|
||||
userInput,
|
||||
codeToEdit,
|
||||
language: language || "",
|
||||
});
|
||||
return typeof rendered === "string"
|
||||
? rendered
|
||||
: stripImages(rendered[rendered.length - 1].content);
|
||||
}
|
||||
|
||||
async function* addIndentation(
|
||||
diffLineGenerator: AsyncGenerator<DiffLine>,
|
||||
indentation: string
|
||||
): AsyncGenerator<DiffLine> {
|
||||
for await (const diffLine of diffLineGenerator) {
|
||||
yield {
|
||||
...diffLine,
|
||||
line: indentation + diffLine.line,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function modelIsInept(model: string): boolean {
|
||||
return !(model.includes("gpt") || model.includes("claude"));
|
||||
}
|
||||
|
||||
export async function* streamDiffLines(
|
||||
oldCode: string,
|
||||
llm: ILLM,
|
||||
input: string,
|
||||
language: string | undefined
|
||||
): AsyncGenerator<DiffLine> {
|
||||
// Strip common indentation for the LLM, then add back after generation
|
||||
const [withoutIndentation, commonIndentation] =
|
||||
dedentAndGetCommonWhitespace(oldCode);
|
||||
oldCode = withoutIndentation;
|
||||
const oldLines = oldCode.split("\n");
|
||||
const prompt = constructPrompt(oldCode, llm, input, language);
|
||||
const inept = modelIsInept(llm.model);
|
||||
|
||||
const completion = llm.streamComplete(prompt);
|
||||
|
||||
let lines = streamLines(completion);
|
||||
|
||||
if (inept) {
|
||||
lines = filterEnglishLinesAtStart(lines);
|
||||
}
|
||||
lines = filterCodeBlockLines(lines);
|
||||
if (inept) {
|
||||
lines = filterEnglishLinesAtEnd(fixCodeLlamaFirstLineIndentation(lines));
|
||||
}
|
||||
|
||||
let diffLines = streamDiff(oldLines, lines);
|
||||
diffLines = addIndentation(diffLines, commonIndentation);
|
||||
diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines);
|
||||
|
||||
for await (let diffLine of diffLines) {
|
||||
yield diffLine;
|
||||
}
|
||||
}
|
||||
|
||||
const VerticalEditSlashCommand: SlashCommand = {
|
||||
name: "verticalEdit",
|
||||
description: "Edit selected code with vertical diff",
|
||||
run: async function* ({ ide, llm, input, contextItems }) {
|
||||
const contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) =>
|
||||
item.editing && item.id.providerTitle === "code"
|
||||
);
|
||||
|
||||
if (!contextItemToEdit) {
|
||||
yield "Highlight the code that you want to edit first";
|
||||
return;
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents =
|
||||
contextItemToRangeInFileWithContents(contextItemToEdit);
|
||||
const startLine = rif.range.start.line;
|
||||
const endLine = rif.range.end.line;
|
||||
const filepath = rif.filepath;
|
||||
|
||||
const diffLineGenerator = streamDiffLines(
|
||||
rif.contents,
|
||||
llm,
|
||||
input,
|
||||
getMarkdownLanguageTagForFile(rif.filepath)
|
||||
);
|
||||
|
||||
for await (const diffLine of diffLineGenerator) {
|
||||
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default VerticalEditSlashCommand;
|
||||
|
|
@ -10,7 +10,7 @@ export interface RangeInFileWithContents {
|
|||
}
|
||||
|
||||
export function contextItemToRangeInFileWithContents(
|
||||
item: ContextItemWithId
|
||||
item: ContextItemWithId,
|
||||
): RangeInFileWithContents {
|
||||
const lines = item.name.split("(")[1].split(")")[0].split("-");
|
||||
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { SerializedContinueConfig } from "..";
|
||||
|
||||
const defaultConfig: SerializedContinueConfig = {
|
||||
export const defaultConfig: SerializedContinueConfig = {
|
||||
models: [
|
||||
{
|
||||
title: "GPT-4 (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4",
|
||||
},
|
||||
{
|
||||
title: "GPT-4 Vision (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4-vision-preview",
|
||||
},
|
||||
{
|
||||
title: "GPT-3.5-Turbo (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
title: "Gemini Pro (Free Trial)",
|
||||
provider: "free-trial",
|
||||
|
|
@ -34,7 +34,7 @@ const defaultConfig: SerializedContinueConfig = {
|
|||
},
|
||||
{
|
||||
name: "share",
|
||||
description: "Download and share this session",
|
||||
description: "Export this session as markdown",
|
||||
},
|
||||
{
|
||||
name: "cmd",
|
||||
|
|
@ -59,6 +59,62 @@ const defaultConfig: SerializedContinueConfig = {
|
|||
{ name: "problems", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder 3b",
|
||||
provider: "ollama",
|
||||
model: "starcoder-3b",
|
||||
},
|
||||
};
|
||||
|
||||
export default defaultConfig;
|
||||
export const defaultConfigJetBrains: SerializedContinueConfig = {
|
||||
models: [
|
||||
{
|
||||
title: "GPT-4 Vision (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4-vision-preview",
|
||||
},
|
||||
{
|
||||
title: "GPT-3.5-Turbo (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
title: "Gemini Pro (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gemini-pro",
|
||||
},
|
||||
{
|
||||
title: "Codellama 70b (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "codellama-70b",
|
||||
},
|
||||
],
|
||||
slashCommands: [
|
||||
{
|
||||
name: "edit",
|
||||
description: "Edit selected code",
|
||||
},
|
||||
{
|
||||
name: "comment",
|
||||
description: "Write comments for the selected code",
|
||||
},
|
||||
{
|
||||
name: "share",
|
||||
description: "Export this session as markdown",
|
||||
},
|
||||
],
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
contextProviders: [
|
||||
{
|
||||
name: "open",
|
||||
params: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
200
core/config/handler.ts
Normal file
200
core/config/handler.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
import { http, https } from "follow-redirects";
|
||||
import * as fs from "fs";
|
||||
import { HttpProxyAgent } from "http-proxy-agent";
|
||||
import { HttpsProxyAgent } from "https-proxy-agent";
|
||||
import fetch from "node-fetch";
|
||||
import { ContinueConfig, ContinueRcJson, IDE, ILLM } from "..";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
finalToBrowserConfig,
|
||||
loadFullConfigNode,
|
||||
} from "./load";
|
||||
const tls = require("tls");
|
||||
export class ConfigHandler {
|
||||
private savedConfig: ContinueConfig | undefined;
|
||||
private savedBrowserConfig?: BrowserSerializedContinueConfig;
|
||||
|
||||
private readonly ide: IDE;
|
||||
private readonly remoteConfigServerUrl: URL | undefined;
|
||||
private readonly writeLog: (text: string) => void;
|
||||
private readonly onConfigUpdate: () => void;
|
||||
constructor(
|
||||
ide: IDE,
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
writeLog: (text: string) => void,
|
||||
onConfigUpdate: () => void,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.remoteConfigServerUrl = remoteConfigServerUrl;
|
||||
this.writeLog = writeLog;
|
||||
this.onConfigUpdate = onConfigUpdate;
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig() {
|
||||
this.savedConfig = undefined;
|
||||
this.savedBrowserConfig = undefined;
|
||||
this.loadConfig();
|
||||
this.onConfigUpdate();
|
||||
}
|
||||
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
if (!this.savedBrowserConfig) {
|
||||
this.savedConfig = await this.loadConfig();
|
||||
this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig);
|
||||
}
|
||||
return this.savedBrowserConfig;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ContinueConfig> {
|
||||
try {
|
||||
if (this.savedConfig) {
|
||||
return this.savedConfig;
|
||||
}
|
||||
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
try {
|
||||
workspaceConfigs = await this.ide.getWorkspaceConfigs();
|
||||
} catch (e) {
|
||||
console.warn("Failed to load workspace configs");
|
||||
}
|
||||
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
this.savedConfig = await loadFullConfigNode(
|
||||
this.ide.readFile,
|
||||
workspaceConfigs,
|
||||
this.remoteConfigServerUrl,
|
||||
ideInfo.ideType,
|
||||
);
|
||||
this.savedConfig.allowAnonymousTelemetry =
|
||||
this.savedConfig.allowAnonymousTelemetry &&
|
||||
(await this.ide.isTelemetryEnabled());
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
this.savedConfig.allowAnonymousTelemetry ?? true,
|
||||
await this.ide.getUniqueId(),
|
||||
);
|
||||
|
||||
return this.savedConfig;
|
||||
} catch (e: any) {
|
||||
console.error("Failed to loadConfig: ", e.message);
|
||||
throw new Error("Failed to loadConfig: " + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
setupLlm(llm: ILLM): ILLM {
|
||||
const TIMEOUT = 7200; // 7200 seconds = 2 hours
|
||||
// Since we know this is happening in Node.js, we can add requestOptions through a custom agent
|
||||
const ca = [...tls.rootCertificates];
|
||||
const customCerts =
|
||||
typeof llm.requestOptions?.caBundlePath === "string"
|
||||
? [llm.requestOptions?.caBundlePath]
|
||||
: llm.requestOptions?.caBundlePath;
|
||||
if (customCerts) {
|
||||
ca.push(
|
||||
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")),
|
||||
);
|
||||
}
|
||||
|
||||
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
|
||||
|
||||
const agentOptions = {
|
||||
ca,
|
||||
rejectUnauthorized: llm.requestOptions?.verifySsl,
|
||||
timeout,
|
||||
sessionTimeout: timeout,
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: timeout,
|
||||
};
|
||||
|
||||
const proxy = llm.requestOptions?.proxy;
|
||||
|
||||
llm._fetch = async (input, init) => {
|
||||
// Create agent
|
||||
const protocol = new URL(input).protocol === "https:" ? https : http;
|
||||
const agent = proxy
|
||||
? new URL(input).protocol === "https:"
|
||||
? new HttpsProxyAgent(proxy, agentOptions)
|
||||
: new HttpProxyAgent(proxy, agentOptions)
|
||||
: new protocol.Agent(agentOptions);
|
||||
|
||||
const headers: { [key: string]: string } =
|
||||
llm!.requestOptions?.headers || {};
|
||||
for (const [key, value] of Object.entries(init?.headers || {})) {
|
||||
headers[key] = value as string;
|
||||
}
|
||||
|
||||
// Replace localhost with 127.0.0.1
|
||||
input = new URL(input);
|
||||
if (input.hostname === "localhost") {
|
||||
input.hostname = "127.0.0.1";
|
||||
}
|
||||
|
||||
let updatedBody: string | undefined = undefined;
|
||||
try {
|
||||
if (
|
||||
llm.requestOptions?.extraBodyProperties &&
|
||||
typeof init.body === "string"
|
||||
) {
|
||||
const parsedBody = JSON.parse(init.body);
|
||||
updatedBody = JSON.stringify({
|
||||
...parsedBody,
|
||||
...llm.requestOptions.extraBodyProperties,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Unable to parse HTTP request body: ", e);
|
||||
}
|
||||
|
||||
const resp = await fetch(input, {
|
||||
...init,
|
||||
body: updatedBody ?? init.body,
|
||||
headers,
|
||||
agent,
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
let text = await resp.text();
|
||||
if (resp.status === 404 && !resp.url.includes("/v1")) {
|
||||
if (text.includes("try pulling it first")) {
|
||||
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
|
||||
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
|
||||
} else if (text.includes("/api/chat")) {
|
||||
text =
|
||||
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
|
||||
} else {
|
||||
text =
|
||||
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
|
||||
);
|
||||
}
|
||||
|
||||
return resp;
|
||||
};
|
||||
|
||||
llm.writeLog = async (log: string) => {
|
||||
this.writeLog(log);
|
||||
};
|
||||
return llm;
|
||||
}
|
||||
|
||||
async llmFromTitle(title?: string): Promise<ILLM> {
|
||||
const config = await this.loadConfig();
|
||||
const model =
|
||||
config.models.find((m) => m.title === title) || config.models[0];
|
||||
if (!model) {
|
||||
throw new Error("No model found");
|
||||
}
|
||||
|
||||
return this.setupLlm(model);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
import {
|
||||
BaseCompletionOptions,
|
||||
BrowserSerializedContinueConfig,
|
||||
Config,
|
||||
ContextProviderDescription,
|
||||
ContextProviderWithParams,
|
||||
ContinueConfig,
|
||||
ContinueRcJson,
|
||||
|
|
@ -10,12 +10,11 @@ import {
|
|||
CustomLLM,
|
||||
EmbeddingsProviderDescription,
|
||||
IContextProvider,
|
||||
IdeType,
|
||||
ModelDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
SlashCommandDescription,
|
||||
} from "..";
|
||||
|
||||
import {
|
||||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
|
|
@ -28,35 +27,57 @@ import TransformersJsEmbeddingsProvider from "../indexing/embeddings/Transformer
|
|||
import { BaseLLM } from "../llm";
|
||||
import { llmFromDescription } from "../llm/llms";
|
||||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import { copyOf } from "../util";
|
||||
import mergeJson from "../util/merge";
|
||||
import {
|
||||
getConfigJsPath,
|
||||
getConfigJsPathForRemote,
|
||||
getConfigJsonPath,
|
||||
getConfigJsonPathForRemote,
|
||||
getConfigTsPath,
|
||||
getContinueDotEnv,
|
||||
migrate,
|
||||
} from "../util/paths";
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
|
||||
let content = fs.readFileSync(filepath, "utf8");
|
||||
let config = JSON.parse(content) as SerializedContinueConfig;
|
||||
if (config.env && Array.isArray(config.env)) {
|
||||
const env = {
|
||||
...process.env,
|
||||
...getContinueDotEnv(),
|
||||
};
|
||||
|
||||
config.env.forEach((envVar) => {
|
||||
content = content.replaceAll(
|
||||
new RegExp(`"${envVar}"`, "g"),
|
||||
`"${env[envVar]}"`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
const configMergeKeys = {
|
||||
models: (a: any, b: any) => a.title === b.title,
|
||||
contextProviders: (a: any, b: any) => a.name === b.name,
|
||||
slashCommands: (a: any, b: any) => a.name === b.name,
|
||||
customCommands: (a: any, b: any) => a.name === b.name,
|
||||
};
|
||||
|
||||
function loadSerializedConfig(
|
||||
workspaceConfigs: ContinueRcJson[]
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
ideType: IdeType,
|
||||
): SerializedContinueConfig {
|
||||
const configPath = getConfigJsonPath();
|
||||
let contents = fs.readFileSync(configPath, "utf8");
|
||||
let config = JSON.parse(contents) as SerializedContinueConfig;
|
||||
const configPath = getConfigJsonPath(ideType);
|
||||
let config = resolveSerializedConfig(configPath);
|
||||
if (config.allowAnonymousTelemetry === undefined) {
|
||||
config.allowAnonymousTelemetry = true;
|
||||
}
|
||||
|
||||
// Migrate to camelCase - replace all instances of "snake_case" with "camelCase"
|
||||
migrate("camelCaseConfig", () => {
|
||||
contents = contents
|
||||
.replace(/(_\w)/g, function (m) {
|
||||
return m[1].toUpperCase();
|
||||
})
|
||||
.replace("openai-aiohttp", "openai");
|
||||
|
||||
fs.writeFileSync(configPath, contents, "utf8");
|
||||
});
|
||||
|
||||
migrate("codebaseContextProvider", () => {
|
||||
if (
|
||||
!config.contextProviders?.filter((cp) => cp.name === "codebase")?.length
|
||||
|
|
@ -111,20 +132,27 @@ function loadSerializedConfig(
|
|||
fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8");
|
||||
});
|
||||
|
||||
migrate("renameFreeTrialProvider", () => {
|
||||
contents = contents.replace(/openai-free-trial/g, "free-trial");
|
||||
fs.writeFileSync(configPath, contents, "utf8");
|
||||
});
|
||||
if (remoteConfigServerUrl) {
|
||||
const remoteConfigJson = resolveSerializedConfig(
|
||||
getConfigJsonPathForRemote(remoteConfigServerUrl),
|
||||
);
|
||||
config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys);
|
||||
}
|
||||
|
||||
for (const workspaceConfig of workspaceConfigs) {
|
||||
config = mergeJson(config, workspaceConfig, workspaceConfig.mergeBehavior);
|
||||
config = mergeJson(
|
||||
config,
|
||||
workspaceConfig,
|
||||
workspaceConfig.mergeBehavior,
|
||||
configMergeKeys,
|
||||
);
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
function serializedToIntermediateConfig(
|
||||
initial: SerializedContinueConfig
|
||||
initial: SerializedContinueConfig,
|
||||
): Config {
|
||||
const slashCommands: SlashCommand[] = [];
|
||||
for (const command of initial.slashCommands || []) {
|
||||
|
|
@ -147,13 +175,13 @@ function serializedToIntermediateConfig(
|
|||
}
|
||||
|
||||
function isModelDescription(
|
||||
llm: ModelDescription | CustomLLM
|
||||
llm: ModelDescription | CustomLLM,
|
||||
): llm is ModelDescription {
|
||||
return (llm as ModelDescription).title !== undefined;
|
||||
}
|
||||
|
||||
function isContextProviderWithParams(
|
||||
contextProvider: CustomContextProvider | ContextProviderWithParams
|
||||
contextProvider: CustomContextProvider | ContextProviderWithParams,
|
||||
): contextProvider is ContextProviderWithParams {
|
||||
return (contextProvider as ContextProviderWithParams).name !== undefined;
|
||||
}
|
||||
|
|
@ -161,7 +189,7 @@ function isContextProviderWithParams(
|
|||
/** Only difference between intermediate and final configs is the `models` array */
|
||||
async function intermediateToFinalConfig(
|
||||
config: Config,
|
||||
readFile: (filepath: string) => Promise<string>
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
): Promise<ContinueConfig> {
|
||||
const models: BaseLLM[] = [];
|
||||
for (const desc of config.models) {
|
||||
|
|
@ -170,7 +198,7 @@ async function intermediateToFinalConfig(
|
|||
desc,
|
||||
readFile,
|
||||
config.completionOptions,
|
||||
config.systemMessage
|
||||
config.systemMessage,
|
||||
);
|
||||
if (!llm) continue;
|
||||
|
||||
|
|
@ -186,15 +214,15 @@ async function intermediateToFinalConfig(
|
|||
title: llm.title + " - " + modelName,
|
||||
},
|
||||
readFile,
|
||||
config.completionOptions,
|
||||
config.systemMessage
|
||||
copyOf(config.completionOptions),
|
||||
config.systemMessage,
|
||||
);
|
||||
})
|
||||
}),
|
||||
);
|
||||
models.push(
|
||||
...(detectedModels.filter(
|
||||
(x) => typeof x !== "undefined"
|
||||
) as BaseLLM[])
|
||||
(x) => typeof x !== "undefined",
|
||||
) as BaseLLM[]),
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn("Error listing models: ", e);
|
||||
|
|
@ -212,7 +240,7 @@ async function intermediateToFinalConfig(
|
|||
new CustomLLMClass({
|
||||
...desc,
|
||||
options: { ...desc.options, model: modelName },
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
models.push(...models);
|
||||
|
|
@ -232,7 +260,7 @@ async function intermediateToFinalConfig(
|
|||
config.tabAutocompleteModel,
|
||||
readFile,
|
||||
config.completionOptions,
|
||||
config.systemMessage
|
||||
config.systemMessage,
|
||||
);
|
||||
} else {
|
||||
autocompleteLlm = new CustomLLMClass(config.tabAutocompleteModel);
|
||||
|
|
@ -275,21 +303,8 @@ async function intermediateToFinalConfig(
|
|||
};
|
||||
}
|
||||
|
||||
interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
slashCommands?: SlashCommandDescription[];
|
||||
contextProviders?: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: string;
|
||||
}
|
||||
|
||||
function finalToBrowserConfig(
|
||||
final: ContinueConfig
|
||||
final: ContinueConfig,
|
||||
): BrowserSerializedContinueConfig {
|
||||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
|
|
@ -321,49 +336,101 @@ function finalToBrowserConfig(
|
|||
};
|
||||
}
|
||||
|
||||
async function buildConfigTs(browser: boolean) {
|
||||
function getTarget() {
|
||||
const os =
|
||||
{
|
||||
aix: "linux",
|
||||
darwin: "darwin",
|
||||
freebsd: "linux",
|
||||
linux: "linux",
|
||||
openbsd: "linux",
|
||||
sunos: "linux",
|
||||
win32: "win32",
|
||||
}[process.platform as string] ?? "linux";
|
||||
const arch = {
|
||||
arm: "arm64",
|
||||
arm64: "arm64",
|
||||
ia32: "x64",
|
||||
loong64: "arm64",
|
||||
mips: "arm64",
|
||||
mipsel: "arm64",
|
||||
ppc: "x64",
|
||||
ppc64: "x64",
|
||||
riscv64: "arm64",
|
||||
s390: "x64",
|
||||
s390x: "x64",
|
||||
x64: "x64",
|
||||
}[process.arch];
|
||||
|
||||
return `${os}-${arch}`;
|
||||
}
|
||||
|
||||
function escapeSpacesInPath(p: string): string {
|
||||
return p.replace(/ /g, "\\ ");
|
||||
}
|
||||
|
||||
async function buildConfigTs() {
|
||||
if (!fs.existsSync(getConfigTsPath())) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
if (process.env.IS_BINARY === "true") {
|
||||
execSync(
|
||||
escapeSpacesInPath(path.dirname(process.execPath)) +
|
||||
`/esbuild${
|
||||
getTarget().startsWith("win32") ? ".exe" : ""
|
||||
} ${escapeSpacesInPath(
|
||||
getConfigTsPath(),
|
||||
)} --bundle --outfile=${escapeSpacesInPath(
|
||||
getConfigJsPath(),
|
||||
)} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`,
|
||||
);
|
||||
} else {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
bundle: true,
|
||||
platform: browser ? "browser" : "node",
|
||||
format: browser ? "esm" : "cjs",
|
||||
outfile: getConfigJsPath(!browser),
|
||||
external: ["fetch", "fs", "path", "os", "child_process"],
|
||||
sourcemap: true,
|
||||
});
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
format: "cjs",
|
||||
outfile: getConfigJsPath(),
|
||||
external: ["fetch", "fs", "path", "os", "child_process"],
|
||||
sourcemap: true,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
"Build error. Please check your ~/.continue/config.ts file: " + e
|
||||
console.log(
|
||||
"Build error. Please check your ~/.continue/config.ts file: " + e,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(getConfigJsPath(!browser))) {
|
||||
if (!fs.existsSync(getConfigJsPath())) {
|
||||
return undefined;
|
||||
}
|
||||
return fs.readFileSync(getConfigJsPath(!browser), "utf8");
|
||||
return fs.readFileSync(getConfigJsPath(), "utf8");
|
||||
}
|
||||
|
||||
async function loadFullConfigNode(
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
workspaceConfigs: ContinueRcJson[]
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
ideType: IdeType,
|
||||
): Promise<ContinueConfig> {
|
||||
let serialized = loadSerializedConfig(workspaceConfigs);
|
||||
let serialized = loadSerializedConfig(
|
||||
workspaceConfigs,
|
||||
remoteConfigServerUrl,
|
||||
ideType,
|
||||
);
|
||||
let intermediate = serializedToIntermediateConfig(serialized);
|
||||
|
||||
const configJsContents = await buildConfigTs(false);
|
||||
const configJsContents = await buildConfigTs();
|
||||
if (configJsContents) {
|
||||
try {
|
||||
// Try config.ts first
|
||||
const configJsPath = getConfigJsPath(true);
|
||||
const configJsPath = getConfigJsPath();
|
||||
const module = await require(configJsPath);
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
if (!module.modifyConfig) {
|
||||
|
|
@ -374,6 +441,24 @@ async function loadFullConfigNode(
|
|||
console.log("Error loading config.ts: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Remote config.js
|
||||
if (remoteConfigServerUrl) {
|
||||
try {
|
||||
const configJsPathForRemote = getConfigJsPathForRemote(
|
||||
remoteConfigServerUrl,
|
||||
);
|
||||
const module = await require(configJsPathForRemote);
|
||||
delete require.cache[require.resolve(configJsPathForRemote)];
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
}
|
||||
intermediate = module.modifyConfig(intermediate);
|
||||
} catch (e) {
|
||||
console.log("Error loading remotely set config.js: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
const finalConfig = await intermediateToFinalConfig(intermediate, readFile);
|
||||
return finalConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,28 @@
|
|||
const Types = `
|
||||
declare global {
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
windowId: string;
|
||||
serverUrl: string;
|
||||
vscMachineId: string;
|
||||
vscMediaUrl: string;
|
||||
fullColorTheme?: {
|
||||
rules?: {
|
||||
token?: string;
|
||||
foreground?: string;
|
||||
}[];
|
||||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChunkWithoutID {
|
||||
content: string;
|
||||
startLine: number;
|
||||
|
|
@ -68,6 +91,8 @@ declare global {
|
|||
countTokens(text: string): number;
|
||||
|
||||
supportsImages(): boolean;
|
||||
|
||||
listModels(): Promise<string[]>;
|
||||
}
|
||||
|
||||
export type ContextProviderType = "normal" | "query" | "submenu";
|
||||
|
|
@ -76,6 +101,7 @@ declare global {
|
|||
title: string;
|
||||
displayTitle: string;
|
||||
description: string;
|
||||
renderInlineAs?: string;
|
||||
type: ContextProviderType;
|
||||
}
|
||||
|
||||
|
|
@ -95,6 +121,7 @@ declare global {
|
|||
title: string;
|
||||
displayTitle?: string;
|
||||
description?: string;
|
||||
renderInlineAs?: string;
|
||||
type?: ContextProviderType;
|
||||
getContextItems(
|
||||
query: string,
|
||||
|
|
@ -264,6 +291,9 @@ declare global {
|
|||
options: CompletionOptions,
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
) => AsyncGenerator<string>;
|
||||
listModels?: (
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
) => Promise<string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -287,14 +317,24 @@ declare global {
|
|||
message: string;
|
||||
}
|
||||
|
||||
export type IdeType = "vscode" | "jetbrains";
|
||||
export interface IdeInfo {
|
||||
ideType: IdeType;
|
||||
name: string;
|
||||
version: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
getSerializedConfig(): Promise<SerializedContinueConfig>;
|
||||
getConfigJsUrl(): Promise<string | undefined>;
|
||||
getIdeInfo(): Promise<IdeInfo>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
getTerminalContents(): Promise<string>;
|
||||
listWorkspaceContents(directory?: string): Promise<string[]>;
|
||||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -302,38 +342,24 @@ declare global {
|
|||
runCommand(command: string): Promise<void>;
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void>;
|
||||
showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void>;
|
||||
verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
|
||||
// Embeddings
|
||||
/**
|
||||
* Returns list of [tag, filepath, hash of contents] that need to be embedded
|
||||
*/
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
|
||||
sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
): void;
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]>;
|
||||
getBranch(dir: string): Promise<string>;
|
||||
getStats(directory: string): Promise<{ [path: string]: number }>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -346,6 +372,8 @@ declare global {
|
|||
input: string;
|
||||
params?: { [key: string]: any } | undefined;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
config: ContinueConfig;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
@ -399,7 +427,9 @@ declare global {
|
|||
| "openchat"
|
||||
| "deepseek"
|
||||
| "xwin-coder"
|
||||
| "neural-chat";
|
||||
| "neural-chat"
|
||||
| "codellama-70b"
|
||||
| "llava";
|
||||
|
||||
type ModelProvider =
|
||||
| "openai"
|
||||
|
|
@ -422,6 +452,7 @@ declare global {
|
|||
| "flowise";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
// OpenAI
|
||||
| "gpt-3.5-turbo"
|
||||
| "gpt-3.5-turbo-16k"
|
||||
|
|
@ -429,6 +460,7 @@ declare global {
|
|||
| "gpt-3.5-turbo-0613"
|
||||
| "gpt-4-32k"
|
||||
| "gpt-4-turbo-preview"
|
||||
| "gpt-4-vision-preview"
|
||||
// Open Source
|
||||
| "mistral-7b"
|
||||
| "mistral-8x7b"
|
||||
|
|
@ -437,6 +469,7 @@ declare global {
|
|||
| "codellama-7b"
|
||||
| "codellama-13b"
|
||||
| "codellama-34b"
|
||||
| "codellama-70b"
|
||||
| "phi2"
|
||||
| "phind-codellama-34b"
|
||||
| "wizardcoder-7b"
|
||||
|
|
@ -444,7 +477,6 @@ declare global {
|
|||
| "wizardcoder-34b"
|
||||
| "zephyr-7b"
|
||||
| "codeup-13b"
|
||||
| "deepseek-1b"
|
||||
| "deepseek-7b"
|
||||
| "deepseek-33b"
|
||||
| "neural-chat-7b"
|
||||
|
|
@ -457,7 +489,12 @@ declare global {
|
|||
// Mistral
|
||||
| "mistral-tiny"
|
||||
| "mistral-small"
|
||||
| "mistral-medium";
|
||||
| "mistral-medium"
|
||||
// Tab autocomplete
|
||||
| "deepseek-1b"
|
||||
| "starcoder-1b"
|
||||
| "starcoder-3b"
|
||||
| "stable-code-3b";
|
||||
|
||||
export interface RequestOptions {
|
||||
timeout?: number;
|
||||
|
|
@ -465,6 +502,7 @@ declare global {
|
|||
caBundlePath?: string | string[];
|
||||
proxy?: string;
|
||||
headers?: { [key: string]: string };
|
||||
extraBodyProperties?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface StepWithParams {
|
||||
|
|
@ -532,6 +570,17 @@ declare global {
|
|||
embed(chunks: string[]): Promise<number[][]>;
|
||||
}
|
||||
|
||||
export interface TabAutocompleteOptions {
|
||||
useCopyBuffer: boolean;
|
||||
useSuffix: boolean;
|
||||
maxPromptTokens: number;
|
||||
debounceDelay: number;
|
||||
maxSuffixPercentage: number;
|
||||
prefixPercentage: number;
|
||||
template?: string;
|
||||
disableMultiLineCompletions?: boolean;
|
||||
}
|
||||
|
||||
export interface SerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
|
|
@ -544,8 +593,16 @@ declare global {
|
|||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: EmbeddingsProviderDescription;
|
||||
tabAutocompleteModel?: ModelDescription;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
export type ConfigMergeType = "merge" | "overwrite";
|
||||
|
||||
export type ContinueRcJson = Partial<SerializedContinueConfig> & {
|
||||
mergeBehavior: ConfigMergeType;
|
||||
};
|
||||
|
||||
export interface Config {
|
||||
/** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://continue.dev/docs/telemetry */
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
|
|
@ -572,6 +629,10 @@ declare global {
|
|||
userToken?: string;
|
||||
/** The provider used to calculate embeddings. If left empty, Continue will use transformers.js to calculate the embeddings with all-MiniLM-L6-v2 */
|
||||
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
|
||||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?: CustomLLM | ModelDescription;
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
export interface ContinueConfig {
|
||||
|
|
@ -585,8 +646,22 @@ declare global {
|
|||
disableIndexing?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
tabAutocompleteModel?: ILLM;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
slashCommands?: SlashCommandDescription[];
|
||||
contextProviders?: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
|
|
|
|||
38
core/config/util.ts
Normal file
38
core/config/util.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { readFileSync, writeFileSync } from "fs";
|
||||
import { ModelDescription } from "..";
|
||||
import { editConfigJson, getConfigJsonPath } from "../util/paths";
|
||||
|
||||
export function addModel(model: ModelDescription) {
|
||||
const config = readFileSync(getConfigJsonPath(), "utf8");
|
||||
const configJson = JSON.parse(config);
|
||||
configJson.models.push(model);
|
||||
const newConfigString = JSON.stringify(
|
||||
configJson,
|
||||
(key, value) => {
|
||||
return value === null ? undefined : value;
|
||||
},
|
||||
2,
|
||||
);
|
||||
writeFileSync(getConfigJsonPath(), newConfigString);
|
||||
return newConfigString;
|
||||
}
|
||||
|
||||
export function addOpenAIKey(key: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.map((m: ModelDescription) => {
|
||||
if (m.provider === "free-trial") {
|
||||
m.apiKey = key;
|
||||
m.provider = "openai";
|
||||
}
|
||||
return m;
|
||||
});
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteModel(title: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.filter((m: any) => m.title !== title);
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
|
@ -22,11 +22,11 @@ export abstract class BaseContextProvider implements IContextProvider {
|
|||
// Maybe just include the chat message in here. Should never have to go back to the context provider once you have the information.
|
||||
abstract getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]>;
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
return [];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,8 +6,7 @@ import {
|
|||
} from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
import { getHighlightsThatFit, ILLMContextSizer } from "llm-code-highlighter/dist/index.continue";
|
||||
import { countTokens } from "../../llm/countTokens";
|
||||
// import { getHighlightsThatFit, ILLMContextSizer } from "llm-code-highlighter/dist/index.continue";
|
||||
|
||||
const HIGHLIGHTS_TOKEN_BUDGET = 2000;
|
||||
|
||||
|
|
@ -21,7 +20,7 @@ class CodeHighlightsContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
|
|
@ -33,32 +32,33 @@ class CodeHighlightsContextProvider extends BaseContextProvider {
|
|||
absPath: filepath,
|
||||
content: `${await ide.readFile(filepath)}`,
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
const contextSizer = {
|
||||
fits(content: string): boolean {
|
||||
return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
}
|
||||
} as ILLMContextSizer
|
||||
const repoMap = await getHighlightsThatFit(
|
||||
contextSizer,
|
||||
[],
|
||||
allFiles
|
||||
.filter((file) => file.content.length > 0)
|
||||
.map((file) => {
|
||||
return {
|
||||
relPath: file.name,
|
||||
code: file.content,
|
||||
};
|
||||
})
|
||||
);
|
||||
return [
|
||||
{
|
||||
content: repoMap ? repoMap : "",
|
||||
name: "Code Highlights",
|
||||
description: "Code highlights from open files",
|
||||
},
|
||||
];
|
||||
// const contextSizer = {
|
||||
// fits(content: string): boolean {
|
||||
// return countTokens(content, "") < HIGHLIGHTS_TOKEN_BUDGET;
|
||||
// }
|
||||
// } as ILLMContextSizer
|
||||
// const repoMap = await getHighlightsThatFit(
|
||||
// contextSizer,
|
||||
// [],
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// })
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: repoMap ? repoMap : "",
|
||||
// name: "Code Highlights",
|
||||
// description: "Code highlights from open files",
|
||||
// },
|
||||
// ];
|
||||
return [];
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
} from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
import { getFileOutlineHighlights } from "llm-code-highlighter/dist/index.continue";
|
||||
// import { getOutlines } from "llm-code-highlighter/dist/index.continue";
|
||||
|
||||
class CodeOutlineContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -18,7 +18,7 @@ class CodeOutlineContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const openFiles = await ide.getOpenFiles();
|
||||
|
|
@ -30,25 +30,26 @@ class CodeOutlineContextProvider extends BaseContextProvider {
|
|||
absPath: filepath,
|
||||
content: `${await ide.readFile(filepath)}`,
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
const outlines = await getFileOutlineHighlights(
|
||||
allFiles
|
||||
.filter((file) => file.content.length > 0)
|
||||
.map((file) => {
|
||||
return {
|
||||
relPath: file.name,
|
||||
code: file.content,
|
||||
};
|
||||
})
|
||||
);
|
||||
return [
|
||||
{
|
||||
content: outlines ? outlines : "",
|
||||
name: "Code Outline",
|
||||
description: "Definition lines only (from open files)",
|
||||
},
|
||||
];
|
||||
// const outlines = await getOutlines(
|
||||
// allFiles
|
||||
// .filter((file) => file.content.length > 0)
|
||||
// .map((file) => {
|
||||
// return {
|
||||
// relPath: file.name,
|
||||
// code: file.content,
|
||||
// };
|
||||
// })
|
||||
// );
|
||||
// return [
|
||||
// {
|
||||
// content: outlines ? outlines : "",
|
||||
// name: "Code Outline",
|
||||
// description: "Definition lines only (from open files)",
|
||||
// },
|
||||
// ];
|
||||
return [];
|
||||
}
|
||||
|
||||
async load(): Promise<void> {}
|
||||
|
|
|
|||
|
|
@ -12,11 +12,12 @@ class CodebaseContextProvider extends BaseContextProvider {
|
|||
displayTitle: "Codebase",
|
||||
description: "Automatically find relevant files",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
return retrieveContextItemsFromEmbeddings(extras, this.options, undefined);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,12 +19,13 @@ class CustomContextProviderClass implements IContextProvider {
|
|||
displayTitle: this.custom.displayTitle || this.custom.title,
|
||||
description: this.custom.description || "",
|
||||
type: this.custom.type || "normal",
|
||||
renderInlineAs: this.custom.renderInlineAs,
|
||||
};
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
return await this.custom.getContextItems(query, extras);
|
||||
}
|
||||
|
|
|
|||
124
core/context/providers/DatabaseContextProvider.ts
Normal file
124
core/context/providers/DatabaseContextProvider.ts
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../..";
|
||||
|
||||
class DatabaseContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "database",
|
||||
displayTitle: "Database",
|
||||
description: "Table schemas",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
const connections = this.options?.connections;
|
||||
|
||||
if (connections === null) {
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
let [connectionName, table] = query.split(".");
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
if (connection.name == connectionName) {
|
||||
const adapter = getDatabaseAdapter(
|
||||
connection.connection_type,
|
||||
connection.connection,
|
||||
);
|
||||
const tablesAndSchemas = await adapter.getAllTablesAndSchemas(
|
||||
connection.connection.database,
|
||||
);
|
||||
|
||||
if (table === "all") {
|
||||
let prompt = `Schema for all tables on ${connection.connection_type} is `;
|
||||
prompt += JSON.stringify(tablesAndSchemas);
|
||||
|
||||
let contextItem = {
|
||||
name: `${connectionName}-all-tables-schemas`,
|
||||
description: `Schema for all tables.`,
|
||||
content: prompt,
|
||||
};
|
||||
|
||||
contextItems.push(contextItem);
|
||||
} else {
|
||||
const tables = Object.keys(tablesAndSchemas);
|
||||
|
||||
tables.forEach((tableName) => {
|
||||
if (table === tableName) {
|
||||
let prompt = `Schema for ${tableName} on ${connection.connection_type} is `;
|
||||
prompt += JSON.stringify(tablesAndSchemas[tableName]);
|
||||
|
||||
let contextItem = {
|
||||
name: `${connectionName}-${tableName}-schema`,
|
||||
description: `${tableName} Schema`,
|
||||
content: prompt,
|
||||
};
|
||||
|
||||
contextItems.push(contextItem);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const contextItems: ContextSubmenuItem[] = [];
|
||||
const connections = this.options?.connections;
|
||||
|
||||
if (connections === null) {
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
let adapter = getDatabaseAdapter(
|
||||
connection.connection_type,
|
||||
connection.connection,
|
||||
);
|
||||
const tablesAndSchemas = await adapter.getAllTablesAndSchemas(
|
||||
connection.connection.database,
|
||||
);
|
||||
const tables = Object.keys(tablesAndSchemas);
|
||||
|
||||
let contextItem = {
|
||||
id: `${connection.name}.all`,
|
||||
title: `${connection.name} all table schemas`,
|
||||
description: ``,
|
||||
};
|
||||
|
||||
contextItems.push(contextItem);
|
||||
|
||||
tables.forEach((tableName) => {
|
||||
let contextItem = {
|
||||
id: `${connection.name}.${tableName}`,
|
||||
title: `${connection.name}.${tableName} schema`,
|
||||
description: ``,
|
||||
};
|
||||
|
||||
contextItems.push(contextItem);
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
}
|
||||
|
||||
export default DatabaseContextProvider;
|
||||
|
|
@ -15,7 +15,7 @@ class DiffContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const diff = await extras.ide.getDiff();
|
||||
return [
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const { retrieveDocs } = await import("../../indexing/docs/db");
|
||||
|
||||
|
|
@ -28,7 +28,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
const chunks = await retrieveDocs(
|
||||
query,
|
||||
vector,
|
||||
this.options?.nRetrieve || 15
|
||||
this.options?.nRetrieve || 15,
|
||||
);
|
||||
|
||||
console.log(chunks);
|
||||
|
|
@ -59,7 +59,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const { listDocs } = await import("../../indexing/docs/db");
|
||||
const docs = await listDocs();
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ class FileContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
// Assume the query is a filepath
|
||||
query = query.trim();
|
||||
|
|
@ -33,13 +33,13 @@ class FileContextProvider extends BaseContextProvider {
|
|||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const workspaceDirs = await args.ide.getWorkspaceDirs();
|
||||
const results = await Promise.all(
|
||||
workspaceDirs.map((dir) => {
|
||||
return args.ide.listWorkspaceContents(dir);
|
||||
})
|
||||
}),
|
||||
);
|
||||
const files = results.flat();
|
||||
return files.map((file) => {
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ class FileTreeContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
let trees = [];
|
||||
|
|
|
|||
|
|
@ -18,13 +18,13 @@ class FolderContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const { retrieveContextItemsFromEmbeddings } = await import("../retrieval");
|
||||
return retrieveContextItemsFromEmbeddings(extras, this.options, query);
|
||||
}
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const folders = await args.ide.listFolders();
|
||||
return folders.map((folder) => {
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const issueId = query;
|
||||
const { Octokit } = await import("@octokit/rest");
|
||||
|
|
@ -58,7 +58,7 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
|
|||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const { Octokit } = await import("@octokit/rest");
|
||||
|
||||
|
|
@ -83,7 +83,7 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
|
|||
repo: repo.repo,
|
||||
issue_number: issue.number,
|
||||
}),
|
||||
}))
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ class GoogleContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const url = "https://google.serper.dev/search";
|
||||
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const response = await fetch(this.options.url, {
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { AxiosInstance } from "axios";
|
||||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
|
|
@ -6,7 +7,7 @@ import {
|
|||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../..";
|
||||
import type { AxiosInstance } from "axios";
|
||||
const { convert } = require("adf-to-md");
|
||||
|
||||
interface JiraComment {
|
||||
id: string;
|
||||
|
|
@ -58,7 +59,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const issueId = query;
|
||||
|
||||
|
|
@ -72,14 +73,11 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
})
|
||||
.then((result) => result.data);
|
||||
|
||||
// @ts-ignore
|
||||
const adf2md = await import("adf2md/dist/adf2md.min.js");
|
||||
|
||||
const parts = [
|
||||
`# Jira Issue ${issue.key}: ${issue.fields.summary}`,
|
||||
"## Description",
|
||||
issue.fields.description
|
||||
? adf2md.convert(issue.fields.description).result
|
||||
? convert(issue.fields.description).result
|
||||
: "No description",
|
||||
];
|
||||
|
||||
|
|
@ -88,10 +86,10 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
|
||||
parts.push(
|
||||
...issue.fields.comment.comments.map((comment) => {
|
||||
const commentText = adf2md.convert(comment.body).result;
|
||||
const commentText = convert(comment.body).result;
|
||||
|
||||
return `### ${comment.author.displayName} on ${comment.created}\n\n${commentText}`;
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -107,7 +105,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const api = await this.createApi();
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class OpenFilesContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const openFiles = this.options?.onlyPinned
|
||||
|
|
@ -27,11 +27,11 @@ class OpenFilesContextProvider extends BaseContextProvider {
|
|||
return {
|
||||
description: filepath,
|
||||
content: `\`\`\`${getBasename(filepath)}\n${await ide.readFile(
|
||||
filepath
|
||||
filepath,
|
||||
)}\n\`\`\``,
|
||||
name: (filepath.split("/").pop() || "").split("\\").pop() || "",
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
146
core/context/providers/PostgresContextProvider.ts
Normal file
146
core/context/providers/PostgresContextProvider.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../..";
|
||||
|
||||
class PostgresContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "postgres",
|
||||
displayTitle: "PostgreSQL",
|
||||
description: "Retrieve PostgreSQL table schema and sample rows",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
static ALL_TABLES = "__all_tables";
|
||||
static DEFAULT_SAMPLE_ROWS = 3;
|
||||
|
||||
constructor(options: {
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
password: string;
|
||||
database: string;
|
||||
schema?: string;
|
||||
sampleRows?: number;
|
||||
}) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
private async getPool() {
|
||||
const pg = await require("pg");
|
||||
return new pg.Pool({
|
||||
host: this.options.host,
|
||||
port: this.options.port,
|
||||
user: this.options.user,
|
||||
password: this.options.password,
|
||||
database: this.options.database,
|
||||
});
|
||||
}
|
||||
|
||||
private async getTableNames(pool: any): Promise<string[]> {
|
||||
const schema = this.options.schema ?? "public";
|
||||
var tablesInfoQuery = `
|
||||
SELECT table_schema, table_name
|
||||
FROM information_schema.tables`;
|
||||
if (schema != null) {
|
||||
tablesInfoQuery += ` WHERE table_schema = '${schema}'`;
|
||||
}
|
||||
const { rows: tablesInfo } = await pool.query(tablesInfoQuery);
|
||||
return tablesInfo.map(
|
||||
(tableInfo: any) => `${tableInfo.table_schema}.${tableInfo.table_name}`,
|
||||
);
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string = "",
|
||||
_: ContextProviderExtras = {} as ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const pool = await this.getPool();
|
||||
|
||||
try {
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
const tableNames = [];
|
||||
if (query === PostgresContextProvider.ALL_TABLES) {
|
||||
tableNames.push(...(await this.getTableNames(pool)));
|
||||
} else {
|
||||
tableNames.push(query);
|
||||
}
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
// Get the table schema
|
||||
if (!tableName.includes(".")) {
|
||||
throw new Error(
|
||||
`Table name must be in format schema.table_name, got ${tableName}`,
|
||||
);
|
||||
}
|
||||
var schemaQuery = `
|
||||
SELECT column_name, data_type, character_maximum_length
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = '${tableName.split(".")[0]}'
|
||||
AND table_name = '${tableName.split(".")[1]}'`;
|
||||
console.log("schemaQuery", schemaQuery);
|
||||
const { rows: tableSchema } = await pool.query(schemaQuery);
|
||||
|
||||
// Get the sample rows
|
||||
const sampleRows =
|
||||
this.options.sampleRows ??
|
||||
PostgresContextProvider.DEFAULT_SAMPLE_ROWS;
|
||||
const { rows: sampleRowResults } = await pool.query(`
|
||||
SELECT *
|
||||
FROM ${tableName}
|
||||
LIMIT ${sampleRows}`);
|
||||
|
||||
// Create prompt from the table schema and sample rows
|
||||
var prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`;
|
||||
prompt += `${JSON.stringify(tableSchema, null, 2)}\n\n`;
|
||||
prompt += `Sample rows: ${JSON.stringify(sampleRowResults, null, 2)}`;
|
||||
|
||||
contextItems.push({
|
||||
name: `${this.options.database}-${tableName}-schema-and-sample-rows`,
|
||||
description: `Schema and sample rows for table ${tableName}`,
|
||||
content: prompt,
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to query PostgreSQL database: ${error}`);
|
||||
} finally {
|
||||
}
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
_: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const pool = await this.getPool();
|
||||
|
||||
try {
|
||||
const contextItems: ContextSubmenuItem[] = [];
|
||||
const tableNames = await this.getTableNames(pool);
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
contextItems.push({
|
||||
id: tableName,
|
||||
title: tableName,
|
||||
description: `Schema from ${tableName} and ${this.options.sampleRows} sample rows.`,
|
||||
});
|
||||
}
|
||||
contextItems.push({
|
||||
id: PostgresContextProvider.ALL_TABLES,
|
||||
title: "All tables",
|
||||
description: `Schema from all tables and ${this.options.sampleRows} sample rows each.`,
|
||||
});
|
||||
|
||||
return contextItems;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to query PostgreSQL database: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default PostgresContextProvider;
|
||||
|
|
@ -16,7 +16,7 @@ class ProblemsContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ide = extras.ide;
|
||||
const problems = await ide.getProblems();
|
||||
|
|
@ -28,18 +28,18 @@ class ProblemsContextProvider extends BaseContextProvider {
|
|||
const rangeContent = lines
|
||||
.slice(
|
||||
Math.max(0, problem.range.start.line - 2),
|
||||
problem.range.end.line + 2
|
||||
problem.range.end.line + 2,
|
||||
)
|
||||
.join("\n");
|
||||
|
||||
return {
|
||||
description: "Problems in current file",
|
||||
content: `\`\`\`${getBasename(
|
||||
problem.filepath
|
||||
problem.filepath,
|
||||
)}\n${rangeContent}\n\`\`\`\n${problem.message}\n\n`,
|
||||
name: `Warning in ${getBasename(problem.filepath)}`,
|
||||
};
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
return items.length === 0
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class SearchContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const results = await extras.ide.getSearchResults(query);
|
||||
return [
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class TerminalContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const content = await extras.ide.getTerminalContents();
|
||||
return [
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class URLContextProvider extends BaseContextProvider {
|
|||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
let url = query.trim();
|
||||
if (!url.startsWith("http")) {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import { ContextProviderName } from "../..";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
import CodeHighlightsContextProvider from "./CodeHighlightsContextProvider";
|
||||
import CodeOutlineContextProvider from "./CodeOutlineContextProvider";
|
||||
import DatabaseContextProvider from "./DatabaseContextProvider";
|
||||
import DiffContextProvider from "./DiffContextProvider";
|
||||
import DocsContextProvider from "./DocsContextProvider";
|
||||
import FileTreeContextProvider from "./FileTreeContextProvider";
|
||||
|
|
@ -10,12 +9,13 @@ import FolderContextProvider from "./FolderContextProvider";
|
|||
import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider";
|
||||
import GoogleContextProvider from "./GoogleContextProvider";
|
||||
import HttpContextProvider from "./HttpContextProvider";
|
||||
import JiraIssuesContextProvider from "./JiraIssuesContextProvider";
|
||||
import OpenFilesContextProvider from "./OpenFilesContextProvider";
|
||||
import PostgresContextProvider from "./PostgresContextProvider";
|
||||
import ProblemsContextProvider from "./ProblemsContextProvider";
|
||||
import SearchContextProvider from "./SearchContextProvider";
|
||||
import TerminalContextProvider from "./TerminalContextProvider";
|
||||
import URLContextProvider from "./URLContextProvider";
|
||||
import JiraIssuesContextProvider from "./JiraIssuesContextProvider";
|
||||
|
||||
const Providers: (typeof BaseContextProvider)[] = [
|
||||
DiffContextProvider,
|
||||
|
|
@ -31,13 +31,15 @@ const Providers: (typeof BaseContextProvider)[] = [
|
|||
ProblemsContextProvider,
|
||||
FolderContextProvider,
|
||||
DocsContextProvider,
|
||||
CodeHighlightsContextProvider,
|
||||
CodeOutlineContextProvider,
|
||||
// CodeHighlightsContextProvider,
|
||||
// CodeOutlineContextProvider,
|
||||
JiraIssuesContextProvider,
|
||||
PostgresContextProvider,
|
||||
DatabaseContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
name: ContextProviderName
|
||||
name: ContextProviderName,
|
||||
): typeof BaseContextProvider | undefined {
|
||||
const cls = Providers.find((cls) => cls.description.title === name);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { Chunk, ContextItem, ContextProviderExtras, ILLM } from "..";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
|
||||
import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex";
|
||||
import { LanceDbIndex } from "../indexing/LanceDbIndex";
|
||||
import { IndexTag } from "../indexing/types";
|
||||
import { llmCanGenerateInParallel } from "../llm/autodetect";
|
||||
import { getBasename } from "../util";
|
||||
|
|
@ -8,7 +8,7 @@ import { getBasename } from "../util";
|
|||
const RERANK_PROMPT = (
|
||||
query: string,
|
||||
documentId: string,
|
||||
document: string
|
||||
document: string,
|
||||
) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query.
|
||||
|
||||
Query: Where is the FastAPI server?
|
||||
|
|
@ -48,7 +48,7 @@ Relevant:
|
|||
async function scoreChunk(
|
||||
chunk: Chunk,
|
||||
llm: ILLM,
|
||||
query: string
|
||||
query: string,
|
||||
): Promise<number> {
|
||||
const completion = await llm.complete(
|
||||
RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content),
|
||||
|
|
@ -58,7 +58,7 @@ async function scoreChunk(
|
|||
llm.providerName.startsWith("openai") && llm.model.startsWith("gpt-4")
|
||||
? "gpt-3.5-turbo"
|
||||
: llm.model,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (!completion) {
|
||||
|
|
@ -78,7 +78,7 @@ async function scoreChunk(
|
|||
return 0.0;
|
||||
} else {
|
||||
console.warn(
|
||||
`Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`
|
||||
`Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`,
|
||||
);
|
||||
return 0.0;
|
||||
}
|
||||
|
|
@ -88,10 +88,10 @@ async function rerank(
|
|||
chunks: Chunk[],
|
||||
llm: ILLM,
|
||||
query: string,
|
||||
nFinal: number
|
||||
nFinal: number,
|
||||
): Promise<Chunk[]> {
|
||||
const scores = await Promise.all(
|
||||
chunks.map((chunk) => scoreChunk(chunk, llm, query))
|
||||
chunks.map((chunk) => scoreChunk(chunk, llm, query)),
|
||||
);
|
||||
const sorted = chunks
|
||||
.map((chunk, i) => ({ chunk, score: scores[i] }))
|
||||
|
|
@ -103,7 +103,7 @@ async function rerank(
|
|||
export async function retrieveContextItemsFromEmbeddings(
|
||||
extras: ContextProviderExtras,
|
||||
options: any | undefined,
|
||||
filterDirectory: string | undefined
|
||||
filterDirectory: string | undefined,
|
||||
): Promise<ContextItem[]> {
|
||||
if (!extras.embeddingsProvider) {
|
||||
return [];
|
||||
|
|
@ -122,35 +122,49 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
throw new Error("No workspace directories found");
|
||||
}
|
||||
|
||||
const branches = await Promise.all(
|
||||
workspaceDirs.map((dir) => extras.ide.getBranch(dir))
|
||||
);
|
||||
const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({
|
||||
directory,
|
||||
branch: branches[i],
|
||||
artifactId: ChunkCodebaseIndex.artifactId,
|
||||
}));
|
||||
const branches = (await Promise.race([
|
||||
Promise.all(workspaceDirs.map((dir) => extras.ide.getBranch(dir))),
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve(["NONE"]);
|
||||
}, 500);
|
||||
}),
|
||||
])) as string[];
|
||||
const tags: (artifactId: string) => IndexTag[] = (artifactId: string) =>
|
||||
workspaceDirs.map((directory, i) => ({
|
||||
directory,
|
||||
branch: branches[i],
|
||||
artifactId,
|
||||
}));
|
||||
|
||||
let ftsResults: Chunk[] = [];
|
||||
|
||||
try {
|
||||
if (extras.fullInput.trim() !== "") {
|
||||
ftsResults = await ftsIndex.retrieve(
|
||||
tags,
|
||||
extras.fullInput.trim().split(" ").join(" OR "),
|
||||
tags(ftsIndex.artifactId),
|
||||
extras.fullInput
|
||||
.trim()
|
||||
.split(" ")
|
||||
.map((element) => `"${element}"`)
|
||||
.join(" OR "),
|
||||
nRetrieve / 2,
|
||||
filterDirectory,
|
||||
undefined
|
||||
undefined,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error retrieving from FTS:", e);
|
||||
}
|
||||
|
||||
let vecResults = await extras.ide.retrieveChunks(
|
||||
const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) =>
|
||||
extras.ide.readFile(path),
|
||||
);
|
||||
let vecResults = await lanceDbIndex.retrieve(
|
||||
tags(lanceDbIndex.artifactId),
|
||||
extras.fullInput,
|
||||
nRetrieve,
|
||||
filterDirectory
|
||||
filterDirectory,
|
||||
);
|
||||
|
||||
// Now combine these (de-duplicate) and re-rank
|
||||
|
|
@ -164,7 +178,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
(r) =>
|
||||
r.filepath === vecResult.filepath &&
|
||||
r.startLine === vecResult.startLine &&
|
||||
r.endLine === vecResult.endLine
|
||||
r.endLine === vecResult.endLine,
|
||||
)
|
||||
) {
|
||||
results.push(vecResult);
|
||||
|
|
@ -178,7 +192,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
|
||||
if (results.length === 0) {
|
||||
throw new Error(
|
||||
"Warning: No results found for @codebase context provider."
|
||||
"Warning: No results found for @codebase context provider.",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ import { LineStream, matchLine } from "./util";
|
|||
*/
|
||||
export async function* streamDiff(
|
||||
oldLines: string[],
|
||||
newLines: LineStream
|
||||
newLines: LineStream,
|
||||
): AsyncGenerator<DiffLine> {
|
||||
oldLines = [...oldLines]; // be careful
|
||||
const mutatedOldLines = [...oldLines]; // be careful
|
||||
let seenIndentationMistake = false;
|
||||
|
||||
let newLineResult = await newLines.next();
|
||||
|
|
@ -21,7 +21,7 @@ export async function* streamDiff(
|
|||
const [matchIndex, isPerfectMatch, newLine] = matchLine(
|
||||
newLineResult.value,
|
||||
oldLines,
|
||||
seenIndentationMistake
|
||||
seenIndentationMistake,
|
||||
);
|
||||
if (!seenIndentationMistake && newLineResult.value !== newLine) {
|
||||
seenIndentationMistake = true;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import { distance } from "fastest-levenshtein";
|
||||
import { ChatMessage } from "..";
|
||||
import { stripImages } from "../llm/countTokens";
|
||||
|
||||
export type LineStream = AsyncGenerator<string>;
|
||||
|
||||
|
|
@ -28,7 +30,7 @@ function linesMatch(lineA: string, lineB: string): boolean {
|
|||
export function matchLine(
|
||||
newLine: string,
|
||||
oldLines: string[],
|
||||
permissiveAboutIndentation: boolean = false
|
||||
permissiveAboutIndentation: boolean = false,
|
||||
): [number, boolean, string] {
|
||||
// Only match empty lines if it's the next one:
|
||||
if (newLine.trim() === "" && oldLines[0]?.trim() === "") {
|
||||
|
|
@ -57,10 +59,12 @@ export function matchLine(
|
|||
* Convert a stream of arbitrary chunks to a stream of lines
|
||||
*/
|
||||
export async function* streamLines(
|
||||
streamCompletion: AsyncGenerator<string>
|
||||
streamCompletion: AsyncGenerator<string | ChatMessage>,
|
||||
): LineStream {
|
||||
let buffer = "";
|
||||
for await (const chunk of streamCompletion) {
|
||||
for await (const update of streamCompletion) {
|
||||
const chunk =
|
||||
typeof update === "string" ? update : stripImages(update.content);
|
||||
buffer += chunk;
|
||||
const lines = buffer.split("\n");
|
||||
buffer = lines.pop() ?? "";
|
||||
|
|
|
|||
|
|
@ -1,131 +0,0 @@
|
|||
import { Chunk, DiffLine, Problem } from "..";
|
||||
import { BrowserSerializedContinueConfig } from "../config/load";
|
||||
import { IDE } from "../index";
|
||||
|
||||
import { ideRequest } from "./messaging";
|
||||
async function r(messageType: string, options: any = {}) {
|
||||
return await ideRequest(messageType, options);
|
||||
}
|
||||
export class ExtensionIde implements IDE {
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
return await r("getSerializedConfig");
|
||||
}
|
||||
|
||||
async getDiff() {
|
||||
return await r("getDiff");
|
||||
}
|
||||
|
||||
async getTerminalContents() {
|
||||
return await r("getTerminalContents");
|
||||
}
|
||||
|
||||
async listWorkspaceContents(directory?: string): Promise<string[]> {
|
||||
return await r("listWorkspaceContents");
|
||||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return await r("getWorkspaceDirs");
|
||||
}
|
||||
|
||||
async showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void> {
|
||||
return await r("showLines", { filepath, startLine, endLine });
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
return await r("listFolders");
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await r("getContinueDir");
|
||||
this._continueDir = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await r("writeFile", { path, contents });
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
await r("showVirtualFile", { name: title, content: contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await r("openFile", { path });
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await r("runCommand", { command });
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await r("saveFile", { filepath });
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await r("readFile", { filepath });
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void> {
|
||||
await r("showDiff", { filepath, newContents, stepIndex });
|
||||
}
|
||||
|
||||
async verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
) {
|
||||
await r("diffLine", { filepath, startLine, endLine, diffLine });
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return r("getOpenFiles");
|
||||
}
|
||||
|
||||
getPinnedFiles(): Promise<string[]> {
|
||||
return r("getPinnedFiles");
|
||||
}
|
||||
|
||||
getSearchResults(query: string): Promise<string> {
|
||||
return r("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]> {
|
||||
return r("getProblems", { filepath });
|
||||
}
|
||||
|
||||
subprocess(command: string): Promise<[string, string]> {
|
||||
return r("subprocess", { command });
|
||||
}
|
||||
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
|
||||
return r("getFilesToEmbed", { providerId });
|
||||
}
|
||||
|
||||
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {
|
||||
return r("sendChunkForFile", { chunk, embedding, tags });
|
||||
}
|
||||
|
||||
async getBranch(dir: string): Promise<string> {
|
||||
return r("getBranch", { dir });
|
||||
}
|
||||
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]> {
|
||||
return r("retrieveChunks", { text, n, directory });
|
||||
}
|
||||
}
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
// import "vscode-webview";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from "..";
|
||||
interface vscode {
|
||||
postMessage(message: any): vscode;
|
||||
}
|
||||
|
||||
declare const vscode: any;
|
||||
|
||||
function _postToIde(type: string, data: any) {
|
||||
if (typeof vscode === "undefined") {
|
||||
if (localStorage.getItem("ide") === "jetbrains") {
|
||||
if (window.postIntellijMessage === undefined) {
|
||||
console.log(
|
||||
"Unable to send message: postIntellijMessage is undefined. ",
|
||||
type,
|
||||
data
|
||||
);
|
||||
throw new Error("postIntellijMessage is undefined");
|
||||
}
|
||||
window.postIntellijMessage?.(type, data);
|
||||
return;
|
||||
} else {
|
||||
console.log("Unable to send message: vscode is undefined. ", type, data);
|
||||
return;
|
||||
}
|
||||
}
|
||||
vscode.postMessage({
|
||||
type,
|
||||
...data,
|
||||
});
|
||||
}
|
||||
|
||||
export function postToIde(type: string, data: any, attempt: number = 0) {
|
||||
try {
|
||||
_postToIde(type, data);
|
||||
} catch (error) {
|
||||
if (attempt < 5) {
|
||||
console.log(`Attempt ${attempt} failed. Retrying...`);
|
||||
setTimeout(
|
||||
() => postToIde(type, data, attempt + 1),
|
||||
Math.pow(2, attempt) * 1000
|
||||
);
|
||||
} else {
|
||||
console.error("Max attempts reached. Message could not be sent.", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function ideRequest(type: string, message: any): Promise<any> {
|
||||
// message, messageId, and type are passed back and forth
|
||||
const messageId = uuidv4();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
window.removeEventListener("message", handler);
|
||||
resolve(event.data.message);
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
});
|
||||
}
|
||||
|
||||
export async function* ideStreamRequest(
|
||||
type: string,
|
||||
message: any,
|
||||
cancelToken?: AbortSignal
|
||||
): AsyncGenerator<any, any> {
|
||||
const messageId = uuidv4();
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
|
||||
let buffer = "";
|
||||
let index = 0;
|
||||
let done = false;
|
||||
let returnVal = undefined;
|
||||
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
if (event.data.message.done) {
|
||||
window.removeEventListener("message", handler);
|
||||
done = true;
|
||||
returnVal = event.data.message.data;
|
||||
} else {
|
||||
buffer += event.data.message.content || "";
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
||||
cancelToken?.addEventListener("abort", () => {
|
||||
postToIde("abort", { messageId });
|
||||
});
|
||||
|
||||
while (!done) {
|
||||
if (buffer.length > index) {
|
||||
const chunk = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
yield chunk;
|
||||
} else {
|
||||
yield undefined;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
|
||||
if (buffer.length > index) {
|
||||
const chunk = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
yield chunk;
|
||||
}
|
||||
|
||||
return returnVal;
|
||||
}
|
||||
|
||||
export async function* llmStreamChat(
|
||||
modelTitle: string,
|
||||
cancelToken: AbortSignal | undefined,
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOptions = {}
|
||||
): AsyncGenerator<ChatMessage, LLMReturnValue> {
|
||||
const gen = ideStreamRequest(
|
||||
"llmStreamChat",
|
||||
{
|
||||
messages,
|
||||
title: modelTitle,
|
||||
completionOptions: options,
|
||||
},
|
||||
cancelToken
|
||||
);
|
||||
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (next.value) {
|
||||
yield { role: "user", content: next.value };
|
||||
}
|
||||
next = await gen.next();
|
||||
}
|
||||
return { prompt: next.value?.prompt, completion: next.value?.completion };
|
||||
}
|
||||
106
core/index.d.ts
vendored
106
core/index.d.ts
vendored
|
|
@ -1,5 +1,3 @@
|
|||
import { BrowserSerializedContinueConfig } from "./config/load";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -15,7 +13,11 @@ declare global {
|
|||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (type: string, data: any) => void;
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string,
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -71,17 +73,17 @@ export interface ILLM extends LLMOptions {
|
|||
|
||||
streamComplete(
|
||||
prompt: string,
|
||||
options?: LLMFullCompletionOptions
|
||||
options?: LLMFullCompletionOptions,
|
||||
): AsyncGenerator<string, LLMReturnValue>;
|
||||
|
||||
streamChat(
|
||||
messages: ChatMessage[],
|
||||
options?: LLMFullCompletionOptions
|
||||
options?: LLMFullCompletionOptions,
|
||||
): AsyncGenerator<ChatMessage, LLMReturnValue>;
|
||||
|
||||
chat(
|
||||
messages: ChatMessage[],
|
||||
options?: LLMFullCompletionOptions
|
||||
options?: LLMFullCompletionOptions,
|
||||
): Promise<ChatMessage>;
|
||||
|
||||
countTokens(text: string): number;
|
||||
|
|
@ -97,6 +99,7 @@ export interface ContextProviderDescription {
|
|||
title: string;
|
||||
displayTitle: string;
|
||||
description: string;
|
||||
renderInlineAs?: string;
|
||||
type: ContextProviderType;
|
||||
}
|
||||
|
||||
|
|
@ -116,13 +119,14 @@ export interface CustomContextProvider {
|
|||
title: string;
|
||||
displayTitle?: string;
|
||||
description?: string;
|
||||
renderInlineAs?: string;
|
||||
type?: ContextProviderType;
|
||||
getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]>;
|
||||
loadSubmenuItems?: (
|
||||
args: LoadSubmenuItemsArgs
|
||||
args: LoadSubmenuItemsArgs,
|
||||
) => Promise<ContextSubmenuItem[]>;
|
||||
}
|
||||
|
||||
|
|
@ -137,7 +141,7 @@ export interface IContextProvider {
|
|||
|
||||
getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]>;
|
||||
|
||||
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
|
||||
|
|
@ -162,6 +166,11 @@ export interface RangeInFile {
|
|||
range: Range;
|
||||
}
|
||||
|
||||
export interface FileWithContents {
|
||||
filepath: string;
|
||||
contents: string;
|
||||
}
|
||||
|
||||
export interface Range {
|
||||
start: Position;
|
||||
end: Position;
|
||||
|
|
@ -278,15 +287,15 @@ export interface CustomLLMWithOptionals {
|
|||
streamCompletion?: (
|
||||
prompt: string,
|
||||
options: CompletionOptions,
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
|
||||
) => AsyncGenerator<string>;
|
||||
streamChat?: (
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
|
||||
) => AsyncGenerator<string>;
|
||||
listModels?: (
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
|
||||
) => Promise<string[]>;
|
||||
}
|
||||
|
||||
|
|
@ -311,13 +320,24 @@ export class Problem {
|
|||
message: string;
|
||||
}
|
||||
|
||||
export type IdeType = "vscode" | "jetbrains";
|
||||
export interface IdeInfo {
|
||||
ideType: IdeType;
|
||||
name: string;
|
||||
version: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
|
||||
getIdeInfo(): Promise<IdeInfo>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
getTerminalContents(): Promise<string>;
|
||||
listWorkspaceContents(directory?: string): Promise<string[]>;
|
||||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -325,21 +345,16 @@ export interface IDE {
|
|||
runCommand(command: string): Promise<void>;
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
endLine: number,
|
||||
): Promise<void>;
|
||||
showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void>;
|
||||
verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
stepIndex: number,
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
|
|
@ -347,22 +362,7 @@ export interface IDE {
|
|||
subprocess(command: string): Promise<[string, string]>;
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
getBranch(dir: string): Promise<string>;
|
||||
|
||||
// Embeddings
|
||||
/**
|
||||
* Returns list of [tag, filepath, hash of contents] that need to be embedded
|
||||
*/
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
|
||||
sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
): void;
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]>;
|
||||
getStats(directory: string): Promise<{ [path: string]: number }>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -375,6 +375,8 @@ export interface ContinueSDK {
|
|||
input: string;
|
||||
params?: { [key: string]: any } | undefined;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
config: ContinueConfig;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
@ -415,7 +417,9 @@ type ContextProviderName =
|
|||
| "codebase"
|
||||
| "problems"
|
||||
| "folder"
|
||||
| "jira";
|
||||
| "jira"
|
||||
| "postgres"
|
||||
| "database";
|
||||
|
||||
type TemplateType =
|
||||
| "llama2"
|
||||
|
|
@ -484,6 +488,9 @@ export type ModelName =
|
|||
| "neural-chat-7b"
|
||||
// Anthropic
|
||||
| "claude-2"
|
||||
| "claude-3-opus-20240229"
|
||||
| "claude-3-sonnet-20240229"
|
||||
| "claude-2.1"
|
||||
// Google PaLM
|
||||
| "chat-bison-001"
|
||||
// Gemini
|
||||
|
|
@ -504,6 +511,7 @@ export interface RequestOptions {
|
|||
caBundlePath?: string | string[];
|
||||
proxy?: string;
|
||||
headers?: { [key: string]: string };
|
||||
extraBodyProperties?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface StepWithParams {
|
||||
|
|
@ -580,10 +588,17 @@ export interface TabAutocompleteOptions {
|
|||
maxSuffixPercentage: number;
|
||||
prefixPercentage: number;
|
||||
template?: string;
|
||||
disableMultiLineCompletions?: boolean;
|
||||
multilineCompletions: "always" | "never" | "auto";
|
||||
slidingWindowPrefixPercentage: number;
|
||||
slidingWindowSize: number;
|
||||
maxSnippetPercentage: number;
|
||||
recentlyEditedSimilarityThreshold: number;
|
||||
useCache: boolean;
|
||||
onlyMyCode: boolean;
|
||||
}
|
||||
|
||||
export interface SerializedContinueConfig {
|
||||
env?: string[];
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
|
|
@ -651,3 +666,16 @@ export interface ContinueConfig {
|
|||
tabAutocompleteModel?: ILLM;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
slashCommands?: SlashCommandDescription[];
|
||||
contextProviders?: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
async *update(
|
||||
tag: IndexTag,
|
||||
results: RefreshIndexResults,
|
||||
markComplete: MarkCompleteCallback
|
||||
markComplete: MarkCompleteCallback,
|
||||
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
|
||||
const db = await SqliteDb.get();
|
||||
await this._createTables(db);
|
||||
|
|
@ -42,17 +42,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
// Insert chunks
|
||||
const chunks = await db.all(
|
||||
`SELECT * FROM chunks WHERE path = ? AND cacheKey = ?`,
|
||||
[item.path, item.cacheKey]
|
||||
[item.path, item.cacheKey],
|
||||
);
|
||||
|
||||
for (let chunk of chunks) {
|
||||
const { lastID } = await db.run(
|
||||
`INSERT INTO fts (path, content) VALUES (?, ?)`,
|
||||
[item.path, chunk.content]
|
||||
[item.path, chunk.content],
|
||||
);
|
||||
await db.run(
|
||||
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)`,
|
||||
[lastID, item.path, item.cacheKey, chunk.id]
|
||||
[lastID, item.path, item.cacheKey, chunk.id],
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -77,7 +77,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
for (const item of results.del) {
|
||||
const { lastID } = await db.run(
|
||||
`DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?`,
|
||||
[item.path, item.cacheKey]
|
||||
[item.path, item.cacheKey],
|
||||
);
|
||||
await db.run(`DELETE FROM fts WHERE rowid = ?`, [lastID]);
|
||||
|
||||
|
|
@ -90,7 +90,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined,
|
||||
filterPaths: string[] | undefined
|
||||
filterPaths: string[] | undefined,
|
||||
): Promise<Chunk[]> {
|
||||
const db = await SqliteDb.get();
|
||||
const tagStrings = tags.map(tagToString);
|
||||
|
|
@ -101,7 +101,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
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
|
||||
|
|
@ -119,7 +119,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
const chunks = await db.all(
|
||||
`SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`,
|
||||
results.map((result) => result.chunkId)
|
||||
results.map((result) => result.chunkId),
|
||||
);
|
||||
|
||||
return chunks.map((chunk) => {
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
|
||||
constructor(
|
||||
embeddingsProvider: EmbeddingsProvider,
|
||||
readFile: (filepath: string) => Promise<string>
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
) {
|
||||
this.embeddingsProvider = embeddingsProvider;
|
||||
this.readFile = readFile;
|
||||
|
|
@ -61,7 +61,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
}
|
||||
|
||||
private async *computeChunks(
|
||||
items: PathAndCacheKey[]
|
||||
items: PathAndCacheKey[],
|
||||
): AsyncGenerator<
|
||||
| [
|
||||
number,
|
||||
|
|
@ -72,7 +72,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
| PathAndCacheKey
|
||||
> {
|
||||
const contents = await Promise.all(
|
||||
items.map(({ path }) => this.readFile(path))
|
||||
items.map(({ path }) => this.readFile(path)),
|
||||
);
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
|
|
@ -84,7 +84,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
items[i].path,
|
||||
content,
|
||||
LanceDbIndex.MAX_CHUNK_SIZE,
|
||||
items[i].cacheKey
|
||||
items[i].cacheKey,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
|
@ -96,7 +96,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
|
||||
// Calculate embeddings
|
||||
const embeddings = await this.embeddingsProvider.embed(
|
||||
chunks.map((c) => c.content)
|
||||
chunks.map((c) => c.content),
|
||||
);
|
||||
|
||||
// Create row format
|
||||
|
|
@ -130,8 +130,8 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
results: RefreshIndexResults,
|
||||
markComplete: (
|
||||
items: PathAndCacheKey[],
|
||||
resultType: IndexResultType
|
||||
) => void
|
||||
resultType: IndexResultType,
|
||||
) => void,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const lancedb = await import("vectordb");
|
||||
const tableName = this.tableNameForTag(tag);
|
||||
|
|
@ -160,7 +160,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
JSON.stringify(row.vector),
|
||||
data.startLine,
|
||||
data.endLine,
|
||||
data.contents
|
||||
data.contents,
|
||||
);
|
||||
|
||||
yield { progress, desc };
|
||||
|
|
@ -193,7 +193,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
const stmt = await sqlite.prepare(
|
||||
"SELECT * FROM lance_db_cache WHERE cacheKey = ? AND path = ?",
|
||||
cacheKey,
|
||||
path
|
||||
path,
|
||||
);
|
||||
const cachedItems = await stmt.all();
|
||||
|
||||
|
|
@ -230,7 +230,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
await sqlite.run(
|
||||
"DELETE FROM lance_db_cache WHERE cacheKey = ? AND path = ?",
|
||||
cacheKey,
|
||||
path
|
||||
path,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -243,7 +243,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
n: number,
|
||||
directory: string | undefined,
|
||||
vector: number[],
|
||||
db: any /// lancedb.Connection
|
||||
db: any, /// lancedb.Connection
|
||||
): Promise<LanceDbRow[]> {
|
||||
const tableName = this.tableNameForTag(tag);
|
||||
const tableNames = await db.tableNames();
|
||||
|
|
@ -267,7 +267,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
tags: IndexTag[],
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
directory: string | undefined,
|
||||
): Promise<Chunk[]> {
|
||||
const lancedb = await import("vectordb");
|
||||
if (!lancedb.connect) {
|
||||
|
|
@ -290,7 +290,7 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
const data = await sqliteDb.all(
|
||||
`SELECT * FROM lance_db_cache WHERE uuid in (${allResults
|
||||
.map((r) => `'${r.uuid}'`)
|
||||
.join(",")})`
|
||||
.join(",")})`,
|
||||
);
|
||||
|
||||
return data.map((d) => {
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
async *update(
|
||||
tag: IndexTag,
|
||||
results: RefreshIndexResults,
|
||||
markComplete: MarkCompleteCallback
|
||||
markComplete: MarkCompleteCallback,
|
||||
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
|
||||
const db = await SqliteDb.get();
|
||||
await this._createTables(db);
|
||||
|
|
@ -50,7 +50,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
|
||||
// Compute chunks for new files
|
||||
const contents = await Promise.all(
|
||||
results.compute.map(({ path }) => this.readFile(path))
|
||||
results.compute.map(({ path }) => this.readFile(path)),
|
||||
);
|
||||
for (let i = 0; i < results.compute.length; i++) {
|
||||
const item = results.compute[i];
|
||||
|
|
@ -60,7 +60,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
item.path,
|
||||
contents[i],
|
||||
MAX_CHUNK_SIZE,
|
||||
item.cacheKey
|
||||
item.cacheKey,
|
||||
)) {
|
||||
const { lastID } = await db.run(
|
||||
`INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
|
|
@ -71,7 +71,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
chunk.startLine,
|
||||
chunk.endLine,
|
||||
chunk.content,
|
||||
]
|
||||
],
|
||||
);
|
||||
|
||||
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
|
||||
|
|
@ -91,7 +91,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
for (const item of results.addTag) {
|
||||
const chunksWithPath = await db.all(
|
||||
`SELECT * FROM chunks WHERE cacheKey = ?`,
|
||||
[item.cacheKey]
|
||||
[item.cacheKey],
|
||||
);
|
||||
|
||||
for (const chunk of chunksWithPath) {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { countTokens } from "../../llm/countTokens";
|
|||
|
||||
export function* basicChunker(
|
||||
contents: string,
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
): Generator<ChunkWithoutID> {
|
||||
let chunkContent = "";
|
||||
let chunkTokens = 0;
|
||||
|
|
@ -11,7 +11,7 @@ export function* basicChunker(
|
|||
let currLine = 0;
|
||||
|
||||
for (const line of contents.split("\n")) {
|
||||
const lineTokens = countTokens(line, "gpt-4");
|
||||
const lineTokens = countTokens(line);
|
||||
if (chunkTokens + lineTokens > maxChunkSize - 5) {
|
||||
yield { content: chunkContent, startLine, endLine: currLine - 1 };
|
||||
chunkContent = "";
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import { codeChunker } from "./code";
|
|||
async function* chunkDocumentWithoutId(
|
||||
filepath: string,
|
||||
contents: string,
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (contents.trim() === "") {
|
||||
return;
|
||||
|
|
@ -23,7 +23,7 @@ async function* chunkDocumentWithoutId(
|
|||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
console.error(`Failed to parse ${filepath}: `, e);
|
||||
// console.error(`Failed to parse ${filepath}: `, e);
|
||||
// falls back to basicChunker
|
||||
}
|
||||
}
|
||||
|
|
@ -35,19 +35,19 @@ export async function* chunkDocument(
|
|||
filepath: string,
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
digest: string
|
||||
digest: string,
|
||||
): AsyncGenerator<Chunk> {
|
||||
let index = 0;
|
||||
for await (let chunkWithoutId of chunkDocumentWithoutId(
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize
|
||||
maxChunkSize,
|
||||
)) {
|
||||
if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) {
|
||||
if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) {
|
||||
console.warn(
|
||||
`Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
filepath,
|
||||
countTokens(chunkWithoutId.content, "gpt-4")
|
||||
countTokens(chunkWithoutId.content),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ function collapsedReplacement(node: SyntaxNode): string {
|
|||
|
||||
function firstChild(
|
||||
node: SyntaxNode,
|
||||
grammarName: string | string[]
|
||||
grammarName: string | string[],
|
||||
): SyntaxNode | null {
|
||||
if (Array.isArray(grammarName)) {
|
||||
return (
|
||||
|
|
@ -30,7 +30,7 @@ function collapseChildren(
|
|||
blockTypes: string[],
|
||||
collapseTypes: string[],
|
||||
collapseBlockTypes: string[],
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
): string {
|
||||
code = code.slice(0, node.endIndex);
|
||||
const block = firstChild(node, blockTypes);
|
||||
|
|
@ -38,7 +38,7 @@ function collapseChildren(
|
|||
|
||||
if (block) {
|
||||
const childrenToCollapse = block.children.filter((child) =>
|
||||
collapseTypes.includes(child.type)
|
||||
collapseTypes.includes(child.type),
|
||||
);
|
||||
for (const child of childrenToCollapse.reverse()) {
|
||||
const grandChild = firstChild(child, collapseBlockTypes);
|
||||
|
|
@ -59,10 +59,7 @@ function collapseChildren(
|
|||
}
|
||||
code = code.slice(node.startIndex);
|
||||
let removedChild = false;
|
||||
while (
|
||||
countTokens(code, "gpt-4") > maxChunkSize &&
|
||||
collapsedChildren.length > 0
|
||||
) {
|
||||
while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) {
|
||||
removedChild = true;
|
||||
// Remove children starting at the end - TODO: Add multiple chunks so no children are missing
|
||||
const childCode = collapsedChildren.pop()!;
|
||||
|
|
@ -102,7 +99,7 @@ function collapseChildren(
|
|||
function constructClassDefinitionChunk(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
): string {
|
||||
return collapseChildren(
|
||||
node,
|
||||
|
|
@ -110,14 +107,14 @@ function constructClassDefinitionChunk(
|
|||
["block", "class_body", "declaration_list"],
|
||||
["method_definition", "function_definition", "function_item"],
|
||||
["block", "statement_block"],
|
||||
maxChunkSize
|
||||
maxChunkSize,
|
||||
);
|
||||
}
|
||||
|
||||
function constructFunctionDefinitionChunk(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
): string {
|
||||
const bodyNode = node.children[node.children.length - 1];
|
||||
const funcText =
|
||||
|
|
@ -147,7 +144,7 @@ const collapsedNodeConstructors: {
|
|||
[key: string]: (
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
) => string;
|
||||
} = {
|
||||
// Classes, structs, etc
|
||||
|
|
@ -164,12 +161,12 @@ function* getSmartCollapsedChunks(
|
|||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number,
|
||||
root = true
|
||||
root = true,
|
||||
): Generator<ChunkWithoutID> {
|
||||
// Keep entire text if not over size
|
||||
if (
|
||||
(root || node.type in collapsedNodeConstructors) &&
|
||||
countTokens(node.text, "gpt-4") < maxChunkSize
|
||||
countTokens(node.text) < maxChunkSize
|
||||
) {
|
||||
yield {
|
||||
content: node.text,
|
||||
|
|
@ -197,7 +194,7 @@ function* getSmartCollapsedChunks(
|
|||
export async function* codeChunker(
|
||||
filepath: string,
|
||||
contents: string,
|
||||
maxChunkSize: number
|
||||
maxChunkSize: number,
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (contents.trim().length === 0) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ function cleanFragment(fragment: string | undefined): string | undefined {
|
|||
}
|
||||
|
||||
// Remove all special characters except alphanumeric, hyphen, space, and underscore
|
||||
fragment = fragment.replace(/[^\w\d-\s]/g, "").trim();
|
||||
fragment = fragment.replace(/[^\w-\s]/g, "").trim();
|
||||
|
||||
// Convert to lowercase
|
||||
fragment = fragment.toLowerCase();
|
||||
|
|
@ -43,7 +43,7 @@ function cleanHeader(header: string | undefined): string | undefined {
|
|||
}
|
||||
|
||||
// Remove all special characters except alphanumeric, hyphen, space, and underscore
|
||||
header = header.replace(/[^\w\d-\s]/g, "").trim();
|
||||
header = header.replace(/[^\w-\s]/g, "").trim();
|
||||
|
||||
return header;
|
||||
}
|
||||
|
|
@ -55,9 +55,9 @@ function findHeader(lines: string[]): string | undefined {
|
|||
export async function* markdownChunker(
|
||||
content: string,
|
||||
maxChunkSize: number,
|
||||
hLevel: number
|
||||
hLevel: number,
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (countTokens(content, "gpt-4") <= maxChunkSize) {
|
||||
if (countTokens(content) <= maxChunkSize) {
|
||||
const header = findHeader(content.split("\n"));
|
||||
yield {
|
||||
content,
|
||||
|
|
@ -122,9 +122,8 @@ export async function* markdownChunker(
|
|||
for (const section of sections) {
|
||||
for await (const chunk of markdownChunker(
|
||||
section.content,
|
||||
maxChunkSize -
|
||||
(section.header ? countTokens(section.header, "gpt-4") : 0),
|
||||
hLevel + 1
|
||||
maxChunkSize - (section.header ? countTokens(section.header) : 0),
|
||||
hLevel + 1,
|
||||
)) {
|
||||
yield {
|
||||
content: section.header + "\n" + chunk.content,
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
|
|||
async function* crawlLinks(
|
||||
path: string,
|
||||
baseUrl: URL,
|
||||
visited: Set<string>
|
||||
visited: Set<string>,
|
||||
): AsyncGenerator<number> {
|
||||
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
|
||||
return;
|
||||
|
|
@ -78,7 +78,7 @@ async function* crawlLinks(
|
|||
children.map(async (child) => {
|
||||
for await (const _ of crawlLinks(child, baseUrl, visited)) {
|
||||
}
|
||||
})
|
||||
}),
|
||||
);
|
||||
yield visited.size;
|
||||
}
|
||||
|
|
@ -105,12 +105,12 @@ async function crawlGithubRepo(baseUrl: URL) {
|
|||
"X-GitHub-Api-Version": "2022-11-28",
|
||||
},
|
||||
recursive: "true",
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const paths = tree.data.tree
|
||||
.filter(
|
||||
(file) => file.type === "blob" && file.path?.endsWith(".md")
|
||||
(file) => file.type === "blob" && file.path?.endsWith(".md"),
|
||||
// ||
|
||||
// file.path?.endsWith(".rst") ||
|
||||
// file.path?.split("/").includes("documentation") ||
|
||||
|
|
@ -125,7 +125,7 @@ async function crawlGithubRepo(baseUrl: URL) {
|
|||
}
|
||||
|
||||
export async function* crawlSubpages(
|
||||
baseUrl: URL
|
||||
baseUrl: URL,
|
||||
): AsyncGenerator<number, string[]> {
|
||||
// Special case for GitHub repos
|
||||
if (baseUrl.hostname === "github.com") {
|
||||
|
|
@ -158,7 +158,7 @@ export async function* crawlSubpages(
|
|||
for await (const count of crawlLinks(
|
||||
realBaseUrl.pathname || "/",
|
||||
realBaseUrl,
|
||||
visited
|
||||
visited,
|
||||
)) {
|
||||
yield count;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ async function createDocsTable(db: Database<sqlite3.Database>) {
|
|||
export async function retrieveDocs(
|
||||
baseUrl: string,
|
||||
vector: number[],
|
||||
nRetrieve: number
|
||||
nRetrieve: number,
|
||||
): Promise<Chunk[]> {
|
||||
const lancedb = await import("vectordb");
|
||||
const lance = await lancedb.connect(getLanceDbPath());
|
||||
|
|
@ -56,7 +56,7 @@ export async function addDocs(
|
|||
title: string,
|
||||
baseUrl: URL,
|
||||
chunks: Chunk[],
|
||||
embeddings: number[][]
|
||||
embeddings: number[][],
|
||||
) {
|
||||
const data: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
|
||||
title: chunk.otherMetadata?.title || title,
|
||||
|
|
@ -87,7 +87,7 @@ export async function addDocs(
|
|||
await db.run(
|
||||
`INSERT INTO docs (title, baseUrl) VALUES (?, ?)`,
|
||||
title,
|
||||
baseUrl.toString()
|
||||
baseUrl.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ import { convertURLToMarkdown } from "./urlToMarkdown";
|
|||
export async function* indexDocs(
|
||||
title: string,
|
||||
baseUrl: URL,
|
||||
embeddingsProvider: EmbeddingsProvider
|
||||
embeddingsProvider: EmbeddingsProvider,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const existingDocs = await listDocs();
|
||||
if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) {
|
||||
|
|
@ -50,7 +50,7 @@ export async function* indexDocs(
|
|||
const embeddings: number[][] = [];
|
||||
|
||||
let markdownForSubpaths = await Promise.all(
|
||||
subpaths.map((subpath) => convertURLToMarkdown(new URL(subpath, baseUrl)))
|
||||
subpaths.map((subpath) => convertURLToMarkdown(new URL(subpath, baseUrl))),
|
||||
);
|
||||
|
||||
// Filter out undefineds
|
||||
|
|
@ -79,7 +79,7 @@ export async function* indexDocs(
|
|||
}
|
||||
|
||||
const subpathEmbeddings = await embeddingsProvider.embed(
|
||||
markdownChunks.map((chunk) => chunk.content)
|
||||
markdownChunks.map((chunk) => chunk.content),
|
||||
);
|
||||
|
||||
markdownChunks.forEach((chunk, index) => {
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ const nhm = new NodeHtmlMarkdown(
|
|||
},
|
||||
},
|
||||
},
|
||||
undefined
|
||||
undefined,
|
||||
);
|
||||
|
||||
const STRIP_BEFORE = ["\n# "];
|
||||
|
|
@ -39,7 +39,7 @@ async function retrieveGitHubBlob(url: URL): Promise<string | undefined> {
|
|||
|
||||
const content = Buffer.from(
|
||||
(response.data as any).content || "",
|
||||
"base64"
|
||||
"base64",
|
||||
).toString();
|
||||
|
||||
const fileExtension = url.pathname.split(".").slice(-1)[0];
|
||||
|
|
@ -51,7 +51,7 @@ async function retrieveGitHubBlob(url: URL): Promise<string | undefined> {
|
|||
}
|
||||
|
||||
export async function convertURLToMarkdown(
|
||||
url: URL
|
||||
url: URL,
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
if (url.hostname === "github.com") {
|
||||
|
|
|
|||
30
core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts
Normal file
30
core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { EmbedOptions } from "../..";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
|
||||
|
||||
class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
model: "sentence-transformers/all-MiniLM-L6-v2",
|
||||
};
|
||||
|
||||
get id(): string {
|
||||
return "deepinfra::" + this.options.model;
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const resp = await fetch(
|
||||
`https://api.deepinfra.com/v1/inference/${this.options.model}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `bearer ${this.options.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({ inputs: chunks }),
|
||||
},
|
||||
);
|
||||
const data = await resp.json();
|
||||
console.log(data);
|
||||
return data.embeddings;
|
||||
}
|
||||
}
|
||||
|
||||
export default DeepInfraEmbeddingsProvider;
|
||||
|
|
@ -26,10 +26,10 @@ class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
return "ollama::" + this.options.model;
|
||||
}
|
||||
|
||||
embed(chunks: string[]) {
|
||||
async embed(chunks: string[]) {
|
||||
const results: any = [];
|
||||
for (const chunk of chunks) {
|
||||
results.push(embedOne(chunk, this.options));
|
||||
results.push(await embedOne(chunk, this.options));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
|
|||
class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.openai.com/v1",
|
||||
model: "text-embedding-3-large",
|
||||
model: "text-embedding-3-small",
|
||||
};
|
||||
|
||||
get id(): string {
|
||||
|
|
@ -32,7 +32,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
});
|
||||
const data = await resp.json();
|
||||
return data.data[0].embedding;
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ import {
|
|||
pipeline,
|
||||
} from "../../vendor/node_modules/@xenova/transformers";
|
||||
|
||||
import path from "path";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
|
||||
|
||||
env.allowLocalModels = true;
|
||||
env.allowRemoteModels = false;
|
||||
if (typeof window === "undefined") {
|
||||
// The embeddings provider should just never be called in the browser
|
||||
env.localModelPath = `${__dirname}/../models`;
|
||||
env.localModelPath = path.join(__dirname, "..", "models");
|
||||
}
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
|
|
@ -57,7 +58,7 @@ class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
) {
|
||||
let chunkGroup = chunks.slice(
|
||||
i,
|
||||
i + TransformersJsEmbeddingsProvider.MaxGroupSize
|
||||
i + TransformersJsEmbeddingsProvider.MaxGroupSize,
|
||||
);
|
||||
let output = await extractor(chunkGroup, {
|
||||
pooling: "mean",
|
||||
|
|
|
|||
59
core/indexing/embeddings/TransformersJsWorkerThread.js
Normal file
59
core/indexing/embeddings/TransformersJsWorkerThread.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import path from "path";
|
||||
import {
|
||||
env,
|
||||
pipeline,
|
||||
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
|
||||
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
|
||||
const { parentPort } = require("worker_threads");
|
||||
|
||||
env.allowLocalModels = true;
|
||||
env.allowRemoteModels = false;
|
||||
if (typeof window === "undefined") {
|
||||
// The embeddings provider should just never be called in the browser
|
||||
env.localModelPath = path.join(__dirname, "..", "models");
|
||||
}
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
static task = "feature-extraction";
|
||||
static model = TransformersJsEmbeddingsProvider.ModelName;
|
||||
static instance = null;
|
||||
|
||||
static async getInstance() {
|
||||
if (this.instance === null) {
|
||||
this.instance = await pipeline(this.task, this.model);
|
||||
}
|
||||
|
||||
return this.instance;
|
||||
}
|
||||
}
|
||||
|
||||
parentPort.on("message", async (chunks) => {
|
||||
try {
|
||||
const extractor = await EmbeddingsPipeline.getInstance();
|
||||
|
||||
if (!extractor) {
|
||||
throw new Error("TransformerJS embeddings pipeline is not initialized");
|
||||
}
|
||||
|
||||
let outputs = [];
|
||||
for (
|
||||
let i = 0;
|
||||
i < chunks.length;
|
||||
i += TransformersJsEmbeddingsProvider.MaxGroupSize
|
||||
) {
|
||||
let chunkGroup = chunks.slice(
|
||||
i,
|
||||
i + TransformersJsEmbeddingsProvider.MaxGroupSize,
|
||||
);
|
||||
let output = await extractor(chunkGroup, {
|
||||
pooling: "mean",
|
||||
normalize: true,
|
||||
});
|
||||
outputs.push(...output.tolist());
|
||||
}
|
||||
|
||||
parentPort.postMessage(outputs);
|
||||
} catch (error) {
|
||||
parentPort.postMessage({ error: error.message });
|
||||
}
|
||||
});
|
||||
119
core/indexing/indexCodebase.ts
Normal file
119
core/indexing/indexCodebase.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { IDE, IndexingProgressUpdate } from "..";
|
||||
import { ConfigHandler } from "../config/handler";
|
||||
import { FullTextSearchCodebaseIndex } from "./FullTextSearch";
|
||||
import { LanceDbIndex } from "./LanceDbIndex";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex";
|
||||
import { CodebaseIndex, IndexTag } from "./types";
|
||||
|
||||
export class PauseToken {
|
||||
constructor(private _paused: boolean) {}
|
||||
|
||||
set paused(value: boolean) {
|
||||
this._paused = value;
|
||||
}
|
||||
|
||||
get paused(): boolean {
|
||||
return this._paused;
|
||||
}
|
||||
}
|
||||
|
||||
export class CodebaseIndexer {
|
||||
configHandler: ConfigHandler;
|
||||
ide: IDE;
|
||||
pauseToken: PauseToken;
|
||||
|
||||
constructor(configHandler: ConfigHandler, ide: IDE, pauseToken: PauseToken) {
|
||||
this.configHandler = configHandler;
|
||||
this.ide = ide;
|
||||
this.pauseToken = pauseToken;
|
||||
}
|
||||
|
||||
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
|
||||
const indexes = [
|
||||
new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first
|
||||
new LanceDbIndex(
|
||||
config.embeddingsProvider,
|
||||
this.ide.readFile.bind(this.ide),
|
||||
),
|
||||
new FullTextSearchCodebaseIndex(),
|
||||
];
|
||||
|
||||
return indexes;
|
||||
}
|
||||
|
||||
async *refresh(
|
||||
workspaceDirs: string[],
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
if (config.disableIndexing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
|
||||
let completedDirs = 0;
|
||||
|
||||
yield {
|
||||
progress: 0,
|
||||
desc: "Starting indexing...",
|
||||
};
|
||||
|
||||
for (let directory of workspaceDirs) {
|
||||
const stats = await this.ide.getStats(directory);
|
||||
const branch = await this.ide.getBranch(directory);
|
||||
let completedIndexes = 0;
|
||||
|
||||
try {
|
||||
for (let codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
const [results, markComplete] = await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath),
|
||||
);
|
||||
|
||||
for await (let { progress, desc } of codebaseIndex.update(
|
||||
tag,
|
||||
results,
|
||||
markComplete,
|
||||
)) {
|
||||
// Handle pausing in this loop because it's the only one really taking time
|
||||
while (this.pauseToken.paused) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs +
|
||||
(completedIndexes + progress) / indexesToBuild.length) /
|
||||
workspaceDirs.length,
|
||||
desc,
|
||||
};
|
||||
}
|
||||
completedIndexes++;
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs + completedIndexes / indexesToBuild.length) /
|
||||
workspaceDirs.length,
|
||||
desc: "Completed indexing " + codebaseIndex.artifactId,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error refreshing index: ", e);
|
||||
}
|
||||
|
||||
completedDirs++;
|
||||
yield {
|
||||
progress: completedDirs / workspaceDirs.length,
|
||||
desc: "Indexing Complete",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -33,7 +33,7 @@ export class SqliteDb {
|
|||
path STRING NOT NULL,
|
||||
cacheKey STRING NOT NULL,
|
||||
lastUpdated INTEGER NOT NULL
|
||||
)`
|
||||
)`,
|
||||
);
|
||||
|
||||
await db.exec(
|
||||
|
|
@ -43,7 +43,7 @@ export class SqliteDb {
|
|||
dir STRING NOT NULL,
|
||||
branch STRING NOT NULL,
|
||||
artifactId STRING NOT NULL
|
||||
)`
|
||||
)`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -67,7 +67,7 @@ export class SqliteDb {
|
|||
}
|
||||
|
||||
async function getSavedItemsForTag(
|
||||
tag: IndexTag
|
||||
tag: IndexTag,
|
||||
): Promise<{ path: string; cacheKey: string; lastUpdated: number }[]> {
|
||||
const db = await SqliteDb.get();
|
||||
const stmt = await db.prepare(
|
||||
|
|
@ -75,7 +75,7 @@ async function getSavedItemsForTag(
|
|||
WHERE dir = ? AND branch = ? AND artifactId = ?`,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
tag.artifactId,
|
||||
);
|
||||
const rows = await stmt.all();
|
||||
return rows;
|
||||
|
|
@ -96,7 +96,7 @@ enum AddRemoveResultType {
|
|||
async function getAddRemoveForTag(
|
||||
tag: IndexTag,
|
||||
currentFiles: LastModifiedMap,
|
||||
readFile: (path: string) => Promise<string>
|
||||
readFile: (path: string) => Promise<string>,
|
||||
): Promise<[PathAndCacheKey[], PathAndCacheKey[], MarkCompleteCallback]> {
|
||||
const newLastUpdatedTimestamp = Date.now();
|
||||
|
||||
|
|
@ -137,8 +137,8 @@ async function getAddRemoveForTag(
|
|||
Object.keys(currentFiles).map(async (path) => {
|
||||
const fileContents = await readFile(path);
|
||||
return { path, cacheKey: calculateHash(fileContents) };
|
||||
})
|
||||
))
|
||||
}),
|
||||
)),
|
||||
);
|
||||
|
||||
// Create the markComplete callback function
|
||||
|
|
@ -159,21 +159,23 @@ async function getAddRemoveForTag(
|
|||
newLastUpdatedTimestamp,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
tag.artifactId,
|
||||
);
|
||||
break;
|
||||
case AddRemoveResultType.Remove:
|
||||
await db.run(
|
||||
`DELETE FROM tag_catalog WHERE
|
||||
path IN (?) AND
|
||||
cacheKey = ? AND
|
||||
path = ? AND
|
||||
dir = ? AND
|
||||
branch = ? AND
|
||||
artifactId = ?
|
||||
`,
|
||||
remove.map((r) => `'${r.path}'`).join(", "),
|
||||
cacheKey,
|
||||
path,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
tag.artifactId,
|
||||
);
|
||||
break;
|
||||
case AddRemoveResultType.UpdateNewVersion:
|
||||
|
|
@ -192,7 +194,7 @@ async function getAddRemoveForTag(
|
|||
path,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
tag.artifactId,
|
||||
);
|
||||
break;
|
||||
case AddRemoveResultType.UpdateOldVersion:
|
||||
|
|
@ -233,11 +235,11 @@ async function getAddRemoveForTag(
|
|||
*/
|
||||
async function getTagsFromGlobalCache(
|
||||
cacheKey: string,
|
||||
artifactId: string
|
||||
artifactId: string,
|
||||
): Promise<IndexTag[]> {
|
||||
const db = await SqliteDb.get();
|
||||
const stmt = await db.prepare(
|
||||
`SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?`
|
||||
`SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?`,
|
||||
);
|
||||
const rows = await stmt.all(cacheKey, artifactId);
|
||||
return rows;
|
||||
|
|
@ -252,12 +254,12 @@ function calculateHash(fileContents: string): string {
|
|||
export async function getComputeDeleteAddRemove(
|
||||
tag: IndexTag,
|
||||
currentFiles: LastModifiedMap,
|
||||
readFile: (path: string) => Promise<string>
|
||||
readFile: (path: string) => Promise<string>,
|
||||
): Promise<[RefreshIndexResults, MarkCompleteCallback]> {
|
||||
const [add, remove, markComplete] = await getAddRemoveForTag(
|
||||
tag,
|
||||
currentFiles,
|
||||
readFile
|
||||
readFile,
|
||||
);
|
||||
|
||||
const compute: PathAndCacheKey[] = [];
|
||||
|
|
@ -331,7 +333,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
|
|||
async *update(
|
||||
tag: IndexTag,
|
||||
results: RefreshIndexResults,
|
||||
_: MarkCompleteCallback
|
||||
_: MarkCompleteCallback,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const add = [...results.compute, ...results.addTag];
|
||||
const remove = [...results.del, ...results.removeTag];
|
||||
|
|
@ -348,26 +350,26 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
|
|||
|
||||
private async computeOrAddTag(
|
||||
cacheKey: string,
|
||||
tag: IndexTag
|
||||
tag: IndexTag,
|
||||
): Promise<void> {
|
||||
await this.db.run(
|
||||
"INSERT INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
|
||||
cacheKey,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
tag.artifactId,
|
||||
);
|
||||
}
|
||||
private async deleteOrRemoveTag(
|
||||
cacheKey: string,
|
||||
tag: IndexTag
|
||||
tag: IndexTag,
|
||||
): Promise<void> {
|
||||
await this.db.run(
|
||||
"DELETE FROM global_cache WHERE cacheKey = ? AND dir = ? AND branch = ? AND artifactId = ?",
|
||||
cacheKey,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
tag.artifactId,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ export enum IndexResultType {
|
|||
|
||||
export type MarkCompleteCallback = (
|
||||
items: PathAndCacheKey[],
|
||||
resultType: IndexResultType
|
||||
resultType: IndexResultType,
|
||||
) => void;
|
||||
|
||||
export interface CodebaseIndex {
|
||||
|
|
@ -17,7 +17,7 @@ export interface CodebaseIndex {
|
|||
update(
|
||||
tag: IndexTag,
|
||||
results: RefreshIndexResults,
|
||||
markComplete: MarkCompleteCallback
|
||||
markComplete: MarkCompleteCallback,
|
||||
): AsyncGenerator<IndexingProgressUpdate>;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import {
|
|||
} from "./templates/chat";
|
||||
import {
|
||||
alpacaEditPrompt,
|
||||
claudeEditPrompt,
|
||||
codeLlama70bEditPrompt,
|
||||
codellamaEditPrompt,
|
||||
deepseekEditPrompt,
|
||||
|
|
@ -34,6 +35,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
|
|||
"openai",
|
||||
"ollama",
|
||||
"together",
|
||||
"anthropic",
|
||||
];
|
||||
|
||||
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
|
||||
|
|
@ -81,7 +83,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
|
|||
|
||||
function llmCanGenerateInParallel(
|
||||
provider: ModelProvider,
|
||||
model: string
|
||||
model: string,
|
||||
): boolean {
|
||||
if (provider === "openai") {
|
||||
return model.includes("gpt");
|
||||
|
|
@ -168,7 +170,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
|
|||
function autodetectTemplateFunction(
|
||||
model: string,
|
||||
provider: ModelProvider,
|
||||
explicitTemplate: TemplateType | undefined = undefined
|
||||
explicitTemplate: TemplateType | undefined = undefined,
|
||||
) {
|
||||
if (
|
||||
explicitTemplate === undefined &&
|
||||
|
|
@ -205,7 +207,7 @@ function autodetectTemplateFunction(
|
|||
|
||||
function autodetectPromptTemplates(
|
||||
model: string,
|
||||
explicitTemplate: TemplateType | undefined = undefined
|
||||
explicitTemplate: TemplateType | undefined = undefined,
|
||||
) {
|
||||
const templateType = explicitTemplate || autodetectTemplateType(model);
|
||||
const templates: Record<string, any> = {};
|
||||
|
|
@ -236,6 +238,8 @@ function autodetectPromptTemplates(
|
|||
editTemplate = neuralChatEditPrompt;
|
||||
} else if (templateType === "codellama-70b") {
|
||||
editTemplate = codeLlama70bEditPrompt;
|
||||
} else if (templateType === "anthropic") {
|
||||
editTemplate = claudeEditPrompt;
|
||||
} else if (templateType) {
|
||||
editTemplate = simplestEditPrompt;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,29 @@
|
|||
import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken";
|
||||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
// @ts-ignore
|
||||
import llamaTokenizer from "llama-tokenizer-js";
|
||||
import { ChatMessage, MessageContent, MessagePart } from "..";
|
||||
import { autodetectTemplateType } from "./autodetect";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
|
||||
|
||||
let encoding: Tiktoken | null = null;
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
}
|
||||
|
||||
function encodingForModel(modelName: string): Tiktoken {
|
||||
if (encoding) {
|
||||
return encoding;
|
||||
let gptEncoding: Encoding | null = null;
|
||||
|
||||
function encodingForModel(modelName: string): Encoding {
|
||||
const modelType = autodetectTemplateType(modelName);
|
||||
|
||||
if (!modelType || modelType === "none") {
|
||||
if (!gptEncoding) {
|
||||
gptEncoding = _encodingForModel("gpt-4");
|
||||
}
|
||||
|
||||
return gptEncoding;
|
||||
}
|
||||
|
||||
encoding = _encodingForModel("gpt-4");
|
||||
return encoding;
|
||||
return llamaTokenizer;
|
||||
}
|
||||
|
||||
function countImageTokens(content: MessagePart): number {
|
||||
|
|
@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number {
|
|||
}
|
||||
}
|
||||
|
||||
function countTokens(content: MessageContent, modelName: string): number {
|
||||
function countTokens(
|
||||
content: MessageContent,
|
||||
// defaults to llama2 because the tokenizer tends to produce more tokens
|
||||
modelName: string = "llama2",
|
||||
): number {
|
||||
const encoding = encodingForModel(modelName);
|
||||
if (Array.isArray(content)) {
|
||||
return content.reduce((acc, part) => {
|
||||
|
|
@ -63,7 +80,7 @@ export function stripImages(content: MessageContent): string {
|
|||
|
||||
function countChatMessageTokens(
|
||||
modelName: string,
|
||||
chatMessage: ChatMessage
|
||||
chatMessage: ChatMessage,
|
||||
): number {
|
||||
// Doing simpler, safer version of what is here:
|
||||
// https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb
|
||||
|
|
@ -72,21 +89,29 @@ function countChatMessageTokens(
|
|||
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
|
||||
}
|
||||
|
||||
function pruneLinesFromTop(prompt: string, maxTokens: number): string {
|
||||
let totalTokens = countTokens(prompt, "gpt-4");
|
||||
function pruneLinesFromTop(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
modelName: string,
|
||||
): string {
|
||||
let totalTokens = countTokens(prompt, modelName);
|
||||
const lines = prompt.split("\n");
|
||||
while (totalTokens > maxTokens && lines.length > 0) {
|
||||
totalTokens -= countTokens(lines.shift()!, "gpt-4");
|
||||
totalTokens -= countTokens(lines.shift()!, modelName);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function pruneLinesFromBottom(prompt: string, maxTokens: number): string {
|
||||
let totalTokens = countTokens(prompt, "gpt-4");
|
||||
function pruneLinesFromBottom(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
modelName: string,
|
||||
): string {
|
||||
let totalTokens = countTokens(prompt, modelName);
|
||||
const lines = prompt.split("\n");
|
||||
while (totalTokens > maxTokens && lines.length > 0) {
|
||||
totalTokens -= countTokens(lines.pop()!, "gpt-4");
|
||||
totalTokens -= countTokens(lines.pop()!, modelName);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
|
|
@ -95,7 +120,7 @@ function pruneLinesFromBottom(prompt: string, maxTokens: number): string {
|
|||
function pruneStringFromBottom(
|
||||
modelName: string,
|
||||
maxTokens: number,
|
||||
prompt: string
|
||||
prompt: string,
|
||||
): string {
|
||||
const encoding = encodingForModel(modelName);
|
||||
|
||||
|
|
@ -110,7 +135,7 @@ function pruneStringFromBottom(
|
|||
function pruneStringFromTop(
|
||||
modelName: string,
|
||||
maxTokens: number,
|
||||
prompt: string
|
||||
prompt: string,
|
||||
): string {
|
||||
const encoding = encodingForModel(modelName);
|
||||
|
||||
|
|
@ -126,7 +151,7 @@ function pruneRawPromptFromTop(
|
|||
modelName: string,
|
||||
contextLength: number,
|
||||
prompt: string,
|
||||
tokensForCompletion: number
|
||||
tokensForCompletion: number,
|
||||
): string {
|
||||
const maxTokens =
|
||||
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
|
||||
|
|
@ -137,7 +162,7 @@ function pruneRawPromptFromBottom(
|
|||
modelName: string,
|
||||
contextLength: number,
|
||||
prompt: string,
|
||||
tokensForCompletion: number
|
||||
tokensForCompletion: number,
|
||||
): string {
|
||||
const maxTokens =
|
||||
contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY;
|
||||
|
|
@ -156,7 +181,7 @@ function pruneChatHistory(
|
|||
modelName: string,
|
||||
chatHistory: ChatMessage[],
|
||||
contextLength: number,
|
||||
tokensForCompletion: number
|
||||
tokensForCompletion: number,
|
||||
): ChatMessage[] {
|
||||
let totalTokens =
|
||||
tokensForCompletion +
|
||||
|
|
@ -170,11 +195,11 @@ function pruneChatHistory(
|
|||
|
||||
const longerThanOneThird = longestMessages.filter(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) > contextLength / 3
|
||||
countTokens(message.content, modelName) > contextLength / 3,
|
||||
);
|
||||
const distanceFromThird = longerThanOneThird.map(
|
||||
(message: ChatMessage) =>
|
||||
countTokens(message.content, modelName) - contextLength / 3
|
||||
countTokens(message.content, modelName) - contextLength / 3,
|
||||
);
|
||||
|
||||
for (let i = 0; i < longerThanOneThird.length; i++) {
|
||||
|
|
@ -242,7 +267,7 @@ function pruneChatHistory(
|
|||
modelName,
|
||||
contextLength,
|
||||
stripImages(message.content),
|
||||
tokensForCompletion
|
||||
tokensForCompletion,
|
||||
);
|
||||
totalTokens = contextLength;
|
||||
}
|
||||
|
|
@ -258,7 +283,7 @@ function compileChatMessages(
|
|||
supportsImages: boolean,
|
||||
prompt: string | undefined = undefined,
|
||||
functions: any[] | undefined = undefined,
|
||||
systemMessage: string | undefined = undefined
|
||||
systemMessage: string | undefined = undefined,
|
||||
): ChatMessage[] {
|
||||
const msgsCopy = msgs ? msgs.map((msg) => ({ ...msg })) : [];
|
||||
|
||||
|
|
@ -289,7 +314,7 @@ function compileChatMessages(
|
|||
|
||||
if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) {
|
||||
throw new Error(
|
||||
`maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`
|
||||
`maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -307,7 +332,7 @@ function compileChatMessages(
|
|||
modelName,
|
||||
msgsCopy,
|
||||
contextLength,
|
||||
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY
|
||||
functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY,
|
||||
);
|
||||
|
||||
if (
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
if (CompletionOptionsForModels[options.model as ModelName]) {
|
||||
this.completionOptions = mergeJson(
|
||||
this.completionOptions,
|
||||
CompletionOptionsForModels[options.model as ModelName] || {}
|
||||
CompletionOptionsForModels[options.model as ModelName] || {},
|
||||
);
|
||||
}
|
||||
this.requestOptions = options.requestOptions;
|
||||
|
|
@ -107,7 +107,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
autodetectTemplateFunction(
|
||||
options.model,
|
||||
this.providerName,
|
||||
options.template
|
||||
options.template,
|
||||
);
|
||||
this.writeLog = options.writeLog;
|
||||
this.llmRequestHook = options.llmRequestHook;
|
||||
|
|
@ -131,7 +131,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
private _compileChatMessages(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
functions?: any[]
|
||||
functions?: any[],
|
||||
) {
|
||||
let contextLength = this.contextLength;
|
||||
if (
|
||||
|
|
@ -150,7 +150,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.supportsImages(),
|
||||
undefined,
|
||||
functions,
|
||||
this.systemMessage
|
||||
this.systemMessage,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -176,7 +176,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
private _compileLogMessage(
|
||||
prompt: string,
|
||||
completionOptions: CompletionOptions
|
||||
completionOptions: CompletionOptions,
|
||||
): string {
|
||||
const dict = { contextLength: this.contextLength, ...completionOptions };
|
||||
const settings = Object.entries(dict)
|
||||
|
|
@ -209,7 +209,7 @@ ${prompt}`;
|
|||
|
||||
protected fetch(
|
||||
url: RequestInfo | URL,
|
||||
init?: RequestInit
|
||||
init?: RequestInit,
|
||||
): Promise<Response> {
|
||||
if (this._fetch) {
|
||||
// Custom Node.js fetch
|
||||
|
|
@ -219,7 +219,7 @@ ${prompt}`;
|
|||
// Most of the requestOptions aren't available in the browser
|
||||
const headers = new Headers(init?.headers);
|
||||
for (const [key, value] of Object.entries(
|
||||
this.requestOptions?.headers || {}
|
||||
this.requestOptions?.headers || {},
|
||||
)) {
|
||||
headers.append(key, value as string);
|
||||
}
|
||||
|
|
@ -238,7 +238,7 @@ ${prompt}`;
|
|||
|
||||
const completionOptions: CompletionOptions = mergeJson(
|
||||
this.completionOptions,
|
||||
options
|
||||
options,
|
||||
);
|
||||
|
||||
return { completionOptions, log, raw };
|
||||
|
|
@ -254,7 +254,7 @@ ${prompt}`;
|
|||
|
||||
async *streamComplete(
|
||||
prompt: string,
|
||||
options: LLMFullCompletionOptions = {}
|
||||
options: LLMFullCompletionOptions = {},
|
||||
) {
|
||||
const { completionOptions, log, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
|
|
@ -263,7 +263,7 @@ ${prompt}`;
|
|||
completionOptions.model,
|
||||
this.contextLength,
|
||||
prompt,
|
||||
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
|
||||
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
|
||||
);
|
||||
|
||||
if (!raw) {
|
||||
|
|
@ -302,7 +302,7 @@ ${prompt}`;
|
|||
completionOptions.model,
|
||||
this.contextLength,
|
||||
prompt,
|
||||
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
|
||||
completionOptions.maxTokens || DEFAULT_MAX_TOKENS,
|
||||
);
|
||||
|
||||
if (!raw) {
|
||||
|
|
@ -338,7 +338,7 @@ ${prompt}`;
|
|||
|
||||
async *streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOptions = {}
|
||||
options: LLMFullCompletionOptions = {},
|
||||
): AsyncGenerator<ChatMessage, LLMReturnValue> {
|
||||
const { completionOptions, log, raw } =
|
||||
this._parseCompletionOptions(options);
|
||||
|
|
@ -363,7 +363,7 @@ ${prompt}`;
|
|||
if (this.templateMessages) {
|
||||
for await (const chunk of this._streamComplete(
|
||||
prompt,
|
||||
completionOptions
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
yield { role: "assistant", content: chunk };
|
||||
|
|
@ -371,7 +371,7 @@ ${prompt}`;
|
|||
} else {
|
||||
for await (const chunk of this._streamChat(
|
||||
messages,
|
||||
completionOptions
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk.content;
|
||||
yield chunk;
|
||||
|
|
@ -392,24 +392,24 @@ ${prompt}`;
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.templateMessages) {
|
||||
throw new Error(
|
||||
"You must either implement templateMessages or _streamChat"
|
||||
"You must either implement templateMessages or _streamChat",
|
||||
);
|
||||
}
|
||||
|
||||
for await (const chunk of this._streamComplete(
|
||||
this.templateMessages(messages),
|
||||
options
|
||||
options,
|
||||
)) {
|
||||
yield { role: "assistant", content: chunk };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,19 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
|
||||
import {
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
ModelProvider,
|
||||
} from "../..";
|
||||
import { streamSse } from "../stream";
|
||||
import { anthropicTemplateMessages } from "../templates/chat";
|
||||
|
||||
class Anthropic extends BaseLLM {
|
||||
static providerName: ModelProvider = "anthropic";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "claude-2",
|
||||
templateMessages: anthropicTemplateMessages,
|
||||
contextLength: 100_000,
|
||||
model: "claude-3-opus-20240229",
|
||||
contextLength: 200_000,
|
||||
completionOptions: {
|
||||
model: "claude-2",
|
||||
model: "claude-3-opus-20240229",
|
||||
maxTokens: 4096,
|
||||
},
|
||||
apiBase: "https://api.anthropic.com/v1",
|
||||
|
|
@ -20,25 +23,24 @@ class Anthropic extends BaseLLM {
|
|||
super(options);
|
||||
}
|
||||
|
||||
private _convertArgs(options: CompletionOptions, prompt: string) {
|
||||
private _convertArgs(options: CompletionOptions) {
|
||||
const finalOptions = {
|
||||
prompt,
|
||||
top_k: options.topK,
|
||||
top_p: options.topP,
|
||||
temperature: options.temperature,
|
||||
max_tokens_to_sample: options.maxTokens,
|
||||
model: options.model,
|
||||
max_tokens: options.maxTokens ?? 2048,
|
||||
model: options.model === "claude-2" ? "claude-2.1" : options.model,
|
||||
stop_sequences: options.stop,
|
||||
};
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
protected async _complete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
): Promise<string> {
|
||||
const response = await this.fetch(this.apiBase + "/complete", {
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const response = await this.fetch(this.apiBase + "/messages", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -47,35 +49,16 @@ class Anthropic extends BaseLLM {
|
|||
"x-api-key": this.apiKey as string,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this._convertArgs(options, prompt),
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
const result = await response.json();
|
||||
return result.completion;
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<string> {
|
||||
const response = await this.fetch(this.apiBase + "/complete", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": this.apiKey as string,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this._convertArgs(options, prompt),
|
||||
...this._convertArgs(options),
|
||||
messages,
|
||||
system: this.systemMessage,
|
||||
stream: true,
|
||||
}),
|
||||
});
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.completion) {
|
||||
yield value.completion;
|
||||
if (value.delta?.text) {
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ class Bedrock extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const response = await this.fetch(
|
||||
`${this.apiBase}/model/${options.model}/invoke-with-response-stream`,
|
||||
|
|
@ -22,7 +22,7 @@ class Bedrock extends BaseLLM {
|
|||
body: JSON.stringify({
|
||||
inputText: prompt,
|
||||
}),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
|
|
|
|||
|
|
@ -5,13 +5,13 @@ class CustomLLMClass extends BaseLLM {
|
|||
private customStreamCompletion?: (
|
||||
prompt: string,
|
||||
options: CompletionOptions,
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
|
||||
) => AsyncGenerator<string>;
|
||||
|
||||
private customStreamChat?: (
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
|
||||
) => AsyncGenerator<string>;
|
||||
|
||||
constructor(custom: CustomLLM) {
|
||||
|
|
@ -22,13 +22,13 @@ class CustomLLMClass extends BaseLLM {
|
|||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (this.customStreamChat) {
|
||||
for await (const content of this.customStreamChat(
|
||||
messages,
|
||||
options,
|
||||
(...args) => this.fetch(...args)
|
||||
(...args) => this.fetch(...args),
|
||||
)) {
|
||||
yield { role: "assistant", content };
|
||||
}
|
||||
|
|
@ -41,13 +41,13 @@ class CustomLLMClass extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
if (this.customStreamCompletion) {
|
||||
for await (const content of this.customStreamCompletion(
|
||||
prompt,
|
||||
options,
|
||||
(...args) => this.fetch(...args)
|
||||
(...args) => this.fetch(...args),
|
||||
)) {
|
||||
yield content;
|
||||
}
|
||||
|
|
@ -55,13 +55,13 @@ class CustomLLMClass extends BaseLLM {
|
|||
for await (const content of this.customStreamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
options,
|
||||
(...args) => this.fetch(...args)
|
||||
(...args) => this.fetch(...args),
|
||||
)) {
|
||||
yield content;
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
"Either streamCompletion or streamChat must be defined in a custom LLM in config.ts"
|
||||
"Either streamCompletion or streamChat must be defined in a custom LLM in config.ts",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -120,7 +120,7 @@ class Flowise extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const message: ChatMessage = { role: "user", content: prompt };
|
||||
for await (const chunk of this._streamChat([message], options)) {
|
||||
|
|
@ -130,7 +130,7 @@ class Flowise extends BaseLLM {
|
|||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const requestBody = this._getRequestBody(messages, options);
|
||||
const { socket, socketInfo } = await this._initializeSocket();
|
||||
|
|
@ -156,7 +156,7 @@ class Flowise extends BaseLLM {
|
|||
|
||||
protected _getRequestBody(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): any {
|
||||
const lastMessage = messages[messages.length - 1];
|
||||
const history = messages
|
||||
|
|
@ -200,7 +200,7 @@ class Flowise extends BaseLLM {
|
|||
socketInfo.internal.hasNextTokenPromiseResolve =
|
||||
hasNextTokenResolve;
|
||||
socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject;
|
||||
}
|
||||
},
|
||||
);
|
||||
};
|
||||
const resetTimeout = () => {
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../..";
|
|||
import { streamResponse } from "../stream";
|
||||
|
||||
// const SERVER_URL = "http://localhost:3000";
|
||||
const SERVER_URL = "https://node-proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
const SERVER_URL = "https://node-proxy-server-green-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
class FreeTrial extends BaseLLM {
|
||||
static providerName: ModelProvider = "free-trial";
|
||||
|
|
@ -29,7 +29,7 @@ class FreeTrial extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const args = this._convertArgs(this.collectArgs(options));
|
||||
|
||||
|
|
@ -67,7 +67,7 @@ class FreeTrial extends BaseLLM {
|
|||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const args = this._convertArgs(this.collectArgs(options));
|
||||
|
||||
|
|
|
|||
|
|
@ -17,11 +17,11 @@ class Gemini extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
for await (const chunk of this._streamChat(
|
||||
[{ role: "user", content: prompt }],
|
||||
options
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(chunk.content);
|
||||
}
|
||||
|
|
@ -29,7 +29,7 @@ class Gemini extends BaseLLM {
|
|||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const apiUrl = `https://${this.region}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/${this.region}/publishers/google/models/gemini-pro:streamGenerateContent`;
|
||||
const body = {
|
||||
|
|
@ -60,12 +60,13 @@ class Gemini extends BaseLLM {
|
|||
if (data[0]?.error) {
|
||||
throw new Error(data[0].error.message);
|
||||
}
|
||||
let combinedText = '';
|
||||
let combinedText = "";
|
||||
for (const entry of data || []) {
|
||||
combinedText += entry?.candidates?.[0]?.content?.parts?.[0]?.text || '';
|
||||
combinedText += entry?.candidates?.[0]?.content?.parts?.[0]?.text || "";
|
||||
}
|
||||
|
||||
yield { role: "assistant", content: combinedText.trim() }; }
|
||||
yield { role: "assistant", content: combinedText.trim() };
|
||||
}
|
||||
}
|
||||
|
||||
export default Gemini;
|
||||
|
|
|
|||
|
|
@ -13,31 +13,53 @@ class GooglePalm extends BaseLLM {
|
|||
static providerName: ModelProvider = "google-palm";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "chat-bison-001",
|
||||
model: "gemini-pro",
|
||||
apiBase: "https://generativelanguage.googleapis.com",
|
||||
};
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
for await (const message of this._streamChat(
|
||||
[{ content: prompt, role: "user" }],
|
||||
options
|
||||
options,
|
||||
)) {
|
||||
yield stripImages(message.content);
|
||||
}
|
||||
}
|
||||
|
||||
private removeSystemMessage(messages: ChatMessage[]) {
|
||||
const msgs = [...messages];
|
||||
|
||||
if (msgs[0]?.role === "system") {
|
||||
let sysMsg = msgs.shift()!.content;
|
||||
// @ts-ignore
|
||||
if (msgs[0]?.role === "user") {
|
||||
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
|
||||
}
|
||||
}
|
||||
|
||||
return msgs;
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
let convertedMsgs = this.removeSystemMessage(messages);
|
||||
if (options.model.includes("gemini")) {
|
||||
for await (const message of this.streamChatGemini(messages, options)) {
|
||||
for await (const message of this.streamChatGemini(
|
||||
convertedMsgs,
|
||||
options,
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
} else {
|
||||
for await (const message of this.streamChatBison(messages, options)) {
|
||||
for await (const message of this.streamChatBison(
|
||||
convertedMsgs,
|
||||
options,
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
}
|
||||
|
|
@ -58,9 +80,9 @@ class GooglePalm extends BaseLLM {
|
|||
|
||||
private async *streamChatGemini(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const apiURL = `https://generativelanguage.googleapis.com/v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`;
|
||||
const apiURL = `${this.apiBase}/v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`;
|
||||
const body = {
|
||||
contents: messages.map((msg) => {
|
||||
return {
|
||||
|
|
@ -128,14 +150,14 @@ class GooglePalm extends BaseLLM {
|
|||
}
|
||||
private async *streamChatBison(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const msgList = [];
|
||||
for (const message of messages) {
|
||||
msgList.push({ content: message.content });
|
||||
}
|
||||
|
||||
const apiURL = `https://generativelanguage.googleapis.com/v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`;
|
||||
const apiURL = `${this.apiBase}/v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`;
|
||||
const body = { prompt: { messages: msgList } };
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -1,34 +1,50 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { ChatMessage, CompletionOptions, ModelProvider } from "../..";
|
||||
import { CompletionOptions, ModelProvider } from "../..";
|
||||
import { streamSse } from "../stream";
|
||||
|
||||
class HuggingFaceInferenceAPI extends BaseLLM {
|
||||
static providerName: ModelProvider = "huggingface-inference-api";
|
||||
|
||||
private _convertArgs(options: CompletionOptions, prompt: string) {
|
||||
const finalOptions = {};
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
protected async _complete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
): Promise<string> {
|
||||
throw new Error("Method not implemented.");
|
||||
private _convertArgs(options: CompletionOptions) {
|
||||
return {
|
||||
max_new_tokens: options.maxTokens ?? 1024,
|
||||
temperature: options.temperature,
|
||||
top_k: options.topK,
|
||||
top_p: options.topP,
|
||||
};
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please add the `apiBase` field in your config.json.",
|
||||
);
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
throw new Error("Method not implemented.");
|
||||
const response = await this.fetch(this.apiBase, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
inputs: prompt,
|
||||
stream: true,
|
||||
parameters: this._convertArgs(options),
|
||||
}),
|
||||
});
|
||||
for await (const chunk of streamSse(response)) {
|
||||
let text = chunk?.token?.text ?? "";
|
||||
if (text.endsWith("</s>")) {
|
||||
yield text.slice(0, -5);
|
||||
} else {
|
||||
yield text;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class HuggingFaceTGI extends BaseLLM {
|
|||
if (response.status !== 200) {
|
||||
console.warn(
|
||||
"Error calling Hugging Face TGI /info endpoint: ",
|
||||
await response.text()
|
||||
await response.text(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
@ -44,7 +44,7 @@ class HuggingFaceTGI extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const args = this._convertArgs(options, prompt);
|
||||
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ class LlamaCpp extends BaseLLM {
|
|||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue