profile dialog showing, merge main

This commit is contained in:
Dallin Romney 2024-11-20 16:23:12 -08:00
commit 4ffb7734fe
159 changed files with 4432 additions and 1518 deletions

6
.gitignore vendored
View file

@ -142,7 +142,7 @@ codeql
.tiktoken_cache
# IntelliJ Plugin
# IntelliJ Plugin
**/**/.gradle
**/**/.qodana
**/**/build
@ -168,4 +168,6 @@ extensions/intellij/.idea/**
**/.idea/shelf/
extensions/intellij/bin
extensions/.continue-debug/
extensions/.continue-debug/
*.vsix

1
.husky/pre-commit Normal file
View file

@ -0,0 +1 @@
npx prettier --write .

View file

@ -1,4 +1,17 @@
binary/bin
binary/build
binary/out
binary/tmp
core/.continue-test
docs/.docusaurus
extensions/.continue-debug
extensions/vscode/continue_rc_schema.json
extensions/vscode/.vscode-test
extensions/vscode/bin
extensions/vscode/build
extensions/vscode/out
gui/dist
**/.continueignore
CHANGELOG.md
**/continue_tutorial.py
**/node_modules

View file

@ -20,6 +20,7 @@
"binary/build/**": true,
"binary/out/**": true,
"binary/tmp/**": true,
"core/edit/lazy/test-examples/**": true,
"core/llm/llamaTokenizer.js": true,
"core/llm/llamaTokenizer.mjs": true,
"core/vendor/**": true,

View file

@ -6,7 +6,7 @@ import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js";
import { constructAutocompletePrompt } from "./constructPrompt.js";
import { aggregateSnippets } from "./aggregateSnippets";
// @prettier-ignore
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
@ -29,6 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get();
const ERRORS_TO_IGNORE = [
// From Ollama
"unexpected server status",
"operation was aborted"
];
export type GetLspDefinitionsFunction = (
@ -176,17 +177,18 @@ export class CompletionProvider {
// or they might separately track recently edited ranges)
const extraSnippets = await this._getExtraSnippets(helper);
let snippets = await constructAutocompletePrompt(
helper,
extraSnippets,
this.contextRetrievalService,
);
const [snippets, diff, workspaceDirs] = await Promise.all([
aggregateSnippets(helper, extraSnippets, this.contextRetrievalService),
this.ide.getDiff(true),
this.ide.getWorkspaceDirs(),
]);
const { prompt, prefix, suffix, completionOptions } = renderPrompt(
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
snippets,
await this.ide.getWorkspaceDirs(),
diff,
workspaceDirs,
helper,
);
});
// Completion
let completion: string | undefined = "";

View file

@ -0,0 +1,45 @@
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import {
fillPromptWithSnippets,
rankAndOrderSnippets,
type AutocompleteSnippet,
} from "./context/ranking/index.js";
import { HelperVars } from "./util/HelperVars.js";
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteSnippet[],
caretWindow: string,
): AutocompleteSnippet[] {
return snippets
.map((snippet) => ({ ...snippet }))
.filter(
(s) =>
s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()),
);
}
export async function aggregateSnippets(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
contextRetrievalService: ContextRetrievalService,
): Promise<AutocompleteSnippet[]> {
let snippets = await contextRetrievalService.retrieveCandidateSnippets(
helper,
extraSnippets,
);
snippets = filterSnippetsAlreadyInCaretWindow(
snippets,
helper.prunedCaretWindow,
);
const scoredSnippets = rankAndOrderSnippets(snippets, helper);
const finalSnippets = fillPromptWithSnippets(
scoredSnippets,
helper.maxSnippetTokens,
helper.modelName,
);
return finalSnippets;
}

View file

@ -1,88 +0,0 @@
import { Position, Range } from "../index.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
import {
fillPromptWithSnippets,
rankAndOrderSnippets,
removeRangeFromSnippets,
type AutocompleteSnippet,
} from "./context/ranking/index.js";
import { HelperVars } from "./util/HelperVars.js";
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteSnippet[],
caretWindow: string,
): AutocompleteSnippet[] {
return snippets
.map((snippet) => ({ ...snippet }))
.filter(
(s) =>
s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()),
);
}
function getRangeOfPrefixAndSuffixWithBuffer(
prefix: string,
suffix: string,
caretPos: Position,
): Range {
// Remove prefix range from snippets
const prefixLines = prefix.split("\n").length;
const suffixLines = suffix.split("\n").length;
const buffer = 8;
const prefixSuffixRangeWithBuffer = {
start: {
line: caretPos.line - prefixLines - buffer,
character: 0,
},
end: {
line: caretPos.line + suffixLines + buffer,
character: 0,
},
};
return prefixSuffixRangeWithBuffer;
}
export async function constructAutocompletePrompt(
helper: HelperVars,
extraSnippets: AutocompleteSnippet[],
contextRetrievalService: ContextRetrievalService,
): Promise<AutocompleteSnippet[]> {
let snippets = await contextRetrievalService.retrieveCandidateSnippets(
helper,
extraSnippets,
);
snippets = filterSnippetsAlreadyInCaretWindow(
snippets,
helper.prunedCaretWindow,
);
const scoredSnippets = rankAndOrderSnippets(snippets, helper);
// This might be redundant with filterSnippetsAlreadyInCaretWindow
let finalSnippets = removeRangeFromSnippets(
scoredSnippets,
helper.filepath.split("://").slice(-1)[0],
getRangeOfPrefixAndSuffixWithBuffer(
helper.prunedPrefix,
helper.prunedSuffix,
helper.pos,
),
);
// Filter snippets below similarity threshold
finalSnippets = finalSnippets.filter(
(snippet) =>
snippet.score >= helper.options.recentlyEditedSimilarityThreshold,
);
finalSnippets = fillPromptWithSnippets(
scoredSnippets,
helper.maxSnippetTokens,
helper.modelName,
);
return finalSnippets;
}

View file

@ -153,24 +153,6 @@ export function fillPromptWithSnippets(
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;
}
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
*/
@ -225,31 +207,3 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
}
return [orig];
}
export function removeRangeFromSnippets(
snippets: Required<AutocompleteSnippet>[],
filepath: string,
range: Range,
): Required<AutocompleteSnippet>[] {
const finalSnippets: Required<AutocompleteSnippet>[] = [];
for (const 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;
}

View file

@ -1,3 +1,13 @@
export const BRACKETS: { [key: string]: string } = {
"(": ")",
"{": "}",
"[": "]",
};
export const BRACKETS_REVERSE: { [key: string]: string } = {
")": "(",
"}": "{",
"]": "[",
};
/**
* We follow the policy of only completing bracket pairs that we started
* But sometimes we started the pair in a previous autocomplete suggestion
@ -6,30 +16,18 @@ export class BracketMatchingService {
private openingBracketsFromLastCompletion: string[] = [];
private lastCompletionFile: string | undefined = undefined;
static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" };
static BRACKETS_REVERSE: { [key: string]: string } = {
")": "(",
"}": "{",
"]": "[",
};
handleAcceptedCompletion(completion: string, filepath: string) {
this.openingBracketsFromLastCompletion = [];
const stack: string[] = [];
for (let i = 0; i < completion.length; i++) {
const char = completion[i];
if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) {
if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
} else if (
Object.values(BracketMatchingService.BRACKETS).includes(char)
) {
} else if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (
stack.length === 0 ||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
) {
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
break;
}
}
@ -63,17 +61,12 @@ export class BracketMatchingService {
(prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? "");
for (let i = 0; i < currentLine.length; i++) {
const char = currentLine[i];
if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) {
if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
} else if (
Object.values(BracketMatchingService.BRACKETS).includes(char)
) {
} else if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (
stack.length === 0 ||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
) {
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
break;
}
}
@ -87,7 +80,7 @@ export class BracketMatchingService {
if (suffix[i] === " ") {
continue;
}
const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]];
const openBracket = BRACKETS_REVERSE[suffix[i]];
if (!openBracket) {
break;
}
@ -115,19 +108,14 @@ export class BracketMatchingService {
const allLines = all.split("\n");
for (let i = 0; i < chunk.length; i++) {
const char = chunk[i];
if (Object.values(BracketMatchingService.BRACKETS).includes(char)) {
if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (
stack.length === 0 ||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
) {
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
// If the stack is empty or the top of the stack doesn't match the current closing bracket
yield chunk.slice(0, i);
return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream
}
} else if (
Object.keys(BracketMatchingService.BRACKETS).includes(char)
) {
} else if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
}

View file

@ -6,6 +6,7 @@ import { stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,
avoidPathLine,
noDoubleNewlineAfterClosingBracket,
showWhateverWeHaveAtXMs,
skipPrefixes,
stopAtLines,
@ -47,6 +48,7 @@ export class StreamTransformPipeline {
);
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator);
for (const lineFilter of helper.lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });

View file

@ -2,6 +2,7 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService";
export type LineFilter = (args: {
lines: LineStream;
@ -545,3 +546,43 @@ export async function* showWhateverWeHaveAtXMs(
}
}
}
export async function* noDoubleNewlineAfterClosingBracket(
lines: LineStream,
): LineStream {
const bracketTypeCounts = new Map<string, number>();
for await (const line of lines) {
if (line.trim() === "") {
// Double newline detected
// Check if any bracket counts are negative
let hasNegativeCount = false;
for (const count of bracketTypeCounts.values()) {
if (count < 0) {
hasNegativeCount = true;
break;
}
}
if (hasNegativeCount) {
// Stop the generator if we've closed brackets we didn't open
return;
}
}
yield line;
// Update bracket counts
for (const char of line) {
if (BRACKETS[char]) {
// It's an opening bracket
const count = bracketTypeCounts.get(char) || 0;
bracketTypeCounts.set(char, count + 1);
} else if (BRACKETS_REVERSE[char]) {
// It's a closing bracket
const openingBracket = BRACKETS_REVERSE[char];
const count = bracketTypeCounts.get(openingBracket) || 0;
bracketTypeCounts.set(openingBracket, count - 1);
}
}
}
}

View file

@ -0,0 +1,166 @@
import { noDoubleNewlineAfterClosingBracket } from "./lineStream";
describe("noDoubleNewlineAfterClosingBracket", () => {
// Helper function to convert an array to an async generator
async function* arrayToAsyncGenerator<T>(array: T[]): AsyncGenerator<T> {
for (const item of array) {
yield item;
}
}
// Helper function to collect lines from the async generator
async function collectLines(lines: AsyncIterable<string>): Promise<string[]> {
const result: string[] = [];
for await (const line of lines) {
result.push(line);
}
return result;
}
test("should yield all lines when no double newline and no unmatched brackets", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should yield all lines when double newline but brackets are matched", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
"",
"",
"// End of function",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => {
const inputLines = [
// "function test() {",
' console.log("Hello World");',
// Unmatched closing bracket
"}",
"",
"",
"// This should not be yielded",
'console.log("End");',
];
const expectedOutputLines = [' console.log("Hello World");', "}"];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should yield all lines when unmatched brackets but no double newline", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
// Unmatched closing bracket
")",
"// Continue code",
'console.log("End");',
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should continue yielding if unmatched closing bracket occurs after double newline", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
"",
"",
// Unmatched closing bracket after double newline
")",
'console.log("End");',
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should yield all lines when brackets are matched even with double newline", async () => {
const inputLines = [
"const arr = [",
" 1, 2, 3,",
"];",
"",
"",
"console.log(arr);",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should stop yielding when unmatched closing bracket occurs before double newline", async () => {
const inputLines = [
"if (condition) {",
" doSomething();",
"}",
// Unmatched closing bracket
"}",
"",
"",
"doSomethingElse();",
];
const expectedOutputLines = [
"if (condition) {",
" doSomething();",
"}",
"}",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should yield all lines when no unmatched closing brackets and double newline", async () => {
const inputLines = [
"while (true) {",
" // Infinite loop",
"}",
"",
"",
"// Loop exited",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
});

View file

@ -63,7 +63,7 @@ function sayHello() {
`,
llmOutput: `world!");
`,
expectedCompletion: "world!\");",
expectedCompletion: 'world!");',
},
{
description: "Should autocomplete Java when inside a block",
@ -131,10 +131,6 @@ public class Calculator {
}
`,
expectedCompletion: `
}
public void subtract(double number) {
result -= number;
}`,
},
{
@ -489,8 +485,8 @@ echo calculateArea(5, 3);`,
$colors = array("Red", "Green", <|fim|>);
echo "First color is: " . $colors[0];`,
llmOutput: "\"Blue\"",
expectedCompletion: "\"Blue\"",
llmOutput: '"Blue"',
expectedCompletion: '"Blue"',
filename: "colors.php",
},
{
@ -775,8 +771,10 @@ func main() {
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
llmOutput:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
{
description:
@ -817,8 +815,8 @@ func main() {
<p>Description text.</p>
</div>
</div>`,
llmOutput: "alt=\"Description of image\"",
expectedCompletion: "alt=\"Description of image\"",
llmOutput: 'alt="Description of image"',
expectedCompletion: 'alt="Description of image"',
filename: "test.html",
},
{
@ -930,8 +928,8 @@ public class App {
<|fim|>
]
}`,
llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }",
expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }",
llmOutput: ', { "id": 3, "name": "Charlie" }',
expectedCompletion: ', { "id": 3, "name": "Charlie" }',
},
{
description: "Should autocomplete within a CSV record",
@ -1237,8 +1235,8 @@ class Counter {
:age 30
<|fim|>
(println "User information loaded"))`,
llmOutput: ":location \"Unknown\"}",
expectedCompletion: ":location \"Unknown\"}",
llmOutput: ':location "Unknown"}',
expectedCompletion: ':location "Unknown"}',
filename: "test.clj",
},
{
@ -1301,8 +1299,8 @@ if (grade >= 90) {
} else {
print("C")
}`,
llmOutput: "print(\"B\")",
expectedCompletion: "print(\"B\")",
llmOutput: 'print("B")',
expectedCompletion: 'print("B")',
},
{
description: "Should autocomplete R ggplot2 plot structure",
@ -1324,8 +1322,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
<|fim|>
}
}`,
llmOutput: "s\"Hello, my name is $name and I am $age years old.\"",
expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"",
llmOutput: 's"Hello, my name is $name and I am $age years old."',
expectedCompletion: 's"Hello, my name is $name and I am $age years old."',
},
{
@ -1335,8 +1333,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
case class Person(name: String, age: Int, address: Address)
val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`,
llmOutput: "\"12345\")",
expectedCompletion: "\"12345\")",
llmOutput: '"12345")',
expectedCompletion: '"12345")',
},
{
@ -2066,8 +2064,8 @@ export default {
<ChildComponent <|fim|> />
</main>
`,
llmOutput: "name=\"World\"",
expectedCompletion: "name=\"World\"",
llmOutput: 'name="World"',
expectedCompletion: 'name="World"',
},
{

View file

@ -25,10 +25,10 @@ export class CompletionStreamer {
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
prefix,
() =>
(abortSignal: AbortSignal) =>
llm.supportsFim()
? llm.streamFim(prefix, suffix, completionOptions)
: llm.streamComplete(prompt, {
? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
: llm.streamComplete(prompt, abortSignal, {
...completionOptions,
raw: true,
}),

View file

@ -0,0 +1,215 @@
import { jest } from "@jest/globals";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
function createMockGenerator(
data: string[],
delay: number = 0,
): (abortSignal: AbortSignal) => AsyncGenerator<string> {
const mockGenerator = async function* () {
for (const chunk of data) {
yield chunk;
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
};
const newGenerator = jest
.fn<() => AsyncGenerator<string>>()
.mockReturnValue(mockGenerator());
return newGenerator;
}
describe("GeneratorReuseManager", () => {
let reuseManager: GeneratorReuseManager;
let onErrorMock: jest.Mock;
beforeEach(() => {
onErrorMock = jest.fn();
reuseManager = new GeneratorReuseManager(onErrorMock);
});
afterEach(() => {
jest.clearAllMocks();
});
test("creates new generator when there is no current generator", async () => {
const data = ["hello ", "world"];
const newGenerator = createMockGenerator(data);
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(data);
expect(newGenerator).toHaveBeenCalledTimes(1);
});
test("reuses generator when prefix matches pending completion", async () => {
const newGenerator = createMockGenerator(["llo ", "world"]);
// First call with initial prefix
const prefix1 = "he";
const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
const output1: string[] = [];
for await (const chunk of generator1) {
output1.push(chunk);
}
expect(output1).toEqual(["llo ", "world"]);
// Second call with extended prefix that matches pending completion
const prefix2 = "hello ";
const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
const output2: string[] = [];
for await (const chunk of generator2) {
output2.push(chunk);
}
expect(output2).toEqual(["world"]);
// Ensure generator was reused (newGenerator should be called only once)
expect(newGenerator).toHaveBeenCalledTimes(1);
});
test("creates new generator when prefix does not match pending completion", async () => {
const data = ["goodbye ", "world"];
const newGenerator = createMockGenerator(data);
// Initial generator with different prefix
reuseManager.pendingGeneratorPrefix = "hello ";
reuseManager.pendingCompletion = "world";
const prefix = "good";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(data);
// Ensure a new generator was created
expect(newGenerator).toHaveBeenCalledTimes(1);
});
test("handles multiline=false by stopping at newline", async () => {
const data = ["first line\n", "second line"];
const newGenerator = createMockGenerator(data);
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, false);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(["first line"]);
// Ensure it stops after the first newline
});
test("handles multiline=true by not stopping at newline", async () => {
const data = ["first line\n", "second line"];
const newGenerator = createMockGenerator(data);
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(data);
});
test("cancels previous generator when creating a new one", async () => {
const data1 = ["data from generator 1", "not generated"];
const data2 = ["data from generator 2"];
const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
const newGenerator2 = createMockGenerator(data2);
const prefix1 = "prefix1";
const prefix2 = "prefix2";
// First generator
const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
const output1: string[] = [];
for await (const chunk of generator1) {
output1.push(chunk);
// Simulate the generator being canceled before completing
reuseManager.currentGenerator?.cancel();
}
expect(output1.length).toEqual(1);
expect(output1[0]).toEqual(data1[0]);
// Second generator
const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
const output2: string[] = [];
for await (const chunk of generator2) {
output2.push(chunk);
}
expect(output2).toEqual(data2);
});
test("calls onError when generator throws an error", async () => {
const error = new Error("Generator error");
const mockGenerator = async function* () {
throw error;
};
const newGenerator = jest
.fn<() => AsyncGenerator<string>>()
.mockReturnValue(mockGenerator());
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
await expect(async () => {
for await (const chunk of generator) {
output.push(chunk);
}
}).not.toThrow(); // getGenerator handles errors internally
expect(onErrorMock).toHaveBeenCalledWith(error);
expect(output).toEqual([]);
});
test("handles backspacing by creating new generator when prefix is shorter", async () => {
const data = ["hello world"];
const newGenerator1 = createMockGenerator(data);
const newGenerator2 = createMockGenerator(data);
// First prefix
const prefix1 = "hello world";
const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
const output1: string[] = [];
for await (const chunk of generator1) {
output1.push(chunk);
}
// Simulate backspace (prefix is shorter)
const prefix2 = "hello worl";
const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
const output2: string[] = [];
for await (const chunk of generator2) {
output2.push(chunk);
}
// Ensure a new generator was created
expect(newGenerator1).toHaveBeenCalledTimes(1);
expect(newGenerator2).toHaveBeenCalledTimes(1);
});
});

View file

@ -8,12 +8,13 @@ export class GeneratorReuseManager {
constructor(private readonly onError: (err: any) => void) {}
private _createListenableGenerator(
abortController: AbortController,
gen: AsyncGenerator<string>,
prefix: string,
) {
this.currentGenerator?.cancel();
const listenableGen = new ListenableGenerator(gen, this.onError);
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
this.pendingGeneratorPrefix = prefix;
@ -21,47 +22,55 @@ export class GeneratorReuseManager {
this.currentGenerator = listenableGen;
}
private shouldReuseExistingGenerator(prefix: string): boolean {
return (
!!this.currentGenerator &&
!!this.pendingGeneratorPrefix &&
(this.pendingGeneratorPrefix + this.pendingCompletion).startsWith(
prefix,
) &&
// for e.g. backspace
this.pendingGeneratorPrefix?.length <= prefix?.length
);
}
async *getGenerator(
prefix: string,
newGenerator: () => AsyncGenerator<string>,
newGenerator: (abortSignal: AbortSignal) => 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
)
) {
// If we can't reuse, then create a new generator
if (!this.shouldReuseExistingGenerator(prefix)) {
// Create a wrapper over the current generator to fix the prompt
this._createListenableGenerator(newGenerator(), prefix);
const abortController = new AbortController();
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
}
let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || "";
// Already typed characters are those that are new in the prefix from the old generator
let typedSinceLastGenerator =
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);
// Ignore already typed characters in the completion
while (chunk.length && typedSinceLastGenerator.length) {
if (chunk[0] === typedSinceLastGenerator[0]) {
typedSinceLastGenerator = typedSinceLastGenerator.slice(1);
chunk = chunk.slice(1);
} else {
break;
}
}
// Break at newline unless we are in multiline mode
const newLineIndex = chunk.indexOf("\n");
if (multiline || newLineIndex === -1) {
yield chunk;
} else {
if (newLineIndex >= 0 && !multiline) {
yield chunk.slice(0, newLineIndex);
break;
} else if (chunk !== "") {
yield chunk;
}
}
}

View file

@ -0,0 +1,149 @@
import { jest } from "@jest/globals";
import { ListenableGenerator } from "./ListenableGenerator";
describe("ListenableGenerator", () => {
// Helper function to create an async generator
async function* asyncGenerator<T>(values: T[], delay = 0) {
for (const value of values) {
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
yield value;
}
}
it("should yield values from the source generator via tee()", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const result: number[] = [];
for await (const value of lg.tee()) {
result.push(value);
}
expect(result).toEqual(values);
expect(onError).not.toHaveBeenCalled();
});
it("should allow listeners to receive values", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const listener = jest.fn();
// Add listener after some delay to simulate late subscription
setTimeout(() => {
lg.listen(listener);
}, 15);
// Wait for generator to finish
await new Promise((resolve) => setTimeout(resolve, 50));
expect(listener).toHaveBeenCalledWith(1);
expect(listener).toHaveBeenCalledWith(2);
expect(listener).toHaveBeenCalledWith(3);
// Listener should receive null at the end
expect(listener).toHaveBeenCalledWith(null);
});
it("should buffer values for listeners added after some values have been yielded", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values, 10);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const initialListener = jest.fn();
lg.listen(initialListener);
// Wait for the first value to be yielded
await new Promise((resolve) => setTimeout(resolve, 15));
// Add a second listener
const newListener = jest.fn();
lg.listen(newListener);
// Wait for generator to finish
await new Promise((resolve) => setTimeout(resolve, 50));
// Both listeners should have received all values
[initialListener, newListener].forEach((listener) => {
expect(listener).toHaveBeenCalledWith(1);
expect(listener).toHaveBeenCalledWith(2);
expect(listener).toHaveBeenCalledWith(3);
expect(listener).toHaveBeenCalledWith(null);
});
});
it("should handle cancellation", async () => {
const values = [1, 2, 3, 4, 5];
const source = asyncGenerator(values, 10);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const result: number[] = [];
const teeIterator = lg.tee();
const consume = async () => {
for await (const value of teeIterator) {
result.push(value);
if (value === 3) {
lg.cancel();
}
}
};
await consume();
expect(result).toEqual([1, 2, 3]);
expect(lg["_isEnded"]).toBe(true);
});
it("should call onError when the source generator throws an error", async () => {
async function* errorGenerator() {
yield 1;
throw new Error("Test error");
}
const source = errorGenerator();
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const result: number[] = [];
for await (const value of lg.tee()) {
result.push(value);
}
expect(result).toEqual([1]);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(new Error("Test error"));
});
it("should notify listeners when the generator ends", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const listener = jest.fn();
lg.listen(listener);
// Wait for the generator to finish
await new Promise((resolve) => setTimeout(resolve, 10));
expect(listener).toHaveBeenCalledWith(1);
expect(listener).toHaveBeenCalledWith(2);
expect(listener).toHaveBeenCalledWith(3);
expect(listener).toHaveBeenCalledWith(null);
});
});

View file

@ -3,16 +3,20 @@ export class ListenableGenerator<T> {
private _buffer: T[] = [];
private _listeners: Set<(value: T) => void> = new Set();
private _isEnded = false;
private _abortController: AbortController
constructor(
source: AsyncGenerator<T>,
private readonly onError: (e: any) => void,
abortController: AbortController
) {
this._source = source;
this._abortController = abortController;
this._start();
}
public cancel() {
this._abortController.abort();
this._isEnded = true;
}

View file

@ -1,5 +1,7 @@
import path from "node:path";
import ignore from "ignore";
import { IDE } from "../..";
import { getBasename } from "../../util";
import { getConfigJsonPath } from "../../util/paths";
@ -31,7 +33,7 @@ async function isDisabledForFile(
}
// @ts-ignore
const pattern = ignore.default().add(options.disableInFiles);
const pattern = ignore.default().add(disableInFiles);
if (pattern.ignores(filepath)) {
return true;
}

View file

@ -11,6 +11,7 @@ import {
getTemplateForModel,
} from "./AutocompleteTemplate";
import { getStopTokens } from "./getStopTokens";
import { countTokens } from "../../llm/countTokens";
export function formatExternalSnippet(
filepath: string,
@ -28,42 +29,22 @@ export function formatExternalSnippet(
];
return lines.join("\n");
}
function renderStringTemplate(
template: string,
prefix: string,
suffix: string,
function getContextComments(
snippets: AutocompleteSnippet[],
lang: AutocompleteLanguageInfo,
filepath: string,
reponame: string,
) {
const filename = getBasename(filepath);
const compiledTemplate = Handlebars.compile(template);
const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`;
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = `${formattedSnippets}\n\n${prefix}`;
} else if (prefix.trim().length === 0 && suffix.trim().length === 0) {
// If it's an empty file, include the file name as a comment
prefix = `${lang.singleLineComment} ${getLastNPathParts(
filepath,
2,
)}\n${prefix}`;
}
const formattedSnippets =
snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n") + fileNameSnippet;
const prompt = compiledTemplate({
prefix,
suffix,
filename,
reponame,
language: lang.name,
});
return prompt;
return formattedSnippets;
}
function getTemplate(helper: HelperVars): AutocompleteTemplate {
@ -77,29 +58,61 @@ function getTemplate(helper: HelperVars): AutocompleteTemplate {
return getTemplateForModel(helper.modelName);
}
export function renderPrompt(
snippets: AutocompleteSnippet[],
workspaceDirs: string[],
helper: HelperVars,
): {
function renderStringTemplate(
template: string,
prefix: string,
suffix: string,
lang: AutocompleteLanguageInfo,
filepath: string,
reponame: string,
) {
const filename = getBasename(filepath);
const compiledTemplate = Handlebars.compile(template);
return compiledTemplate({
prefix,
suffix,
filename,
reponame,
language: lang.name,
});
}
const formatDiff = (helper: HelperVars, diff?: string) => {
if (!diff) return "";
const tokenCount = countTokens(diff, helper.modelName);
if (tokenCount > helper.maxDiffTokens) {
return "";
}
return `${diff}\n\n`;
};
export function renderPrompt({
snippets,
workspaceDirs,
helper,
diff,
}: {
snippets: AutocompleteSnippet[];
workspaceDirs: string[];
helper: HelperVars;
diff?: string;
}): {
prompt: string;
prefix: string;
suffix: string;
completionOptions: Partial<CompletionOptions> | undefined;
} {
// If prefix is manually passed
let prefix = helper.prunedPrefix;
let suffix = helper.prunedSuffix;
let prefix = helper.input.manuallyPassPrefix || helper.prunedPrefix;
let suffix = helper.input.manuallyPassPrefix ? "" : helper.prunedSuffix;
if (helper.input.manuallyPassPrefix) {
prefix = helper.input.manuallyPassPrefix;
suffix = "";
}
let prompt: string;
const reponame = getBasename(workspaceDirs[0] ?? "myproject");
let { template, compilePrefixSuffix, completionOptions } =
const { template, compilePrefixSuffix, completionOptions } =
getTemplate(helper);
// Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix
@ -112,40 +125,50 @@ export function renderPrompt(
reponame,
snippets,
);
}
// Templates can be passed as a Handlebars template string or a function
if (typeof template === "string") {
prompt = renderStringTemplate(
template,
prefix,
suffix,
} else {
const contextComments = getContextComments(
snippets,
helper.lang,
helper.filepath,
reponame,
);
} else {
prompt = template(
prefix,
suffix,
helper.filepath,
reponame,
helper.lang.name,
snippets,
);
const formattedDiff = formatDiff(helper, diff);
prefix = `${formattedDiff}${contextComments}${prefix}`;
}
const prompt =
// Templates can be passed as a Handlebars template string or a function
typeof template === "string"
? renderStringTemplate(
template,
prefix,
suffix,
helper.lang,
helper.filepath,
reponame,
)
: template(
prefix,
suffix,
helper.filepath,
reponame,
helper.lang.name,
snippets,
);
const stopTokens = getStopTokens(
completionOptions,
helper.lang,
helper.modelName,
);
completionOptions = {
...completionOptions,
stop: stopTokens,
return {
prompt,
prefix,
suffix,
completionOptions: {
...completionOptions,
stop: stopTokens,
},
};
return { prompt, prefix, suffix, completionOptions };
}

View file

@ -39,7 +39,9 @@ export class HelperVars {
private async init() {
// Don't do anything if already initialized
if (this._fileContents !== undefined) {return;}
if (this._fileContents !== undefined) {
return;
}
this._fileContents =
this.input.manuallyPassFileContents ??
@ -115,6 +117,11 @@ export class HelperVars {
get maxSnippetTokens() {
return this.options.maxPromptTokens * this.options.maxSnippetPercentage;
}
get maxDiffTokens() {
return this.options.maxPromptTokens * this.options.maxDiffPercentage;
}
get prunedCaretWindow() {
return this.prunedPrefix + this.prunedSuffix;
}

View file

@ -58,7 +58,7 @@ export function slashFromCustomCommand(
}
}
for await (const chunk of llm.streamChat(messages)) {
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -24,7 +24,9 @@ const GenerateTerminalCommand: SlashCommand = {
"${input}"
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`);
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
new AbortController().signal
);
const lines = streamLines(gen);
let cmd = "";

View file

@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = {
const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
])) {
], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -30,7 +30,7 @@ const DraftIssueCommand: SlashCommand = {
return;
}
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: `,
`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: `, new AbortController().signal,
{ maxTokens: 20 },
);
@ -43,7 +43,7 @@ const DraftIssueCommand: SlashCommand = {
{ role: "user", content: PROMPT(input, title) },
];
for await (const chunk of llm.streamChat(messages)) {
for await (const chunk of llm.streamChat(messages, new AbortController().signal)) {
body += chunk.content;
yield stripImages(chunk.content);
}

View file

@ -478,7 +478,7 @@ const EditSlashCommand: SlashCommand = {
messages = rendered;
}
const completion = llm.streamComplete(rendered as string, {
const completion = llm.streamComplete(rendered as string, new AbortController().signal, {
maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096),
raw: true,
});
@ -494,7 +494,7 @@ const EditSlashCommand: SlashCommand = {
);
} else {
async function* gen() {
for await (const chunk of llm.streamChat(messages, {
for await (const chunk of llm.streamChat(messages, new AbortController().signal,{
temperature: 0.5, // TODO
maxTokens: Math.min(
maxTokens,
@ -609,7 +609,7 @@ ${lines.join("\n")}
Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`;
for await (const update of llm.streamComplete(prompt)) {
for await (const update of llm.streamComplete(prompt, new AbortController().signal)) {
yield update;
}
}

View file

@ -39,7 +39,7 @@ const MultiFileEditSlashCommand: SlashCommand = {
const content = createPrompt(filesToEditStr, additionalContextStr, input);
for await (const chunk of llm.streamChat([{ role: "user", content }])) {
for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -47,7 +47,7 @@ const OnboardSlashCommand: SlashCommand = {
for await (const chunk of llm.streamChat([
{ role: "user", content: prompt },
])) {
], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},
@ -134,7 +134,7 @@ function createOnboardingPrompt(context: string): string {
Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
Here is an example of a valid response:
## Important folders
### /folder1

View file

@ -45,7 +45,7 @@ const ReviewMessageCommand: SlashCommand = {
for await (const chunk of llm.streamChat([
{ role: "user", content: content },
])) {
], new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -125,7 +125,7 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}

View file

@ -836,7 +836,7 @@ declare global {
slidingWindowPrefixPercentage: number;
slidingWindowSize: number;
maxSnippetPercentage: number;
recentlyEditedSimilarityThreshold: number;
maxDiffPercentage: number;
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;

View file

@ -9,7 +9,6 @@ import {
} from "../..";
import DocsService from "../../indexing/docs/DocsService";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
import { Telemetry } from "../../util/posthog";
import { INSTRUCTIONS_BASE_ITEM } from "./utils";
@ -88,38 +87,10 @@ class DocsContextProvider extends BaseContextProvider {
return [];
}
const isJetBrainsAndPreIndexedDocsProvider =
await docsService.isJetBrainsAndPreIndexedDocsProvider();
if (isJetBrainsAndPreIndexedDocsProvider) {
void extras.ide.showToast(
"error",
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
"the embeddings provider, but it cannot be used with JetBrains. " +
"Please select a different embeddings provider to use the '@docs' " +
"context provider.",
);
return [];
}
const preIndexedDoc = preIndexedDocs[query];
if (!!preIndexedDoc) {
void Telemetry.capture("docs_pre_indexed_doc_used", {
doc: preIndexedDoc["title"],
});
}
const embeddingsProvider = await docsService.getEmbeddingsProvider(
!!preIndexedDoc,
);
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
let chunks = await docsService.retrieveChunks(
await docsService.isInitialized;
let chunks = await docsService.retrieveChunksFromQuery(
extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case
query,
vector,
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
);
@ -175,7 +146,7 @@ class DocsContextProvider extends BaseContextProvider {
return [];
}
const docs = (await docsService.list()) ?? [];
const docs = (await docsService.listMetadata()) ?? [];
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
const submenuItemsMap = new Map<string, ContextSubmenuItem>();

View file

@ -21,11 +21,12 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
): Promise<ContextItem[]> {
const issueId = query;
const { Octokit } = await import("@octokit/rest");
const domain = this.options?.domain ?? "github.com";
const octokit = new Octokit({
auth: this.options?.githubToken,
baseUrl: `https://${domain}/api/v3`,
baseUrl: this.options?.domain
? `https://${this.options.domain}/api/v3`
: undefined,
request: {
fetch: extras.fetch,
},

View file

@ -6,7 +6,7 @@ const RERANK_PROMPT = (
documentId: 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?
Snippet:
\`\`\`/Users/andrew/Desktop/server/main.py
@ -17,7 +17,7 @@ const RERANK_PROMPT = (
return {{"Hello": "World"}}
\`\`\`
Relevant: Yes
Query: Where in the documentation does it talk about the UI?
Snippet:
\`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs
@ -32,13 +32,13 @@ const RERANK_PROMPT = (
}}
\`\`\`
Relevant: No
Query: ${query}
Snippet:
\`\`\`${documentId}
${document}
\`\`\`
Relevant:
Relevant:
`;
export class LLMReranker implements Reranker {
@ -49,6 +49,7 @@ export class LLMReranker implements Reranker {
async scoreChunk(chunk: Chunk, query: string): Promise<number> {
const completion = await this.llm.complete(
RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content),
new AbortController().signal,
{
maxTokens: 1,
model:

View file

@ -61,7 +61,7 @@ This is the question that you should select relevant files for: "${input}"`;
const response = await llm.chat([
{ role: "user", content: prompt },
{ role: "assistant", content: "<reasoning>" },
]);
], new AbortController().signal);
const content = stripImages(response.content);
console.debug("Repo map retrieval response: ", content);

View file

@ -34,6 +34,7 @@ import {
setupInitialDotContinueDirectory,
} from "./util/paths";
import { Telemetry } from "./util/posthog";
import { getSymbolsForManyFiles } from "./util/treeSitter";
import { TTS } from "./util/tts";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
@ -46,7 +47,7 @@ export class Core {
codebaseIndexerPromise: Promise<CodebaseIndexer>;
completionProvider: CompletionProvider;
continueServerClientPromise: Promise<ContinueServerClient>;
indexingState: IndexingProgressUpdate;
codebaseIndexingState: IndexingProgressUpdate;
controlPlaneClient: ControlPlaneClient;
private docsService: DocsService;
private globalContext = new GlobalContext();
@ -92,7 +93,11 @@ export class Core {
// Ensure .continue directory is created
setupInitialDotContinueDirectory();
this.indexingState = { status: "loading", desc: "loading", progress: 0 };
this.codebaseIndexingState = {
status: "loading",
desc: "loading",
progress: 0,
};
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
@ -152,6 +157,7 @@ export class Core {
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
this.indexingPauseToken.paused = true;
if (ideSettings.pauseCodebaseIndexOnStart) {
void this.messenger.request("indexProgress", {
progress: 1,
@ -280,34 +286,15 @@ export class Core {
// Context providers
on("context/addDocs", async (msg) => {
let hasFailed = false;
for await (const result of this.docsService.indexAndAdd(msg.data)) {
if (result.status === "failed") {
hasFailed = true;
break;
}
}
if (hasFailed) {
void this.ide.showToast("info", `Failed to index ${msg.data.startUrl}`);
} else {
void this.ide.showToast(
"info",
`Successfully indexed ${msg.data.startUrl}`,
);
this.messenger.send("refreshSubmenuItems", undefined);
}
void this.docsService.indexAndAdd(msg.data);
});
on("context/removeDocs", async (msg) => {
await this.docsService.delete(msg.data.startUrl);
this.messenger.send("refreshSubmenuItems", undefined);
});
on("context/indexDocs", async (msg) => {
await this.docsService.indexAllDocs(msg.data.reIndex);
this.messenger.send("refreshSubmenuItems", undefined);
await this.docsService.syncOrReindexAllDocsWithPrompt(msg.data.reIndex);
});
on("context/loadSubmenuItems", async (msg) => {
@ -373,6 +360,11 @@ export class Core {
}
});
on("context/getSymbolsForFiles", async (msg) => {
const { uris } = msg.data;
return await getSymbolsForManyFiles(uris, this.ide);
});
on("config/getSerializedProfileInfo", async (msg) => {
return {
config: await this.configHandler.getSerializedConfig(),
@ -395,6 +387,7 @@ export class Core {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
@ -436,6 +429,7 @@ export class Core {
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamComplete(
msg.data.prompt,
new AbortController().signal,
msg.data.completionOptions,
);
let next = await gen.next();
@ -468,6 +462,7 @@ export class Core {
const model = await this.configHandler.llmFromTitle(msg.data.title);
const completion = await model.complete(
msg.data.prompt,
new AbortController().signal,
msg.data.completionOptions,
);
return completion;
@ -548,33 +543,39 @@ export class Core {
}
}, 100);
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
}
if (content) {
yield { content };
try {
for await (const content of slashCommand.run({
input,
history,
llm,
contextItems,
params,
ide,
addContextItem: (item) => {
void messenger.request("addContextItem", {
item,
historyIndex,
});
},
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
break;
}
if (content) {
yield { content };
}
}
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
}
clearInterval(checkActiveInterval);
yield { done: true, content: "" };
}
on("command/run", (msg) =>
@ -686,6 +687,8 @@ export class Core {
const rows = await DevDataSqliteDb.getTokensPerModel();
return rows;
});
// Codebase indexing
on("index/forceReIndex", async ({ data }) => {
if (data?.shouldClearIndexes) {
const codebaseIndexer = await this.codebaseIndexerPromise;
@ -701,17 +704,41 @@ export class Core {
}
});
on("index/setPaused", (msg) => {
new GlobalContext().update("indexingPaused", msg.data);
this.globalContext.update("indexingPaused", msg.data);
this.indexingPauseToken.paused = msg.data;
});
on("index/indexingProgressBarInitialized", async (msg) => {
// Triggered when progress bar is initialized.
// If a non-default state has been stored, update the indexing display to that state
if (this.indexingState.status !== "loading") {
void this.messenger.request("indexProgress", this.indexingState);
if (this.codebaseIndexingState.status !== "loading") {
void this.messenger.request(
"indexProgress",
this.codebaseIndexingState,
);
}
});
// Docs, etc. indexing
on("indexing/reindex", async (msg) => {
if (msg.data.type === "docs") {
void this.docsService.reindexDoc(msg.data.id);
}
});
on("indexing/abort", async (msg) => {
if (msg.data.type === "docs") {
this.docsService.abort(msg.data.id);
}
});
on("indexing/setPaused", async (msg) => {
if (msg.data.type === "docs") {
this.docsService.setPaused(msg.data.id, msg.data.paused);
}
});
on("indexing/initStatuses", async (msg) => {
return this.docsService.initStatuses();
});
//
on("didChangeSelectedProfile", (msg) => {
void this.configHandler.setSelectedProfile(msg.data.id);
void this.configHandler.reloadConfig();
@ -768,7 +795,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -802,7 +829,7 @@ export class Core {
}
void this.messenger.request("indexProgress", updateToSend);
this.indexingState = updateToSend;
this.codebaseIndexingState = updateToSend;
if (update.status === "failed") {
void this.sendIndexingErrorTelemetry(update);
@ -811,4 +838,6 @@ export class Core {
this.messenger.send("refreshSubmenuItems", undefined);
}
// private
}

View file

@ -86,7 +86,7 @@ export async function* getReplacementWithLlm(
const completion = await llm.streamChat([
{ role: "user", content: userPrompt },
{ role: "assistant", content: assistantPrompt },
]);
], new AbortController().signal);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);

View file

@ -23,7 +23,7 @@ export async function* streamLazyApply(
}
const promptMessages = promptFactory(oldCode, filename, newCode);
const lazyCompletion = llm.streamChat(promptMessages);
const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal);
// Do find and replace over the lazy edit response
async function* replacementFunction(

View file

@ -96,8 +96,8 @@ export async function* streamDiffLines(
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt, { raw: true, prediction })
: llm.streamChat(prompt, {
? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction })
: llm.streamChat(prompt, new AbortController().signal, {
prediction,
});

61
core/index.d.ts vendored
View file

@ -1,3 +1,4 @@
import Parser from "web-tree-sitter";
import { GetGhTokenArgs } from "./protocol/ide";
declare global {
@ -45,6 +46,30 @@ export interface IndexingProgressUpdate {
debugInfo?: string;
}
// This is more or less a V2 of IndexingProgressUpdate
export interface IndexingStatus {
id: string;
type: "docs";
progress: number;
description: string;
status:
| "indexing"
| "complete"
| "paused"
| "failed"
| "aborted"
| "deleted"
| "pending";
embeddingsProviderId: string;
isReindexing?: boolean;
debugInfo?: string;
title: string;
icon?: string;
url?: string;
}
export type IndexingStatusMap = Map<string, IndexingStatus>;
export type PromptTemplateFunction = (
history: ChatMessage[],
otherData: Record<string, string>,
@ -78,26 +103,34 @@ export interface ILLM extends LLMOptions {
region?: string;
projectId?: string;
complete(prompt: string, options?: LLMFullCompletionOptions): Promise<string>;
complete(
prompt: string,
signal: AbortSignal,
options?: LLMFullCompletionOptions
): Promise<string>;
streamComplete(
prompt: string,
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): AsyncGenerator<string, PromptLog>;
streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): AsyncGenerator<string, PromptLog>;
streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): AsyncGenerator<ChatMessage, PromptLog>;
chat(
messages: ChatMessage[],
signal: AbortSignal,
options?: LLMFullCompletionOptions,
): Promise<ChatMessage>;
@ -200,11 +233,16 @@ export interface IContextProvider {
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
}
export interface Checkpoint {
[filepath: string]: string;
}
export interface PersistedSessionInfo {
history: ChatHistory;
title: string;
workspaceDirectory: string;
sessionId: string;
checkpoints?: Checkpoint[];
}
export interface SessionInfo {
@ -298,13 +336,19 @@ export interface InputModifiers {
noContext: boolean;
}
export interface SymbolWithRange extends RangeInFile {
name: string;
type: Parser.SyntaxNode["type"];
}
export type FileSymbolMap = Record<string, SymbolWithRange[]>;
export interface PromptLog {
modelTitle: string;
completionOptions: CompletionOptions;
prompt: string;
completion: string;
}
export interface ChatHistoryItem {
message: ChatMessage;
editorState?: any;
@ -383,11 +427,13 @@ export interface CustomLLMWithOptionals {
options: LLMOptions;
streamCompletion?: (
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
streamChat?: (
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
@ -654,7 +700,8 @@ type ModelProvider =
| "askSage"
| "vertexai"
| "nebius"
| "xAI";
| "xAI"
| "moonshot";
export type ModelName =
| "AUTODETECT"
@ -749,7 +796,11 @@ export type ModelName =
| "starcoder-1b"
| "starcoder-3b"
| "starcoder2-3b"
| "stable-code-3b";
| "stable-code-3b"
// Moonshot
| "moonshot-v1-8k"
| "moonshot-v1-32k"
| "moonshot-v1-128k";
export interface RequestOptions {
timeout?: number;
@ -927,7 +978,7 @@ export interface TabAutocompleteOptions {
slidingWindowPrefixPercentage: number;
slidingWindowSize: number;
maxSnippetPercentage: number;
recentlyEditedSimilarityThreshold: number;
maxDiffPercentage: number;
useCache: boolean;
onlyMyCode: boolean;
useOtherFiles: boolean;

View file

@ -95,6 +95,6 @@ export default DocsCrawler;
export {
CheerioCrawler,
ChromiumCrawler,
ChromiumInstaller as ChromiumInstaller,
ChromiumInstaller,
GitHubCrawler,
};

View file

@ -66,23 +66,20 @@ describe.skip("DocsService Integration Tests", () => {
});
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(mockSiteConfig);
let latestConfig = await getReloadedConfig();
// Sqlite check
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
// config.json check
expect(latestConfig.docs).toContainEqual(mockSiteConfig);
// Lance DB check
const embeddingsProvider = await docsService.getEmbeddingsProvider();
const [mockVector] = await embeddingsProvider.embed(["test"]);
let retrievedChunks = await docsService.retrieveChunks(
let retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
mockVector,
5,
);
@ -91,7 +88,7 @@ describe.skip("DocsService Integration Tests", () => {
await docsService.delete(mockSiteConfig.startUrl);
// Sqlite check
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
// config.json check
latestConfig = await getReloadedConfig();
@ -100,9 +97,9 @@ describe.skip("DocsService Integration Tests", () => {
);
// LanceDB check
retrievedChunks = await docsService.retrieveChunks(
retrievedChunks = await docsService.retrieveChunksFromQuery(
"test",
mockSiteConfig.startUrl,
mockVector,
5,
);
expect(retrievedChunks.length).toBe(0);
@ -133,17 +130,15 @@ describe.skip("DocsService Integration Tests", () => {
test("Handles pulling down and adding pre-indexed docs", async () => {
const preIndexedDoc = Object.values(preIndexedDocs)[0];
const generator = docsService.indexAndAdd(preIndexedDoc);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(preIndexedDoc);
});
test("Config synchronization with SQLite", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}
await docsService.indexAndAdd(mockSiteConfig);
await getReloadedConfig();
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(true);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(true);
editConfigJson((config) => {
const { docs, ...restConfig } = config;
@ -164,6 +159,6 @@ describe.skip("DocsService Integration Tests", () => {
await new Promise((resolve) => setTimeout(resolve, 100));
}
expect(await docsService.has(mockSiteConfig.startUrl)).toBe(false);
expect(await docsService.hasMetadata(mockSiteConfig.startUrl)).toBe(false);
});
});

File diff suppressed because it is too large Load diff

View file

@ -330,6 +330,12 @@ const preIndexedDocs: Record<
startUrl: "https://llama-stack.readthedocs.io/",
rootUrl: "https://llama-stack.readthedocs.io/",
},
"https://go.dev/doc": {
title: "Go",
startUrl: "https://go.dev/doc",
rootUrl: "https://go.dev",
faviconUrl: "https://go.dev/favicon.ico",
},
};
export default preIndexedDocs;

View file

@ -117,6 +117,7 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
"huggingface-inference-api",
"huggingface-tgi",
"mistral",
"moonshot",
"free-trial",
"replicate",
"together",
@ -149,9 +150,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
lower.includes("chat-bison") ||
lower.includes("pplx") ||
lower.includes("gemini") ||
lower.includes("grok")
lower.includes("grok")||
lower.includes("moonshot")
) {
return undefined;
return undefined;
}
if (lower.includes("llama3")) {

View file

@ -372,10 +372,11 @@ export abstract class BaseLLM implements ILLM {
`HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`,
);
} else {
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);
if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here
console.debug(
`${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`,
);
}
if (
e.code === "ECONNREFUSED" &&
e.message.includes("http://127.0.0.1:11434")
@ -424,6 +425,7 @@ export abstract class BaseLLM implements ILLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string, PromptLog> {
throw new Error("Not implemented");
@ -432,6 +434,7 @@ export abstract class BaseLLM implements ILLM {
async *streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<string> {
const { completionOptions, log } = this._parseCompletionOptions(options);
@ -452,6 +455,7 @@ export abstract class BaseLLM implements ILLM {
for await (const chunk of this._streamFim(
prefix,
suffix,
signal,
completionOptions,
)) {
completion += chunk;
@ -477,6 +481,7 @@ export abstract class BaseLLM implements ILLM {
async *streamComplete(
_prompt: string,
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
) {
const { completionOptions, log, raw } =
@ -506,6 +511,7 @@ export abstract class BaseLLM implements ILLM {
try {
for await (const chunk of this._streamComplete(
prompt,
signal,
completionOptions,
)) {
completion += chunk;
@ -527,7 +533,7 @@ export abstract class BaseLLM implements ILLM {
};
}
async complete(_prompt: string, options: LLMFullCompletionOptions = {}) {
async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
@ -551,7 +557,7 @@ export abstract class BaseLLM implements ILLM {
}
}
const completion = await this._complete(prompt, completionOptions);
const completion = await this._complete(prompt, signal, completionOptions);
this._logTokensGenerated(completionOptions.model, prompt, completion);
@ -562,9 +568,9 @@ export abstract class BaseLLM implements ILLM {
return completion;
}
async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) {
async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) {
let completion = "";
for await (const chunk of this.streamChat(messages, options)) {
for await (const chunk of this.streamChat(messages, signal, options)) {
completion += chunk.content;
}
return { role: "assistant" as ChatMessageRole, content: completion };
@ -572,6 +578,7 @@ export abstract class BaseLLM implements ILLM {
async *streamChat(
_messages: ChatMessage[],
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
): AsyncGenerator<ChatMessage, PromptLog> {
const { completionOptions, log, raw } =
@ -597,6 +604,7 @@ export abstract class BaseLLM implements ILLM {
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
signal,
completionOptions,
)) {
completion += chunk;
@ -605,6 +613,7 @@ export abstract class BaseLLM implements ILLM {
} else {
for await (const chunk of this._streamChat(
messages,
signal,
completionOptions,
)) {
completion += chunk.content;
@ -633,6 +642,7 @@ export abstract class BaseLLM implements ILLM {
// biome-ignore lint/correctness/useYield: Purposefully not implemented
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
throw new Error("Not implemented");
@ -640,6 +650,7 @@ export abstract class BaseLLM implements ILLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (!this.templateMessages) {
@ -650,15 +661,16 @@ export abstract class BaseLLM implements ILLM {
for await (const chunk of this._streamComplete(
this.templateMessages(messages),
signal,
options,
)) {
yield { role: "assistant", content: chunk };
}
}
protected async _complete(prompt: string, options: CompletionOptions) {
protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) {
let completion = "";
for await (const chunk of this._streamComplete(prompt, options)) {
for await (const chunk of this._streamComplete(prompt, signal, options)) {
completion += chunk;
}
return completion;

View file

@ -37,7 +37,9 @@ class Anthropic extends BaseLLM {
public convertMessages(msgs: ChatMessage[]): any[] {
// should be public for use within VertexAI
const filteredmessages = msgs.filter((m) => m.role !== "system");
const filteredmessages = msgs.filter(
(m) => m.role !== "system" && !!m.content,
);
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)
@ -95,16 +97,18 @@ class Anthropic extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const shouldCacheSystemMessage =
@ -137,6 +141,7 @@ class Anthropic extends BaseLLM {
]
: systemMessage,
}),
signal
});
if (options.stream === false) {
@ -146,7 +151,9 @@ class Anthropic extends BaseLLM {
}
for await (const value of streamSse(response)) {
if (value.type == "message_start") {console.log(value);}
if (value.type == "message_start") {
console.log(value);
}
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}

View file

@ -98,6 +98,7 @@ class Asksage extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions
): Promise<string> {
if (typeof prompt !== "string" || prompt.trim() === "") {
@ -126,14 +127,16 @@ class Asksage extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions
): AsyncGenerator<string> {
const completion = await this._complete(prompt, options);
const completion = await this._complete(prompt, signal, options);
yield completion;
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(options, messages);
@ -142,6 +145,7 @@ class Asksage extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(args),
signal
});
if (!response.ok) {

View file

@ -5,6 +5,10 @@ import OpenAI from "./OpenAI.js";
class Azure extends OpenAI {
static providerName: ModelProvider = "azure";
protected supportsPrediction(model: string): boolean {
return false;
}
static defaultOptions: Partial<LLMOptions> = {
apiVersion: "2024-02-15-preview",
apiType: "azure",

View file

@ -14,6 +14,11 @@ import {
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
/**
* Bedrock class implements AWS Bedrock LLM integration.
* It handles streaming completions and chat messages using AWS Bedrock runtime.
* Supports both text and image inputs through Claude 3 models.
*/
class Bedrock extends BaseLLM {
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
@ -37,16 +42,18 @@ class Bedrock extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
@ -84,7 +91,7 @@ class Bedrock extends BaseLLM {
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);
const response = await client.send(command, { abortSignal: signal});
if (response.stream) {
for await (const chunk of response.stream) {
@ -120,7 +127,9 @@ class Bedrock extends BaseLLM {
// TODO: Additionally, consider implementing a global exception handler for the providers to give users clearer feedback.
// For example, differentiate between client-side errors (4XX status codes) and server-side issues (5XX status codes),
// providing meaningful error messages to improve the user experience.
stopSequences: options.stop?.filter((stop) => stop.trim() !== "").slice(0, 4),
stopSequences: options.stop
?.filter((stop) => stop.trim() !== "")
.slice(0, 4),
},
};
}
@ -162,7 +171,7 @@ class Bedrock extends BaseLLM {
try {
return await fromIni({
profile: this.profile,
ignoreCache: true
ignoreCache: true,
})();
} catch (e) {
console.warn(

View file

@ -37,6 +37,7 @@ class BedrockImport extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
@ -51,7 +52,7 @@ class BedrockImport extends BaseLLM {
const input = this._generateInvokeModelCommandInput(prompt, options);
const command = new InvokeModelWithResponseStreamCommand(input);
const response = await client.send(command);
const response = await client.send(command, {abortSignal: signal});
if (response.body) {
for await (const item of response.body) {

View file

@ -16,6 +16,7 @@ export default class Cloudflare extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage, any, unknown> {
const headers = {
@ -35,6 +36,7 @@ export default class Cloudflare extends BaseLLM {
model: this.model,
...this._convertArgs(options),
}),
signal
});
for await (const value of streamSse(resp)) {
@ -46,10 +48,12 @@ export default class Cloudflare extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield stripImages(chunk.content);

View file

@ -46,16 +46,18 @@ class Cohere extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
for await (const update of this._streamChat(messages, signal, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const headers = {
@ -73,6 +75,7 @@ class Cohere extends BaseLLM {
chat_history: this._convertMessages(messages),
preamble: this.systemMessage,
}),
signal
});
if (options.stream === false) {

View file

@ -13,12 +13,14 @@ class CustomLLMClass extends BaseLLM {
private customStreamCompletion?: (
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
private customStreamChat?: (
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,
) => AsyncGenerator<string>;
@ -31,18 +33,20 @@ class CustomLLMClass extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (this.customStreamChat) {
for await (const content of this.customStreamChat(
messages,
signal,
options,
(...args) => this.fetch(...args),
)) {
yield { role: "assistant", content };
}
} else {
for await (const update of super._streamChat(messages, options)) {
for await (const update of super._streamChat(messages, signal, options)) {
yield update;
}
}
@ -50,11 +54,13 @@ class CustomLLMClass extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (this.customStreamCompletion) {
for await (const content of this.customStreamCompletion(
prompt,
signal,
options,
(...args) => this.fetch(...args),
)) {
@ -63,6 +69,7 @@ class CustomLLMClass extends BaseLLM {
} else if (this.customStreamChat) {
for await (const content of this.customStreamChat(
[{ role: "user", content: prompt }],
signal,
options,
(...args) => this.fetch(...args),
)) {

View file

@ -23,6 +23,7 @@ class Deepseek extends OpenAI {
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("beta/completions", this.apiBase);
@ -45,6 +46,7 @@ class Deepseek extends OpenAI {
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].text;

View file

@ -121,16 +121,18 @@ class Flowise extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const message: ChatMessage = { role: "user", content: prompt };
for await (const chunk of this._streamChat([message], options)) {
for await (const chunk of this._streamChat([message], signal, options)) {
yield stripImages(chunk.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const requestBody = this._getRequestBody(messages, options);
@ -139,6 +141,7 @@ class Flowise extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal
}).then((res) => res.json());
while (await socketInfo.hasNextToken()) {

View file

@ -60,6 +60,7 @@ class FreeTrial extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(this.collectArgs(options));
@ -73,6 +74,7 @@ class FreeTrial extends BaseLLM {
prompt,
...args,
}),
signal
});
let completion = "";
@ -103,6 +105,7 @@ class FreeTrial extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const args = this._convertArgs(this.collectArgs(options));
@ -120,6 +123,7 @@ class FreeTrial extends BaseLLM {
messages: messages.map(this._convertMessage),
...args,
}),
signal
});
let completion = "";
@ -140,6 +144,7 @@ class FreeTrial extends BaseLLM {
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(this.collectArgs(options));
@ -153,6 +158,7 @@ class FreeTrial extends BaseLLM {
suffix,
...args,
}),
signal
});
let completion = "";

View file

@ -46,10 +46,12 @@ class Gemini extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
signal,
options,
)) {
yield stripImages(message.content);
@ -72,6 +74,7 @@ class Gemini extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
// Ensure this.apiBase is used if available, otherwise use default
@ -89,6 +92,7 @@ class Gemini extends BaseLLM {
if (options.model.includes("gemini")) {
for await (const message of this.streamChatGemini(
convertedMsgs,
signal,
options,
)) {
yield message;
@ -96,6 +100,7 @@ class Gemini extends BaseLLM {
} else {
for await (const message of this.streamChatBison(
convertedMsgs,
signal,
options,
)) {
yield message;
@ -118,6 +123,7 @@ class Gemini extends BaseLLM {
private async *streamChatGemini(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
@ -159,6 +165,7 @@ class Gemini extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
});
let buffer = "";
@ -211,6 +218,7 @@ class Gemini extends BaseLLM {
}
private async *streamChatBison(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const msgList = [];
@ -226,6 +234,7 @@ class Gemini extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
});
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };

View file

@ -16,6 +16,7 @@ class HuggingFaceInferenceAPI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (!this.apiBase) {
@ -36,6 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM {
stream: true,
parameters: this._convertArgs(options),
}),
signal
});
async function* stream() {

View file

@ -48,6 +48,7 @@ class HuggingFaceTGI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args = this._convertArgs(options, prompt);
@ -60,6 +61,7 @@ class HuggingFaceTGI extends BaseLLM {
"Content-Type": "application/json",
},
body: JSON.stringify({ inputs: prompt, parameters: args }),
signal
},
);

View file

@ -26,6 +26,7 @@ class LlamaCpp extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const headers = {
@ -42,6 +43,7 @@ class LlamaCpp extends BaseLLM {
stream: true,
...this._convertArgs(options, prompt),
}),
signal
});
for await (const value of streamSse(resp)) {

View file

@ -7,6 +7,7 @@ class Mock extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
yield this.completion;
@ -14,6 +15,7 @@ class Mock extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
for (const char of this.completion) {

61
core/llm/llms/Moonshot.ts Normal file
View file

@ -0,0 +1,61 @@
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
class Moonshot extends OpenAI {
static providerName: ModelProvider = "moonshot";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.moonshot.cn/v1/",
model: "moonshot-v1-8k",
promptTemplates: {
edit: osModelsEditPrompt,
},
useLegacyCompletionsEndpoint: false,
};
maxStopWords: number | undefined = 16;
supportsFim(): boolean {
return true;
}
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("v1/chat/completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
messages: [
{
role: "user",
content: prefix + "[fill]" + suffix,
},
],
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].delta.content;
}
}
}
export default Moonshot;

View file

@ -30,7 +30,7 @@ interface ModelFileParams {
min_p?: number;
// deprecated?
num_thread?: number;
use_mmap?: boolean;
use_mmap?: boolean;
num_gqa?: number;
num_gpu?: number;
}
@ -77,7 +77,6 @@ class Ollama extends BaseLLM {
if (options.model === "AUTODETECT") {
return;
}
this.fetch(this.getEndpoint("api/show"), {
method: "POST",
headers: {
@ -262,6 +261,7 @@ class Ollama extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
@ -271,6 +271,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getGenerateOptions(options, prompt)),
signal
});
let buffer = "";
@ -301,6 +302,7 @@ class Ollama extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const response = await this.fetch(this.getEndpoint("api/chat"), {
@ -310,6 +312,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getChatOptions(options, messages)),
signal
});
let buffer = "";
@ -348,8 +351,10 @@ class Ollama extends BaseLLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(this.getEndpoint("api/generate"), {
method: "POST",
headers: {
@ -357,6 +362,7 @@ class Ollama extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)),
signal
});
let buffer = "";

View file

@ -95,11 +95,8 @@ class OpenAI extends BaseLLM {
);
}
private supportsPrediction(model: string): boolean {
return [
"gpt-4o-mini",
"gpt-4o"
].includes(model);
protected supportsPrediction(model: string): boolean {
return ["gpt-4o-mini", "gpt-4o"].includes(model);
}
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) {
@ -120,9 +117,9 @@ class OpenAI extends BaseLLM {
: url.host === "api.deepseek.com"
? options.stop?.slice(0, 16)
: url.port === "1337" ||
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
url.host === "api.openai.com" ||
url.host === "api.groq.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
@ -143,10 +140,12 @@ class OpenAI extends BaseLLM {
}
if (options.prediction && this.supportsPrediction(options.model)) {
if (finalOptions.presence_penalty) { // prediction doesn't support > 0
if (finalOptions.presence_penalty) {
// prediction doesn't support > 0
finalOptions.presence_penalty = undefined;
}
if (finalOptions.frequency_penalty) { // prediction doesn't support > 0
if (finalOptions.frequency_penalty) {
// prediction doesn't support > 0
finalOptions.frequency_penalty = undefined;
}
finalOptions.max_completion_tokens = undefined;
@ -167,11 +166,13 @@ class OpenAI extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): Promise<string> {
let completion = "";
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
completion += chunk.content;
@ -200,10 +201,12 @@ class OpenAI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield stripImages(chunk.content);
@ -212,6 +215,7 @@ class OpenAI extends BaseLLM {
protected async *_legacystreamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const args: any = this._convertArgs(options, []);
@ -225,6 +229,7 @@ class OpenAI extends BaseLLM {
...args,
stream: true,
}),
signal
});
for await (const value of streamSse(response)) {
@ -236,6 +241,7 @@ class OpenAI extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (
@ -247,6 +253,7 @@ class OpenAI extends BaseLLM {
) {
for await (const content of this._legacystreamComplete(
stripImages(messages[messages.length - 1]?.content || ""),
signal,
options,
)) {
yield {
@ -267,6 +274,7 @@ class OpenAI extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify(body),
signal
});
// Handle non-streaming response
@ -286,6 +294,7 @@ class OpenAI extends BaseLLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("fim/completions", this.apiBase);
@ -309,6 +318,7 @@ class OpenAI extends BaseLLM {
"x-api-key": this.apiKey ?? "",
Authorization: `Bearer ${this.apiKey}`,
},
signal
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].delta.content;

View file

@ -41,11 +41,13 @@ class Replicate extends BaseLLM {
private _convertArgs(
options: CompletionOptions,
prompt: string,
): [`${string}/${string}:${string}`, { input: any }] {
signal: AbortSignal
): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] {
return [
Replicate.MODEL_IDS[options.model] || (options.model as any),
{
input: { prompt, message: prompt },
signal
},
];
}
@ -57,9 +59,10 @@ class Replicate extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): Promise<string> {
const [model, args] = this._convertArgs(options, prompt);
const [model, args] = this._convertArgs(options, prompt, signal);
const response = await this._replicate.run(model, args);
return (response as any)[0];
@ -67,9 +70,10 @@ class Replicate extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const [model, args] = this._convertArgs(options, prompt);
const [model, args] = this._convertArgs(options, prompt, signal);
for await (const event of this._replicate.stream(model, args)) {
if (event.event === "output") {
yield event.data;

View file

@ -32,6 +32,7 @@ class SageMaker extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
@ -45,7 +46,7 @@ class SageMaker extends BaseLLM {
});
const toolkit = new CompletionAPIToolkit(this);
const command = toolkit.generateCommand([], prompt, options);
const response = await client.send(command);
const response = await client.send(command, { abortSignal: signal });
if (response.Body) {
let buffer = "";
for await (const rawValue of response.Body) {
@ -82,6 +83,7 @@ class SageMaker extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
@ -96,7 +98,7 @@ class SageMaker extends BaseLLM {
const toolkit = new MessageAPIToolkit(this);
const command = toolkit.generateCommand(messages, "", options);
const response = await client.send(command);
const response = await client.send(command, { abortSignal: signal });
if (response.Body) {
let buffer = "";
for await (const rawValue of response.Body) {

View file

@ -41,9 +41,10 @@ class Together extends OpenAI {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._legacystreamComplete(prompt, options)) {
for await (const chunk of this._legacystreamComplete(prompt,signal, options)) {
yield chunk;
}
}

View file

@ -49,7 +49,7 @@ class VertexAI extends BaseLLM {
"unknown";
this.anthropicInstance = new Anthropic(_options);
this.geminiInstance = new Gemini(_options);
}
async fetch(url: RequestInfo | URL, init?: RequestInit) {
@ -307,6 +307,7 @@ class VertexAI extends BaseLLM {
protected async *StreamFimMistral(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const apiBase = this.apiBase!;
@ -329,6 +330,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal
});
for await (const chunk of streamSse(response)) {
@ -342,6 +344,7 @@ class VertexAI extends BaseLLM {
protected async *streamFimGecko(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase);
@ -363,6 +366,7 @@ class VertexAI extends BaseLLM {
}
}),
signal
});
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
@ -373,6 +377,7 @@ class VertexAI extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const isV1API = this.apiBase.includes("/v1/");
@ -396,10 +401,12 @@ class VertexAI extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const message of this._streamChat(
[{ content: prompt, role: "user" }],
signal,
options,
)) {
yield stripImages(message.content);
@ -409,15 +416,16 @@ class VertexAI extends BaseLLM {
protected async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
if (this.model === "code-gecko") {
yield* this.streamFimGecko(prefix, suffix, options);
yield* this.streamFimGecko(prefix, suffix, signal, options);
} else if (this.model.includes("codestral")) {
yield* this.StreamFimMistral(prefix, suffix, options);
yield* this.StreamFimMistral(prefix, suffix, signal, options);
} else {
throw new Error(`Unsupported model: ${this.model}`);
}

View file

@ -140,11 +140,13 @@ class WatsonX extends BaseLLM {
protected async _complete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): Promise<string> {
let completion = "";
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
completion += chunk.content;
@ -155,10 +157,12 @@ class WatsonX extends BaseLLM {
protected async *_streamComplete(
prompt: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
for await (const chunk of this._streamChat(
[{ role: "user", content: prompt }],
signal,
options,
)) {
yield stripImages(chunk.content);
@ -167,6 +171,7 @@ class WatsonX extends BaseLLM {
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
var now = new Date().getTime() / 1000;
@ -219,6 +224,7 @@ class WatsonX extends BaseLLM {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal
});
if (!response.ok || response.body === null) {

View file

@ -31,6 +31,7 @@ import Llamafile from "./Llamafile";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import Mock from "./Mock";
import Moonshot from "./Moonshot";
import Msty from "./Msty";
import Nebius from "./Nebius";
import Nvidia from "./Nvidia";
@ -54,6 +55,7 @@ const LLMs = [
FreeTrial,
Gemini,
Llamafile,
Moonshot,
Ollama,
Replicate,
TextGenWebUI,

View file

@ -6827,9 +6827,9 @@
}
},
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
"integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==",
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",

View file

@ -90,7 +90,7 @@ export function slashCommandFromPromptFile(
systemMessage,
);
for await (const chunk of context.llm.streamChat(messages)) {
for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) {
yield stripImages(chunk.content);
}
},

View file

@ -7,7 +7,9 @@ import type {
ContextItemWithId,
ContextSubmenuItem,
DiffLine,
FileSymbolMap,
IdeSettings,
IndexingStatusMap,
LLMFullCompletionOptions,
MessageContent,
ModelDescription,
@ -77,6 +79,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
ContextItemWithId[],
];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
"context/addDocs": [SiteIndexingConfig, void];
@ -143,6 +146,8 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{ model: string; promptTokens: number; generatedTokens: number }[],
];
"tts/kill": [undefined, void];
// Codebase indexing
"index/setPaused": [boolean, void];
"index/forceReIndex": [
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
@ -156,6 +161,13 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
// Docs etc. Indexing. TODO move codebase to this
"indexing/reindex": [{ type: string; id: string }, void];
"indexing/abort": [{ type: string; id: string }, void];
"indexing/setPaused": [{ type: string; id: string; paused: boolean }, void];
"indexing/initStatuses": [undefined, void];
addAutocompleteModel: [{ model: ModelDescription }, void];
"profiles/switch": [{ id: string }, undefined];

View file

@ -27,6 +27,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
},
void,
];
overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
toggleDevTools: [undefined, void];
@ -39,8 +40,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
"jetbrains/isOSREnabled": [undefined, void];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string }, void];
rejectDiff: [{ filepath: string }, void];
acceptDiff: [{ filepath: string; streamId?: string }, void];
rejectDiff: [{ filepath: string; streamId?: string }, void];
"edit/sendPrompt": [
{ prompt: MessageContent; range: RangeInFileWithContents },
void,
@ -63,11 +64,17 @@ export type EditStatus =
| "accepting:full-diff"
| "done";
export type ApplyStateStatus =
| "streaming" // Changes are being applied to the file
| "done" // All changes have been applied, awaiting user to accept/reject
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
export interface ApplyState {
streamId: string;
status?: "streaming" | "done" | "closed";
status?: ApplyStateStatus;
numDiffs?: number;
filepath?: string;
fileContent?: string;
}
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {

View file

@ -24,6 +24,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/listProfiles",
"config/openLocalConfigFile",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",
"context/addDocs",
"context/removeDocs",
@ -41,10 +42,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"chatDescriber/describe",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase
"index/setPaused",
"index/forceReIndex",
"index/forceReIndexFiles",
"index/indexingProgressBarInitialized",
// Docs, etc.
"indexing/initStatuses",
"indexing/reindex",
"indexing/abort",
"indexing/setPaused",
//
"completeOnboarding",
"addAutocompleteModel",
"profiles/switch",
@ -56,7 +64,8 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
[
"configUpdate",
"getDefaultModelTitle",
"indexProgress",
"indexProgress", // Codebase
"indexing/statusUpdate", // Docs, etc.
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",

View file

@ -1,13 +1,18 @@
import { ConfigValidationError } from "../config/validation.js";
import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js";
import type {
ContextItemWithId,
IndexingProgressUpdate,
IndexingStatus,
} from "../index.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [undefined, void];
configError: [ConfigValidationError[] | undefined, void];
openSelectedConfigProfile: [undefined, void];
getDefaultModelTitle: [undefined, string];
indexProgress: [IndexingProgressUpdate, void];
indexProgress: [IndexingProgressUpdate, void]; // Codebase
"indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc.
refreshSubmenuItems: [undefined, void];
isContinueInputFocused: [undefined, boolean];
addContextItem: [

View file

@ -52,6 +52,7 @@ export class ChatDescriber {
content: ChatDescriber.prompt + message,
},
],
new AbortController().signal,
completionOptions,
);

View file

@ -11,8 +11,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
multilineCompletions: "auto",
slidingWindowPrefixPercentage: 0.75,
slidingWindowSize: 500,
maxSnippetPercentage: 0.6,
recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold.
maxSnippetPercentage: 0.5,
maxDiffPercentage: 0.5,
useCache: true,
onlyMyCode: true,
useOtherFiles: true,

View file

@ -2,6 +2,7 @@ import fs from "node:fs";
import * as path from "node:path";
import Parser, { Language } from "web-tree-sitter";
import { FileSymbolMap, IDE, SymbolWithRange } from "..";
export enum LanguageName {
CPP = "cpp",
@ -205,3 +206,93 @@ async function loadLanguageForFileExt(
);
return await Parser.Language.load(wasmPath);
}
// See https://tree-sitter.github.io/tree-sitter/using-parsers
const GET_SYMBOLS_FOR_NODE_TYPES: Parser.SyntaxNode["type"][] = [
"class_declaration",
"class_definition",
"function_item", // function name = first "identifier" child
"function_definition",
"method_declaration", // method name = first "identifier" child
"method_definition",
"generator_function_declaration",
// property_identifier
// field_declaration
// "arrow_function",
];
export async function getSymbolsForFile(
filepath: string,
contents: string,
): Promise<SymbolWithRange[] | undefined> {
const parser = await getParserForFile(filepath);
if (!parser) {
return;
}
const tree = parser.parse(contents);
// console.log(`file: ${filepath}`);
// Function to recursively find all named nodes (classes and functions)
const symbols: SymbolWithRange[] = [];
function findNamedNodesRecursive(node: Parser.SyntaxNode) {
// console.log(`node: ${node.type}, ${node.text}`);
if (GET_SYMBOLS_FOR_NODE_TYPES.includes(node.type)) {
// console.log(`parent: ${node.type}, ${node.text.substring(0, 200)}`);
// node.children.forEach((child) => {
// console.log(`child: ${child.type}, ${child.text}`);
// });
// Empirically, the actual name is the last identifier in the node
// Especially with languages where return type is declared before the name
// TODO use findLast in newer version of node target
let identifier: Parser.SyntaxNode | undefined = undefined;
for (let i = node.children.length - 1; i >= 0; i--) {
if (
node.children[i].type === "identifier" ||
node.children[i].type === "property_identifier"
) {
identifier = node.children[i];
break;
}
}
if (identifier?.text) {
symbols.push({
filepath,
type: node.type,
name: identifier.text,
range: {
start: {
character: node.startPosition.column,
line: node.startPosition.row,
},
end: {
character: node.endPosition.column + 1,
line: node.endPosition.row + 1,
},
},
});
}
}
node.children.forEach(findNamedNodesRecursive);
}
findNamedNodesRecursive(tree.rootNode);
return symbols;
}
export async function getSymbolsForManyFiles(
uris: string[],
ide: IDE,
): Promise<FileSymbolMap> {
const filesAndSymbols = await Promise.all(
uris.map(async (uri): Promise<[string, SymbolWithRange[]]> => {
const contents = await ide.readFile(uri);
const symbols = await getSymbolsForFile(uri, contents);
return [uri, symbols ?? []];
}),
);
return Object.fromEntries(filesAndSymbols);
}

View file

@ -291,7 +291,7 @@ Reference the conversation in a Jira issue.
"name": "jira",
"params": {
"domain": "company.atlassian.net",
"token ": "ATATT..."
"token": "ATATT..."
}
}
]

View file

@ -0,0 +1,60 @@
# Moonshot
[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance.
## Configuration
To use Moonshot AI models, you need to:
1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/)
2. Add the following configuration to your `config.json`:
```json
{
"models": [
{
"title": "Moonshot",
"provider": "moonshot",
"model": "moonshot-v1-8k",
"apiKey": "YOUR_API_KEY"
}
]
}
```
## Available Models
Moonshot AI currently provides the following models:
- `moonshot-v1-8k`: Base model with 8K context window
- `moonshot-v1-32k`: Base model with 32K context window
- `moonshot-v1-128k`: Base model with 128K context window
## Configuration Options
| Option | Description | Default |
|--------|-------------|---------|
| `apiKey` | Moonshot API key | Required |
| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` |
| `model` | Model name to use | `moonshot-v1-8k` |
## Example
Here's a complete configuration example:
```json
{
"models": [
{
"title": "Moonshot-8K",
"provider": "moonshot",
"model": "moonshot-v1-8k",
"apiKey": "YOUR_API_KEY",
"completionOptions": {
"temperature": 0.7,
"topP": 0.95,
"maxTokens": 2048
}
}
]
}

View file

@ -27,7 +27,6 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
}
```
## Autocomplete model
We recommend configuring **Codestral** or **code-gecko** as your autocomplete model.
@ -43,6 +42,7 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo
}
}
```
## Embeddings model
We recommend configuring **text-embedding-004** as your embeddings model.

View file

@ -1,5 +1,5 @@
---
title: Reference
title: config.json Reference
description: Reference for the Continue _config.json_ configuration file
keywords: [config, config_schema.json, json]
---

View file

@ -7,7 +7,7 @@ sidebar_position: 5
## 内置的斜杠命令
Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。
Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。
## 定制斜杠命令

View file

@ -5,7 +5,7 @@ keywords: [定制]
sidebar_position: 5
---
Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡:
Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡:
```json title="config.json"
"tabAutocompleteOptions": {

View file

@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
:::info
这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。
这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。
:::
## 最好的总体体验

View file

@ -44,7 +44,7 @@ ollama run starcoder2:3b
}
```
如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。
如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。
## 配置选项

View file

@ -0,0 +1,52 @@
---
title: NVIDIA
---
:::info
[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key.
:::
## Chat model
We recommend configuring **Nemotron-4-340B-Instruct** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Nemotron-4-340B-Instruct",
"provider": "nvidia",
"model": "nvidia-nemotron-4-340b-instruct",
"apiKey": "[API_KEY]"
}
]
}
```
## Autocomplete model
NVIDIA currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "nvidia",
"model": "nvidia/nv-embedqa-mistral-7b-v2",
"apiKey": "[API_KEY]"
}
}
```
## Reranking model
NVIDIA currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.

View file

@ -0,0 +1,65 @@
---
title: Vertex AI
slug: ../vertexai
---
:::info
You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc).
:::
## Chat model
We recommend configuring **Claude 3.5 Sonnet** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "vertexai",
"model": "claude-3-5-sonnet-20240620",
"projectId": "[PROJECT_ID]",
"region": "us-east5"
}
]
}
```
## Autocomplete model
We recommend configuring **Codestral** or **code-gecko** as your autocomplete model.
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Codestral (Vertex AI)",
"provider": "vertexai",
"model": "codestral",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
}
```
## Embeddings model
We recommend configuring **text-embedding-004** as your embeddings model.
```json title="config.json"
{
"embeddingsProvider": {
"provider": "vertexai",
"model": "text-embedding-004",
"projectId": "[PROJECT_ID]",
"region": "us-central1"
}
}
```
## Reranking model
<!-- Vertex AI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers. -->

View file

@ -0,0 +1,53 @@
---
title: xAI
slug: ../xai
---
:::info
You can get an API key from the [xAI console](https://console.x.ai/)
:::
## Chat model
We recommend configuring **grok-beta** as your chat model.
```json title="config.json"
{
"models": [
{
"title": "Grok Beta",
"provider": "xAI",
"model": "grok-beta",
"apiKey": "[API_KEY]"
}
]
}
```
## Autocomplete model
xAI currently does not offer any autocomplete models.
[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers.
## Embeddings model
xAI currently does not offer any embeddings models.
[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers.
## Reranking model
xAI currently does not offer any reranking models.
[Click here](../../model-types/reranking.md) to see a list of reranking model providers.
## Legacy Completions
To force usage of `chat/completions` instead of `completions` endpoint you can set
```json
"useLegacyCompletionsEndpoint": false
```

View file

@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config
## 开始
要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。
要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。
当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。
## 每个工作区的配置
如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。
如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。
## 可编程的配置

View file

@ -5,6 +5,6 @@ description: 如何设置一个编辑模型
keywords: [编辑, cmd l, 模型]
---
默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。
默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。
你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。
你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。

View file

@ -0,0 +1,446 @@
---
title: Reference
description: Reference for the Continue _config.json_ configuration file
keywords: [config, config_schema.json, json]
---
Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json).
**All properties at all levels are optional unless explicitly marked required**
### `models`
Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md).
Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json.
**Properties:**
- `title` (**required**): The title to assign to your model, shown in dropdowns, etc.
- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions.
- `model` (**required**): The name of the model, used for prompt template auto-detection.
- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere.
- `apiBase`: The base URL of the LLM API.
- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048).
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions.
- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt).
- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override.
- `systemMessage`: A system message that will precede responses from the LLM.
- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override.
- `apiType`: Specifies the type of API (`openai` or `azure`).
- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`).
- `engine`: Engine for Azure OpenAI requests.
- `capabilities`: Override auto-detected capabilities:
- `uploadImage`: Boolean indicating if the model supports image uploads.
_(AWS Only)_
- `profile`: AWS security profile for authorization.
- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider).
- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`).
Example:
```json title="config.json"
{
"models": [
{
"title": "Ollama",
"provider": "ollama",
"model": "AUTODETECT"
},
{
"model": "gpt-4o",
"contextLength": 128000,
"title": "GPT-4o",
"provider": "openai",
"apiKey": "YOUR_API_KEY"
}
]
}
```
### `tabAutocompleteModel`
Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model.
Example
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "My Starcoder",
"provider": "ollama",
"model": "starcoder2:3b"
}
}
```
### `tabAutocompleteOptions`
Specifies options for tab autocompletion behavior.
**Properties:**
- `disable`: If `true`, disables tab autocomplete (default: `false`).
- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt.
- `useFileSuffix`: If `true`, includes file suffix in the prompt.
- `maxPromptTokens`: Maximum number of tokens for the prompt.
- `debounceDelay`: Delay (in ms) before triggering autocomplete.
- `maxSuffixPercentage`: Maximum percentage of prompt for suffix.
- `prefixPercentage`: Percentage of input for prefix.
- `template`: Template string for autocomplete, using Mustache templating.
- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`).
- `useCache`: If `true`, caches completions.
- `onlyMyCode`: If `true`, only includes code within the repository.
- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`).
- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled.
Example
```json title="config.json"
{
"tabAutocompleteOptions": {
"debounceDelay": 500,
"maxPromptTokens": 1500,
"disableInFiles": ["*.md"]
}
}
```
### `embeddingsProvider`
Embeddings model settings - the model used for @Codebase and @docs.
**Properties:**
- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc
- `model`: Model name for embeddings.
- `apiKey`: API key for the provider.
- `apiBase`: Base URL for API requests.
- `requestOptions`: Additional HTTP request settings specific to the embeddings provider.
- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens.
- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk.
(AWS ONLY)
- `region`: Specifies the region hosting the model.
- `profile`: AWS security profile.
Example:
```json title="config.json"
{
"embeddingsProvider": {
"provider": "openai",
"model": "text-embedding-ada-002",
"apiKey": "<API_KEY>",
"maxChunkSize": 256,
"maxBatchSize": 5
}
}
```
### `completionOptions`
Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_.
**Properties:**
- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`).
- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs.
- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass.
- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability.
- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output.
- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition.
- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0).
- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions.
- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`).
- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`.
- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes).
- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream.
Example
```json title="config.json"
{
"completionOptions": {
"stream": false,
"temperature": 0.5
}
}
```
### `requestOptions`
Default HTTP request options that apply to all models and context providers, unless overridden at the model level.
**Properties:**
- `timeout`: Timeout for each request to the LLM (default: 7200 seconds).
- `verifySsl`: Whether to verify SSL certificates for requests.
- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths)
- `proxy`: Proxy URL to use for HTTP requests.
- `headers`: Custom headers for HTTP requests.
- `extraBodyProperties`: Additional properties to merge with the HTTP request body.
- `noProxy`: List of hostnames that should bypass the specified proxy.
- `clientCertificate`: Client certificate for HTTP requests.
- `cert`: Path to the client certificate file.
- `key`: Path to the client certificate key file.
- `passphrase`: Optional passphrase for the client certificate key file.
Example
```json title="config.json"
{
"requestOptions": {
"headers": {
"X-Auth-Token": "xxx"
}
}
}
```
### `reranker`
Configuration for the reranker model used in response ranking.
**Properties:**
- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`
- `params`:
- `model`: Model name
- `apiKey`: Api key
Example
```json title="config.json"
{
"reranker": {
"name": "voyage",
"params": {
"model": "rerank-2",
"apiKey": "<VOYAGE_API_KEY>"
}
}
}
```
### `docs`
List of documentation sites to index.
**Properties:**
- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc.
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL
- `maxDepth`: Maximum depth for crawling. Default `3`
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
Example
```json title="config.json"
"docs": [
{
"title": "Continue",
"startUrl": "https://docs.continue.dev/intro",
"rootUrl": "https://docs.continue.dev",
"faviconUrl": "https://docs.continue.dev/favicon.ico",
}
]
```
### `analytics`
Configuration for analytics tracking.
**Properties:**
- `provider`: Analytics provider (`"posthog"` or `"logstash"`).
- `url`: URL for analytics data.
- `clientKey`: Client key for analytics.
### `slashCommands`
Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined.
**Properties:**
- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review".
- `description`: Brief description of the command.
- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options.
- `params`: Additional parameters to configure command behavior (command-specific - see code for command)
Example:
```json title="config.json"
{
"slashCommands": [
{
"name": "commit",
"description": "Generate a commit message"
},
{
"name": "share",
"description": "Export this session as markdown"
},
{
"name": "cmd",
"description": "Generate a shell command"
}
]
}
```
### `customCommands`
User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions.
**Properties:**
- `name`: The name of the custom command.
- `prompt`: Text prompt for the command.
- `description`: Brief description explaining the command's function.
Example:
```json title="config.json"
{
"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`
List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`.
**Properties:**
- `name`: Name of the context provider, e.g. `docs` or `web`
- `params`: A context-provider-specific record of params to configure the context behavior
Example
```json title="config.json"
{
"contextProviders": [
{
"name": "code",
"params": {}
},
{
"name": "docs",
"params": {}
},
{
"name": "diff",
"params": {}
},
{
"name": "open",
"params": {}
}
]
}
```
### `disableSessionTitles`
Prevents generating summary titles for each chat session when set to `true`.
### `ui`
Customizable UI settings to control interface appearance and behavior.
**Properties:**
- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`.
- `fontSize`: Specifies font size for UI elements.
- `displayRawMarkdown`: If `true`, shows raw markdown in responses.
- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window.
Example:
```json title="config.json"
{
"ui": {
"codeBlockToolbarPosition": "bottom",
"fontSize": 14,
"displayRawMarkdown": false
}
}
```
### `allowAnonymousTelemetry`
When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`.
### `userToken`
An optional token that identifies the user, primarily for authenticated services.
### `systemMessage`
Defines a system message that appears before every response from the language model, providing guidance or context.
### `disableIndexing`
Prevents indexing of the codebase, useful primarily for debugging purposes.
### `experimental`
Several experimental config parameters are available, as described below:
`experimental`:
- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.=
- `modelRoles`:
- `inlineEdit`: Model title for inline edits.
- `applyCodeBlock`: Model title for applying code blocks.
- `repoMapFileSelection`: Model title for repo map selections.
- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`.
- `promptPath`: Change the path to custom prompt files from the default ".prompts"
- `quickActions`: Array of custom quick actions
- `title` (**required**): Display title for the quick action.
- `prompt` (**required**): Prompt for quick action.
- `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`.
- `contextMenuPrompts`:
- `comment`: Prompt for commenting code.
- `docstring`: Prompt for adding docstrings.
- `fix`: Prompt for fixing code.
- `optimize`: Prompt for optimizing code.
- `fixGrammar`: Prompt for fixing grammar or spelling.
- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`..
Example
```json title="config.json"
{
"experimental": {
"modelRoles": {
"inlineEdit": "Edit Model"
},
"promptPath": "custom/.prompts",
"quickActions": [
{
"title": "Tags",
"prompt": "Return a list of any function and class names from the included code block",
"sendToChat": true
}
],
"contextMenuPrompts": {
"fixGrammar": "Fix grammar in the above but allow for typos."
},
"readResponseTTS": false,
"useChromiumForDocsCrawling": true
}
}
```

View file

@ -205,7 +205,8 @@
"nebius",
"vertexai",
"xAI",
"kindo"
"kindo",
"moonshot"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)",
@ -242,7 +243,8 @@
"### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).",
"### Ask Sage\nAsk Sage is an agnostic hosted service that provides language models. To get started with Ask Sage:\n1. Obtain an API key from your account. For more information, visit [Ask Sage](https://docs.asksage.ai/).\n2. Paste the API key below.\n3. Select a model preset.\n> [Reference](https://docs.asksage.ai/)",
"### xAI offers a world class developer tool set to build scalable applications powered by Grok. To get started, obtain an API key from [the x Console](https://console.x.ai/), and see the [docs](https://docs.x.ai/docs/)",
"### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)"
"### Secure AI management software that helps enterprises adopt and manage AI across their workforce. To get started, obtain an API key from [the Kindo console](https://app.kindo.ai/settings/api), and see the [website](https://app.kindo.ai//)",
"### Moonshot\nTo get started with Moonshot AI, obtain your API key from [Moonshot AI](https://platform.moonshot.cn/). Moonshot AI provides high-quality large language models with competitive pricing.\n> [Reference](https://platform.moonshot.cn/docs/api)"
],
"type": "string"
},
@ -1147,6 +1149,35 @@
"required": ["projectId", "region"]
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["moonshot"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"moonshot-v1-8k",
"moonshot-v1-32k",
"moonshot-v1-128k",
"AUTODETECT"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {
@ -2325,7 +2356,7 @@
"type": "integer",
"description": "The maximum depth to crawl the documentation site"
},
"favicon": {
"faviconUrl": {
"type": "string",
"description": "The URL path to a favicon for the site - by default, it will be `/favicon.ico` path from the Start URL"
}

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.231",
"version": "0.9.232",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -390,11 +390,6 @@
"mac": "alt+cmd+n",
"key": "alt+ctrl+n"
},
{
"command": "continue.quickEdit",
"mac": "cmd+shift+i",
"key": "ctrl+shift+i"
},
{
"command": "continue.edit",
"mac": "cmd+i",
@ -437,9 +432,6 @@
],
"menus": {
"commandPalette": [
{
"command": "continue.quickEdit"
},
{
"command": "continue.focusContinueInput"
},

View file

@ -271,7 +271,10 @@ const commandsMap: (
}
return {
"continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => {
"continue.acceptDiff": async (
newFilepath?: string | vscode.Uri,
streamId?: string,
) => {
captureCommandTelemetry("acceptDiff");
let fullPath = newFilepath;
@ -290,8 +293,23 @@ const commandsMap: (
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId && fullPath) {
const fileContent = await ide.readFile(fullPath);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: fullPath,
streamId: streamId,
status: "closed",
numDiffs: 0,
});
}
},
"continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => {
"continue.rejectDiff": async (
newFilepath?: string | vscode.Uri,
streamId?: string,
) => {
captureCommandTelemetry("rejectDiff");
let fullPath = newFilepath;
@ -309,6 +327,18 @@ const commandsMap: (
void sidebar.webviewProtocol.request("setEditStatus", {
status: "done",
});
if (streamId && fullPath) {
const fileContent = await ide.readFile(fullPath);
await sidebar.webviewProtocol.request("updateApplyState", {
fileContent,
filepath: fullPath,
streamId: streamId,
status: "closed",
numDiffs: 0,
});
}
},
"continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => {
captureCommandTelemetry("acceptVerticalDiffBlock");
@ -735,7 +765,7 @@ const commandsMap: (
!selected ||
!autocompleteModels.some((model) => model.title === selected)
) {
selected = autocompleteModels[0].title;
selected = autocompleteModels[0]?.title;
}
// Toggle between Disabled, Paused, and Enabled

View file

@ -18,6 +18,7 @@ export interface VerticalDiffHandlerOptions {
onStatusUpdate: (
status?: ApplyState["status"],
numDiffs?: ApplyState["numDiffs"],
fileContent?: ApplyState["fileContent"],
) => void;
}
@ -271,6 +272,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.options.onStatusUpdate(
"closed",
this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0,
this.editor.document.getText(),
);
this.cancelled = true;
@ -362,6 +364,7 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.options.onStatusUpdate(
"done",
this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0,
this.editor.document.getText(),
);
// Reject on user typing
@ -416,7 +419,11 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.editorToVerticalDiffCodeLens.get(this.filepath)?.length ?? 0;
const status = numDiffs === 0 ? "closed" : undefined;
this.options.onStatusUpdate(status, numDiffs);
this.options.onStatusUpdate(
status,
numDiffs,
this.editor.document.getText(),
);
}
private shiftCodeLensObjects(startLine: number, offset: number) {

View file

@ -217,11 +217,13 @@ export class VerticalDiffManager {
endLine,
{
instant,
onStatusUpdate: (status, numDiffs) =>
onStatusUpdate: (status, numDiffs, fileContent) =>
void this.webviewProtocol.request("updateApplyState", {
streamId,
status,
numDiffs,
fileContent,
filepath,
}),
},
);
@ -336,12 +338,14 @@ export class VerticalDiffManager {
endLine,
{
input,
onStatusUpdate: (status, numDiffs) =>
onStatusUpdate: (status, numDiffs, fileContent) =>
streamId &&
void this.webviewProtocol.request("updateApplyState", {
streamId,
status,
numDiffs,
fileContent,
filepath,
}),
},
);

View file

@ -147,15 +147,35 @@ export class VsCodeMessenger {
);
});
webviewProtocol.on("acceptDiff", async ({ data: { filepath } }) => {
void vscode.commands.executeCommand("continue.acceptDiff", filepath);
});
webviewProtocol.on(
"acceptDiff",
async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(
"continue.acceptDiff",
filepath,
streamId,
);
},
);
webviewProtocol.on("rejectDiff", async ({ data: { filepath } }) => {
void vscode.commands.executeCommand("continue.rejectDiff", filepath);
});
webviewProtocol.on(
"rejectDiff",
async ({ data: { filepath, streamId } }) => {
await vscode.commands.executeCommand(
"continue.rejectDiff",
filepath,
streamId,
);
},
);
this.onWebview("applyToFile", async ({ data }) => {
webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "streaming",
fileContent: data.text,
});
let filepath = data.filepath;
// If there is a filepath, verify it exists and then open the file
@ -168,18 +188,10 @@ export class VsCodeMessenger {
const fileExists = await this.ide.fileExists(fullPath);
// If it's a new file, no need to apply, just write directly
// If there is no existing file at the path, create it
if (!fileExists) {
await this.ide.writeFile(fullPath, data.text);
await this.ide.writeFile(fullPath, "");
await this.ide.openFile(fullPath);
void webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
numDiffs: 0,
});
return;
}
await this.ide.openFile(fullPath);
@ -198,11 +210,14 @@ export class VsCodeMessenger {
editor.edit((builder) =>
builder.insert(new vscode.Position(0, 0), data.text),
);
void webviewProtocol.request("updateApplyState", {
streamId: data.streamId,
status: "done",
status: "closed",
numDiffs: 0,
fileContent: data.text,
});
return;
}
@ -290,6 +305,37 @@ export class VsCodeMessenger {
this.onWebview("openUrl", (msg) => {
vscode.env.openExternal(vscode.Uri.parse(msg.data));
});
this.onWebview(
"overwriteFile",
async ({ data: { prevFileContent, filepath } }) => {
if (prevFileContent === null) {
// TODO: Delete the file
return;
}
await this.ide.openFile(filepath);
// Get active text editor
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage("No active editor to apply edits to");
return;
}
editor.edit((builder) =>
builder.replace(
new vscode.Range(
editor.document.positionAt(0),
editor.document.positionAt(editor.document.getText().length),
),
prevFileContent,
),
);
},
);
this.onWebview("insertAtCursor", async (msg) => {
const editor = vscode.window.activeTextEditor;
if (editor === undefined || !editor.selection) {

Some files were not shown because too many files have changed in this diff Show more