diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 28f31d4b0..9667352fd 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,17 +1,19 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; +import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { IDE, ILLM } from "../index.js"; +import OpenAI from "../llm/llms/OpenAI.js"; 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 { AutocompleteSnippet } from "./context/ranking/index.js"; -import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore -import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; -import OpenAI from "../llm/llms/OpenAI.js"; -import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; + import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; +import { AutocompleteSnippet } from "./context/ranking/index.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; +import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { renderPrompt } from "./templating/index.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; @@ -259,13 +261,10 @@ export class CompletionProvider { ////////// - // Do some stuff later so as not to block return. Latency matters - const completionToCache = outcome.completion; - setTimeout(async () => { - if (!outcome.cacheHit) { - (await this.autocompleteCache).put(outcome.prefix, completionToCache); - } - }, 100); + // Save to cache + if (!outcome.cacheHit) { + (await this.autocompleteCache).put(outcome.prefix, outcome.completion); + } // When using the JetBrains extension, Mark as displayed const ideType = (await this.ide.getIdeInfo()).ideType; diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 18bbf2ff9..ccd5a9717 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -28,7 +28,7 @@ export const Python = { name: "Python", // """"#" is for .ipynb files, where we add '"""' surrounding markdown blocks. // This stops the model from trying to complete the start of a new markdown block - topLevelKeywords: ["def", "class", '"""#'], + topLevelKeywords: ["def", "class", "\"\"\"#"], singleLineComment: "#", endOfLine: [], }; diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 2c5d43f42..f15b1c4e1 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,4 +1,5 @@ import { Position, Range } from "../index.js"; + import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index a12d1962e..24f6e9182 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,6 +1,7 @@ import { IDE } from "../.."; import { HelperVars } from "../util/HelperVars"; import { RecentlyEditedRange } from "../util/types"; + import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; diff --git a/core/autocomplete/context/NearbyDefinitionsService.ts b/core/autocomplete/context/NearbyDefinitionsService.ts index 6e4cece83..8b526b261 100644 --- a/core/autocomplete/context/NearbyDefinitionsService.ts +++ b/core/autocomplete/context/NearbyDefinitionsService.ts @@ -1,5 +1,6 @@ import { IDE, Location } from "../.."; import { LANGUAGES } from "../constants/AutocompleteLanguageInfo"; + import { getSymbolsForSnippet } from "./ranking"; interface FileInfo { diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 54ec763f2..7b650eb44 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,4 +1,5 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; + import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; function* slidingWindow( diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts deleted file mode 100644 index fad65fcfb..000000000 --- a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import fs from "fs"; -import path from "path"; -import { Range } from "../../.."; -import { testIde } from "../../../test/util/fixtures"; -import { getAst, getTreePathAtCursor } from "../../util/ast"; -import { ImportDefinitionsService } from "../ImportDefinitionsService"; -import { RootPathContextService } from "./RootPathContextService"; - -function splitTextAtRange(fileContent: string, range: Range): [string, string] { - const lines = fileContent.split("\n"); - let currentPos = 0; - - if (range.start.line === range.end.line) { - // If range is on the same line, calculate position once - for (let i = 0; i < range.start.line; i++) { - currentPos += lines[i].length + 1; // +1 for the newline character - } - const startPos = currentPos + range.start.character; - const endPos = currentPos + range.end.character; - return [fileContent.slice(0, startPos), fileContent.slice(endPos)]; - } - - // Calculate position of range start - for (let i = 0; i < range.start.line; i++) { - currentPos += lines[i].length + 1; - } - const startPos = currentPos + range.start.character; - - // Calculate position of range end - currentPos = 0; - for (let i = 0; i < range.end.line; i++) { - currentPos += lines[i].length + 1; - } - const endPos = currentPos + range.end.character; - - return [fileContent.slice(0, startPos), fileContent.slice(endPos)]; -} - -export async function testRootPathContext( - folderName: string, - relativeFilepath: string, - rangeToFill: Range, - expectedSnippets: string[], -) { - const ide = testIde; - const importDefinitionsService = new ImportDefinitionsService(ide); - const service = new RootPathContextService(importDefinitionsService, ide); - - // Copy the folder to the test directory - const folderPath = path.join( - __dirname, - "autocomplete", - "context", - "root-path-context", - "test", - folderName, - ); - const workspaceDir = (await ide.getWorkspaceDirs())[0]; - const testFolderPath = path.join(workspaceDir, folderName); - fs.cpSync(folderPath, testFolderPath, { - recursive: true, - force: true, - }); - - // Get results of root path context - const startPath = path.join(testFolderPath, relativeFilepath); - const [prefix, suffix] = splitTextAtRange( - fs.readFileSync(startPath, "utf8"), - rangeToFill, - ); - const fileContents = prefix + suffix; - const ast = await getAst(startPath, fileContents); - if (!ast) { - throw new Error("AST is undefined"); - } - - const treePath = await getTreePathAtCursor(ast, prefix.length); - const snippets = await service.getContextForPath(startPath, treePath); - - expectedSnippets.forEach((expectedSnippet) => { - const found = snippets.find((snippet) => - snippet.contents.includes(expectedSnippet), - ); - expect(found).toBeDefined(); - }); -} - -describe("RootPathContextService", () => { - it.skip("should be true", async () => { - await testRootPathContext( - "typescript", - "file1.ts", - { start: { line: 3, character: 2 }, end: { line: 3, character: 24 } }, - ["export interface Person", "export interface Address"], - ); - }); -}); diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index ba99b2e83..accd4f6df 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -1,8 +1,10 @@ import { createHash } from "crypto"; + import { LRUCache } from "lru-cache"; import Parser from "web-tree-sitter"; + import { IDE } from "../../.."; -import { getQueryForFile, TSQueryType } from "../../../util/treeSitter"; +import { getQueryForFile } from "../../../util/treeSitter"; import { AstPath } from "../../util/ast"; import { ImportDefinitionsService } from "../ImportDefinitionsService"; import { AutocompleteSnippet } from "../ranking"; @@ -24,7 +26,10 @@ export class RootPathContextService { private static TYPES_TO_USE = new Set([ "program", "function_declaration", + "function_definition", "method_definition", + "class_declaration", + "class_definition", ]); /** @@ -52,23 +57,12 @@ export class RootPathContextService { case "program": this.importDefinitionsService.get(filepath); break; - case "function_declaration": + default: query = await getQueryForFile( filepath, - TSQueryType.FunctionDeclaration, + `root-path-context-queries/${node.type}`, ); break; - case "method_definition": - query = await getQueryForFile(filepath, TSQueryType.MethodDefinition); - break; - case "function_definition": - query = await getQueryForFile(filepath, TSQueryType.FunctionDefinition); - break; - case "method_declaration": - query = await getQueryForFile(filepath, TSQueryType.MethodDeclaration); - break; - default: - break; } if (!query) { @@ -77,28 +71,38 @@ export class RootPathContextService { await Promise.all( query.matches(node).map(async (match) => { - const startPosition = match.captures[0].node.startPosition; - const endPosition = match.captures[0].node.endPosition; - const definitions = await this.ide.gotoDefinition({ - filepath, - position: { - line: endPosition.row, - character: endPosition.column, - }, - }); - const newSnippets = await Promise.all( - definitions.map(async (def) => ({ - ...def, - contents: await this.ide.readRangeInFile(def.filepath, def.range), - })), - ); - snippets.push(...newSnippets); + for (const item of match.captures) { + const endPosition = item.node.endPosition; + const newSnippets = await this.getSnippets(filepath, endPosition); + snippets.push(...newSnippets); + } }), ); return snippets; } + private async getSnippets( + filepath: string, + endPosition: Parser.Point, + ): Promise { + const definitions = await this.ide.gotoDefinition({ + filepath, + position: { + line: endPosition.row, + character: endPosition.column, + }, + }); + const newSnippets = await Promise.all( + definitions.map(async (def) => ({ + ...def, + contents: await this.ide.readRangeInFile(def.filepath, def.range), + })), + ); + + return newSnippets; + } + async getContextForPath( filepath: string, astPath: AstPath, diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts new file mode 100644 index 000000000..196a7b643 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -0,0 +1,63 @@ +import { testRootPathContext } from "./testUtils"; + +const TEST_CASES = [ + { + nodeType: "function_declaration", + fileName: "file1.ts", + language: "TypeScript", + cursorPosition: { line: 10, character: 24 }, + definitionPositions: [ + { row: 9, column: 34 }, // Person + { row: 9, column: 44 }, // Address + ], + }, + { + nodeType: "method_declaration", + fileName: "file1.ts", + language: "TypeScript", + cursorPosition: { line: 22, character: 30 }, + definitionPositions: [ + { row: 13, column: 29 }, // BaseClass + { row: 13, column: 55 }, // FirstInterface + { row: 13, column: 72 }, // SecondInterface + { row: 21, column: 33 }, // Person + { row: 21, column: 43 }, // Address + ], + }, + { + nodeType: "function_definition", + fileName: "file1.py", + language: "Python", + cursorPosition: { line: 4, character: 25 }, + definitionPositions: [ + { row: 3, column: 30 }, // Person + { row: 3, column: 42 }, // Address + ], + }, + { + nodeType: "function_definition (inside a class)", + fileName: "file1.py", + language: "Python", + cursorPosition: { line: 12, character: 33 }, + definitionPositions: [ + { row: 6, column: 21 }, // BaseClass + { row: 6, column: 33 }, // Collection + { row: 11, column: 47 }, // Person + { row: 11, column: 59 }, // Address + ], + }, +]; + +describe("RootPathContextService", () => { + test.each(TEST_CASES)( + "Should look for correct type definitions when editing inside a $nodeType in $language", + async ({ fileName, cursorPosition, definitionPositions }) => { + await testRootPathContext( + "files", + fileName, + cursorPosition, + definitionPositions, + ); + }, + ); +}); diff --git a/core/autocomplete/context/root-path-context/test/files/__init__.py b/core/autocomplete/context/root-path-context/test/files/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/core/autocomplete/context/root-path-context/test/files/base_module.py b/core/autocomplete/context/root-path-context/test/files/base_module.py new file mode 100644 index 000000000..cf0dc0abb --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/base_module.py @@ -0,0 +1,26 @@ +# File: base_module.py + +class BaseClass: + def __init__(self): + print("BaseClass initialized") + +class Collection: + def __init__(self): + print("Collection initialized") + +class Address: + def __init__(self, street: str, city: str, zip_code: str): + self.street = street + self.city = city + self.zip_code = zip_code + + def __str__(self): + return f"{self.street}, {self.city}, {self.zip_code}" + +class Person: + def __init__(self, name: str, address: Address): + self.name = name + self.address = address + + def __str__(self): + return f"{self.name} lives at {self.address}" diff --git a/core/autocomplete/context/root-path-context/test/files/file1.py b/core/autocomplete/context/root-path-context/test/files/file1.py new file mode 100644 index 000000000..55c3d9c25 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/file1.py @@ -0,0 +1,13 @@ +from .base_module import BaseClass, Collection, Person, Address +from typing import List + +def get_address(person: Person) -> Address: + return person.address + +class Group(BaseClass, Collection): + def __init__(self, people: List[Person]) -> None: + super().__init__() + self.people = people + + def get_person_address(self, person: Person) -> Address: + return get_address(person) diff --git a/core/autocomplete/context/root-path-context/test/files/file1.ts b/core/autocomplete/context/root-path-context/test/files/file1.ts new file mode 100644 index 000000000..ba09c5709 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/file1.ts @@ -0,0 +1,25 @@ +import { + Address, + Person, + BaseClass, + FirstInterface, + SecondInterface, + // @ts-ignore +} from "./types"; + +function getAddress(person: Person): Address { + return person.address; +} + +class Group extends BaseClass implements FirstInterface, SecondInterface { + people: Person[]; + + constructor(people: Person[]) { + super(); + this.people = people; + } + + getPersonAddress(person: Person): Address { + return getAddress(person); + } +} diff --git a/core/autocomplete/context/root-path-context/test/testUtils.ts b/core/autocomplete/context/root-path-context/test/testUtils.ts new file mode 100644 index 000000000..9526cacdb --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/testUtils.ts @@ -0,0 +1,89 @@ +import { jest } from "@jest/globals"; +import fs from "fs"; +import path from "path"; + +import Parser from "web-tree-sitter"; +import { Position } from "../../../.."; +import { testIde } from "../../../../test/util/fixtures"; +import { getAst, getTreePathAtCursor } from "../../../util/ast"; +import { ImportDefinitionsService } from "../../ImportDefinitionsService"; +import { RootPathContextService } from "../RootPathContextService"; + +function splitTextAtPosition( + fileContent: string, + position: Position, +): [string, string] { + const lines = fileContent.split("\n"); + let currentPos = 0; + + // Calculate position based on the provided line and character + for (let i = 0; i < position.line; i++) { + currentPos += lines[i].length + 1; // +1 for the newline character + } + const splitPos = currentPos + position.character; + + return [fileContent.slice(0, splitPos), fileContent.slice(splitPos)]; +} + +export async function testRootPathContext( + folderName: string, + relativeFilepath: string, + position: Position, + expectedDefinitionPositions: Parser.Point[], +) { + // Create a mocked instance of RootPathContextService + const ide = testIde; + const importDefinitionsService = new ImportDefinitionsService(ide); + const service = new RootPathContextService(importDefinitionsService, ide); + + const getSnippetsMock = jest + // @ts-ignore + .spyOn(service, "getSnippets") + // @ts-ignore + .mockImplementation(async (_filepath, _endPosition) => { + return []; + }); + + // Copy the folder to the test directory + const folderPath = path.join( + __dirname, + "autocomplete", + "context", + "root-path-context", + "test", + folderName, + ); + const workspaceDir = (await ide.getWorkspaceDirs())[0]; + const testFolderPath = path.join(workspaceDir, folderName); + fs.cpSync(folderPath, testFolderPath, { + recursive: true, + force: true, + }); + + // Get results of root path context + const startPath = path.join(testFolderPath, relativeFilepath); + const [prefix, suffix] = splitTextAtPosition( + fs.readFileSync(startPath, "utf8"), + position, + ); + const fileContents = prefix + suffix; + const ast = await getAst(startPath, fileContents); + if (!ast) { + throw new Error("AST is undefined"); + } + + const treePath = await getTreePathAtCursor(ast, prefix.length); + await service.getContextForPath(startPath, treePath); + + expect(getSnippetsMock).toHaveBeenCalledTimes( + expectedDefinitionPositions.length, + ); + + expectedDefinitionPositions.forEach((position, index) => { + expect(getSnippetsMock).toHaveBeenNthCalledWith( + index + 1, + expect.any(String), // filepath argument + position, + ); + }); +} diff --git a/core/autocomplete/context/root-path-context/test/typescript/file1.ts b/core/autocomplete/context/root-path-context/test/typescript/file1.ts deleted file mode 100644 index c67ae91e2..000000000 --- a/core/autocomplete/context/root-path-context/test/typescript/file1.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Address, Person } from "./types"; - -function getAddress(person: Person): Address { - return person.address; -} - -class Group { - people: Person[]; - - constructor(people: Person[]) { - this.people = people; - } -} diff --git a/core/autocomplete/context/root-path-context/test/typescript/types.ts b/core/autocomplete/context/root-path-context/test/typescript/types.ts deleted file mode 100644 index 272ec27d7..000000000 --- a/core/autocomplete/context/root-path-context/test/typescript/types.ts +++ /dev/null @@ -1,11 +0,0 @@ -export interface Person { - firstName: string; - lastName: string; - age: number; - address: Address; -} - -export interface Address { - street: string; - city: string; -} diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 8d7f3e23f..5576ee26b 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,6 +1,7 @@ import { streamLines } from "../../../diff/util"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters"; import { HelperVars } from "../../util/HelperVars"; + import { stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index 2ef41bda0..0a99a5a91 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -1,4 +1,5 @@ import { jest } from "@jest/globals"; + import * as lineStream from "./lineStream"; describe("lineStream", () => { diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 308da41dd..8c7936e2d 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -1,4 +1,5 @@ import { distance } from "fastest-levenshtein"; + import { DiffLine } from "../../.."; import { LineStream } from "../../../diff/util"; diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts index 62ef65512..e6c07b951 100644 --- a/core/autocomplete/filtering/test/filter.test.ts +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -1,9 +1,10 @@ +import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; + +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; import { AutocompleteFileringTestInput, testAutocompleteFiltering, } from "./util"; -import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; -import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { if (tests.some((test) => test.options?.only)) { @@ -13,7 +14,7 @@ const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { return tests; }; -describe("llms/Mock", () => { +describe("Autocomplete filtering tests", () => { beforeAll(async () => { tearDownTestDir(); setUpTestDir(); @@ -23,27 +24,25 @@ describe("llms/Mock", () => { tearDownTestDir(); }); - describe("Autocomplete Filtering Tests", () => { - beforeEach(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); - describe("Should return unmodified LLM output", () => { - it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( - "$description", - async (testCase) => { - await testAutocompleteFiltering(testCase); - }, - ); - }); + describe("Should return unmodified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); - describe("Should return modified LLM output", () => { - it.each(filterTestCases(TEST_CASES_WITH_DIFF))( - "$description", - async (testCase) => { - await testAutocompleteFiltering(testCase); - }, - ); - }); + describe("Should return modified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); }); }); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 9715db4c6..406faf66f 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -1,4 +1,5 @@ import { dedent } from "../../../util"; + import { AutocompleteFileringTestInput } from "./util"; export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [ @@ -62,7 +63,7 @@ function sayHello() { `, llmOutput: `world!"); `, - expectedCompletion: `world!");`, + expectedCompletion: "world!\");", }, { description: "Should autocomplete Java when inside a block", @@ -375,8 +376,8 @@ button { border: 2px solid #000; border-radius<|fim|> }`, - llmOutput: `: 5px;`, - expectedCompletion: `: 5px;`, + llmOutput: ": 5px;", + expectedCompletion: ": 5px;", }, { @@ -391,8 +392,8 @@ button { border-bottom-right-radius: 8px; } `, - llmOutput: `8`, - expectedCompletion: `8`, + llmOutput: "8", + expectedCompletion: "8", }, { @@ -404,8 +405,8 @@ input:focus { border: 2px solid <|fim|>; } `, - llmOutput: `#4CAF50;`, - expectedCompletion: `#4CAF50;`, + llmOutput: "#4CAF50;", + expectedCompletion: "#4CAF50;", }, { @@ -422,8 +423,8 @@ input:focus { padding: var(--padding); } `, - llmOutput: `--primary-color`, - expectedCompletion: `--primary-color`, + llmOutput: "--primary-color", + expectedCompletion: "--primary-color", }, { description: "Should complete CSS grid template columns", @@ -435,8 +436,8 @@ input:focus { grid-gap: 10px; } `, - llmOutput: `3, 1fr`, - expectedCompletion: `3, 1fr`, + llmOutput: "3, 1fr", + expectedCompletion: "3, 1fr", }, { @@ -476,8 +477,8 @@ function calculateArea($length, $width) { } echo calculateArea(5, 3);`, - llmOutput: `return $length * $width;`, - expectedCompletion: `return $length * $width;`, + llmOutput: "return $length * $width;", + expectedCompletion: "return $length * $width;", filename: "areaCalculator.php", }, @@ -488,8 +489,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", }, { @@ -529,8 +530,8 @@ export const Counter = () => { ); };`, - llmOutput: `0`, - expectedCompletion: `0`, + llmOutput: "0", + expectedCompletion: "0", filename: "Counter.tsx", }, @@ -557,8 +558,8 @@ export const Timer = () => { ); };`, - llmOutput: `return () => clearInterval(interval);`, - expectedCompletion: `return () => clearInterval(interval);`, + llmOutput: "return () => clearInterval(interval);", + expectedCompletion: "return () => clearInterval(interval);", filename: "Timer.tsx", }, @@ -593,8 +594,8 @@ class Form extends React.Component { ); } }`, - llmOutput: `this.setState({ name: event.target.value });`, - expectedCompletion: `this.setState({ name: event.target.value });`, + llmOutput: "this.setState({ name: event.target.value });", + expectedCompletion: "this.setState({ name: event.target.value });", filename: "Form.tsx", }, { @@ -646,8 +647,8 @@ print(even_squares) odd_squares = [<|fim|> print(odd_squares) `, - llmOutput: `x for x in squares if x % 2 != 0`, - expectedCompletion: `x for x in squares if x % 2 != 0`, + llmOutput: "x for x in squares if x % 2 != 0", + expectedCompletion: "x for x in squares if x % 2 != 0", }, { description: "Should autocomplete a simple Go function declaration", @@ -731,8 +732,8 @@ func main() { WHERE release_year > 2000 AND director = 'Christopher Nolan' GROUP BY name HAVING avg_rating > <|fim|>`, - llmOutput: `8.5)`, - expectedCompletion: `8.5)`, + llmOutput: "8.5)", + expectedCompletion: "8.5)", }, { description: @@ -774,8 +775,8 @@ 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: @@ -790,8 +791,8 @@ func main() { ELSE 'Unknown' END as order_status FROM orders`, - llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, - expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, + llmOutput: "WHEN status = 'cancelled' THEN 'Cancelled'", + expectedCompletion: "WHEN status = 'cancelled' THEN 'Cancelled'", }, { description: "Should autocomplete HTML paragraph content", @@ -803,8 +804,8 @@ func main() {

<|fim|>

`, - llmOutput: `This is a paragraph with some sample text.`, - expectedCompletion: `This is a paragraph with some sample text.`, + llmOutput: "This is a paragraph with some sample text.", + expectedCompletion: "This is a paragraph with some sample text.", filename: "test.html", }, { @@ -816,8 +817,8 @@ func main() {

Description text.

`, - llmOutput: `alt="Description of image"`, - expectedCompletion: `alt="Description of image"`, + llmOutput: "alt=\"Description of image\"", + expectedCompletion: "alt=\"Description of image\"", filename: "test.html", }, { @@ -827,8 +828,8 @@ func main() {
  • Item 2
  • Item 3
  • `, - llmOutput: `>Item 4`, - expectedCompletion: `>Item 4`, + llmOutput: ">Item 4", + expectedCompletion: ">Item 4", filename: "test.html", }, @@ -874,8 +875,8 @@ end numbers = [1, 2, 3, 4, 5] squared_numbers = numbers.<|fim|> `, - llmOutput: `map { |n| n ** 2 }`, - expectedCompletion: `map { |n| n ** 2 }`, + llmOutput: "map { |n| n ** 2 }", + expectedCompletion: "map { |n| n ** 2 }", filename: "array_methods.rb", }, { @@ -888,8 +889,8 @@ public class App { System.out.println(message); } }`, - llmOutput: `World`, - expectedCompletion: `World`, + llmOutput: "World", + expectedCompletion: "World", }, { description: @@ -929,8 +930,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", @@ -938,8 +939,8 @@ public class App { input: `Name, Age, City John Doe, 30, New York Jane Smith<|fim|>`, - llmOutput: `, 25, Los Angeles`, - expectedCompletion: `, 25, Los Angeles`, + llmOutput: ", 25, Los Angeles", + expectedCompletion: ", 25, Los Angeles", }, { description: @@ -948,8 +949,8 @@ Jane Smith<|fim|>`, input: `Product, Price, Quantity Laptop, 1200, 5 Smart<|fim|>`, - llmOutput: `phone, 800, 10`, - expectedCompletion: `phone, 800, 10`, + llmOutput: "phone, 800, 10", + expectedCompletion: "phone, 800, 10", }, { description: "Should complete CSV structure adding closing brackets", @@ -957,8 +958,8 @@ Smart<|fim|>`, input: `ID, Name, JoiningDate 1, Alice, 2023-01-10 2, B<|fim|>`, - llmOutput: `ob, 2023-02-10`, - expectedCompletion: `ob, 2023-02-10`, + llmOutput: "ob, 2023-02-10", + expectedCompletion: "ob, 2023-02-10", }, { description: "Should complete YAML list item and preserve structure", @@ -1125,8 +1126,8 @@ sumTree (Node left right) = let leftSum = <|fim|> rightSum = sumTree right in leftSum + rightSum`, - llmOutput: `sumTree left`, - expectedCompletion: `sumTree left`, + llmOutput: "sumTree left", + expectedCompletion: "sumTree left", }, { description: "Haskell: Complex function with where clause and guards", @@ -1142,8 +1143,8 @@ solveQuadratic a b c sqrtD = sqrt discriminant x1 = (-b + sqrtD) / (2*a) <|fim|> = (-b - sqrtD) / (2*a)`, - llmOutput: `x2`, - expectedCompletion: `x2`, + llmOutput: "x2", + expectedCompletion: "x2", }, { description: "Haskell: List comprehension with complex filter", @@ -1153,8 +1154,8 @@ solveQuadratic a b c primesUpTo :: Int -> [Int] primesUpTo n = [x | x <- [2..n], isPrime x] where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, - llmOutput: `num > 1`, - expectedCompletion: `num > 1`, + llmOutput: "num > 1", + expectedCompletion: "num > 1", }, { description: "Should autocomplete Dart class methods", @@ -1192,8 +1193,8 @@ void main() { var name = "World"; print('Hello, <|fim|>!'); }`, - llmOutput: `\${name}`, - expectedCompletion: `\${name}`, + llmOutput: "${name}", + expectedCompletion: "${name}", }, { description: "Should autocomplete within a Dart function body", @@ -1213,8 +1214,8 @@ class Counter { count = 0; } }`, - llmOutput: `count--;`, - expectedCompletion: `count--;`, + llmOutput: "count--;", + expectedCompletion: "count--;", }, { description: @@ -1223,8 +1224,8 @@ class Counter { (let [sum (+ a b)] (println "The sum is" sum) sum<|fim|>`, - llmOutput: `))`, - expectedCompletion: `))`, + llmOutput: "))", + expectedCompletion: "))", filename: "test.clj", }, { @@ -1236,8 +1237,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", }, { @@ -1248,8 +1249,8 @@ class Counter { (when (seq nums) (println (first nums)) (recur (rest nums)))))`, - llmOutput: ` 7,`, - expectedCompletion: ` 7,`, + llmOutput: " 7,", + expectedCompletion: " 7,", filename: "test.clj", }, { @@ -1273,8 +1274,8 @@ numbers <- c(1, 2, 3, 4, 5) for (number in numbers) { print(<|fim|>) }`, - llmOutput: `number)`, - expectedCompletion: `number)`, + llmOutput: "number)", + expectedCompletion: "number)", }, { description: "Should autocomplete R data frame creation", @@ -1285,8 +1286,8 @@ data <- data.frame( Age = c(25, 30, 35), <|fim|> )`, - llmOutput: `Height = c(165, 180, 175)`, - expectedCompletion: `Height = c(165, 180, 175)`, + llmOutput: "Height = c(165, 180, 175)", + expectedCompletion: "Height = c(165, 180, 175)", }, { description: "Should autocomplete R if-else statement", @@ -1300,8 +1301,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", @@ -1312,8 +1313,8 @@ library(ggplot2) ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() + <|fim|>`, - llmOutput: `geom_smooth(method='lm', se=FALSE)`, - expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, + llmOutput: "geom_smooth(method='lm', se=FALSE)", + expectedCompletion: "geom_smooth(method='lm', se=FALSE)", }, { description: "Should autocomplete Scala class with a method", @@ -1323,8 +1324,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.\"", }, { @@ -1334,8 +1335,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\")", }, { @@ -1380,8 +1381,8 @@ int main() { printf("Result: %d", add(2, 3)); return 0; }`, - llmOutput: `return a - b;`, - expectedCompletion: `return a - b;`, + llmOutput: "return a - b;", + expectedCompletion: "return a - b;", }, { @@ -1400,8 +1401,8 @@ int main() { printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); return 0; }`, - llmOutput: `5.5`, - expectedCompletion: `5.5`, + llmOutput: "5.5", + expectedCompletion: "5.5", }, { @@ -1453,8 +1454,8 @@ data class User( val email: String, <|fim|> )`, - llmOutput: `val age: Int`, - expectedCompletion: `val age: Int`, + llmOutput: "val age: Int", + expectedCompletion: "val age: Int", }, { description: @@ -1490,8 +1491,8 @@ contract SimpleStorage { } } `, - llmOutput: `return data;`, - expectedCompletion: `return data;`, + llmOutput: "return data;", + expectedCompletion: "return data;", }, { @@ -1508,8 +1509,8 @@ contract EventExample { } } `, - llmOutput: `id, content`, - expectedCompletion: `id, content`, + llmOutput: "id, content", + expectedCompletion: "id, content", }, { @@ -1582,8 +1583,8 @@ const multiplyNumbers = (a: number, b: number): number => { console.log(multiplyNumbers(2, 3)); `, - llmOutput: `turn a * b;`, - expectedCompletion: `turn a * b;`, + llmOutput: "turn a * b;", + expectedCompletion: "turn a * b;", }, // TODO @@ -1677,8 +1678,8 @@ public class Person { void <|fim|> }`, - llmOutput: `Greet();`, - expectedCompletion: `Greet();`, + llmOutput: "Greet();", + expectedCompletion: "Greet();", }, { description: "Should autocomplete inside C# method with if condition", @@ -1696,8 +1697,8 @@ public class Calculator return 0; } }`, - llmOutput: `a > 0 && b > 0`, - expectedCompletion: `a > 0 && b > 0`, + llmOutput: "a > 0 && b > 0", + expectedCompletion: "a > 0 && b > 0", }, { description: "Should complete a simple Julia function", @@ -1706,8 +1707,8 @@ public class Calculator <|fim|> end `, - llmOutput: `return length * width`, - expectedCompletion: `return length * width`, + llmOutput: "return length * width", + expectedCompletion: "return length * width", }, { description: "Should autocomplete Julia for loop", @@ -1721,8 +1722,8 @@ end println(squared_numbers) `, - llmOutput: `push!(squared_numbers, num^2)`, - expectedCompletion: `push!(squared_numbers, num^2)`, + llmOutput: "push!(squared_numbers, num^2)", + expectedCompletion: "push!(squared_numbers, num^2)", }, { description: "Should complete a Julia struct definition", @@ -1756,8 +1757,8 @@ end println(get_grade("Alice")) # Should print 90 `, - llmOutput: `student_name`, - expectedCompletion: `student_name`, + llmOutput: "student_name", + expectedCompletion: "student_name", }, { description: "Should complete a Julia module declaration", @@ -1776,8 +1777,8 @@ end <|fim|> `, - llmOutput: `end`, - expectedCompletion: `end`, + llmOutput: "end", + expectedCompletion: "end", }, { description: "Should complete F# let-binding with function definition", @@ -1786,8 +1787,8 @@ end let calculateArea length width = <|fim|>`, - llmOutput: `length * width`, - expectedCompletion: `length * width`, + llmOutput: "length * width", + expectedCompletion: "length * width", }, { @@ -1828,8 +1829,8 @@ let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, input: `let squares = [ for x in 1..10 -> x * x ] let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] let oddSquares = [<|fim|>]`, - llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, - expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, + llmOutput: " for x in squares do if x % 2 <> 0 then yield x ]", + expectedCompletion: " for x in squares do if x % 2 <> 0 then yield x ]", }, { description: "Should complete an F# recursive function", @@ -1837,8 +1838,8 @@ let oddSquares = [<|fim|>]`, input: `let rec factorial n = if n <= 1 then 1 else n <|fim|> factorial (n - 1)`, - llmOutput: `*`, - expectedCompletion: `*`, + llmOutput: "*", + expectedCompletion: "*", }, { description: "Should complete F# member method inside a class type", @@ -1919,8 +1920,8 @@ let oddSquares = [<|fim|>]`, box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } }`, - llmOutput: ` transition(all 0.3s ease);`, - expectedCompletion: ` transition(all 0.3s ease);`, + llmOutput: " transition(all 0.3s ease);", + expectedCompletion: " transition(all 0.3s ease);", }, { @@ -1937,8 +1938,8 @@ $secondary-color: #6c757d; color: #fff; border-radius: 4px; }`, - llmOutput: `$primary-`, - expectedCompletion: `$primary-`, + llmOutput: "$primary-", + expectedCompletion: "$primary-", }, { description: "Should autocomplete Vue component method", @@ -2027,8 +2028,8 @@ export default { }; `, - llmOutput: `this.completed`, - expectedCompletion: `this.completed`, + llmOutput: "this.completed", + expectedCompletion: "this.completed", }, { description: "Should autocomplete Svelte reactive statement", @@ -2048,8 +2049,8 @@ export default { Clicked {count} times `, - llmOutput: `doubledCount = count * 2`, - expectedCompletion: `doubledCount = count * 2`, + llmOutput: "doubledCount = count * 2", + expectedCompletion: "doubledCount = count * 2", }, { @@ -2065,8 +2066,8 @@ export default { /> `, - llmOutput: `name="World"`, - expectedCompletion: `name="World"`, + llmOutput: "name=\"World\"", + expectedCompletion: "name=\"World\"", }, { @@ -2083,7 +2084,7 @@ export default { {/each<|fim|> `, - llmOutput: `}`, - expectedCompletion: `}`, + llmOutput: "}", + expectedCompletion: "}", }, ]; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 5a9b61a72..42ab196b7 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import path from "node:path"; + import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; import { CompletionProvider } from "../../CompletionProvider"; diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index 3f46f5033..f516ad04b 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -1,6 +1,7 @@ import { CompletionOptions, ILLM } from "../.."; import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; import { HelperVars } from "../util/HelperVars"; + import { GeneratorReuseManager } from "./GeneratorReuseManager"; export class CompletionStreamer { diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index 127874d68..b80da6b50 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -1,7 +1,8 @@ -import type { ILLM } from "../../index.js"; import { longestCommonSubsequence } from "../../util/lcs.js"; import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js"; +import type { ILLM } from "../../index.js"; + function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix .split("\n") diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index a7343817d..bc3b3bcaa 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,4 +1,5 @@ import path from "node:path"; + import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts index d4024bf06..2bf6fb067 100644 --- a/core/autocomplete/templating/constructPrefixSuffix.ts +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -1,7 +1,6 @@ import { IDE } from "../.."; import { getRangeInString } from "../../util/ranges"; import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; - import { AutocompleteInput } from "../util/types"; /** diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 05a10bbed..87bc7cfd9 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,11 @@ import Handlebars from "handlebars"; + import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; + import { AutocompleteTemplate, getTemplateForModel, diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 7fd3d24cb..ff0c5d493 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -1,6 +1,7 @@ import { logDevData } from "../../util/devdata"; import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters"; import { Telemetry } from "../../util/posthog"; + import { AutocompleteOutcome } from "./types"; export class AutocompleteLoggingService { diff --git a/core/autocomplete/util/AutocompleteLruCache.ts b/core/autocomplete/util/AutocompleteLruCache.ts index ec9478c8a..a93b23c5a 100644 --- a/core/autocomplete/util/AutocompleteLruCache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -1,6 +1,7 @@ import { Mutex } from "async-mutex"; import { open } from "sqlite"; import sqlite3 from "sqlite3"; + import { DatabaseConnection, truncateSqliteLikePattern, diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index a6ecb21a9..2d9f74ab5 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -9,6 +9,7 @@ import { languageForFilepath, } from "../constants/AutocompleteLanguageInfo"; import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix"; + import { AstPath, getAst, getTreePathAtCursor } from "./ast"; import { AutocompleteInput } from "./types"; @@ -38,7 +39,7 @@ 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 ?? diff --git a/core/autocomplete/util/ast.ts b/core/autocomplete/util/ast.ts index 600b84126..6bd6e1f88 100644 --- a/core/autocomplete/util/ast.ts +++ b/core/autocomplete/util/ast.ts @@ -1,4 +1,5 @@ import Parser from "web-tree-sitter"; + import { RangeInFileWithContents } from "../../commands/util.js"; import { getParserForFile } from "../../util/treeSitter.js"; diff --git a/core/commands/index.ts b/core/commands/index.ts index 94b57c2b9..806e918db 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,6 +1,7 @@ import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; + import SlashCommands from "./slash"; export function slashFromCustomCommand( diff --git a/core/commands/slash/comment.ts b/core/commands/slash/comment.ts index e3b601c04..adadb026c 100644 --- a/core/commands/slash/comment.ts +++ b/core/commands/slash/comment.ts @@ -1,4 +1,5 @@ import { SlashCommand } from "../../"; + import EditSlashCommand from "./edit"; const CommentSlashCommand: SlashCommand = { diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index a7738a041..8d3433c25 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -1,13 +1,15 @@ -import { IDE, SlashCommand } from "../.."; import * as fs from "fs/promises"; import * as path from "path"; -import { stripImages } from "../../llm/images"; + import ignore from "ignore"; + +import { IDE, SlashCommand } from "../.."; import { defaultIgnoreDir, defaultIgnoreFile, gitIgArrayFromFile, } from "../../indexing/ignore"; +import { stripImages } from "../../llm/images"; const LANGUAGE_DEP_MGMT_FILENAMES = [ "package.json", // JavaScript (Node.js) diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index a43b694da..5ee1fd938 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -1,6 +1,7 @@ import * as fs from "node:fs"; import { homedir } from "node:os"; import path from "path"; + import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; import { stripImages } from "../../llm/images.js"; diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index f04f1d716..26de42ec7 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -1,8 +1,10 @@ import fs from "node:fs"; import path from "node:path"; + import { testConfigHandler } from "../test/util/fixtures"; import { TEST_DIR } from "../test/util/testDir"; import { getConfigTsPath } from "../util/paths"; + import { defaultConfig } from "./default"; describe.skip("Test the ConfigHandler and E2E config loading", () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 80768ea4b..bd615f2e0 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -12,6 +12,7 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; + import { ConfigResult } from "./load.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, @@ -19,7 +20,6 @@ import { } from "./onboarding.js"; import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; - import { ProfileDescription, ProfileLifecycleManager, diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index b9788e328..85116f213 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -1,4 +1,5 @@ import { config } from "dotenv"; + import { BrowserSerializedContinueConfig, ContinueConfig, @@ -6,7 +7,6 @@ import { } from "../index.js"; import { ConfigResult, finalToBrowserConfig } from "./load.js"; - import { IProfileLoader } from "./profile/IProfileLoader.js"; export interface ProfileDescription { diff --git a/core/config/load.ts b/core/config/load.ts index d9d020d2d..0e405301e 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -3,6 +3,7 @@ import * as JSONC from "comment-json"; import * as fs from "fs"; import os from "os"; import path from "path"; + import * as tar from "tar"; import { BrowserSerializedContinueConfig, @@ -32,6 +33,7 @@ import ContinueProxyContextProvider from "../context/providers/ContinueProxyCont import CustomContextProviderClass from "../context/providers/CustomContextProvider"; import FileContextProvider from "../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../context/providers/index"; +import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; import { AllRerankers } from "../context/rerankers/index"; import { LLMReranker } from "../context/rerankers/llm"; import { allEmbeddingsProviders } from "../indexing/embeddings"; @@ -42,6 +44,7 @@ import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; import { copyOf } from "../util"; import { fetchwithRequestOptions } from "../util/fetchWithOptions"; +import { GlobalContext } from "../util/GlobalContext"; import mergeJson from "../util/merge"; import { DEFAULT_CONFIG_TS_CONTENTS, @@ -54,6 +57,7 @@ import { getEsbuildBinaryPath, readAllGlobalPromptFiles, } from "../util/paths"; + import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -67,9 +71,6 @@ import { } from "./promptFile.js"; import { ConfigValidationError, validateConfig } from "./validation.js"; -import PromptFilesContextProvider from "../context/providers/PromptFilesContextProvider"; -import { GlobalContext } from "../util/GlobalContext"; - export interface ConfigResult { config: T | undefined; errors: ConfigValidationError[] | undefined; @@ -135,6 +136,13 @@ function loadSerializedConfig( config.allowAnonymousTelemetry = true; } + if (config.ui?.getChatTitles === undefined) { + config.ui = { + ...config.ui, + getChatTitles: true, + }; + } + if (ideSettings.remoteConfigServerUrl) { try { const remoteConfigJson = resolveSerializedConfig( @@ -207,7 +215,10 @@ async function serializedToIntermediateConfig( promptFiles.push(...readAllGlobalPromptFiles()); for (const file of promptFiles) { - slashCommands.push(slashCommandFromPromptFile(file.path, file.content)); + const slashCommand = slashCommandFromPromptFile(file.path, file.content); + if (slashCommand) { + slashCommands.push(slashCommand); + } } } diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index c0c5d7e9d..fa6d54945 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -1,4 +1,5 @@ import { SerializedContinueConfig } from "../"; + import { FREE_TRIAL_MODELS } from "./default"; export const TRIAL_FIM_MODEL = "codestral-latest"; diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 5862fab6c..448dbdb42 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -1,4 +1,5 @@ import { ConfigJson } from "@continuedev/config-types"; + import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, @@ -7,8 +8,9 @@ import { SerializedContinueConfig, } from "../../index.js"; import { ConfigResult } from "../load.js"; -import { IProfileLoader } from "./IProfileLoader.js"; + import doLoadConfig from "./doLoadConfig.js"; +import { IProfileLoader } from "./IProfileLoader.js"; export default class ControlPlaneProfileLoader implements IProfileLoader { private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 1b4f06696..0705c8745 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,6 +1,7 @@ import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ConfigResult } from "../load.js"; + import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 44646ec95..aa19f3b0c 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -1,12 +1,21 @@ -import Handlebars from "handlebars"; import path from "path"; + +import Handlebars from "handlebars"; import * as YAML from "yaml"; -import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from ".."; + import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString"; import { getBasename } from "../util/index"; -import { BaseContextProvider } from "../context"; + +import type { + ChatMessage, + ContextItem, + ContinueSDK, + IContextProvider, + IDE, + SlashCommand, +} from ".."; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; @@ -90,12 +99,16 @@ export async function createNewPromptFile( export function slashCommandFromPromptFile( path: string, content: string, -): SlashCommand { - const { name, description, systemMessage, prompt } = parsePromptFile( +): SlashCommand | null { + const { name, description, systemMessage, prompt, version } = parsePromptFile( path, content, ); + if (version !== 1) { + return null; + } + return { name, description, @@ -131,6 +144,7 @@ function parsePromptFile(path: string, content: string) { const preamble = YAML.parse(preambleRaw) ?? {}; const name = preamble.name ?? getBasename(path).split(".prompt")[0]; const description = preamble.description ?? name; + const version = preamble.version ?? 2; let systemMessage: string | undefined = undefined; if (prompt.includes("")) { @@ -138,7 +152,7 @@ function parsePromptFile(path: string, content: string) { prompt = prompt.split("")[1].trim(); } - return { name, description, systemMessage, prompt }; + return { name, description, systemMessage, prompt, version }; } function extractUserInput(input: string, commandName: string): string { @@ -148,7 +162,11 @@ function extractUserInput(input: string, commandName: string): string { return input; } -async function renderPrompt(prompt: string, context: ContinueSDK, userInput: string) { +async function renderPrompt( + prompt: string, + context: ContinueSDK, + userInput: string, +) { const helpers = getContextProviderHelpers(context); // A few context providers that don't need to be in config.json to work in .prompt files diff --git a/core/config/types.ts b/core/config/types.ts index 3fb9fe494..ad80cdeab 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -628,6 +628,11 @@ declare global { | "mistral-large-latest" | "mistral-7b" | "mistral-8x7b" + | "mistral-8x22b" + | "mistral-tiny" + | "mistral-small" + | "mistral-medium" + | "mistral-nemo" // Llama 2 | "llama2-7b" | "llama2-13b" @@ -641,6 +646,8 @@ declare global { | "llama3-70b" // Other Open-source | "phi2" + | "phi-3-mini" + | "phi-3-medium" | "phind-codellama-34b" | "wizardcoder-7b" | "wizardcoder-13b" @@ -649,9 +656,12 @@ declare global { | "codeup-13b" | "deepseek-7b" | "deepseek-33b" + | "deepseek-2-lite" | "neural-chat-7b" | "gemma-7b-it" + | "gemma2-2b-it" | "gemma2-9b-it" + | "olmo-7b" // Anthropic | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" @@ -669,10 +679,6 @@ declare global { | "gemini-1.5-pro" | "gemini-1.5-flash-latest" | "gemini-1.5-flash" - // Mistral - | "mistral-tiny" - | "mistral-small" - | "mistral-medium" // Tab autocomplete | "deepseek-1b" | "starcoder-1b" diff --git a/core/context/providers/CodebaseContextProvider.ts b/core/context/providers/CodebaseContextProvider.ts index 5e77c537b..51881f457 100644 --- a/core/context/providers/CodebaseContextProvider.ts +++ b/core/context/providers/CodebaseContextProvider.ts @@ -1,9 +1,9 @@ +import { BaseContextProvider } from "../"; import { ContextItem, ContextProviderDescription, ContextProviderExtras, } from "../../"; -import { BaseContextProvider } from "../"; import { retrieveContextItemsFromEmbeddings } from "../retrieval/retrieval"; class CodebaseContextProvider extends BaseContextProvider { diff --git a/core/context/providers/CurrentFileContextProvider.ts b/core/context/providers/CurrentFileContextProvider.ts index 5e75f85c8..ccb1b231d 100644 --- a/core/context/providers/CurrentFileContextProvider.ts +++ b/core/context/providers/CurrentFileContextProvider.ts @@ -1,10 +1,10 @@ +import { BaseContextProvider } from "../"; import { ContextItem, ContextProviderDescription, ContextProviderExtras, } from "../../"; import { getBasename } from "../../util/"; -import { BaseContextProvider } from "../"; class CurrentFileContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { diff --git a/core/context/providers/DatabaseContextProvider.ts b/core/context/providers/DatabaseContextProvider.ts index 3e7b54f0e..ea82c9e75 100644 --- a/core/context/providers/DatabaseContextProvider.ts +++ b/core/context/providers/DatabaseContextProvider.ts @@ -1,3 +1,5 @@ +import { getDatabaseAdapter } from "dbinfoz"; + import { ContextItem, ContextProviderDescription, @@ -6,7 +8,6 @@ import { LoadSubmenuItemsArgs, } from "../../index.js"; import { BaseContextProvider } from "../index.js"; -import { getDatabaseAdapter } from "dbinfoz"; class DatabaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index f54692c47..a290589e4 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -1,4 +1,3 @@ -import { INSTRUCTIONS_BASE_ITEM } from "./utils"; import { BaseContextProvider } from "../"; import { Chunk, @@ -12,6 +11,8 @@ import DocsService from "../../indexing/docs/DocsService"; import preIndexedDocs from "../../indexing/docs/preIndexedDocs"; import { Telemetry } from "../../util/posthog"; +import { INSTRUCTIONS_BASE_ITEM } from "./utils"; + class DocsContextProvider extends BaseContextProvider { static nRetrieve = 30; static nFinal = 15; diff --git a/core/context/providers/GitLabMergeRequestContextProvider.ts b/core/context/providers/GitLabMergeRequestContextProvider.ts index 631de479c..3e8f77a67 100644 --- a/core/context/providers/GitLabMergeRequestContextProvider.ts +++ b/core/context/providers/GitLabMergeRequestContextProvider.ts @@ -1,4 +1,5 @@ import { AxiosError, AxiosInstance } from "axios"; + import { ContextItem, ContextProviderDescription, diff --git a/core/context/providers/GreptileContextProvider.ts b/core/context/providers/GreptileContextProvider.ts index c6b7620c4..3ae6fa214 100644 --- a/core/context/providers/GreptileContextProvider.ts +++ b/core/context/providers/GreptileContextProvider.ts @@ -1,12 +1,14 @@ + import { execSync } from "child_process"; + import * as fs from "fs"; + import * as path from "path"; + import { ContextItem, ContextProviderDescription, ContextProviderExtras, } from "../../index.js"; import { BaseContextProvider } from "../index.js"; - import { execSync } from "child_process"; - import * as path from "path"; - import * as fs from "fs"; + class GreptileContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -35,7 +37,7 @@ import { throw new Error("Failed to determine the workspace directory."); } - var remoteUrl = getRemoteUrl(absPath) + var remoteUrl = getRemoteUrl(absPath); remoteUrl = getRemoteUrl(absPath); const repoName = extractRepoName(remoteUrl); const branch = getCurrentBranch(absPath); @@ -46,11 +48,11 @@ import { } const options = { - method: 'POST', + method: "POST", headers: { Authorization: `Bearer ${greptileToken}`, - 'X-GitHub-Token': githubToken, - 'Content-Type': 'application/json', + "X-GitHub-Token": githubToken, + "Content-Type": "application/json", }, body: JSON.stringify({ messages: [{ id: "", content: query, role: "user" }], @@ -66,7 +68,7 @@ import { }; try { - const response = await extras.fetch('https://api.greptile.com/v2/query', options); + const response = await extras.fetch("https://api.greptile.com/v2/query", options); const rawText = await response.text(); // Check for HTTP errors @@ -84,7 +86,7 @@ import { })); } catch (error) { console.error("Error getting context items from Greptile:", error); - throw new Error(`Error getting context items from Greptile`); + throw new Error("Error getting context items from Greptile"); } } @@ -102,34 +104,34 @@ import { if (workspaceDirs && workspaceDirs.length > 0) { return workspaceDirs[0]; } else { - console.warn(`extras.ide.getWorkspaceDirs() returned undefined or empty array.`); + console.warn("extras.ide.getWorkspaceDirs() returned undefined or empty array."); } } catch (err) { - console.warn(`Failed to get workspace directories from extras.ide.getWorkspaceDirs():`); + console.warn("Failed to get workspace directories from extras.ide.getWorkspaceDirs():"); } // Fallback to using Git commands try { const currentDir = process.cwd(); if (this.isGitRepository(currentDir)) { - const workspaceDir = execSync('git rev-parse --show-toplevel').toString().trim(); + const workspaceDir = execSync("git rev-parse --show-toplevel").toString().trim(); return workspaceDir; } else { console.warn(`Current directory is not a Git repository: ${currentDir}`); return null; } } catch (err) { - console.warn(`Failed to get workspace directory using Git commands: `); + console.warn("Failed to get workspace directory using Git commands: "); return null; } } private isGitRepository(dir: string): boolean { try { - const gitDir = path.join(dir, '.git'); + const gitDir = path.join(dir, ".git"); return fs.existsSync(gitDir); } catch (err) { - console.warn(`Failed to check if directory is a Git repository:`); + console.warn("Failed to check if directory is a Git repository:"); return false; } } @@ -141,7 +143,7 @@ import { const remote = execSync(`git -C ${absPath} remote get-url origin`).toString().trim(); return remote; } catch (err) { - console.warn(`Failed to get remote URL`); + console.warn("Failed to get remote URL"); return ""; } } @@ -151,7 +153,7 @@ import { const branch = execSync(`git -C ${absPath} rev-parse --abbrev-ref HEAD`).toString().trim(); return branch; } catch (err) { - console.warn(`Failed to get current branch`); + console.warn("Failed to get current branch"); return "master"; // Default to 'master' if the current branch cannot be determined } } diff --git a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts index d747f76f1..9a83d279d 100644 --- a/core/context/providers/JiraIssuesContextProvider/JiraClient.ts +++ b/core/context/providers/JiraIssuesContextProvider/JiraClient.ts @@ -1,7 +1,8 @@ -import { RequestOptions } from "../../../"; // @ts-ignore import adf2md from "adf-to-md"; +import { RequestOptions } from "../../../"; + interface JiraClientOptions { domain: string; username: string; diff --git a/core/context/providers/JiraIssuesContextProvider/index.ts b/core/context/providers/JiraIssuesContextProvider/index.ts index 381099012..d13022140 100644 --- a/core/context/providers/JiraIssuesContextProvider/index.ts +++ b/core/context/providers/JiraIssuesContextProvider/index.ts @@ -6,6 +6,7 @@ import { LoadSubmenuItemsArgs, } from "../../../index.js"; import { BaseContextProvider } from "../../index.js"; + import { JiraClient } from "./JiraClient.js"; class JiraIssuesContextProvider extends BaseContextProvider { diff --git a/core/context/providers/OSContextProvider.ts b/core/context/providers/OSContextProvider.ts index 45852c934..298cb84e7 100644 --- a/core/context/providers/OSContextProvider.ts +++ b/core/context/providers/OSContextProvider.ts @@ -1,4 +1,5 @@ import os from "os"; + import { ContextItem, ContextProviderDescription, diff --git a/core/context/providers/URLContextProvider.ts b/core/context/providers/URLContextProvider.ts index b0f4bd9ce..02f4eb36e 100644 --- a/core/context/providers/URLContextProvider.ts +++ b/core/context/providers/URLContextProvider.ts @@ -1,6 +1,7 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; import { NodeHtmlMarkdown } from "node-html-markdown"; + import { BaseContextProvider } from "../"; import { ContextItem, diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index ec1d7c6ad..316e4936b 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,5 +1,6 @@ import { BaseContextProvider } from "../"; import { ContextProviderName } from "../../"; + import CodeContextProvider from "./CodeContextProvider"; import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; import CurrentFileContextProvider from "./CurrentFileContextProvider"; @@ -16,8 +17,8 @@ import GoogleContextProvider from "./GoogleContextProvider"; import GreptileContextProvider from "./GreptileContextProvider"; import HttpContextProvider from "./HttpContextProvider"; import JiraIssuesContextProvider from "./JiraIssuesContextProvider/"; -import OSContextProvider from "./OSContextProvider"; import OpenFilesContextProvider from "./OpenFilesContextProvider"; +import OSContextProvider from "./OSContextProvider"; import PostgresContextProvider from "./PostgresContextProvider"; import ProblemsContextProvider from "./ProblemsContextProvider"; import RepoMapContextProvider from "./RepoMapContextProvider"; diff --git a/core/context/rerankers/ContinueProxyReranker.ts b/core/context/rerankers/ContinueProxyReranker.ts index 1ca10436b..a2404dac4 100644 --- a/core/context/rerankers/ContinueProxyReranker.ts +++ b/core/context/rerankers/ContinueProxyReranker.ts @@ -1,4 +1,5 @@ import fetch from "node-fetch"; + import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { Chunk, Reranker } from "../../index.js"; diff --git a/core/context/rerankers/cohere.ts b/core/context/rerankers/cohere.ts index 7a0dcf2dc..170565c4d 100644 --- a/core/context/rerankers/cohere.ts +++ b/core/context/rerankers/cohere.ts @@ -1,4 +1,5 @@ import fetch from "node-fetch"; + import { Chunk, Reranker } from "../../index.js"; export class CohereReranker implements Reranker { diff --git a/core/context/rerankers/freeTrial.ts b/core/context/rerankers/freeTrial.ts index 43dbf6fb6..14a639b0d 100644 --- a/core/context/rerankers/freeTrial.ts +++ b/core/context/rerankers/freeTrial.ts @@ -1,4 +1,5 @@ import fetch from "node-fetch"; + import { getHeaders } from "../../continueServer/stubs/headers.js"; import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; import { Chunk, Reranker } from "../../index.js"; diff --git a/core/context/rerankers/index.ts b/core/context/rerankers/index.ts index c60c0825a..9b1db230d 100644 --- a/core/context/rerankers/index.ts +++ b/core/context/rerankers/index.ts @@ -1,4 +1,5 @@ import { RerankerName } from "../../index.js"; + import { CohereReranker } from "./cohere.js"; import { ContinueProxyReranker } from "./ContinueProxyReranker.js"; import { FreeTrialReranker } from "./freeTrial.js"; diff --git a/core/context/rerankers/tei.ts b/core/context/rerankers/tei.ts index 2d3f9ab12..315964560 100644 --- a/core/context/rerankers/tei.ts +++ b/core/context/rerankers/tei.ts @@ -1,4 +1,5 @@ import fetch from "node-fetch"; + import { Chunk, Reranker } from "../../index.js"; export class HuggingFaceTEIReranker implements Reranker { diff --git a/core/context/rerankers/voyage.ts b/core/context/rerankers/voyage.ts index b448bf656..f7c6fb8a4 100644 --- a/core/context/rerankers/voyage.ts +++ b/core/context/rerankers/voyage.ts @@ -1,4 +1,5 @@ import fetch from "node-fetch"; + import { Chunk, Reranker } from "../../index.js"; export class VoyageReranker implements Reranker { diff --git a/core/context/retrieval/recentlyEditedFilesCache.ts b/core/context/retrieval/recentlyEditedFilesCache.ts index 1f74ea3c9..c795fda87 100644 --- a/core/context/retrieval/recentlyEditedFilesCache.ts +++ b/core/context/retrieval/recentlyEditedFilesCache.ts @@ -1,4 +1,5 @@ import QuickLRU from "quick-lru"; + import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js"; // The cache key and value are both a filepath string diff --git a/core/control-plane/TeamAnalytics.ts b/core/control-plane/TeamAnalytics.ts index 7dedf563d..c9f543bb4 100644 --- a/core/control-plane/TeamAnalytics.ts +++ b/core/control-plane/TeamAnalytics.ts @@ -1,5 +1,7 @@ -import { Analytics } from "@continuedev/config-types"; import os from "node:os"; + +import { Analytics } from "@continuedev/config-types"; + import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js"; import { ControlPlaneProxyInfo, diff --git a/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts b/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts index e7edd6930..bb63bcf74 100644 --- a/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts +++ b/core/control-plane/analytics/ContinueProxyAnalyticsProvider.ts @@ -1,6 +1,8 @@ import { Analytics } from "@continuedev/config-types"; import fetch from "node-fetch"; + import { ControlPlaneClient } from "../client.js"; + import { ControlPlaneProxyInfo, IAnalyticsProvider, diff --git a/core/control-plane/analytics/LogStashAnalyticsProvider.ts b/core/control-plane/analytics/LogStashAnalyticsProvider.ts index 3a94bd9d6..aa2821707 100644 --- a/core/control-plane/analytics/LogStashAnalyticsProvider.ts +++ b/core/control-plane/analytics/LogStashAnalyticsProvider.ts @@ -1,5 +1,7 @@ -import { Analytics } from "@continuedev/config-types"; import net from "node:net"; + +import { Analytics } from "@continuedev/config-types"; + import { ControlPlaneProxyInfo, IAnalyticsProvider, diff --git a/core/control-plane/analytics/PostHogAnalyticsProvider.ts b/core/control-plane/analytics/PostHogAnalyticsProvider.ts index db8ac1065..268825e96 100644 --- a/core/control-plane/analytics/PostHogAnalyticsProvider.ts +++ b/core/control-plane/analytics/PostHogAnalyticsProvider.ts @@ -1,4 +1,5 @@ import { Analytics } from "@continuedev/config-types"; + import { ControlPlaneProxyInfo, IAnalyticsProvider, diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 22d5c7cdb..b84e24570 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -1,6 +1,8 @@ import { ConfigJson } from "@continuedev/config-types"; import fetch, { RequestInit, Response } from "node-fetch"; + import { ModelDescription } from "../index.js"; + import { controlPlaneEnv } from "./env.js"; export interface ControlPlaneSessionInfo { diff --git a/core/core.ts b/core/core.ts index 87eeb52da..6df1482ef 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,7 +1,8 @@ -import ignore from "ignore"; import path from "path"; + +import ignore from "ignore"; import { v4 as uuidv4 } from "uuid"; -import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; + import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { @@ -21,18 +22,20 @@ import DocsService from "./indexing/docs/DocsService"; import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; -import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; -import { GlobalContext } from "./util/GlobalContext"; import { ChatDescriber } from "./util/chatDescriber"; import { logDevData } from "./util/devdata"; import { DevDataSqliteDb } from "./util/devdataSqlite"; import { fetchwithRequestOptions } from "./util/fetchWithOptions"; +import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import type { IMessenger, Message } from "./util/messenger"; import { editConfigJson, setupInitialDotContinueDirectory } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { TTS } from "./util/tts"; +import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; +import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; +import type { IMessenger, Message } from "./util/messenger"; + export class Core { // implements IMessenger configHandler: ConfigHandler; diff --git a/core/diff/myers.test.ts b/core/diff/myers.test.ts index 5d68cfabf..d07b298c7 100644 --- a/core/diff/myers.test.ts +++ b/core/diff/myers.test.ts @@ -1,4 +1,5 @@ import { dedent } from "../util"; + import { myersDiff } from "./myers"; describe("Test myers diff function", () => { diff --git a/core/diff/myers.ts b/core/diff/myers.ts index 06b0ce7ec..22a2fc4e3 100644 --- a/core/diff/myers.ts +++ b/core/diff/myers.ts @@ -1,4 +1,5 @@ import { diffLines, type Change } from "diff"; + import { DiffLine } from ".."; export function convertMyersChangeToDiffLines(change: Change): DiffLine[] { diff --git a/core/diff/streamDiff.test.ts b/core/diff/streamDiff.test.ts index 0b884369e..fa7db52ac 100644 --- a/core/diff/streamDiff.test.ts +++ b/core/diff/streamDiff.test.ts @@ -1,9 +1,10 @@ import fs from "node:fs"; -import { streamDiff } from "../diff/streamDiff.js"; -import { DiffLine, DiffLineType } from "../index.js"; +import path from "node:path"; + // @ts-ignore no typings available import { changed, diff as myersDiff } from "myers-diff"; -import path from "node:path"; +import { streamDiff } from "../diff/streamDiff.js"; +import { DiffLine, DiffLineType } from "../index.js"; import { generateLines } from "./util.js"; // "modification" is an extra type used to represent an "old" + "new" diff line diff --git a/core/diff/streamDiff.ts b/core/diff/streamDiff.ts index 2761b5d97..4daa30804 100644 --- a/core/diff/streamDiff.ts +++ b/core/diff/streamDiff.ts @@ -1,4 +1,5 @@ import { DiffLine, DiffLineType } from "../index.js"; + import { LineStream, matchLine } from "./util.js"; /** diff --git a/core/diff/util.ts b/core/diff/util.ts index 9dda0ff02..839ab15b1 100644 --- a/core/diff/util.ts +++ b/core/diff/util.ts @@ -1,4 +1,5 @@ import { distance } from "fastest-levenshtein"; + import { ChatMessage } from "../index.js"; import { stripImages } from "../llm/images.js"; diff --git a/core/edit/lazy/applyCodeBlock.ts b/core/edit/lazy/applyCodeBlock.ts index 3a0083d65..86b2d67b4 100644 --- a/core/edit/lazy/applyCodeBlock.ts +++ b/core/edit/lazy/applyCodeBlock.ts @@ -1,7 +1,9 @@ import path from "path"; + import { DiffLine, ILLM } from "../.."; import { generateLines } from "../../diff/util"; import { supportedLanguages } from "../../util/treeSitter"; + import { deterministicApplyLazyEdit } from "./deterministic"; import { streamLazyApply } from "./streamLazyApply"; diff --git a/core/edit/lazy/deterministic.test.ts b/core/edit/lazy/deterministic.test.ts index ba79573a0..997c24c3a 100644 --- a/core/edit/lazy/deterministic.test.ts +++ b/core/edit/lazy/deterministic.test.ts @@ -1,8 +1,8 @@ import fs from "node:fs"; +import path from "node:path"; // @ts-ignore no typings available import { diff as myersDiff } from "myers-diff"; -import path from "node:path"; import { DiffLine } from "../.."; import { myersDiff as continueMyersDiff } from "../../diff/myers"; import { dedent } from "../../util"; diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index bb938b050..564656d23 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -1,10 +1,13 @@ -import { distance } from "fastest-levenshtein"; import path from "path"; + +import { distance } from "fastest-levenshtein"; import Parser from "web-tree-sitter"; + import { DiffLine } from "../.."; import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo"; import { myersDiff } from "../../diff/myers"; import { getParserForFile } from "../../util/treeSitter"; + import { findInAst } from "./findInAst"; type AstReplacements = Array<{ diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index f101c6981..135aa3170 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -6,6 +6,7 @@ import { import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; + import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js"; import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js"; diff --git a/core/index.d.ts b/core/index.d.ts index f501ac5d0..dbef816dd 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -45,12 +45,12 @@ export interface IndexingProgressUpdate { debugInfo?: string; } -export type PromptTemplate = - | string - | (( - history: ChatMessage[], - otherData: Record, - ) => string | ChatMessage[]); +export type PromptTemplateFunction = ( + history: ChatMessage[], + otherData: Record, +) => string | ChatMessage[]; + +export type PromptTemplate = string | PromptTemplateFunction; export interface ILLM extends LLMOptions { get providerName(): ModelProvider; @@ -685,10 +685,12 @@ export type ModelName = | "mistral-large-latest" | "mistral-7b" | "mistral-8x7b" + | "mistral-8x22b" | "mistral-tiny" | "mistral-small" | "mistral-medium" | "mistral-embed" + | "mistral-nemo" // Llama 2 | "llama2-7b" | "llama2-13b" @@ -713,6 +715,8 @@ export type ModelName = | "grok-beta" // Other Open-source | "phi2" + | "phi-3-mini" + | "phi-3-medium" | "phind-codellama-34b" | "wizardcoder-7b" | "wizardcoder-13b" @@ -721,9 +725,13 @@ export type ModelName = | "codeup-13b" | "deepseek-7b" | "deepseek-33b" + | "deepseek-2-lite" | "neural-chat-7b" | "gemma-7b-it" + | "gemma2-2b-it" | "gemma2-9b-it" + | "olmo-7b" + | "qwen-coder2.5-7b" // Anthropic | "claude-3-5-sonnet-latest" | "claude-3-5-sonnet-20240620" @@ -941,6 +949,7 @@ export interface ContinueUIConfig { fontSize?: number; displayRawMarkdown?: boolean; showChatScrollbar?: boolean; + getChatTitles?: boolean; } interface ContextMenuConfig { @@ -1003,11 +1012,6 @@ interface ExperimentalConfig { */ readResponseTTS?: boolean; - /** - * Prompt the user's LLM for a title given the current chat content - */ - getChatTitles?: boolean; - /** * If set to true, we will attempt to pull down and install an instance of Chromium * that is compatible with the current version of Puppeteer. diff --git a/core/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts index 9f34f7627..97d086d23 100644 --- a/core/indexing/CodeSnippetsIndex.test.ts +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -1,10 +1,12 @@ import { jest } from "@jest/globals"; + import { testIde } from "../test/util/fixtures"; import { insertMockChunks, mockPathAndCacheKey, updateIndexAndAwaitGenerator, } from "../test/util/indexing"; + import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { IndexResultType } from "./types"; diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 70872aff9..8e1edcc7b 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -1,4 +1,21 @@ import Parser from "web-tree-sitter"; + +import { getBasename, getLastNPathParts } from "../util/"; +import { migrate } from "../util/paths"; +import { + TSQueryType, + getParserForFile, + getQueryForFile, +} from "../util/treeSitter"; + +import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex"; +import { + IndexResultType, + MarkCompleteCallback, + RefreshIndexResults, + type CodebaseIndex, +} from "./types"; + import type { ChunkWithoutID, ContextItem, @@ -7,20 +24,6 @@ import type { IndexTag, IndexingProgressUpdate, } from "../"; -import { getBasename, getLastNPathParts } from "../util/"; -import { migrate } from "../util/paths"; -import { - TSQueryType, - getParserForFile, - getQueryForFile, -} from "../util/treeSitter"; -import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex"; -import { - IndexResultType, - MarkCompleteCallback, - RefreshIndexResults, - type CodebaseIndex, -} from "./types"; type SnippetChunk = ChunkWithoutID & { title: string; signature: string }; diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 042814fa4..5b59c39fa 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -1,7 +1,9 @@ -import { jest } from "@jest/globals"; import { execSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; + +import { jest } from "@jest/globals"; + import { ContinueServerClient } from "../continueServer/stubs/client.js"; import { testConfigHandler, testIde } from "../test/util/fixtures.js"; import { @@ -11,6 +13,7 @@ import { TEST_DIR, } from "../test/util/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; + import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; @@ -73,8 +76,8 @@ describe("CodebaseIndexer", () => { setUpTestDir(); execSync("git init", { cwd: TEST_DIR }); - execSync('git config user.email "test@example.com"', { cwd: TEST_DIR }); - execSync('git config user.name "Test"', { cwd: TEST_DIR }); + execSync("git config user.email \"test@example.com\"", { cwd: TEST_DIR }); + execSync("git config user.name \"Test\"", { cwd: TEST_DIR }); }); afterAll(async () => { diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 6eca76268..b4962d182 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,9 +1,11 @@ import * as fs from "fs/promises"; + import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js"; import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js"; import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; + import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; diff --git a/core/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts index ef5b9e398..d46e47fd4 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.test.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -1,9 +1,11 @@ import { jest } from "@jest/globals"; + import { insertMockChunks, mockPathAndCacheKey, updateIndexAndAwaitGenerator, } from "../test/util/indexing"; + import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { IndexResultType } from "./types"; diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index 8ab705535..f0c711e93 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -1,5 +1,6 @@ import { jest } from "@jest/globals"; import lance from "vectordb"; + import { testConfigHandler, testIde } from "../test/util/fixtures"; import { mockPathAndCacheKey, @@ -8,6 +9,7 @@ import { updateIndexAndAwaitGenerator, } from "../test/util/indexing"; import { getLanceDbPath } from "../util/paths"; + import { LanceDbIndex } from "./LanceDbIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; import { IndexResultType } from "./types"; diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 57ee34e8a..3759cf5b0 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -2,6 +2,7 @@ import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; import lance, { Table } from "vectordb"; + import { IContinueServerClient } from "../continueServer/interface.js"; import { BranchAndDir, @@ -12,6 +13,7 @@ import { } from "../index.js"; import { getBasename } from "../util/index.js"; import { getLanceDbPath, migrate } from "../util/paths.js"; + import { chunkDocument, shouldChunk } from "./chunk/chunk.js"; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js"; import { diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts index 7031fd992..e36dff7ce 100644 --- a/core/indexing/TestCodebaseIndex.ts +++ b/core/indexing/TestCodebaseIndex.ts @@ -1,4 +1,3 @@ -import type { IndexTag, IndexingProgressUpdate } from "../index.js"; import { DatabaseConnection, SqliteDb } from "./refreshIndex.js"; import { IndexResultType, @@ -7,6 +6,8 @@ import { type CodebaseIndex, } from "./types.js"; +import type { IndexTag, IndexingProgressUpdate } from "../index.js"; + /** * This is a CodebaseIndex used for testing which files get indexed. * It maintains a SQLite database of all file/tag pairs diff --git a/core/indexing/chunk/ChunkCodebaseIndex.test.ts b/core/indexing/chunk/ChunkCodebaseIndex.test.ts index 7453e8a78..c2f95d560 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.test.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.test.ts @@ -1,4 +1,5 @@ import { jest } from "@jest/globals"; + import { testIde } from "../../test/util/fixtures"; import { mockFileContents, @@ -10,6 +11,7 @@ import { import { addToTestDir } from "../../test/util/testDir"; import { DatabaseConnection, SqliteDb } from "../refreshIndex"; import { IndexResultType } from "../types"; + import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex"; jest.useFakeTimers(); diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index e2d316d67..7bd856ff1 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -1,5 +1,7 @@ import * as path from "path"; + import { RunResult } from "sqlite3"; + import { IContinueServerClient } from "../../continueServer/interface.js"; import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; import { getBasename } from "../../util/index.js"; @@ -11,6 +13,7 @@ import { RefreshIndexResults, type CodebaseIndex, } from "../types.js"; + import { chunkDocument, shouldChunk } from "./chunk.js"; export class ChunkCodebaseIndex implements CodebaseIndex { diff --git a/core/indexing/chunk/chunk.test.ts b/core/indexing/chunk/chunk.test.ts index a9559ca27..85683a51e 100644 --- a/core/indexing/chunk/chunk.test.ts +++ b/core/indexing/chunk/chunk.test.ts @@ -1,4 +1,5 @@ import path from "path"; + import { shouldChunk } from "./chunk"; describe("shouldChunk", () => { diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 7513ccabb..596f116dc 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -3,6 +3,7 @@ import { countTokensAsync } from "../../llm/countTokens.js"; import { extractMinimalStackTraceInfo } from "../../util/extractMinimalStackTraceInfo.js"; import { Telemetry } from "../../util/posthog.js"; import { supportedLanguages } from "../../util/treeSitter.js"; + import { basicChunker } from "./basic.js"; import { codeChunker } from "./code.js"; diff --git a/core/indexing/chunk/code.test.ts b/core/indexing/chunk/code.test.ts index c852ecafd..5e11880ca 100644 --- a/core/indexing/chunk/code.test.ts +++ b/core/indexing/chunk/code.test.ts @@ -1,4 +1,5 @@ import { ChunkWithoutID } from "../.."; + import { codeChunker } from "./code"; async function genToArr(generator: AsyncGenerator): Promise { diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index be02fbb2a..45487d551 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -1,4 +1,5 @@ import { SyntaxNode } from "web-tree-sitter"; + import { ChunkWithoutID } from "../../index.js"; import { countTokensAsync } from "../../llm/countTokens.js"; import { getParserForFile } from "../../util/treeSitter.js"; diff --git a/core/indexing/chunk/markdown.ts b/core/indexing/chunk/markdown.ts index a4edaed77..5a0df6776 100644 --- a/core/indexing/chunk/markdown.ts +++ b/core/indexing/chunk/markdown.ts @@ -1,5 +1,6 @@ import { ChunkWithoutID } from "../../"; import { countTokens } from "../../llm/countTokens"; + import { basicChunker } from "./basic"; export function cleanFragment( diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts index 4e9f00de8..57d712fed 100644 --- a/core/indexing/docs/DocsCrawler.skip.ts +++ b/core/indexing/docs/DocsCrawler.skip.ts @@ -1,10 +1,13 @@ +import os from "os"; + +import { jest } from "@jest/globals"; + +import { ContinueConfig } from "../.."; +import { testConfigHandler } from "../../test/util/fixtures"; +import FileSystemIde from "../../util/filesystem"; + import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler"; import preIndexedDocs from "./preIndexedDocs"; -import { jest } from "@jest/globals"; -import FileSystemIde from "../../util/filesystem"; -import { testConfigHandler } from "../../test/util/fixtures"; -import os from "os"; -import { ContinueConfig } from "../.."; // Temporary workaround until we have better caching of Chromium // download between test runs diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index d0851f95b..cb9146ab5 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -1,7 +1,9 @@ import { URL } from "node:url"; + // @ts-ignore // @prettier-ignore import { ContinueConfig, IDE } from "../.."; + import CheerioCrawler from "./crawlers/CheerioCrawler"; import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler"; import { DefaultCrawler } from "./crawlers/DefaultCrawler"; diff --git a/core/indexing/docs/DocsService.test.ts b/core/indexing/docs/DocsService.test.ts index f0caa5b95..9bac503c9 100644 --- a/core/indexing/docs/DocsService.test.ts +++ b/core/indexing/docs/DocsService.test.ts @@ -7,6 +7,7 @@ import { SiteIndexingConfig } from "../../index.js"; import FileSystemIde from "../../util/filesystem.js"; import { editConfigJson } from "../../util/paths.js"; import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js"; + import DocsService from "./DocsService.js"; import preIndexedDocs from "./preIndexedDocs.js"; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 0224dc3a0..46fedf9d0 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -1,6 +1,7 @@ import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; import lancedb, { Connection } from "vectordb"; + import { Chunk, ContinueConfig, @@ -13,6 +14,7 @@ import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; import DocsContextProvider from "../../context/providers/DocsContextProvider"; import { FromCoreProtocol, ToCoreProtocol } from "../../protocol"; +import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; import { GlobalContext } from "../../util/GlobalContext"; import { IMessenger } from "../../util/messenger"; import { @@ -22,6 +24,7 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider"; + import { Article, chunkArticle, pageToArticle } from "./article"; import DocsCrawler from "./DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; @@ -32,7 +35,6 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; -import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -360,11 +362,16 @@ export default class DocsService { isPreIndexedDoc: !!preIndexedDocs[startUrl], }); - const docs: LanceDbDocsRow[] = await table - .search(vector) - .limit(nRetrieve) - .where(`starturl = '${startUrl}'`) - .execute(); + let docs: LanceDbDocsRow[] = []; + try { + docs = await table + .search(vector) + .limit(nRetrieve) + .where(`starturl = '${startUrl}'`) + .execute(); + } catch (e: any) { + console.error("Error retrieving chunks from LanceDB", e); + } const hasIndexedDoc = await this.hasIndexedDoc(startUrl); @@ -551,9 +558,8 @@ export default class DocsService { private async getLanceTableNameFromEmbeddingsProvider( isPreIndexedDoc: boolean, ) { - const embeddingsProvider = await this.getEmbeddingsProvider( - isPreIndexedDoc, - ); + const embeddingsProvider = + await this.getEmbeddingsProvider(isPreIndexedDoc); const tableName = this.sanitizeLanceTableName( `${DocsService.lanceTableName}${embeddingsProvider.id}`, diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index c86bdb838..1bc74c62e 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -1,7 +1,9 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; + import { Chunk } from "../../"; import { cleanFragment, cleanHeader } from "../chunk/markdown"; + import { type PageData } from "./DocsCrawler"; export type ArticleComponent = { diff --git a/core/indexing/docs/crawlers/CheerioCrawler.ts b/core/indexing/docs/crawlers/CheerioCrawler.ts index df3eaf1bd..cfdf68f12 100644 --- a/core/indexing/docs/crawlers/CheerioCrawler.ts +++ b/core/indexing/docs/crawlers/CheerioCrawler.ts @@ -1,5 +1,7 @@ -import * as cheerio from "cheerio"; import { URL } from "node:url"; + +import * as cheerio from "cheerio"; + import { PageData } from "../DocsCrawler"; export default class CheerioCrawler { diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts index 1b4dbab01..ee49270a8 100644 --- a/core/indexing/docs/crawlers/ChromiumCrawler.ts +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -1,15 +1,18 @@ import * as fs from "fs"; import { URL } from "node:url"; + import { Handler, HTTPResponse, Page } from "puppeteer"; + +// @ts-ignore +// @prettier-ignore +import PCR from "puppeteer-chromium-resolver"; + +import { ContinueConfig, IDE } from "../../.."; import { editConfigJson, getChromiumPath, getContinueUtilsPath, } from "../../../util/paths"; -// @ts-ignore -// @prettier-ignore -import PCR from "puppeteer-chromium-resolver"; -import { ContinueConfig, IDE } from "../../.."; import { PageData } from "../DocsCrawler"; export class ChromiumCrawler { diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts index 64a65c8fd..7f0351080 100644 --- a/core/indexing/docs/crawlers/DefaultCrawler.ts +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -1,4 +1,5 @@ import { URL } from "node:url"; + import { getHeaders } from "../../../continueServer/stubs/headers"; import { TRIAL_PROXY_URL } from "../../../control-plane/client"; import { PageData } from "../DocsCrawler"; diff --git a/core/indexing/docs/crawlers/GitHubCrawler.ts b/core/indexing/docs/crawlers/GitHubCrawler.ts index 41362cf72..ebad52fc3 100644 --- a/core/indexing/docs/crawlers/GitHubCrawler.ts +++ b/core/indexing/docs/crawlers/GitHubCrawler.ts @@ -1,5 +1,7 @@ -import { Octokit } from "@octokit/rest"; import { URL } from "node:url"; + +import { Octokit } from "@octokit/rest"; + import { PageData } from "../DocsCrawler"; class GitHubCrawler { diff --git a/core/indexing/docs/migrations.ts b/core/indexing/docs/migrations.ts index f617098af..e3483d507 100644 --- a/core/indexing/docs/migrations.ts +++ b/core/indexing/docs/migrations.ts @@ -1,6 +1,8 @@ -import { Table } from "vectordb"; -import { editConfigJson, migrate } from "../../util/paths.js"; import { type Database } from "sqlite"; +import { Table } from "vectordb"; + +import { editConfigJson, migrate } from "../../util/paths.js"; + import DocsService, { SqliteDocsRow } from "./DocsService.js"; export async function runLanceMigrations(table: Table) { diff --git a/core/indexing/docs/preIndexed.ts b/core/indexing/docs/preIndexed.ts index 705693e36..73778a2b0 100644 --- a/core/indexing/docs/preIndexed.ts +++ b/core/indexing/docs/preIndexed.ts @@ -1,6 +1,7 @@ -import { Chunk } from "../../"; import request from "request"; +import { Chunk } from "../../"; + export function getS3Filename( embeddingsProviderId: string, title: string, diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 48b777b21..01935af9e 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -325,6 +325,11 @@ const preIndexedDocs: Record< rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/", faviconUrl: "https://docs.aws.amazon.com/favicon.ico", }, + "https://llama-stack.readthedocs.io/": { + title: "Llama Stack", + startUrl: "https://llama-stack.readthedocs.io/", + rootUrl: "https://llama-stack.readthedocs.io/", + }, }; export default preIndexedDocs; diff --git a/core/indexing/embeddings/BaseEmbeddingsProvider.ts b/core/indexing/embeddings/BaseEmbeddingsProvider.ts index a3aec7cb1..4f988705d 100644 --- a/core/indexing/embeddings/BaseEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BaseEmbeddingsProvider.ts @@ -4,7 +4,6 @@ import { EmbeddingsProviderName, FetchFunction, } from "../../index.js"; - import { DEFAULT_MAX_CHUNK_SIZE } from "../../llm/constants.js"; export interface IBaseEmbeddingsProvider extends EmbeddingsProvider { diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts index a5cfce6c4..a490cf0ff 100644 --- a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts +++ b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts @@ -3,7 +3,9 @@ import { InvokeModelCommand, } from "@aws-sdk/client-bedrock-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; + import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; interface ModelConfig { @@ -79,7 +81,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { private _getModelConfig() { const modelConfigs: { [key: string]: ModelConfig } = { - 'cohere': { + "cohere": { formatPayload: (text: string) => ({ texts: [text], input_type: "search_document", @@ -87,7 +89,7 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider { }), extractEmbeddings: (responseBody: any) => responseBody.embeddings || [], }, - 'amazon.titan-embed': { + "amazon.titan-embed": { formatPayload: (text: string) => ({ inputText: text, }), diff --git a/core/indexing/embeddings/CohereEmbeddingsProvider.ts b/core/indexing/embeddings/CohereEmbeddingsProvider.ts index 1375073e4..46db24c27 100644 --- a/core/indexing/embeddings/CohereEmbeddingsProvider.ts +++ b/core/indexing/embeddings/CohereEmbeddingsProvider.ts @@ -1,6 +1,8 @@ import { Response } from "node-fetch"; + import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class CohereEmbeddingsProvider extends BaseEmbeddingsProvider { diff --git a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts index 811a4fb0f..8fa6fc15f 100644 --- a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts +++ b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts @@ -1,5 +1,6 @@ import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { EmbeddingsProviderName } from "../../index.js"; + import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider { diff --git a/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts b/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts index 11444ab68..1249116d8 100644 --- a/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts +++ b/core/indexing/embeddings/DeepInfraEmbeddingsProvider.ts @@ -1,5 +1,6 @@ import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider { diff --git a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts index e0a29f850..9e9d28474 100644 --- a/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts +++ b/core/indexing/embeddings/FreeTrialEmbeddingsProvider.ts @@ -1,4 +1,5 @@ import { Response } from "node-fetch"; + import { getHeaders } from "../../continueServer/stubs/headers.js"; import { TRIAL_PROXY_URL } from "../../control-plane/client.js"; import { @@ -7,6 +8,7 @@ import { FetchFunction, } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider { diff --git a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts index a0d657321..f39cedc50 100644 --- a/core/indexing/embeddings/GeminiEmbeddingsProvider.ts +++ b/core/indexing/embeddings/GeminiEmbeddingsProvider.ts @@ -1,6 +1,8 @@ import { Response } from "node-fetch"; + import { EmbeddingsProviderName } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; /** diff --git a/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts b/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts index adcf4b7ee..c331f4529 100644 --- a/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts +++ b/core/indexing/embeddings/HuggingFaceTEIEmbeddingsProvider.ts @@ -1,10 +1,12 @@ import { Response } from "node-fetch"; + import { EmbeddingsProviderName, EmbedOptions, FetchFunction, } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider { diff --git a/core/indexing/embeddings/LMStudio.ts b/core/indexing/embeddings/LMStudio.ts index f5ec128d3..31a9d6edf 100644 --- a/core/indexing/embeddings/LMStudio.ts +++ b/core/indexing/embeddings/LMStudio.ts @@ -1,4 +1,5 @@ import { EmbeddingsProviderName, EmbedOptions } from "../.."; + import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; class LMStudioEmbeddingsProvider extends OpenAIEmbeddingsProvider { diff --git a/core/indexing/embeddings/MistralEmbeddingsProvider.ts b/core/indexing/embeddings/MistralEmbeddingsProvider.ts index 5a46a8554..ffff08ae5 100644 --- a/core/indexing/embeddings/MistralEmbeddingsProvider.ts +++ b/core/indexing/embeddings/MistralEmbeddingsProvider.ts @@ -1,4 +1,5 @@ import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; + import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; class MistralEmbeddingsProvider extends OpenAIEmbeddingsProvider { diff --git a/core/indexing/embeddings/NebiusEmbeddingsProvider.ts b/core/indexing/embeddings/NebiusEmbeddingsProvider.ts index 4bf20e868..c9cf44877 100644 --- a/core/indexing/embeddings/NebiusEmbeddingsProvider.ts +++ b/core/indexing/embeddings/NebiusEmbeddingsProvider.ts @@ -1,4 +1,5 @@ import { EmbeddingsProviderName, EmbedOptions } from "../.."; + import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; class NebiusEmbeddingsProvider extends OpenAIEmbeddingsProvider { diff --git a/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts b/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts index 8e47a6db8..04ae18ec4 100644 --- a/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts +++ b/core/indexing/embeddings/NvidiaEmbeddingsProvider.ts @@ -1,6 +1,8 @@ import { Response } from "node-fetch"; + import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider { @@ -37,9 +39,9 @@ class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider { } // Input list must be non empty and all elements must be non empty, therefore, for all empty elements replace it with a token - const emptyToken = '[EMPTY]'; + const emptyToken = "[EMPTY]"; for (let i = 0; i < batch.length; i++) { - if (batch[i].trim() === '') { + if (batch[i].trim() === "") { batch[i] = emptyToken; } } @@ -51,7 +53,7 @@ class NvidiaEmbeddingsProvider extends BaseEmbeddingsProvider { body: JSON.stringify({ input: batch, model: this.options.model, - input_type: 'passage', + input_type: "passage", truncate: "END", }), headers: { diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts index 43aa84020..ca4eee262 100644 --- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts @@ -4,6 +4,7 @@ import { FetchFunction, } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider, { IBaseEmbeddingsProvider, } from "./BaseEmbeddingsProvider.js"; diff --git a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts index 95308bbd9..65c37cdf6 100644 --- a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts @@ -1,6 +1,8 @@ import { Response } from "node-fetch"; + import { EmbeddingsProviderName, EmbedOptions } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { diff --git a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts index c5c698efd..f0d1ea0c4 100644 --- a/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts +++ b/core/indexing/embeddings/TransformersJsEmbeddingsProvider.ts @@ -1,8 +1,10 @@ import path from "path"; + import { EmbeddingsProviderName } from "../../index.js"; // @ts-ignore // prettier-ignore import { type PipelineType } from "../../vendor/modules/@xenova/transformers/src/transformers.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; class EmbeddingsPipeline { diff --git a/core/indexing/embeddings/VertexEmbeddingsProvider.ts b/core/indexing/embeddings/VertexEmbeddingsProvider.ts index 7188254a1..67bd801c7 100644 --- a/core/indexing/embeddings/VertexEmbeddingsProvider.ts +++ b/core/indexing/embeddings/VertexEmbeddingsProvider.ts @@ -1,7 +1,9 @@ import { GoogleAuth } from "google-auth-library"; import { Response } from "node-fetch"; + import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; /** diff --git a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts index 3972b3402..df78f401b 100644 --- a/core/indexing/embeddings/VoyageEmbeddingsProvider.ts +++ b/core/indexing/embeddings/VoyageEmbeddingsProvider.ts @@ -1,4 +1,5 @@ import { EmbeddingsProviderName, EmbedOptions } from "../.."; + import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider"; class VoyageEmbeddingsProvider extends OpenAIEmbeddingsProvider { diff --git a/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts index 1c352697a..cb605d0c1 100644 --- a/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts +++ b/core/indexing/embeddings/WatsonxEmbeddingsProvider.ts @@ -4,6 +4,7 @@ import { FetchFunction, } from "../../index.js"; import { withExponentialBackoff } from "../../util/withExponentialBackoff.js"; + import BaseEmbeddingsProvider, { IBaseEmbeddingsProvider, } from "./BaseEmbeddingsProvider.js"; diff --git a/core/indexing/embeddings/index.ts b/core/indexing/embeddings/index.ts index b0508d3fd..90e450361 100644 --- a/core/indexing/embeddings/index.ts +++ b/core/indexing/embeddings/index.ts @@ -1,6 +1,6 @@ import { EmbeddingsProviderName } from "../../index.js"; + import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js"; -import SageMakerEmbeddingsProvider from "./SageMakerEmbeddingsProvider.js"; import BedrockEmbeddingsProvider from "./BedrockEmbeddingsProvider.js"; import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js"; import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js"; @@ -8,16 +8,17 @@ import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js"; import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js"; import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js"; import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js"; +import LMStudioEmbeddingsProvider from "./LMStudio.js"; import MistralEmbeddingsProvider from "./MistralEmbeddingsProvider.js"; +import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; +import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js"; import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js"; import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js"; +import SageMakerEmbeddingsProvider from "./SageMakerEmbeddingsProvider.js"; import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js"; -import NvidiaEmbeddingsProvider from "./NvidiaEmbeddingsProvider.js"; -import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; import VertexEmbeddingsProvider from "./VertexEmbeddingsProvider.js"; +import VoyageEmbeddingsProvider from "./VoyageEmbeddingsProvider.js"; import WatsonxEmbeddingsProvider from "./WatsonxEmbeddingsProvider.js"; -import NebiusEmbeddingsProvider from "./NebiusEmbeddingsProvider.js"; -import LMStudioEmbeddingsProvider from "./LMStudio.js"; type EmbeddingsProviderConstructor = new ( ...args: any[] diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 351455695..b647cc333 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -1,5 +1,7 @@ import fs from "fs"; + import ignore from "ignore"; + import { getGlobalContinueIgnorePath } from "../util/paths"; export const DEFAULT_IGNORE_FILETYPES = [ diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index ba2dbd820..fc71bb046 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -1,10 +1,13 @@ import crypto from "node:crypto"; import * as fs from "node:fs"; + import plimit from "p-limit"; import { open, type Database } from "sqlite"; import sqlite3 from "sqlite3"; + import { IndexTag, IndexingProgressUpdate } from "../index.js"; import { getIndexSqlitePath } from "../util/paths.js"; + import { CodebaseIndex, IndexResultType, diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 7fa5ed00c..748e958e9 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -1,12 +1,13 @@ import path from "path"; + import { walkDir, WalkerOptions } from "../indexing/walkDir"; -import FileSystemIde from "../util/filesystem"; import { TEST_DIR, setUpTestDir, tearDownTestDir, addToTestDir, } from "../test/util/testDir"; +import FileSystemIde from "../util/filesystem"; const ide = new FileSystemIde(TEST_DIR); diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 44f785ab4..9e40ccb57 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -1,6 +1,9 @@ -import ignore, { Ignore } from "ignore"; import path from "node:path"; + +import ignore, { Ignore } from "ignore"; + import { FileType, IDE } from "../index.d.js"; + import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES, diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index a4c024332..b5fbacc11 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -1,7 +1,8 @@ // https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 +import { TextDecoder, TextEncoder } from "util"; + import { jest } from "@jest/globals"; import fetch, { Request, Response } from "node-fetch"; -import { TextDecoder, TextEncoder } from "util"; if (process.env.DEBUG === "jest") { jest.setTimeout(5 * 60 * 1000); diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index 5fd39eed6..fab2e5a3c 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -1,4 +1,5 @@ import path from "path"; + import workerpool from "workerpool"; export interface AsyncEncoder { diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 64e0634a5..17f104a52 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,4 +1,5 @@ import { ModelCapability, ModelProvider, TemplateType } from "../index.js"; + import { anthropicTemplateMessages, chatmlTemplateMessages, diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 52265d509..59a9c301a 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -1,4 +1,4 @@ -const DEFAULT_MAX_TOKENS = 2048; +const DEFAULT_MAX_TOKENS = 4096; const DEFAULT_CONTEXT_LENGTH = 8096; const DEFAULT_TEMPERATURE = 0.5; @@ -7,7 +7,7 @@ const DEFAULT_ARGS = { temperature: DEFAULT_TEMPERATURE, }; -const GPT_4_CTX_LEN = 4096; +const GPT_4_CTX_LEN = 128_000; const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { "gpt-3.5-turbo": 4096, @@ -16,9 +16,9 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { "gpt-35-turbo-16k": 16_384, "gpt-35-turbo-0613": 4096, "gpt-35-turbo": 4096, - "gpt-4": GPT_4_CTX_LEN, - "gpt-4-32k": GPT_4_CTX_LEN, - "gpt-4-turbo-preview": GPT_4_CTX_LEN, + "gpt-4": 4096, + "gpt-4-32k": 32_000, + "gpt-4-turbo-preview": 32_000, "gpt-4o": GPT_4_CTX_LEN, "gpt-4o-mini": GPT_4_CTX_LEN, "gpt-4-vision": GPT_4_CTX_LEN, diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 0fbadf68b..7ae3da1b7 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,5 +1,7 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; + import { ChatMessage, MessageContent, MessagePart } from "../index.js"; + import { AsyncEncoder, GPTAsyncEncoder, diff --git a/core/llm/index.test.ts b/core/llm/index.test.ts index 8d5d1cc35..0ada014ab 100644 --- a/core/llm/index.test.ts +++ b/core/llm/index.test.ts @@ -1,6 +1,7 @@ -import { BaseLLM } from "."; import { ChatMessage, LLMOptions, ModelProvider } from ".."; +import { BaseLLM } from "."; + class DummyLLM extends BaseLLM { static providerName: ModelProvider = "openai"; static defaultOptions: Partial = { diff --git a/core/llm/index.ts b/core/llm/index.ts index 4d3f2fd6e..d3148f833 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -1,5 +1,6 @@ import { findLlmInfo } from "@continuedev/llm-info"; import Handlebars from "handlebars"; + import { CacheBehavior, ChatMessage, @@ -22,6 +23,7 @@ import { fetchwithRequestOptions } from "../util/fetchWithOptions.js"; import mergeJson from "../util/merge.js"; import { Telemetry } from "../util/posthog.js"; import { withExponentialBackoff } from "../util/withExponentialBackoff.js"; + import { autodetectPromptTemplates, autodetectTemplateFunction, diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index eaedde8de..8db42eefa 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -146,7 +146,7 @@ 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 }; } diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index a8f119445..0daec0850 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index c143fa412..67d8a4167 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -3,6 +3,7 @@ import { ConverseStreamCommand, } from "@aws-sdk/client-bedrock-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; + import { ChatMessage, CompletionOptions, diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index a265c7679..44a57205e 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -3,6 +3,7 @@ import { InvokeModelWithResponseStreamCommand, } from "@aws-sdk/client-bedrock-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; + import { CompletionOptions, LLMOptions, diff --git a/core/llm/llms/Cerebras.ts b/core/llm/llms/Cerebras.ts index 4b0a1752c..0c5a95147 100644 --- a/core/llm/llms/Cerebras.ts +++ b/core/llm/llms/Cerebras.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class Cerebras extends OpenAI { diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 7084360f2..93b9c4433 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -1,6 +1,6 @@ -import { BaseLLM } from "../index.js"; import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { stripImages } from "../images.js"; +import { BaseLLM } from "../index.js"; import { streamSse } from "../stream.js"; export default class Cloudflare extends BaseLLM { diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index fd6df4f82..83f255904 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -1,4 +1,3 @@ -import { BaseLLM } from "../index.js"; import { ChatMessage, CompletionOptions, @@ -6,6 +5,7 @@ import { ModelProvider, } from "../../index.js"; import { stripImages } from "../images.js"; +import { BaseLLM } from "../index.js"; import { streamJSON } from "../stream.js"; class Cohere extends BaseLLM { diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index 487eec7d9..d35dfabde 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -1,10 +1,10 @@ -import { BaseLLM } from "../index.js"; import { ChatMessage, CompletionOptions, CustomLLM, ModelProvider, } from "../../index.js"; +import { BaseLLM } from "../index.js"; class CustomLLMClass extends BaseLLM { get providerName(): ModelProvider { diff --git a/core/llm/llms/DeepInfra.ts b/core/llm/llms/DeepInfra.ts index 592d28009..0bcbbb596 100644 --- a/core/llm/llms/DeepInfra.ts +++ b/core/llm/llms/DeepInfra.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class DeepInfra extends OpenAI { diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index 105a2e20c..cfba34e85 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -1,6 +1,7 @@ import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; import { streamSse } from "../stream.js"; import { osModelsEditPrompt } from "../templates/edit.js"; + import OpenAI from "./OpenAI.js"; class Deepseek extends OpenAI { diff --git a/core/llm/llms/Fireworks.ts b/core/llm/llms/Fireworks.ts index 02a310761..a9dc44707 100644 --- a/core/llm/llms/Fireworks.ts +++ b/core/llm/llms/Fireworks.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class Fireworks extends OpenAI { diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 876595f43..0d9e617a0 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -1,4 +1,5 @@ import socketIOClient, { Socket } from "socket.io-client"; + import { ChatMessage, CompletionOptions, diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index b69e2c020..0f28f8eb9 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class Groq extends OpenAI { diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts index 855e386de..8010fff16 100644 --- a/core/llm/llms/Kindo.ts +++ b/core/llm/llms/Kindo.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../.."; + import OpenAI from "./OpenAI"; class Kindo extends OpenAI { diff --git a/core/llm/llms/LMStudio.ts b/core/llm/llms/LMStudio.ts index d1e15c395..03a3378d4 100644 --- a/core/llm/llms/LMStudio.ts +++ b/core/llm/llms/LMStudio.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class LMStudio extends OpenAI { diff --git a/core/llm/llms/Llamafile.ts b/core/llm/llms/Llamafile.ts index 0f95787ef..91f7e8a50 100644 --- a/core/llm/llms/Llamafile.ts +++ b/core/llm/llms/Llamafile.ts @@ -1,4 +1,5 @@ import { ModelProvider } from "../../index.js"; + import LlamaCpp from "./LlamaCpp.js"; class Llamafile extends LlamaCpp { diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index 992e650c7..f18aff0e7 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -1,5 +1,6 @@ import { ChatMessage, LLMOptions, ModelProvider } from "../../index.js"; import { gptEditPrompt } from "../templates/edit.js"; + import OpenAI from "./OpenAI.js"; class Mistral extends OpenAI { diff --git a/core/llm/llms/Msty.ts b/core/llm/llms/Msty.ts index bb1b69b1b..73c3e7aa1 100644 --- a/core/llm/llms/Msty.ts +++ b/core/llm/llms/Msty.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import Ollama from "./Ollama.js"; class Msty extends Ollama { diff --git a/core/llm/llms/Nebius.ts b/core/llm/llms/Nebius.ts index 4e2b56721..e1935815d 100644 --- a/core/llm/llms/Nebius.ts +++ b/core/llm/llms/Nebius.ts @@ -1,12 +1,34 @@ import { LLMOptions, ModelProvider } from "../.."; + import OpenAI from "./OpenAI"; class Nebius extends OpenAI { - static providerName: ModelProvider = "nvidia"; + static providerName: ModelProvider = "nebius"; static defaultOptions: Partial = { apiBase: "https://api.studio.nebius.ai/v1/", useLegacyCompletionsEndpoint: false, }; + + private static MODEL_IDS: { [name: string]: string } = { + "llama3.1-70b-nemotron": "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF-fast", + "llama3.1-8b": "meta-llama/Meta-Llama-3.1-70B-Instruct-fast", + "llama3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-fast", + "llama3.1-405b": "meta-llama/Meta-Llama-3.1-405B-Instruct", + "mistral-nemo": "mistralai/Mistral-Nemo-Instruct-2407-fast", + "mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1-fast", + "mistral-8x22b": "mistralai/Mixtral-8x22B-Instruct-v0.1-fast", + "qwen-coder2.5-7b": "Qwen/Qwen2.5-Coder-7B-Instruct-fast", + "deepseek-2-lite": "deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct-fast", + "phi-3-mini": "microsoft/Phi-3-mini-4k-instruct-fast", + "phi-3-medium": "microsoft/Phi-3-medium-128k-instruct-fast", + "gemma2-2b-it": "google/gemma-2-2b-it-fast", + "gemma2-9b-it": "google/gemma-2-9b-it-fast", + "olmo-7b": "allenai/OLMo-7B-Instruct-hf", + }; + + protected _convertModelName(model: string) { + return Nebius.MODEL_IDS[model] || this.model; + } } export default Nebius; diff --git a/core/llm/llms/Nvidia.ts b/core/llm/llms/Nvidia.ts index ccfd1d19e..159f34222 100644 --- a/core/llm/llms/Nvidia.ts +++ b/core/llm/llms/Nvidia.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider, ChatMessage } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class Nvidia extends OpenAI { diff --git a/core/llm/llms/OpenRouter.ts b/core/llm/llms/OpenRouter.ts index d01a19ec5..46b5afecd 100644 --- a/core/llm/llms/OpenRouter.ts +++ b/core/llm/llms/OpenRouter.ts @@ -1,5 +1,6 @@ import { LLMOptions, ModelProvider } from "../../index.js"; import { osModelsEditPrompt } from "../templates/edit.js"; + import OpenAI from "./OpenAI.js"; class OpenRouter extends OpenAI { diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 5dde24014..414975ac4 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -1,4 +1,5 @@ import ReplicateClient from "replicate"; + import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index d5e9039de..c88261941 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -56,7 +56,7 @@ class SageMaker extends BaseLLM { while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); try { - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); let text = undefined; if ("choices" in data) { if ("delta" in data.choices[0]) { @@ -107,7 +107,7 @@ class SageMaker extends BaseLLM { while ((position = buffer.indexOf("\n")) >= 0) { const line = buffer.slice(0, position); try { - const data = JSON.parse(line.replace(/^data:/, '')); + const data = JSON.parse(line.replace(/^data:/, "")); let text = undefined; if ("choices" in data) { if ("delta" in data.choices[0]) { diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 39a216681..7719a6e9b 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -1,6 +1,7 @@ +import OpenAI from "./OpenAI.js"; + import type { LLMOptions, ModelProvider } from "../../index.js"; -import OpenAI from "./OpenAI.js"; class SambaNova extends OpenAI { static providerName: ModelProvider = "sambanova"; diff --git a/core/llm/llms/TextGenWebUI.ts b/core/llm/llms/TextGenWebUI.ts index 2ee36f94a..8aa701286 100644 --- a/core/llm/llms/TextGenWebUI.ts +++ b/core/llm/llms/TextGenWebUI.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class TextGenWebUI extends OpenAI { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index 862226394..f5b5f0bac 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -1,10 +1,11 @@ +import OpenAI from "./OpenAI.js"; + import type { CompletionOptions, LLMOptions, ModelProvider, } from "../../index.js"; -import OpenAI from "./OpenAI.js"; class Together extends OpenAI { static providerName: ModelProvider = "together"; diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index e3435b6ae..e945831e6 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -1,7 +1,5 @@ import { GoogleAuth } from "google-auth-library"; -import { BaseLLM } from "../index.js"; -import { stripImages } from "../images.js"; -import { streamSse } from "../stream.js"; + import { ChatMessage, CompletionOptions, @@ -9,7 +7,11 @@ import { MessagePart, ModelProvider, } from "../../index.js"; +import { stripImages } from "../images.js"; +import { BaseLLM } from "../index.js"; +import { streamSse } from "../stream.js"; import { streamResponse } from "../stream.js"; + import Anthropic from "./Anthropic.js"; import Gemini from "./Gemini.js"; @@ -46,7 +48,7 @@ class VertexAI extends BaseLLM { ? "gemini" : "unknown"; this.anthropicInstance = new Anthropic(_options); - this.geminiInstance = new Gemini(_options) + this.geminiInstance = new Gemini(_options); } @@ -123,7 +125,7 @@ class VertexAI 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 }; } @@ -384,7 +386,7 @@ class VertexAI extends BaseLLM { } else if (this.vertexProvider == "mistral") { yield* this.StreamChatMistral(messages, options); } else if (this.vertexProvider == "anthropic") { - yield* this.StreamChatAnthropic(messages, options) + yield* this.StreamChatAnthropic(messages, options); } else { if (options.model.includes("bison")) { yield* this.streamChatBison(convertedMsgs, options); diff --git a/core/llm/llms/Vllm.ts b/core/llm/llms/Vllm.ts index 6c6f81451..8877fed27 100644 --- a/core/llm/llms/Vllm.ts +++ b/core/llm/llms/Vllm.ts @@ -1,4 +1,5 @@ import { LLMOptions, ModelProvider } from "../../index.js"; + import OpenAI from "./OpenAI.js"; class Vllm extends OpenAI { diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 94a7b66fa..89a2d13dc 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -11,7 +11,7 @@ import { streamResponse } from "../stream.js"; let watsonxToken = { expiration: 0, token: "" -} +}; class WatsonX extends BaseLLM { diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 17ff45725..48088dc34 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -7,6 +7,7 @@ import { } from "../.."; import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString"; import { BaseLLM } from "../index"; + import Anthropic from "./Anthropic"; import Asksage from "./Asksage"; import Azure from "./Azure"; @@ -25,9 +26,9 @@ import Groq from "./Groq"; import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; import HuggingFaceTGI from "./HuggingFaceTGI"; import Kindo from "./Kindo"; -import LMStudio from "./LMStudio"; import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; +import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; import Mock from "./Mock"; import Msty from "./Msty"; @@ -39,12 +40,12 @@ import OpenRouter from "./OpenRouter"; import Replicate from "./Replicate"; import SageMaker from "./SageMaker"; import SambaNova from "./SambaNova"; +import ContinueProxy from "./stubs/ContinueProxy"; import TextGenWebUI from "./TextGenWebUI"; import Together from "./Together"; import VertexAI from "./VertexAI"; import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; -import ContinueProxy from "./stubs/ContinueProxy"; import xAI from "./xAI"; const LLMs = [ diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 0db131bed..0d04f77f5 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -1,8 +1,9 @@ import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js"; -import type { LLMOptions, ModelProvider } from "../../../index.js"; import { Telemetry } from "../../../util/posthog.js"; import OpenAI from "../OpenAI.js"; +import type { LLMOptions, ModelProvider } from "../../../index.js"; + class ContinueProxy extends OpenAI { set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) { this.apiKey = value.workOsAccessToken; diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index 9be515993..e6ad4d6b6 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -1,4 +1,5 @@ import { ChatMessage, PromptTemplate } from "../../index.js"; +import { gptEditPrompt } from "./edit/gpt.js"; const simplifiedEditPrompt = `Consider the following code: \`\`\`{{{language}}} @@ -18,49 +19,6 @@ Here is the edit requested: Here is the code after editing:`; -const gptEditPrompt: PromptTemplate = (_, otherData) => { - if (otherData?.codeToEdit?.trim().length === 0) { - return `\ -\`\`\`${otherData.language} -${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix} -\`\`\` - -Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request: - -"${otherData.userInput}" - -Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`; - } - - const paragraphs = [ - "The user has requested a section of code in a file to be rewritten.", - ]; - if (otherData.prefix?.trim().length > 0) { - paragraphs.push(`This is the prefix of the file: -\`\`\`${otherData.language} -${otherData.prefix} -\`\`\``); - } - - if (otherData.suffix?.trim().length > 0) { - paragraphs.push(`This is the suffix of the file: -\`\`\`${otherData.language} -${otherData.suffix} -\`\`\``); - } - - paragraphs.push(`This is the code to rewrite: -\`\`\`${otherData.language} -${otherData.codeToEdit} -\`\`\` - -The user's request is: "${otherData.userInput}" - -Here is the rewritten code:`); - - return paragraphs.join("\n\n"); -}; - const codellamaInfillEditPrompt = "{{filePrefix}}{{fileSuffix}}"; const START_TAG = ""; diff --git a/core/llm/templates/edit/claude.ts b/core/llm/templates/edit/claude.ts new file mode 100644 index 000000000..5ec103fa9 --- /dev/null +++ b/core/llm/templates/edit/claude.ts @@ -0,0 +1,44 @@ +import { PromptTemplateFunction } from "../../.."; + +export const claudeEditPrompt: PromptTemplateFunction = (_, otherData) => { + if (otherData?.codeToEdit?.trim().length === 0) { + return `\ +\`\`\`${otherData.language} +${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix} +\`\`\` + +Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request: + +"${otherData.userInput}" + +Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`; + } + + const paragraphs = [ + "The user has requested a section of code in a file to be rewritten.", + ]; + if (otherData.prefix?.trim().length > 0) { + paragraphs.push(`This is the prefix of the file: +\`\`\`${otherData.language} +${otherData.prefix} +\`\`\``); + } + + if (otherData.suffix?.trim().length > 0) { + paragraphs.push(`This is the suffix of the file: +\`\`\`${otherData.language} +${otherData.suffix} +\`\`\``); + } + + paragraphs.push(`This is the code to rewrite: +\`\`\`${otherData.language} +${otherData.codeToEdit} +\`\`\` + +The user's request is: "${otherData.userInput}" + +Here is the rewritten code:`); + + return paragraphs.join("\n\n"); +}; diff --git a/core/llm/templates/edit/gpt.ts b/core/llm/templates/edit/gpt.ts new file mode 100644 index 000000000..4dcc39523 --- /dev/null +++ b/core/llm/templates/edit/gpt.ts @@ -0,0 +1,71 @@ +import { PromptTemplateFunction } from "../../.."; +import { dedent } from "../../../util"; + +const gptInsertionEditPrompt: PromptTemplateFunction = (_, otherData) => { + return dedent` + \`\`\`${otherData.language} + ${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix} + \`\`\` + + Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request: + + "${otherData.userInput}" + + Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`; +}; + +const gptFullFileEditPrompt: PromptTemplateFunction = (_, otherData) => { + return dedent` + \`\`\`${otherData.language} + ${otherData.codeToEdit} + \`\`\` + + Please rewrite the above file to address the following request: + + ${otherData.userInput} + + You should rewrite the entire file without any natural language explanation. DO NOT surround the code in a code block and DO NOT explain yourself.`; +}; + +export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => { + if (otherData?.codeToEdit?.trim().length === 0) { + return gptInsertionEditPrompt(history, otherData); + } else if ( + otherData?.prefix?.trim().length === 0 && + otherData?.suffix?.trim().length === 0 + ) { + return gptFullFileEditPrompt(history, otherData); + } + + const paragraphs = [ + "The user has requested a section of code in a file to be rewritten.", + ]; + + if (otherData.prefix?.trim().length > 0) { + paragraphs.push(dedent` + This is the prefix of the file: + \`\`\`${otherData.language} + ${otherData.prefix} + \`\`\``); + } + + if (otherData.suffix?.trim().length > 0) { + paragraphs.push(dedent` + This is the suffix of the file: + \`\`\`${otherData.language} + ${otherData.suffix} + \`\`\``); + } + + paragraphs.push(dedent` + This is the code to rewrite: + \`\`\`${otherData.language} + ${otherData.codeToEdit} + \`\`\` + + The user's request is: "${otherData.userInput}" + + Here is the rewritten code:`); + + return paragraphs.join("\n\n"); +}; diff --git a/core/promptFiles/v1/createNewPromptFile.ts b/core/promptFiles/v1/createNewPromptFile.ts index e6386056c..19286fe6d 100644 --- a/core/promptFiles/v1/createNewPromptFile.ts +++ b/core/promptFiles/v1/createNewPromptFile.ts @@ -1,7 +1,9 @@ import path from "path"; -import { DEFAULT_PROMPTS_FOLDER } from "."; + import { IDE } from "../.."; +import { DEFAULT_PROMPTS_FOLDER } from "."; + const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file # It is used to define and reuse prompts within Continue # Continue will automatically create a slash command for each prompt in the .prompts folder diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index a272c2872..4b77360fe 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -1,7 +1,9 @@ import * as YAML from "yaml"; + import { ContinueSDK, SlashCommand } from "../.."; import { stripImages } from "../../llm/images"; import { getBasename } from "../../util/index"; + import { getContextProviderHelpers } from "./getContextProviderHelpers"; import { renderTemplatedString } from "./renderTemplatedString"; import { updateChatHistory } from "./updateChatHistory"; diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/v2/createNewPromptFile.ts index aea2f917b..a8ea87109 100644 --- a/core/promptFiles/v2/createNewPromptFile.ts +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -1,6 +1,8 @@ import path from "path"; + import { IDE } from "../.."; import { GlobalContext } from "../../util/GlobalContext"; + import { DEFAULT_PROMPTS_FOLDER_V2 } from "./getPromptFiles"; const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file @@ -64,11 +66,14 @@ export async function createNewPromptFileV2( counter++; } while (await ide.fileExists(promptFilePath)); + const globalContext = new GlobalContext(); const PROMPT_FILE = - new GlobalContext().get("hasAlreadyCreatedAPromptFile") === true + globalContext.get("hasAlreadyCreatedAPromptFile") === true ? DEFAULT_PROMPT_FILE : FIRST_TIME_DEFAULT_PROMPT_FILE; + globalContext.update("hasAlreadyCreatedAPromptFile", true); + await ide.writeFile(promptFilePath, PROMPT_FILE); await ide.openFile(promptFilePath); } diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index ae02013a3..c78068899 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -1,4 +1,5 @@ import path from "path"; + import { IDE } from "../.."; import { walkDir } from "../../indexing/walkDir"; import { readAllGlobalPromptFiles } from "../../util/paths"; diff --git a/core/promptFiles/v2/parse.ts b/core/promptFiles/v2/parse.ts index 9f5ecf832..d0c71c962 100644 --- a/core/promptFiles/v2/parse.ts +++ b/core/promptFiles/v2/parse.ts @@ -1,4 +1,5 @@ import * as YAML from "yaml"; + import { getBasename } from "../../util"; export function extractName(preamble: { name?: string }, path: string): string { diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index 243c007dd..bb70b19a2 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -1,6 +1,7 @@ import { ContextItem, ContextProviderExtras } from "../.."; import URLContextProvider from "../../context/providers/URLContextProvider"; import { getBasename } from "../../util"; + import { getPreambleAndBody } from "./parse"; async function resolveAttachment( diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 86f65b3f0..2c9af1433 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,3 +1,6 @@ +import { AutocompleteInput } from "../autocomplete/util/types"; +import { ProfileDescription } from "../config/ConfigHandler"; + import type { BrowserSerializedContinueConfig, ChatMessage, @@ -15,8 +18,6 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ done?: boolean; diff --git a/core/protocol/coreWebview.ts b/core/protocol/coreWebview.ts index f124cf2a6..1622b4be5 100644 --- a/core/protocol/coreWebview.ts +++ b/core/protocol/coreWebview.ts @@ -1,4 +1,5 @@ import { ProfileDescription } from "../config/ConfigHandler.js"; + import { ToCoreFromIdeOrWebviewProtocol } from "./core.js"; import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js"; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index d6b6a90d3..a9b1d8cf9 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -1,3 +1,5 @@ +import { ControlPlaneSessionInfo } from "../control-plane/client"; + import type { ContinueRcJson, DiffLine, @@ -12,7 +14,6 @@ import type { RangeInFile, Thread, } from "../"; -import { ControlPlaneSessionInfo } from "../control-plane/client"; export interface GetGhTokenArgs { force?: boolean; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 22b1ab530..77f958b92 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -59,7 +59,12 @@ export interface EditModeArgs { highlightedCode: RangeInFileWithContents; } -export type EditStatus = "not-started" | "streaming" | "accepting" | "done"; +export type EditStatus = + | "not-started" + | "streaming" + | "accepting" + | "accepting:full-diff" + | "done"; export interface ApplyState { streamId: string; @@ -109,6 +114,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { applyCodeFromChat: [undefined, void]; updateApplyState: [ApplyState, void]; startEditMode: [EditModeArgs, void]; - setEditStatus: [{ status: EditStatus }, void]; + setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void]; exitEditMode: [undefined, void]; }; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index ef2daacf0..d974c1516 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,4 +1,5 @@ import { ConfigValidationError } from "../config/validation.js"; + import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js"; export type ToWebviewFromIdeOrCoreProtocol = { diff --git a/core/test/context/providers/index.skip.ts b/core/test/context/providers/index.skip.ts index a01931f14..1d4e9f1b1 100644 --- a/core/test/context/providers/index.skip.ts +++ b/core/test/context/providers/index.skip.ts @@ -1,4 +1,5 @@ import fetch from "node-fetch"; + import { ContextProviderExtras, ContextProviderWithParams, diff --git a/core/test/llm.test.ts b/core/test/llm.test.ts index 3828eb97d..2cb81da72 100644 --- a/core/test/llm.test.ts +++ b/core/test/llm.test.ts @@ -107,4 +107,7 @@ describe.skip("LLM", () => { // testLLM( // new Flowise({ apiKey: process.env.FLOWISE_API_KEY, model: "gpt-3.5-turbo" }) // ); + // testLLM( + // new Nebius({ apiKey: process.env.NEBIUS_API_KEY, model: "llama3.1-8b" }) + // ); }); diff --git a/core/test/util/fixtures.ts b/core/test/util/fixtures.ts index 89c1c0b3b..e0aa06d14 100644 --- a/core/test/util/fixtures.ts +++ b/core/test/util/fixtures.ts @@ -1,6 +1,7 @@ import { ConfigHandler } from "../../config/ConfigHandler"; import { ControlPlaneClient } from "../../control-plane/client"; import FileSystemIde from "../../util/filesystem"; + import { TEST_DIR } from "./testDir"; export const testIde = new FileSystemIde(TEST_DIR); diff --git a/core/test/util/history.test.ts b/core/test/util/history.test.ts index d3dedac7f..c69e662a6 100644 --- a/core/test/util/history.test.ts +++ b/core/test/util/history.test.ts @@ -1,7 +1,8 @@ +import { v4 as uuidv4 } from "uuid"; + import { PersistedSessionInfo } from "../.."; import historyManager from "../../util/history"; import { getSessionFilePath } from "../../util/paths"; -import { v4 as uuidv4 } from "uuid"; const sessionId = uuidv4(); const testSession: PersistedSessionInfo = { diff --git a/core/test/util/indexing.ts b/core/test/util/indexing.ts index 650cc5b56..16137236a 100644 --- a/core/test/util/indexing.ts +++ b/core/test/util/indexing.ts @@ -1,15 +1,20 @@ -import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; -import { IContinueServerClient } from "../../continueServer/interface"; -import { testIde } from "./fixtures"; -import { addToTestDir, TEST_DIR } from "./testDir"; +import { jest } from "@jest/globals"; + import { IndexTag } from "../.."; +import { IContinueServerClient } from "../../continueServer/interface"; +import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; +import { tagToString } from "../../indexing/refreshIndex"; import { CodebaseIndex, PathAndCacheKey, RefreshIndexResults, } from "../../indexing/types"; -import { jest } from "@jest/globals"; -import { tagToString } from "../../indexing/refreshIndex"; + +import { testIde } from "./fixtures"; +import { addToTestDir, TEST_DIR } from "./testDir"; + + + export const mockFilename = "test.py"; export const mockPathAndCacheKey = { diff --git a/core/test/util/merge.test.ts b/core/test/util/merge.test.ts index a39a5bc30..cf7ba99d5 100644 --- a/core/test/util/merge.test.ts +++ b/core/test/util/merge.test.ts @@ -9,7 +9,7 @@ describe("mergeJson", () => { expect(result).toEqual({ a: 1, b: 3, c: 4 }); }); - it('should overwrite values when mergeBehavior is "overwrite"', () => { + it("should overwrite values when mergeBehavior is \"overwrite\"", () => { const first = { a: 1, b: 2 }; const second = { b: 3, c: 4 }; const result = mergeJson(first, second, "overwrite"); diff --git a/core/test/util/testDir.ts b/core/test/util/testDir.ts index d6bc462dc..62cbbb02c 100644 --- a/core/test/util/testDir.ts +++ b/core/test/util/testDir.ts @@ -1,6 +1,6 @@ import fs from "fs"; -import path from "path"; import os from "os"; +import path from "path"; // Want this outside of the git repository so we can change branches in tests export const TEST_DIR = path.join(os.tmpdir(), "testDir"); diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 097dac5d1..7804460c6 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,5 +1,7 @@ import fs from "node:fs"; + import { EmbeddingsProvider } from "../"; + import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { diff --git a/core/util/ca.ts b/core/util/ca.ts index 3890226c0..83d6f0c70 100644 --- a/core/util/ca.ts +++ b/core/util/ca.ts @@ -1,4 +1,5 @@ import { globalAgent } from "https"; + // @ts-ignore import { systemCertsAsync } from "system-ca"; diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 7a4f2d546..5f3d1bdc1 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -1,9 +1,11 @@ -import type { IMessenger } from "./messenger"; -import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import { ILLM, LLMFullCompletionOptions } from ".."; import { stripImages } from "../llm/images"; + import { removeQuotesAndEscapes } from "."; +import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; +import type { IMessenger } from "./messenger"; + /** * Removes code blocks from a message. * @@ -40,7 +42,7 @@ export class ChatDescriber { return; } - completionOptions.maxTokens = 24; + completionOptions.maxTokens = 6; // Prompt the user's current LLM for the title const titleResponse = await model.chat( diff --git a/core/util/dedent.test.ts b/core/util/dedent.test.ts index 3b0d526e1..95908ab4a 100644 --- a/core/util/dedent.test.ts +++ b/core/util/dedent.test.ts @@ -135,4 +135,21 @@ World expect(result).toBe("Hello\n\nWorld"); }); + + it("should work with templated strings", () => { + const language = "typescript"; + const code = "console.log('hello');\nconsole.log('world');"; + + const result = dedent` + This is the prefix of the file: + \`\`\`${language} + ${code} + \`\`\``; + + expect(result).toBe(`\ +This is the prefix of the file: +\`\`\`${language} +${code} +\`\`\``); + }); }); diff --git a/core/util/devdata.ts b/core/util/devdata.ts index fc223c6e2..12723e915 100644 --- a/core/util/devdata.ts +++ b/core/util/devdata.ts @@ -1,4 +1,5 @@ import { writeFileSync } from "fs"; + import { getDevDataFilePath } from "./paths.js"; export function logDevData(tableName: string, data: any) { diff --git a/core/util/devdataSqlite.ts b/core/util/devdataSqlite.ts index 103140c0d..bd9e45dca 100644 --- a/core/util/devdataSqlite.ts +++ b/core/util/devdataSqlite.ts @@ -1,7 +1,10 @@ import fs from "fs"; + import { open } from "sqlite"; import sqlite3 from "sqlite3"; + import { DatabaseConnection } from "../indexing/refreshIndex.js"; + import { getDevDataSqlitePath } from "./paths.js"; export class DevDataSqliteDb { diff --git a/core/util/fetchFavicon.ts b/core/util/fetchFavicon.ts index 8b1c8616a..54f6b362e 100644 --- a/core/util/fetchFavicon.ts +++ b/core/util/fetchFavicon.ts @@ -14,7 +14,7 @@ export async function findFaviconPath(url: URL): Promise { const document = dom.window.document; // Look for favicon in tags - const linkTags = document.querySelectorAll('link[rel*="icon"]'); + const linkTags = document.querySelectorAll("link[rel*=\"icon\"]"); for (const link of linkTags) { const href = link.getAttribute("href"); diff --git a/core/util/fetchWithOptions.ts b/core/util/fetchWithOptions.ts index f2e782266..1d2a8e94f 100644 --- a/core/util/fetchWithOptions.ts +++ b/core/util/fetchWithOptions.ts @@ -1,10 +1,13 @@ -import * as followRedirects from "follow-redirects"; -import { HttpProxyAgent } from "http-proxy-agent"; import { globalAgent } from "https"; -import { HttpsProxyAgent } from "https-proxy-agent"; -import fetch, { RequestInit, Response } from "node-fetch"; import * as fs from "node:fs"; import tls from "node:tls"; + +import * as followRedirects from "follow-redirects"; +import { HttpProxyAgent } from "http-proxy-agent"; +import { HttpsProxyAgent } from "https-proxy-agent"; +import fetch, { RequestInit, Response } from "node-fetch"; + + import { RequestOptions } from "../index.js"; const { http, https } = (followRedirects as any).default; diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 459e0adee..de71c15e2 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,5 +1,6 @@ import * as fs from "node:fs"; import * as path from "node:path"; + import { ContinueRcJson, FileType, @@ -14,8 +15,8 @@ import { Thread, ToastType, } from "../index.d.js"; - import { GetGhTokenArgs } from "../protocol/ide.js"; + import { getContinueGlobalPath } from "./paths.js"; class FileSystemIde implements IDE { diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts index fb4be85d7..0aa4db341 100644 --- a/core/util/generateRepoMap.ts +++ b/core/util/generateRepoMap.ts @@ -1,9 +1,11 @@ import fs from "node:fs"; import path from "node:path"; + import { IDE, ILLM } from ".."; import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; import { walkDirAsync } from "../indexing/walkDir"; import { pruneLinesFromTop } from "../llm/countTokens"; + import { getRepoMapFilePath } from "./paths"; export interface RepoMapOptions { diff --git a/core/util/history.ts b/core/util/history.ts index 08bc26994..f147c4e07 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -1,6 +1,8 @@ import * as fs from "fs"; + import { PersistedSessionInfo, SessionInfo } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; + import { getSessionFilePath, getSessionsListPath } from "./paths.js"; function safeParseArray( diff --git a/core/util/index.ts b/core/util/index.ts index 3de43957e..7f46278f9 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -276,31 +276,55 @@ export function deduplicateArray( export type TODO = any; export function dedent(strings: TemplateStringsArray, ...values: any[]) { - let result = strings.reduce( - (acc, str, i) => acc + str + (values[i] || ""), - "", - ); - result = result.replace(/^\n/, "").replace(/\n\s*$/, ""); + let raw = ""; + for (let i = 0; i < strings.length; i++) { + raw += strings[i]; + + // Handle the value if it exists + if (i < values.length) { + let value = String(values[i]); + // If the value contains newlines, we need to adjust the indentation + if (value.includes("\n")) { + // Find the indentation level of the last line in strings[i] + let lines = strings[i].split("\n"); + let lastLine = lines[lines.length - 1]; + let match = lastLine.match(/(^|\n)([^\S\n]*)$/); + let indent = match ? match[2] : ""; + // Add indentation to all lines except the first line of value + let valueLines = value.split("\n"); + valueLines = valueLines.map((line, index) => + index === 0 ? line : indent + line, + ); + value = valueLines.join("\n"); + } + raw += value; + } + } + + // Now dedent the full string + let result = raw.replace(/^\n/, "").replace(/\n\s*$/, ""); let lines = result.split("\n"); - // Remove leading white-space-only lines + // Remove leading/trailing blank lines while (lines.length > 0 && lines[0].trim() === "") { lines.shift(); } - - // Remove trailing white-space-only lines while (lines.length > 0 && lines[lines.length - 1].trim() === "") { lines.pop(); } - const minIndent = lines.reduce((min, line) => { - if (line.trim() === "") { - // Don't consider empty lines when calculating indentation - return min; - } - const match = line.match(/^\s*/); - return Math.min(min, match ? match[0].length : Infinity); - }, Infinity); + // Calculate minimum indentation (excluding empty lines) + let minIndent = lines.reduce((min: any, line: any) => { + if (line.trim() === "") return min; + let match = line.match(/^(\s*)/); + let indent = match ? match[1].length : 0; + return min === null ? indent : Math.min(min, indent); + }, null); - return lines.map((line) => line.slice(minIndent)).join("\n"); + if (minIndent !== null && minIndent > 0) { + // Remove the minimum indentation from each line + lines = lines.map((line) => line.slice(minIndent)); + } + + return lines.join("\n"); } diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 75c980809..b157a1078 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -1,3 +1,9 @@ +import { + GetGhTokenArgs, + ToIdeFromWebviewOrCoreProtocol, +} from "../protocol/ide.js"; +import { FromIdeProtocol } from "../protocol/index.js"; + import type { ContinueRcJson, FileType, @@ -11,11 +17,6 @@ import type { RangeInFile, Thread, } from "../index.js"; -import { - GetGhTokenArgs, - ToIdeFromWebviewOrCoreProtocol, -} from "../protocol/ide.js"; -import { FromIdeProtocol } from "../protocol/index.js"; export class MessageIde implements IDE { constructor( diff --git a/core/util/messenger.ts b/core/util/messenger.ts index 2b0593ef3..ea7efebed 100644 --- a/core/util/messenger.ts +++ b/core/util/messenger.ts @@ -1,4 +1,5 @@ import { v4 as uuidv4 } from "uuid"; + import type { IProtocol } from "../protocol/index.js"; export interface Message { diff --git a/core/util/paths.ts b/core/util/paths.ts index da20e0632..f8b70159f 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -1,8 +1,10 @@ -import * as JSONC from "comment-json"; -import dotenv from "dotenv"; import * as fs from "fs"; import * as os from "os"; import * as path from "path"; + +import * as JSONC from "comment-json"; +import dotenv from "dotenv"; + import { IdeType, SerializedContinueConfig } from "../"; import { defaultConfig, defaultConfigJetBrains } from "../config/default"; import Types from "../config/types"; diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 58828dacd..615f77b82 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -1,4 +1,5 @@ import os from "node:os"; + import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; diff --git a/core/util/reverseMessageIde.ts b/core/util/reverseMessageIde.ts index a42ece75c..256251f94 100644 --- a/core/util/reverseMessageIde.ts +++ b/core/util/reverseMessageIde.ts @@ -1,5 +1,6 @@ import { IDE } from "../index.js"; import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js"; + import { Message } from "./messenger.js"; export class ReverseMessageIde { diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index bf6891f23..b877a251b 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -1,5 +1,6 @@ import fs from "node:fs"; import * as path from "node:path"; + import Parser, { Language } from "web-tree-sitter"; export const supportedLanguages: { [key: string]: string } = { @@ -139,7 +140,7 @@ export enum TSQueryType { export async function getQueryForFile( filepath: string, - queryType: TSQueryType, + queryPath: string, ): Promise { const language = await getLanguageForFile(filepath); if (!language) { @@ -153,7 +154,7 @@ export async function getQueryForFile( ...(process.env.NODE_ENV === "test" ? ["extensions", "vscode", "tree-sitter"] : ["tree-sitter"]), - queryType, + queryPath, `${fullLangName}.scm`, ); if (!fs.existsSync(sourcePath)) { diff --git a/core/util/tts.ts b/core/util/tts.ts index 248c38518..9bde6e57c 100644 --- a/core/util/tts.ts +++ b/core/util/tts.ts @@ -1,5 +1,6 @@ -import os from "node:os"; import { exec, ChildProcess } from "child_process"; +import os from "node:os"; + import type { IMessenger } from "./messenger"; import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index bf968ad12..a5668786b 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -82,6 +82,18 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your ] ``` + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "nebius", + "model": "llama3.1-405b", + "apiKey": "[NEBIUS_API_KEY]" + } + ] + ``` + ### GPT-4o from OpenAI diff --git a/docs/docs/customize/model-providers/more/nebius.md b/docs/docs/customize/model-providers/more/nebius.md new file mode 100644 index 000000000..d4cfa344b --- /dev/null +++ b/docs/docs/customize/model-providers/more/nebius.md @@ -0,0 +1,36 @@ +# Nebius AI Studio + +You can get an API key from the [Nebius AI Studio API keys page](https://studio.nebius.ai/settings/api-keys) + +## Availible models + +Available models can be found on the [Nebius AI Studio models page](https://studio.nebius.ai/models/text2text) + +## Chat model + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "nebius", + "model": "llama3.1-405b", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Embeddings model + +Available models can be found on the [Nebius AI Studio embeddings page](https://studio.nebius.ai/models/embedding) + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "nebius", + "model": "BAAI/bge-en-icl", + "apiKey": "[API_KEY]" + } +} +``` diff --git a/docs/docs/introduction.md b/docs/docs/introduction.md index b3f6d87d6..64f83436d 100644 --- a/docs/docs/introduction.md +++ b/docs/docs/introduction.md @@ -15,7 +15,7 @@ keywords: ] --- -![Continue Logo](/img/intro.png) +![Continue Logo](../static/img/intro.png) **Continue is the leading open-source AI code assistant inside of [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)** diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index 52732288b..207011d64 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -31,7 +31,7 @@ const config = { // to replace "en" with "zh-Hans". i18n: { defaultLocale: "en", - locales: ["en"], + locales: ["en", "zh-CN"], }, themes: [], @@ -110,6 +110,10 @@ const config = { position: "right", className: "discord-navbar", }, + { + type: "localeDropdown", + position: "right", + }, ], }, footer: { @@ -384,6 +388,10 @@ const config = { to: "/customize/model-providers/more/watsonx", from: "/reference/Model Providers/watsonx", }, + { + to: "/customize/model-providers/more/nebius", + from: "/reference/Model Providers/nebius", + }, // Sidebar items that should route directly to a subpage { to: "/chat/how-to-use-it", diff --git a/docs/i18n/zh-CN/code.json b/docs/i18n/zh-CN/code.json new file mode 100644 index 000000000..09908d027 --- /dev/null +++ b/docs/i18n/zh-CN/code.json @@ -0,0 +1,440 @@ +{ + "theme.ErrorPageContent.title": { + "message": "页面已崩溃。", + "description": "The title of the fallback page when the page crashed" + }, + "theme.BackToTopButton.buttonAriaLabel": { + "message": "回到顶部", + "description": "The ARIA label for the back to top button" + }, + "theme.blog.archive.title": { + "message": "历史博文", + "description": "The page & hero title of the blog archive page" + }, + "theme.blog.archive.description": { + "message": "历史博文", + "description": "The page & hero description of the blog archive page" + }, + "theme.blog.paginator.navAriaLabel": { + "message": "博文列表分页导航", + "description": "The ARIA label for the blog pagination" + }, + "theme.blog.paginator.newerEntries": { + "message": "较新的博文", + "description": "The label used to navigate to the newer blog posts page (previous page)" + }, + "theme.blog.paginator.olderEntries": { + "message": "较旧的博文", + "description": "The label used to navigate to the older blog posts page (next page)" + }, + "theme.blog.post.paginator.navAriaLabel": { + "message": "博文分页导航", + "description": "The ARIA label for the blog posts pagination" + }, + "theme.blog.post.paginator.newerPost": { + "message": "较新一篇", + "description": "The blog post button label to navigate to the newer/previous post" + }, + "theme.blog.post.paginator.olderPost": { + "message": "较旧一篇", + "description": "The blog post button label to navigate to the older/next post" + }, + "theme.tags.tagsPageLink": { + "message": "查看所有标签", + "description": "The label of the link targeting the tag list page" + }, + "theme.colorToggle.ariaLabel": { + "message": "切换浅色/暗黑模式(当前为{mode})", + "description": "The ARIA label for the navbar color mode toggle" + }, + "theme.colorToggle.ariaLabel.mode.dark": { + "message": "暗黑模式", + "description": "The name for the dark color mode" + }, + "theme.colorToggle.ariaLabel.mode.light": { + "message": "浅色模式", + "description": "The name for the light color mode" + }, + "theme.docs.breadcrumbs.navAriaLabel": { + "message": "页面路径", + "description": "The ARIA label for the breadcrumbs" + }, + "theme.docs.DocCard.categoryDescription.plurals": { + "message": "{count} 个项目", + "description": "The default description for a category card in the generated index about how many items this category includes" + }, + "theme.docs.paginator.navAriaLabel": { + "message": "文件选项卡", + "description": "The ARIA label for the docs pagination" + }, + "theme.docs.paginator.previous": { + "message": "上一页", + "description": "The label used to navigate to the previous doc" + }, + "theme.docs.paginator.next": { + "message": "下一页", + "description": "The label used to navigate to the next doc" + }, + "theme.docs.tagDocListPageTitle.nDocsTagged": { + "message": "{count} 篇文档带有标签", + "description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.docs.tagDocListPageTitle": { + "message": "{nDocsTagged}「{tagName}」", + "description": "The title of the page for a docs tag" + }, + "theme.docs.versionBadge.label": { + "message": "版本:{versionLabel}" + }, + "theme.docs.versions.unreleasedVersionLabel": { + "message": "此为 {siteTitle} {versionLabel} 版尚未发行的文档。", + "description": "The label used to tell the user that he's browsing an unreleased doc version" + }, + "theme.docs.versions.unmaintainedVersionLabel": { + "message": "此为 {siteTitle} {versionLabel} 版的文档,现已不再积极维护。", + "description": "The label used to tell the user that he's browsing an unmaintained doc version" + }, + "theme.docs.versions.latestVersionSuggestionLabel": { + "message": "最新的文档请参阅 {latestVersionLink} ({versionLabel})。", + "description": "The label used to tell the user to check the latest version" + }, + "theme.docs.versions.latestVersionLinkLabel": { + "message": "最新版本", + "description": "The label used for the latest version suggestion link label" + }, + "theme.common.editThisPage": { + "message": "编辑此页", + "description": "The link label to edit the current page" + }, + "theme.common.headingLinkTitle": { + "message": "{heading}的直接链接", + "description": "Title for link to heading" + }, + "theme.lastUpdated.atDate": { + "message": "于 {date} ", + "description": "The words used to describe on which date a page has been last updated" + }, + "theme.lastUpdated.byUser": { + "message": "由 {user} ", + "description": "The words used to describe by who the page has been last updated" + }, + "theme.lastUpdated.lastUpdatedAtBy": { + "message": "最后{byUser}{atDate}更新", + "description": "The sentence used to display when a page has been last updated, and by who" + }, + "theme.navbar.mobileVersionsDropdown.label": { + "message": "选择版本", + "description": "The label for the navbar versions dropdown on mobile view" + }, + "theme.NotFound.title": { + "message": "找不到页面", + "description": "The title of the 404 page" + }, + "theme.tags.tagsListLabel": { + "message": "标签:", + "description": "The label alongside a tag list" + }, + "theme.AnnouncementBar.closeButtonAriaLabel": { + "message": "关闭", + "description": "The ARIA label for close button of announcement bar" + }, + "theme.admonition.caution": { + "message": "警告", + "description": "The default label used for the Caution admonition (:::caution)" + }, + "theme.admonition.danger": { + "message": "危险", + "description": "The default label used for the Danger admonition (:::danger)" + }, + "theme.admonition.info": { + "message": "信息", + "description": "The default label used for the Info admonition (:::info)" + }, + "theme.admonition.note": { + "message": "备注", + "description": "The default label used for the Note admonition (:::note)" + }, + "theme.admonition.tip": { + "message": "提示", + "description": "The default label used for the Tip admonition (:::tip)" + }, + "theme.admonition.warning": { + "message": "注意", + "description": "The default label used for the Warning admonition (:::warning)" + }, + "theme.blog.sidebar.navAriaLabel": { + "message": "最近博文导航", + "description": "The ARIA label for recent posts in the blog sidebar" + }, + "theme.CodeBlock.copied": { + "message": "复制成功", + "description": "The copied button label on code blocks" + }, + "theme.CodeBlock.copyButtonAriaLabel": { + "message": "复制代码到剪贴板", + "description": "The ARIA label for copy code blocks button" + }, + "theme.CodeBlock.copy": { + "message": "复制", + "description": "The copy button label on code blocks" + }, + "theme.CodeBlock.wordWrapToggle": { + "message": "切换自动换行", + "description": "The title attribute for toggle word wrapping button of code block lines" + }, + "theme.DocSidebarItem.expandCategoryAriaLabel": { + "message": "展开侧边栏分类 '{label}'", + "description": "The ARIA label to expand the sidebar category" + }, + "theme.DocSidebarItem.collapseCategoryAriaLabel": { + "message": "折叠侧边栏分类 '{label}'", + "description": "The ARIA label to collapse the sidebar category" + }, + "theme.NavBar.navAriaLabel": { + "message": "主导航", + "description": "The ARIA label for the main navigation" + }, + "theme.navbar.mobileLanguageDropdown.label": { + "message": "选择语言", + "description": "The label for the mobile language switcher dropdown" + }, + "theme.NotFound.p1": { + "message": "我们找不到您要找的页面。", + "description": "The first paragraph of the 404 page" + }, + "theme.NotFound.p2": { + "message": "请联系原始链接来源网站的所有者,并告知他们链接已损坏。", + "description": "The 2nd paragraph of the 404 page" + }, + "theme.TOCCollapsible.toggleButtonLabel": { + "message": "本页总览", + "description": "The label used by the button on the collapsible TOC component" + }, + "theme.blog.post.readingTime.plurals": { + "message": "阅读需 {readingTime} 分钟", + "description": "Pluralized label for \"{readingTime} min read\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.blog.post.readMore": { + "message": "阅读更多", + "description": "The label used in blog post item excerpts to link to full blog posts" + }, + "theme.blog.post.readMoreLabel": { + "message": "阅读 {title} 的全文", + "description": "The ARIA label for the link to full blog posts from excerpts" + }, + "theme.docs.sidebar.collapseButtonTitle": { + "message": "收起侧边栏", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.collapseButtonAriaLabel": { + "message": "收起侧边栏", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.breadcrumbs.home": { + "message": "主页面", + "description": "The ARIA label for the home page in the breadcrumbs" + }, + "theme.docs.sidebar.navAriaLabel": { + "message": "文档侧边栏", + "description": "The ARIA label for the sidebar navigation" + }, + "theme.docs.sidebar.closeSidebarButtonAriaLabel": { + "message": "关闭导航栏", + "description": "The ARIA label for close button of mobile sidebar" + }, + "theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": { + "message": "← 回到主菜单", + "description": "The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)" + }, + "theme.docs.sidebar.toggleSidebarButtonAriaLabel": { + "message": "切换导航栏", + "description": "The ARIA label for hamburger menu button of mobile navigation" + }, + "theme.docs.sidebar.expandButtonTitle": { + "message": "展开侧边栏", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.docs.sidebar.expandButtonAriaLabel": { + "message": "展开侧边栏", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.SearchBar.seeAll": { + "message": "查看全部 {count} 个结果" + }, + "theme.SearchPage.documentsFound.plurals": { + "message": "找到 {count} 份文件", + "description": "Pluralized label for \"{count} documents found\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.SearchPage.existingResultsTitle": { + "message": "「{query}」的搜索结果", + "description": "The search page title for non-empty query" + }, + "theme.SearchPage.emptyResultsTitle": { + "message": "在文档中搜索", + "description": "The search page title for empty query" + }, + "theme.SearchPage.inputPlaceholder": { + "message": "在此输入搜索字词", + "description": "The placeholder for search page input" + }, + "theme.SearchPage.inputLabel": { + "message": "搜索", + "description": "The ARIA label for search page input" + }, + "theme.SearchPage.algoliaLabel": { + "message": "通过 Algolia 搜索", + "description": "The ARIA label for Algolia mention" + }, + "theme.SearchPage.noResultsText": { + "message": "未找到任何结果", + "description": "The paragraph for empty search result" + }, + "theme.SearchPage.fetchingNewResults": { + "message": "正在获取新的搜索结果...", + "description": "The paragraph for fetching new search results" + }, + "theme.SearchBar.label": { + "message": "搜索", + "description": "The ARIA label and placeholder for search button" + }, + "theme.SearchModal.searchBox.resetButtonTitle": { + "message": "清除查询", + "description": "The label and ARIA label for search box reset button" + }, + "theme.SearchModal.searchBox.cancelButtonText": { + "message": "取消", + "description": "The label and ARIA label for search box cancel button" + }, + "theme.SearchModal.startScreen.recentSearchesTitle": { + "message": "最近搜索", + "description": "The title for recent searches" + }, + "theme.SearchModal.startScreen.noRecentSearchesText": { + "message": "没有最近搜索", + "description": "The text when no recent searches" + }, + "theme.SearchModal.startScreen.saveRecentSearchButtonTitle": { + "message": "保存这个搜索", + "description": "The label for save recent search button" + }, + "theme.SearchModal.startScreen.removeRecentSearchButtonTitle": { + "message": "从历史记录中删除这个搜索", + "description": "The label for remove recent search button" + }, + "theme.SearchModal.startScreen.favoriteSearchesTitle": { + "message": "收藏", + "description": "The title for favorite searches" + }, + "theme.SearchModal.startScreen.removeFavoriteSearchButtonTitle": { + "message": "从收藏列表中删除这个搜索", + "description": "The label for remove favorite search button" + }, + "theme.SearchModal.errorScreen.titleText": { + "message": "无法获取结果", + "description": "The title for error screen of search modal" + }, + "theme.SearchModal.errorScreen.helpText": { + "message": "你可能需要检查网络连接。", + "description": "The help text for error screen of search modal" + }, + "theme.SearchModal.footer.selectText": { + "message": "选中", + "description": "The explanatory text of the action for the enter key" + }, + "theme.SearchModal.footer.selectKeyAriaLabel": { + "message": "Enter 键", + "description": "The ARIA label for the Enter key button that makes the selection" + }, + "theme.SearchModal.footer.navigateText": { + "message": "导航", + "description": "The explanatory text of the action for the Arrow up and Arrow down key" + }, + "theme.SearchModal.footer.navigateUpKeyAriaLabel": { + "message": "向上键", + "description": "The ARIA label for the Arrow up key button that makes the navigation" + }, + "theme.SearchModal.footer.navigateDownKeyAriaLabel": { + "message": "向下键", + "description": "The ARIA label for the Arrow down key button that makes the navigation" + }, + "theme.SearchModal.footer.closeText": { + "message": "关闭", + "description": "The explanatory text of the action for Escape key" + }, + "theme.SearchModal.footer.closeKeyAriaLabel": { + "message": "Esc 键", + "description": "The ARIA label for the Escape key button that close the modal" + }, + "theme.SearchModal.footer.searchByText": { + "message": "搜索提供", + "description": "The text explain that the search is making by Algolia" + }, + "theme.SearchModal.noResultsScreen.noResultsText": { + "message": "没有结果:", + "description": "The text explains that there are no results for the following search" + }, + "theme.SearchModal.noResultsScreen.suggestedQueryText": { + "message": "试试搜索", + "description": "The text for the suggested query when no results are found for the following search" + }, + "theme.SearchModal.noResultsScreen.reportMissingResultsText": { + "message": "认为这个查询应该有结果?", + "description": "The text for the question where the user thinks there are missing results" + }, + "theme.SearchModal.noResultsScreen.reportMissingResultsLinkText": { + "message": "请告知我们。", + "description": "The text for the link to report missing results" + }, + "theme.SearchModal.placeholder": { + "message": "搜索文档", + "description": "The placeholder of the input of the DocSearch pop-up modal" + }, + "theme.blog.post.plurals": { + "message": "{count} 篇博文", + "description": "Pluralized label for \"{count} posts\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.blog.tagTitle": { + "message": "{nPosts} 含有标签「{tagName}」", + "description": "The title of the page for a blog tag" + }, + "theme.blog.author.pageTitle": { + "message": "{authorName} - {nPosts}", + "description": "The title of the page for a blog author" + }, + "theme.blog.authorsList.pageTitle": { + "message": "Authors", + "description": "The title of the authors page" + }, + "theme.blog.authorsList.viewAll": { + "message": "View All Authors", + "description": "The label of the link targeting the blog authors page" + }, + "theme.contentVisibility.unlistedBanner.title": { + "message": "未列出页", + "description": "The unlisted content banner title" + }, + "theme.contentVisibility.unlistedBanner.message": { + "message": "此页面未列出。搜索引擎不会对其索引,只有拥有直接链接的用户才能访问。", + "description": "The unlisted content banner message" + }, + "theme.contentVisibility.draftBanner.title": { + "message": "Draft page", + "description": "The draft content banner title" + }, + "theme.contentVisibility.draftBanner.message": { + "message": "This page is a draft. It will only be visible in dev and be excluded from the production build.", + "description": "The draft content banner message" + }, + "theme.ErrorPageContent.tryAgain": { + "message": "重试", + "description": "The label of the button to try again rendering when the React error boundary captures an error" + }, + "theme.common.skipToMainContent": { + "message": "跳到主要内容", + "description": "The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation" + }, + "theme.tags.tagsPageTitle": { + "message": "标签", + "description": "The title of the tag list page" + } +} diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-blog/options.json b/docs/i18n/zh-CN/docusaurus-plugin-content-blog/options.json new file mode 100644 index 000000000..9239ff706 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-blog/options.json @@ -0,0 +1,14 @@ +{ + "title": { + "message": "Blog", + "description": "The title for the blog used in SEO" + }, + "description": { + "message": "Blog", + "description": "The description for the blog used in SEO" + }, + "sidebar.title": { + "message": "Recent posts", + "description": "The label for the left sidebar" + } +} diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current.json b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current.json new file mode 100644 index 000000000..e4e781f70 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current.json @@ -0,0 +1,50 @@ +{ + "version.label": { + "message": "Next", + "description": "The label for version current" + }, + "sidebar.docsSidebar.category.Getting started": { + "message": "开始", + "description": "The label for category Getting started in sidebar docsSidebar" + }, + "sidebar.docsSidebar.category.Chat": { + "message": "聊天", + "description": "The label for category Chat in sidebar docsSidebar" + }, + "sidebar.docsSidebar.category.Autocomplete": { + "message": "自动补全", + "description": "The label for category Autocomplete in sidebar docsSidebar" + }, + "sidebar.docsSidebar.category.Edit": { + "message": "编辑", + "description": "The label for category Edit in sidebar docsSidebar" + }, + "sidebar.docsSidebar.category.Actions": { + "message": "Actions", + "description": "The label for category Actions in sidebar docsSidebar" + }, + "sidebar.docsSidebar.link.Customize": { + "message": "定制", + "description": "The label for link Customize in sidebar docsSidebar, linking to /customize/overview" + }, + "sidebar.customizingSidebar.category.Model providers": { + "message": "模型提供者", + "description": "The label for category Model providers in sidebar customizingSidebar" + }, + "sidebar.customizingSidebar.category.More": { + "message": "更多", + "description": "The label for category More in sidebar customizingSidebar" + }, + "sidebar.customizingSidebar.category.Model types": { + "message": "模型类型", + "description": "The label for category Model types in sidebar customizingSidebar" + }, + "sidebar.customizingSidebar.category.Deep dives": { + "message": "深入理解", + "description": "The label for category Deep dives in sidebar customizingSidebar" + }, + "sidebar.customizingSidebar.category.Tutorials": { + "message": "教程", + "description": "The label for category Tutorials in sidebar customizingSidebar" + } +} diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/context-selection.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/context-selection.md new file mode 100644 index 000000000..428aeb2df --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/context-selection.md @@ -0,0 +1,36 @@ +--- +title: 上下文选择 +description: Actions \-上下文选择 +keywords: [上下文, 斜杠, 调试, 快速修复, 右击] +sidebar_position: 3 +--- + +## 斜杠命令 + +斜杠命令可以与更多的指令结合,包括 [上下文提供者](chat/context-selection.md) 或 [高亮代码](chat/context-selection.md) 。 + +例如,使用 "/edit" 斜杠命令,你应该描述你想要 LLM 执行的编辑。 + +一些斜杠命令不会理会你的输入,例如, "/share" 斜杠命令只是创建一个当前交谈的 markdown 副本,忽略任何你请求它做的。 + +## 快速 action + +快速 action 总是显示在一个类和函数上,将会编辑那个类或函数,但是不会对外面的东西有影响。 + +## 右击 action + +你选择的高亮代码将会包含在你的提示词中,和一些基于选择的 action 提前写好的指令一起。这是模型想要尝试的仅有的代码块。 + +## 调试 action + +调试 action 选择最近运行的终端命令以及它的输出,然后插入以下提示词到聊天窗口中。没有更多的,不可见的信息发送给语言模型。 + +``` +I got the following error, can you please help explain how to fix it? + +[ERROR_MESSAGE] +``` + +## 快速修复 + +类似于调试 action ,快速 action 透明地添加提示词到聊天窗口中。当你选择 "Ask Continue" ,错误的上下 3 行会发送给聊天,跟上问题 "How do I fix the following problem in the above code?: [ERROR_MESSAGE]" 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-it-works.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-it-works.md new file mode 100644 index 000000000..9403093f8 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-it-works.md @@ -0,0 +1,12 @@ +--- +title: 它是如何工作的 +description: actions 是如何工作的 +keywords: [如何, 斜杠, 命令, 提示词, 右击, 快速修复, 调试, action] +sidebar_position: 4 +--- + +很多 action 基于模板提示词,可以使用 .prompt 文件配置,在底层有一些执行更复杂的代码。 + +action 生成行内 diff ,比如 "/edit", "/comment" 或右击 action ,使用与 [编辑](edit/how-it-works.md) 相同的提示词和响应处理逻辑。 + +要了解其他斜杠命令如何工作的, [在这里](../customize/slash-commands.md) 查看完整参考。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md new file mode 100644 index 000000000..940fedc65 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-customize.md @@ -0,0 +1,58 @@ +--- +title: 如何定制 +description: 如何定制 actions +keywords: [定制, actions] +sidebar_position: 5 +--- + +## 内置的斜杠命令 + +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。 + +## 定制斜杠命令 + +有两种方法添加定制斜杠命令: + +1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompt-files.md) 查看完整参考。 +2. 使用 `config.ts` - 这给你对于 LLM, IDE 和其他重要的入口可编程的访问,通过编写 JavaScript/TypeScript 函数 + +### 使用 `config.ts` 定制斜杠命令 + + + + +如果你想比使用自然语言编写定制命令更进一步,你可以编写一个定制函数返回响应。这需要使用 `config.ts` 替代 `config.json` 。 + +要做这个,放一个新的 `SlashCommand` 对象到 `slashCommands` 列表中。这个对象包含 "name" ,你输入用来触发斜杠命令的名字, "description", 在下拉菜单中看到的描述,以及 "run" 。 `run` 函数是任何异步生成器,应该生成你希望流式地返回到 UI 的字符串。作为这个函数的一个参数,你可以访问 `ContinueSDK` 对象实用工具,例如访问 IDE 中确定的信息/action ,当前的语言模型,以及一些其他的实用工具。例如,这是一个生成 commit 说明的斜杠命令: + +```typescript title="config.ts" +export function modifyConfig(config: Config): Config { + config.slashCommands?.push({ + name: "commit", + description: "Write a commit message", + run: async function* (sdk) { + const diff = await sdk.ide.getDiff(); + for await (const message of sdk.llm.streamComplete( + `${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`, + { + maxTokens: 20, + }, + )) { + yield message; + } + }, + }); + return config; +} +``` + + + + +## 其他定制 action + +目前,其他 action 触发器没有开放配置,但是我们计划在未来通过 .prompt 文件来允许。 + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md new file mode 100644 index 000000000..f265a9885 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/how-to-use-it.md @@ -0,0 +1,85 @@ +--- +title: Actions +description: 如何使用 Actions +sidebar_label: 如何使用它 +keywords: [如何, 斜杠, 命令, 提示词, 右击, 快速修复, 调试, 操作] +sidebar_position: 1 +--- + +![actions](/img/actions.gif) + +## 如何使用它 + +Actions 是常见用例的快捷方式。例如,你可能想要审查代码,编写测试,或添加一个文档字符串。 + +### 斜杠命令 + +最常见的调用 action 的方法是使用斜杠命令。通过输入 '/' 并在下拉框中选择,这里有快捷方式会被激活。例如,内置的 '/edit' 斜杠命令,让你可以直接在你的编辑器中流式地编辑。 + +![slash-commands](/img/slash-commands.png) + +一些最常用的斜杠命令默认是可用的,比如 "/edit", "/comment" 和 "/share" ,但是 Continue 有大量内置的其他选择的库。要启用它们,[在这里](../customize/slash-commands.md) 了解更多。 + +### prompt 文件 + +通过定义一个 ".prompt 文件" ,也可以编写你自己的斜杠命令。 prompt 文件可以是个简单的文本文件,但是也包含模板,所以你可以引用文件, URL ,高亮代码以及更多。 + +完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt-files.md) 。 + +:::tip[Prompt 库] +为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples) 。我们鼓励社区贡献到这个仓库,所以请考虑为你的 prompt 创建一个拉取请求! +::: + +以下是一个快速示例,设置一个使用 Jest 编写单元测试的 prompt 文件。 + +1. 在你的工作区的最高层级,创建一个名为 `.prompts/` 的目录。 +2. 在这个目录中,添加一个名为 `test.prompt` 的文件。这个文件的名称将是你用来生成提示词的斜杠命令的名称。 +3. 写入以下内容到 `test.prompt` 并保存。 + +``` +{{{ input }}} + +Write unit tests for the above selected code, following each of these instructions: +- Use `jest` +- Properly set up and tear down +- Include important edge cases +- The tests should be complete and sophisticated +- Give the tests just as chat output, don't edit any file +- Don't explain how to set up `jest` +``` + +现在要使用这个提示词,你可以高亮代码,并使用 `cmd/ctrl+L` 来选择它到 Continue 侧边栏中。 + +然后,输入 "/" 来查看斜杠命令列表,选择名为 "test" 的那个。按下回车, LLM 会响应你的 prompt 文件中给出的指令。 + +### action 的其他触发器 (VS Code) + +:::info +目前,所有这些只在 VS Code 中有效 +::: + +为了让常见用例更可用,我们提供了一些其他方法来触发 action 。 + +#### 快速 action + +快速 action 在你源码中的顶级类和函数上显示为按钮,让你可以一键触发 action 。它们也可以使用 .prompt 文件定制,来执行定制的 action 。 + +![quick-actions](/img/quick-actions.png) + +默认情况下,快速 action 是禁用的,但是可以在 VS Code 的设置中通过 "Continue: Enable Quick Actions" 启用。 + +#### 右击 action + +右击 action 让你高亮期望的代码区域,右击,然后在下拉菜单中选择一个 action 。 + +![context-menu](/img/context-menu.png) + +#### 调试 action + +调试 action 是 VS Code 扩展中一个特殊的内置键盘快捷方式。使用 `cmd/ctrl+shift+R` 来快速复制当前终端的内容到聊天侧边栏,并获得调试建议。 + +#### 快速修复 + +无论何时在你的代码中看到红色/黄色下划线表示错误,你可以把光标放到附近, VS Code 会显示一个灯泡图标。无论点击灯泡,或使用 `cmd/ctrl+.` 快捷键,将会显示一个快速修复的下拉菜单。其中之一是 "Ask Continue" action 。无论单击或再次使用 `cmd/ctrl+.` , Continue 将尝试帮助解决问题。 + +![ask-continue](/img/ask-continue.png) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/model-setup.md new file mode 100644 index 000000000..abfff3275 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/actions/model-setup.md @@ -0,0 +1,8 @@ +--- +title: 模型设置 +description: Actions 模型设置 +keywords: [模型] +sidebar_position: 2 +--- + +默认情况下, action 使用与 [聊天](chat/model-setup.mdx) 相同的模型,所以,对于执行的复杂指令,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/context-selection.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/context-selection.md new file mode 100644 index 000000000..4ae6f0a56 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/context-selection.md @@ -0,0 +1,24 @@ +--- +title: 上下文选择 +description: 自动补全上下文选择 +keywords: [上下文, 自动补全, lsp, 最近的] +sidebar_position: 3 +--- + +自动补全会基于当前的光标位置自动地确定上下文。我们使用以下的技术来确定什么包含在提示词中: + +### 文件前缀/后缀 + +我们总是包含你的文件中光标前后的代码。 + +### 来自语言服务协议的定义 + +类似于你如何在编辑器中使用 `cmd/ctrl + click` ,我们使用相同的工具 (LSP) 来增强 "转到定义" 。例如,如果你输入一个函数调用,我们将包含函数定义。或者,如果你在一个方法中写代码,我们将包含类型定义中的任何参数或返回类型。 + +### 导入文件 + +因为通常有很多导入,我们不能包含它们所有。相反,我们查找你的光标附近的标识,使用它所匹配的导入作为上下文。 + +### 最近的文件 + +我们自动考虑最近打开的或编辑的文件,并包含与当前补全相关的片段。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-it-works.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-it-works.md new file mode 100644 index 000000000..44c6c07c4 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-it-works.md @@ -0,0 +1,33 @@ +--- +title: 它是如何工作的 +description: 自动补全是如何工作的 +keywords: [如何, 自动补全, 上下分] +sidebar_position: 4 +--- + +自动补全是一个 [复合人工智能系统](https://bair.berkeley.edu/blog/2024/02/18/compound-ai-systems/),使用检索方法和响应处理技术的结合。系统可以大致理解为三个部分。 + +## 时机 + +为了快速地显示建议,并且不需要发送太多请求,我们做了下面这些: + +- 去抖动: 如果你快速输入,我们不会为每个按键创建一个请求。相反,我们等待直到你完成输入。 +- 缓存: 如果你的光标在一个我们已经生成补全的位置,这个补全将会被使用。例如,如果你回退,我们将可以直接显示你之前看到的建议。 + +## 上下文 + +就像 [上下文选择](context-selection.md) 页面解释的那样, Continue 使用了大量的检索方法,来查找你的代码库中相关的片断,包含在提示词中。 + +## 过滤 + +语言模型不是完美的,但是可以通过调整它们的输出接近完美。在显示建议之前,我们对响应做了大量的后处理,包括: + +- 过滤出指定的 token +- 当重新生成代码时,提前停止 +- 修复缩进 + +如果响应是坏的,我们也会偶尔过滤掉整个响应。这通常是因为过度的重复。 + +You can learn more about how it works in the [Autocomplete deep dive](../customize/deep-dives/autocomplete.md). + +你可以在 [深入理解自动补全](../customize/deep-dives/autocomplete.md) 中了解它是如何工作的。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md new file mode 100644 index 000000000..5e7b8fad2 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-customize.md @@ -0,0 +1,24 @@ +--- +title: 如何定制 +description: 如何定制自动补全 +keywords: [定制] +sidebar_position: 5 +--- + +Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: + +```json title="config.json" + "tabAutocompleteOptions": { + "useCopyBuffer": false, + "maxPromptTokens": 400, + "prefixPercentage": 0.5, + "multilineCompletions": "always" + } +``` + +- `useCopyBuffer`: 决定剪贴板的内容是否包含在提示词构建中 +- `maxPromptTokens`: 设置提示词的最大 token 数,平衡上下文和速度 +- `prefixPercentage`: 决定提示词使用光标前代码的比例 +- `multilineCompletions`: 控制建议是否可以跨多行 ("always", "never" 或 "auto") + +对于所有配置选项和它们的影响的综合指南,查看 [深入理解自动补全](../customize/deep-dives/autocomplete.md) 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-use-it.md new file mode 100644 index 000000000..d649ae3c9 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/how-to-use-it.md @@ -0,0 +1,25 @@ +--- +title: 自动补全 +description: 自动补全 \- 如何使用它 +sidebar_label: 如何使用它 +keywords: [如何] +sidebar_position: 1 +--- + +![autocomplete](/img/autocomplete.gif) + +## 如何使用它 + +自动补全随着你的输入提供行内代码建议。要启用它,只需要简单地点击状态栏中的 "Continue" 按钮,在你的 IDE 右下侧,或者在你的 IDE 设置中勾选 "启用 Tab 自动补全" 选项。 + +### 接受整个建议 + +按下 `Tab` ,接受整个建议 + +### 拒绝整个建议 + +按下 `Esc` ,拒绝整个建议 + +### 部分接受建议 + +对于更细粒度的控制,使用 `cmd/ctrl + →` 来逐字地接受部分建议。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md new file mode 100644 index 000000000..01747b24c --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/autocomplete/model-setup.md @@ -0,0 +1,52 @@ +--- +title: 模型设置 +description: 自动补全 \- 模型设置 +keywords: [模型, 自动补全] +sidebar_position: 2 +--- + +## 最好的总体体验 + +为了最好的自动补全体验,我们推荐通过 [Mistral API](https://console.mistral.ai/) 使用 Codestral 。这个模型提供高质量的补全,使用极好的代码上下文理解: + +```json title="config.json"" +{ + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "YOUR_API_KEY" + } +} +``` + +:::tip[Codestral API Key] +Codestral 的 API key 和通常的 Mistral API 是不同的。如果你使用 Codestral ,你可能想要一个 Codestral API key ,但是如果你想分享 key 给团队或其他人想要使用 `api.mistral.ai` ,那么确保在你的 `tabAutocompleteModel` 中设置 `"apiBase": "https://api.mistral.ai/v1"` 。 +::: + +## 本地的,离线的/自托管的体验 + +对于倾向于本地执行或自托管的, `StarCoder2-3b` 提供了一个对于大多数用户性能和质量的平衡: + +```json title="config.json"" +{ + "tabAutocompleteModel": { + "title": "StarCoder2-3b", + "model": "starcoder2:3b", + "provider": "ollama" + } +} +``` + +## 可替代的体验 + +- 补全太慢?在更弱的机器上,试试 `deepseek-coder:1.3b-base` 更快的补全 +- 有更多的计算?使用 `deepseek-coder:6.7b-base` 获取可能更高质量的建议 + +:::note +对于 LM Studio 用户,导航到 "My Models" 章节,找到你想要的模型,复制它的路径 (例如, second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf) 。使用这个路径作为你的配置中的 `model` 值。 +::: + +## 其他体验 + +有很多更多的模型或提供者可以用来补全。在 [这里](../customize/model-types/autocomplete.md) 查看它们。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md new file mode 100644 index 000000000..761554eb6 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/context-selection.md @@ -0,0 +1,46 @@ +--- +title: 上下文选择 +description: 如何为聊天选择上下文 +keywords: [上下文] +sidebar_position: 3 +--- + +## 输入 + +输入一个问题或指令到输入框中是仅有的必须的上下文。所有列在下面选择和包含更多上下文的其他方法都是可选的。 + +## 高亮代码 + +你通过按下 `cmd/ctrl + L` (VS Code) 或 `cmd/ctrl + J` (JetBrains) 选择的高亮代码,将包含在你的提示词中,和你提供的输入一起。这是提供给模型的仅有的代码片段,除非你高亮更多的片段,或使用以下的选择方法之一。 + +## 活动文件 + +在发送请求时,你可以通过按下 `cmd/ctrl + opt + enter` 包含当前打开的文件作为上下文。 + +## 指定文件 + +你可以通过输入 [`@Files`](../customize/context-providers.md#files) 并选择文件,包含当前工作区中的指定文件作为上下文。 + +## 指定目录 + +你可以通过输入 [`@Folder`](../customize/context-providers.md#folders) 并选择目录,包含当前工作区中指定目录作为上下文。它像 [`@Codebase`](../customize/deep-dives/codebase.md) 一样工作,但是只包含指定目录中的文件。 + +## 整个代码库 + +你可以通过输入 [`@Codebase`](../customize/context-providers.md#codebase-retrieval) 包含整个代码库作为上下文。你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的。 + +## 文档网址 + +你可以通过输入 [`@Docs`](../customize/context-providers.md#documentation) 并选择文档网址,包含文档网址作文上下文。你可以 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 是如何工作的。 + +## 终端内容 + +你可以通过输入 [`@Terminal`](../customize/context-providers.md#terminal) ,包含 IDE 中终端的内容作为上下文。 + +## Git diff + +你可以通过输入 [`@Git Diff`](../customize/context-providers.md#git-diff) ,包含当前分支中你做的所有变更作为上下文。 + +## 其他上下文 + +你可以 [在这里](../customize/context-providers.md) 看到完整的内置上下文提供者列表,以及 [在这里](../customize/tutorials/build-your-own-context-provider.md) 看到如何创建你自己定制的上下文提供者。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-it-works.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-it-works.md new file mode 100644 index 000000000..87323824a --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-it-works.md @@ -0,0 +1,16 @@ +--- +title: 它是如何工作的 +description: 聊天是如何工作的 +keywords: [如何, 聊天, 工作] +sidebar_position: 4 +--- + +使用任何选择的代码片段,你使用 @ 选择的所有上下文,以及你的输入指令,在侧边栏中,我们将提示词给模型,让它提供一个响应。如果你询问跟进的问题,那么所有前面的会话上下文也会被包含。没有其他更多的上下文提供给模型。 + +模型的响应会直接流式地返回到侧边栏。每个响应中的代码片段将放在它自己的代码块中,每个代码块会给你一些按钮,“应用到当前文件”, “插入到光标处” 或 “复制” 。当你在会话的结尾按下 `cmd/ctrl + L` (VS Code) 或 `cmd/ctrl + J` (JetBrains) ,所有上下文会被清除,一个新的会话将会开始,让你可以开始一个新的任务。 + +如果你想查看聊天中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](troubleshooting.md#llm-prompt-logs) 。 + +You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md). + +你可以 [在这里](../customize/deep-dives/codebase.md) 了解 `@Codebase` 是如何工作的, 以及 [在这里](../customize/deep-dives/docs.md) 了解 `@Docs` 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-to-customize.md new file mode 100644 index 000000000..ed56b125c --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-to-customize.md @@ -0,0 +1,13 @@ +--- +title: 如何定制 +description: 如何定制聊天 +keywords: [定制, 聊天] +sidebar_position: 5 +--- + +这里有多种不同的方法来定制聊天 + +- 你可以配置 [`@Codebase`](../customize/deep-dives/codebase.md) +- 你可以创建自己的 [定制代码 RAG](../customize/tutorials/custom-code-rag.md) +- 你可以配置 [`@Docs`](../customize/deep-dives/docs.md) +- 你可以 [构建自己的上下文提供者](../customize/tutorials/build-your-own-context-provider.md) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-to-use-it.md new file mode 100644 index 000000000..ce2acac9d --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/how-to-use-it.md @@ -0,0 +1,39 @@ +--- +title: 聊天 +description: 如何使用聊天 +sidebar_label: 如何使用它 +keywords: [如何, 使用, 聊天] +sidebar_position: 1 +--- + +![chat](/img/chat.gif) + +## 如何使用它 + +聊天方便向 LLM 寻求帮助,而不需要离开 IDE 。你发送一个任务给它,包含任何相关信息,它回复最可能完成那个任务的文本或代码。如果它没有给出你想要的,那么你可以发送追加的消息,来明确和调整它的建议,直到任务完成。 + +聊天最好用来理解和迭代代码或者作为搜索引擎查询的替代。 + +## 输入请求并按下回车 + +你发送一个问题给它,它回复答案。你告诉它解决一个问题,它提供一个解决方案。你请求一些代码,它生成代码。 + +## 高亮代码片段作为上下文 + +你使用鼠标选择代码片段,按下 `cmd/ctrl + L` (VS Code) 或 `cmd/ctrl + J` (JetBrains) 将它发送给 LLM ,然后让它给你解释,或者请求它以某种方式优化。 + +## 使用 @ 符号标记上下文 + +如果有来自代码库,文档, IDE 或其他工具的信息,你想要包含在上下文中,你可以输入 @ 来选择和包含它作为上下文。你可以在 [聊天上下文选择](context-selection.md) 中了解更多关于如何使用这个。 + +## 应用生成的代码到你的文件中 + +当 LLM 回复编辑到文件中,你可以点击 “应用” 按钮。这将更新编辑器中存在的代码,对建议的变更作出反应。 + +## 对于新的任务开始一个新的会话 + +一旦你完成任务,想要开始一个新的,按下 `cmd/ctrl + L` (VS Code) 或 `cmd/ctrl + J` (JetBrains) 来开始一个新的会话,确保只有下一个任务相关的上下文提供给 LLM 。 + +## 在不同的模型中切换 + +如果你配置了多个模型,你可以使用下拉框或按下 `cmd/ctrl + ’`在不同的模型中切换。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx new file mode 100644 index 000000000..fe24f18fb --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/chat/model-setup.mdx @@ -0,0 +1,184 @@ +--- +title: 模型设置 +description: 如何设置一个聊天模型 +keywords: [模型] +sidebar_position: 2 +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +:::info +这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。 +::: + +## 最好的总体体验 + +为了最好的总体聊天体验,你将想要使用一个 400B+ 参数模型或领先的模型之一。 + +### 来自 Anthropic 的 Claude Sonnet 3.5 + +我们现在最推荐的是来自 [Anthropic](../customize/model-providers/top-level/anthropic.md) 的 Claude Sonnet 3.5 。 + +```json title="config.json" + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "anthropic", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "[ANTHROPIC_API_KEY]" + } + ] +``` + +### 来自 Meta 的 Llama 3.1 405B + +如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。 + + + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "together", + "model": "llama3.1-405b", + "apiKey": "[TOGETHER_API_KEY]" + } + ] + ``` + + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "groq", + "model": "llama3.1-405b", + "apiKey": "[GROQ_API_KEY]" + } + ] + ``` + + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "vllm", + "model": "llama3.1-405b" + } + ] + ``` + + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 405B", + "provider": "ollama", + "model": "llama3.1-405b" + } + ] + ``` + + + +### 来自 OpenAI 的 GPT-4o + +如果你倾向于使用来自 [OpenAI](../customize/model-providers/top-level/openai.md) 的模型,那么我们推荐 GPT-4o 。 + +```json title="config.json" + "models": [ + { + "title": "GPT-4o", + "provider": "openai", + "model": "", + "apiKey": "[OPENAI_API_KEY]" + } + ] +``` + +### 来自 Google 的 Gemini 1.5 Pro + +如果你倾向于使用来自 [Google](../customize/model-providers/top-level/gemini.md) 的模型,那么我们推荐 Gemini 1.5 Pro 。 + +```json title="config.json" + "models": [ + { + "title": "Gemini 1.5 Pro", + "provider": "gemini", + "model": "gemini-1.5-pro-latest", + "apiKey": "[GEMINI_API_KEY]" + } + ] +``` + +## 本地的,离线的体验 + +为了最好的本地的,离线的聊天体验,你想要你的机器上使用一个大的但是足够快的模型。 + +### Llama 3.1 8B + +如果你的本地机器可以运行一个 8B 参数的模型,那么我们推荐在你的机器上运行 Llama 3.1 8B (比如使用 [Ollama](../customize/model-providers/top-level/ollama.md) 或 [LM Studio](../customize/model-providers/more/lmstudio.md))。 + + + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "ollama", + "model": "llama3.1-8b" + } + ] + ``` + + + ```json title="config.json" + "models": [ + { + "title": "Llama 3.1 8B", + "provider": "lmstudio", + "model": "llama3.1-8b" + } + ] + ``` + + + +### DeepSeek Coder 2 16B + +如果你的机器可以运行一个 16B 参数的模型,那么我们推荐运行 DeepSeek Coder 2 16B (比如使用 [Ollama](../customize/model-providers/top-level/ollama.md) 或 [LM Studio](../customize/model-providers/more/lmstudio.md))。 + + + + ```json title="config.json" + "models": [ + { + "title": "DeepSeek Coder 2 16B", + "provider": "ollama", + "model": "deepseek-coder-v2:16b" + } + ] + ``` + + + + + ```json title="config.json" + "models": [ + { + "title": "DeepSeek Coder 2 16B", + "provider": "lmstudio", + "model": "deepseek-coder-v2:16b" + } + ] + ``` + + + + +## 其他体验 + +除了以上提到的这些,还有更多的模型和提供者,你可以使用来聊天。在 [这里](../customize/model-types/chat.md) 了解更多。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx new file mode 100644 index 000000000..ab9b5cb58 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/changelog.mdx @@ -0,0 +1,30 @@ +--- +title: 变更日志 +description: VSCode 和 JetBrains 扩展最新版本的变更日志 +keywords: [变更日志] +hide_table_of_contents: true +--- + +import VSCodeChangelog from "../../../../../../extensions/vscode/CHANGELOG.md"; +import JetBrainsChangelog from "../../../../../../extensions/intellij/CHANGELOG.md"; + +以下是 VSCode 和 JetBrains 扩展最新版本的变更日志。在 2024-07-02 之前,变更日志没有反映所有更新。 + +import TOCInline from "@theme/TOCInline"; + + + node.value === "VSCode Changelog" || node.value === "JetBrains Changelog", + )} +/> + +
    + +## VSCode 变更日志 + + + +## JetBrains 变更日志 + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/config.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/config.mdx new file mode 100644 index 000000000..95f05dba5 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/config.mdx @@ -0,0 +1,22 @@ +--- +title: config.json 参考 +keywords: [config.json, 配置, 选项] +--- + +import Schema from "@site/static/schemas/config.json"; +import JSONSchemaViewer from "@theme/JSONSchemaViewer"; + +# 配置选项 + +以下显示在 `config.json` 定义的 JSON Schema 。 + +你还可以定义部分的 `config.json` 对象,在一个在你的工作区根目录名为 `.continuerc.json` 的文件中。这将应用在来自 `config.json` 的任何配置之上。 + + + +[查看源码](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/context-providers.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/context-providers.md new file mode 100644 index 000000000..e8667ae57 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/context-providers.md @@ -0,0 +1,487 @@ +--- +title: 上下文提供者 +description: 输入 '@' 选择内容到 LLM 作为上下文 +keywords: [上下文, "@", 提供者, LLM] +--- + +上下文提供者允许你输入 '@' ,看到一个上下文下拉框,都可以提供给 LLM 作为上下文。每个上下文提供者是一个插件,也就是说,如果你想要关联一些没有在这里看到的信息源,你可以请求(或构建!)一个新的上下文提供者。 + +举一个例子,比如你工作在解决一个新的 GitHub Issue 。你输入 '@Issue' 并选择你工作的那个。 Continue 现在可以看到 issue 标题和内容。你还知道那个 issue 关联到文件 'readme.md' 和 'helloNested.py' ,所以你输入 '@readme' 和 '@hello' 查看并选择它们。现在,这里有 3 个 "上下文条目" 在行内显示,和你的其他输入一起。 + +![上下文条目](/img/context-provider-example.png) + +## 内置的上下文提供者 + +为了使用任何内置的上下文提供者,打开 `config.json` 并将它添加到 `contextProviders` 列表中。 + +### `@File` + +关联你的当前工作区的任何文件。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "file" + } + ] +} +``` + +### `@Code` + +关联你的项目中特定的函数或类。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code" + } + ] +} +``` + +### `@Git Diff` + +关联你对当前分支所在的所有修改。这是有用的,如果你想要在提交之前,总结你做了什么,或询问一个关于你的工作通用的评审。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "diff" + } + ] +} +``` + +### `@Terminal` + +关联你的 IDE 终端的内容。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "terminal" + } + ] +} +``` + +### `@Docs` + +关联任何文档网站的内容。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "docs" + } + ] +} +``` + +注意这只启用 `@Docs` 上下文提供者。 + +为了使用它,你需要添加一个文档网站到你的 `config.json` 。查看 [docs](../customize/deep-dives/docs.md) 页面获取更多信息。 + +### `@Open` + +关联你打开的所有文件的内容。设置 `onlyPinned` 为 `true` 只关联固定的文件。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "open", + "params": { + "onlyPinned": true + } + } + ] +} +``` + +### `@Codebase` + +关联你的代码库中最相关的片段。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "codebase" + } + ] +} +``` + +在 [这里](../customize/deep-dives/codebase.md) 查看更多关于索引和检索。 + +### `@Folder` + +使用和 `@Codebase` 相同的检索机制,但是只在一个单独的文件夹上。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "folder" + } + ] +} +``` + +### `@Search` + +关联代码库搜索的结果,就像你从 VS Code 搜索获得的结果。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "search" + } + ] +} +``` + +这个上下文提供者是由 [ripgrep](https://github.com/BurntSushi/ripgrep) 支持的。 + +### `@Url` + +关联给定 URL 的 markdown 转换内容。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "url" + } + ] +} +``` + +### `@Tree` + +关联你当前工作区的结构。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "tree" + } + ] +} +``` + +### `@Google` + +关联 Google 搜索的结果。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "google", + "params": { + "serperApiKey": "" + } + } + ] +} +``` + +例如,输入 "@Google python tutorial" ,如果你想要搜索或讨论学习 Python 的方法。 + +注意:你可以在 [serper.dev](https://serper.dev) 免费获得 API key 。 + +### `@Issue` + +关联一个 GitHub issue 的交谈信息。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "issue", + "params": { + "repos": [ + { + "owner": "continuedev", + "repo": "continue" + } + ], + "githubToken": "ghp_xxx" + } + } + ] +} +``` + +确保包含你自己的 [GitHub 个人访问 token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) 来避免频率限制。 + +### `@Gitlab Merge Request` + +关联一个 Gitlab 上这个分支上打开的 MR 。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "gitlab-mr", + "params": { + "token": "..." + } + } + ] +} +``` + +你需要创建一个使用 `read_api` 范围的 [个人访问 token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html)。 + +#### 使用自托管的 GitLab + +你可以指定要访问的域名,通过在你的配置中设置 `domain` 参数。默认情况下是 `gitlab.com` 。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "gitlab-mr", + "params": { + "token": "...", + "domain": "gitlab.example.com" + } + } + ] +} +``` + +#### 过滤评论 + +如果你选择一些代码被编辑,你可以有上下文提供者过滤其他文件的评论。要启用这个特性,设置 `filterComments` 为 `true` 。 + +### `@Jira` + +关联一个 Jira issue 的交谈信息。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "jira", + "params": { + "domain": "company.atlassian.net", + "token ": "ATATT..." + } + } + ] +} +``` + +确认包含你自己的 [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens) ,或者使用你的 `email` 和 `token` , token 设置为你的密码获得基本认证。如果你使用自己的 Atlassian API Token ,不要配置你的邮箱。 + +#### Jira Datacenter 支持 + +这个上下文提供者支持 Jira API 版本 2 和 3 。默认情况下,它将使用版本 3 ,因为这是云版本使用的,但是如果你有 datacenter 版本的 Jira ,你需要使用 `apiVersion` 属性设置 API Version 为 2 。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "jira", + "params": { + "apiVersion": "2" + } + } + ] +} +``` + +#### Issue 查询 + +默认情况下,以下查询用来查找 issue : + +```jql +assignee = currentUser() AND resolution = Unresolved order by updated DESC +``` + +你可以覆盖这个查询,通过设置 `issueQuery` 参数。 + +### `@Postgres` + +关联表的 schema ,和一些示例行 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "postgres", + "params": { + "host": "localhost", + "port": 5436, + "user": "myuser", + "password": "catsarecool", + "database": "animals", + "schema": "public", + "sampleRows": 3 + } + } + ] +} +``` + +仅需要的配置是那些创建数据库连接所需要的: `host`, `port`, `user`, `password` 和 `database` 。 + +默认情况下, `schema` 过滤器设置为 `public` , `sampleRows` 设置为 3 。你可以取消设置 schema ,如果你想要包含所有 schema 的表。 + +[这是一个简单的 demo](https://github.com/continuedev/continue/pull/859) 。 + +### `@Database` + +关联 Sqlite, Postgres 和 MySQL 数据库的表 schema 。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "database", + "params": { + "connections": [ + { + "name": "examplePostgres", + "connection_type": "postgres", + "connection": { + "user": "username", + "host": "localhost", + "database": "exampleDB", + "password": "yourPassword", + "port": 5432 + } + }, + { + "name": "exampleSqlite", + "connection_type": "sqlite", + "connection": { + "filename": "/path/to/your/sqlite/database.db" + } + } + ] + } + } + ] +} +``` + +每个连接应该有一个单独的名称,`connection_type` ,以及每个数据库类型特定的必须的连接参数。 + +可用的连接类型: + +- `postgres` +- `mysql` +- `sqlite` + +### `@Locals` + +关联调试器中本地变量的内容。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "locals", + "params": { + "stackDepth": 3 + } + } + ] +} +``` + +使用最多 _n_ 级 (默认是 3) 的当前线程的调用栈。 + +### `@Repository Map` + +关联你的代码库的概览。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "repo-map" + } + ] +} +``` + +提供一个文件列表,以及这些文件中的最高级的类、函数和方法的调用签名。这帮助模型更好地理解,一段特定的代码如何关联其他的代码库。 + +在出现的子菜单中,你可以选择 `Entire codebase` 或指定一个子文件夹,来生成仓库映射。 + +这个上下文提供者想法来自 [Aider's repository map](https://aider.chat/2023/10/22/repomap.html) 。 + +### `@Operating System` + +关联你当前操作系统的架构和平台。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "os" + } + ] +} +``` + +### `@HTTP` + +HttpContextProvider 创建一个 POST 请求到配置中的 url 。服务器必须返回 200 OK ,以及一个 ContextItem 对象或一个 ContextItems 列表。 + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "http", + "params": { + "url": "https://api.example.com/v1/users", + } + } + ] +} +``` + +接收的 URL 应该接收下面的参数: +```json title="POST parameters" +{ + query: string, + fullInput: string +} +``` + +响应 200 OK 应该是一个有以下结构的 JSON 对象: +```json title="Response" +[ + { + "name": "", + "description": "", + "content": "" + } +] + +// OR +{ + "name": "", + "description": "", + "content": "" +} +``` + +### 请求上下文提供者 + +没有看到你想要的?[在这里](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) 创建一个 issue 来请求一个新的上下文提供者。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md new file mode 100644 index 000000000..ea07525ee --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -0,0 +1,147 @@ +--- +title: 自动补全 +keywords: [自动补全] +--- + +### 设置 Codestral (推荐) + +如果你想要有最好的自动补全体验,我们推荐使用 Codestral ,它可以通过 [Mistral API](https://console.mistral.ai/) 使用。要做这个,获取一个 API key 并把它添加到你的 `config.json` 中: + +```json +{ + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "YOUR_API_KEY" + } +} +``` + +### 设置 Ollama (默认) + +如果你想要本地运行自己的自动补全模型,我们推荐使用 Ollama 。要做这个,首先从 [这里](https://ollama.ai) 下载最新版的 Ollama 。然后,运行下面的命令下载我们推荐的模型: + +```bash +ollama run starcoder2:3b +``` + +一旦它下载完成,你应该可以再 VS Code 中看到补全。 + +### 设置自定义模型 + +所有配置选项对聊天可用的模型对 tab 自动补全可用。例如,如果你想要使用一个远程 Ollama 实例,你应该编辑你的 `config.json` 像这样(注意,它不在 models 列表中): + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Tab Autocomplete Model", + "provider": "ollama", + "model": "starcoder2:3b", + "apiBase": "https://" + }, + ... +} +``` + +如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。 + +## 配置选项 + +以下可以在 `config.json` 配置: + +### `tabAutocompleteModel` + +这是另一个对象,就像 `config.json` 中的 `"models"` 列表。你可以选择和配置任何你想要的模型,但是我们强烈建议使用针对 tab 自动补全的小的模型,例如 `deepseek-1b`, `starcoder-1b` 或 `starcoder2-3b` 。 + +### `tabAutocompleteOptions` + +这个对象允许你定制 tab 自动补全的行为。可用的选项显示在下面,你可以在 [这里](https://github.com/continuedev/continue/blob/fbeb2e4fe15d4b434a30a136f74b672485c852d9/core/util/parameters.ts) 找到它们的默认值。 + +- `disable`: 禁用自动补全(也可以在 IDE 配置中完成) +- `template`: 一个用来自动补全的可选的模板字符串。它使用 Mustache 模板语言渲染,并且传递 'prefix' 和 'suffix' 变量。(字符串) +- `useCopyBuffer`: 决定 copy buffer 是否考虑为构建提示词。(布尔型) +- `useFileSuffix`: 决定是否使用文件后缀在提示词中。(布尔型) +- `maxPromptTokens`: 提示词使用的 token 的最大数量。一个较小的数字生成较快的补全,但是较少的上下文。(数字) +- `prefixPercentage`: 输入专注于前缀的百分比。(数字) +- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) +- `maxSuffixPercentage`: 提示词专注于后缀的最大百分比。(数字) +- `debounceDelay`: 在按键之后触发自动补全的毫秒延迟。(数字) +- `multilineCompletions`: 是否启用多行补全 ("always", "never" 或 "auto") 。默认情况下是 "auto" 。 +- `useCache`: 是否缓存和重新使用补全,当提示词与前一个相同时。对于测试的目的可能是有用的。 +- `useOtherFiles`: 是否包含当前文件之外的文件的上下文。关闭这个预期会减少补全的准确性,但是对于测试可能是有用的。 +- `disableInFiles`: 一个你想要禁用 tab 自动补全的 glob 模式的文件列表。 + +### 完整示例 + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Tab Autocomplete Model", + "provider": "ollama", + "model": "starcoder2:3b", + "apiBase": "https://" + }, + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +## 常见问题 + +### 我想要更好的补全,是否应该使用 GPT-4 ? + +可能出乎意料,答案是否定的。我们推荐的自动补全模型是通过高度特定提示词格式训练的,这运行它们响应请求来补全代码(在 [这里](https://github.com/continuedev/continue/blob/d2bc6359e8ebf647892ec953e418042dc7f8a685/core/autocomplete/templates.ts) 查看这些提示词的示例)。一些最好的商业化模型,比如 GPT-4 或 Claude 不是通过这种提示词格式训练的,这意味着它们不能生成有用的补全。幸运地,好的自动补全不需要很大的模型。大多数先进的自动补全模型不大于 10b 参数,增加超过这个没有明显地提高性能。 + +### 我没有看到任何补全 + +查看下面的步骤,确认所有东西设置正确: + +1. 确保你有 "Enable Tab Autocomplete" 设置勾选,(在 VS Code 中,你可以切换,通过点击状态栏中的 "Continue" 按钮,在 JetBrains 中,通过 Settings -> Tools -> Continue )。 +2. 确保你下载了 Ollama 。 +3. 运行 `ollama run starcoder2:3b` 确认模型下载完成。 +4. 确保任何其他补全提供者被禁用(例如 Copilot ),它们可能会干扰。 +5. 检查输出的日志,查找可能得错误( cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab 在 VS Code 中,~/.continue/logs/core.log 在 JetBrains 中)。 +6. 检查 VS Code 设置,确保 `"editor.inlineSuggest.enabled"` 设置为 `true` (使用 `cmd/ctrl+,` 然后搜索这个并勾选方框) +7. 如果你仍然有问题,请在我们的 [Discord](https://discord.gg/vapESyrFmJ) 让我们知道,我们将会尽快提供帮助。 + +### 补全太慢 + +基于你的硬件,你想要尝试一个更小、更快的模型。如果 3b 不能对你有效工作,我们推荐尝试 `deepseek-coder:1.3b-base` 。 + +### 补全总是单行的 + +为了确保你能收到多行补全,你可以设置 `"multilineCompletions": "always"` 再 `tabAutocompleteOptions` 中。默认情况下,它是 `"auto"` 。如果你仍然发现你只能看到单行补全,这可能是因为一些模型偏向产生短的补全,当在文件中开始时。你可以尝试临时移动光标下的文本到激活文件外,或者切换到一个更大的模型。 + +### 我是否可以配置自动补全 "trigger key" ? + +是的,在 VS Code 中,如果你不想要自动显示建议,你可以: + +1. 设置 `"editor.inlineSuggest.enabled": false` 在 VS Code 设置中,禁止自动建议 +2. 打开 "快捷键" (cmd/ctrl+k, cmd/ctrl+s) 并查找 `editor.action.inlineSuggest.trigger` +3. 点击 "+" 图标添加一个新的键绑定 +4. 按下你想要触发建议的键组合(例如 `ctrl+space`) +5. 现在,无论何时你想要查看建议,按下键绑定(例如,`ctrl+space` )来手动触发建议 + +### 是否有快捷键一次接受一行? + +这是 VS Code 的一个内置特性,但是比较隐藏。查看这个很好的 [StackOverflow 回答](https://stackoverflow.com/questions/72228174/accept-line-by-line-from-autocompletion/78001122#78001122) 获取更多信息。 + +### 如何关闭自动补全 + +#### VS Code + +点击屏幕右下角状态栏中的 "Continue" 按钮。选择标志会变成 "cancel" 符号,你将不会再看到补全。你可以再次点击它,重新打开补全。 + +另外,打开 VS Code 设置,搜索 "Continue" 并取消勾选 "Enable Tab Autocomplete" 方框。 + +#### JetBrains + +打开 Settings -> Tools -> Continue 并取消勾选 "Enable Tab Autocomplete" 方框。 + +#### 反馈 + +如果你关闭自动补全,我们想要知道如何提高!请让我们知道,在我们的 [Discord](https://discord.gg/vapESyrFmJ) 或者在 GitHub 提交一个 issue 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md new file mode 100644 index 000000000..eb55aa668 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/codebase.md @@ -0,0 +1,76 @@ +--- +description: 与你的代码库交互 +keywords: [交互, 嵌入, 重排器, 代码库, 试验性的] +--- + +# @Codebase + +Continue 索引你的代码库,以便它可以之后自动地拉取你的工作区最相关的上下文。这是通过基于嵌入的检索和关键字搜索结合完成的。默认情况下,所有嵌入都是通过 `all-MiniLM-L6-v2` 本地计算的,保存在 `~/.continue/index` 。 + +目前,代码库检索功能可用在 "codebase" 和 "folder" 上下文提供者。你可以使用它们,通过在输入框输入 `@Codebase` 或 `@Folder` ,然后询问问题。输入框的内容将会与其他代码库(或目录)的嵌入进行比较,来决定相关的文件。 + +这是一些通用的使用情况,它是有用的: + +- 询问关于你的代码库的高级别问题 + - "我如何添加一个新的端点到服务器?" + - "我们是否再任何地方使用 VS Code 的 CodeLens 特性?" + - "这里是否有任何写好的代码将 HTML 转换为 markdown ?" +- 生成代码,使用已有的示例作为参考 + - "生成一个新的有日期选择器的 React 组件,使用与已有组件相同的模式" + - "使用 Python 的 argparse 编写一个这个项目的 CLI 应用的草稿" + - "实现一个 `foo` 方法在 `bar` 类中, 根据在其他 `baz` 子类中看到的模式" +- 使用 `@Folder` 询问关于特定目录的问题,增加相关结果的可能性 + - "这个目录的主要目的是什么?" + - "我们如何使用 VS Code 的 CodeLens API ?" + - 或者任何上面的示例,但是使用 `@Folder` 代替 `@Codebase` + +这是一些使用情况,它是没用的: + +- 当你想要 LLM 查看你的代码库中的 _字面上每个_ 文件 + - "查找 `foo` 函数被调用的每个地方" + - "检查我们的代码库,查找任何拼写错误" +- 重构 + - "添加一个新的参数到 `bar` 函数并更新使用方法" + +## 配置 + +这里有一些选项,让你可以配置 codebase 上下文提供者的行为。这些可以再 `config.json` 设置,对于 codebase 和 folder 上下文提供者是一样的: + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "codebase", + "params": { + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } + } + ] +} +``` + +### `nRetrieve` + +从向量数据库开始检索的结果数量(默认值: 25) + +### `nFinal` + +重排之后使用的结果的最终数量(默认值:5) + +### `useReranking` + +是否使用重排,允许最初选择 `nRetrieve` 结果,然后使用 LLM 选择最上面的 `nFinal` 结果(默认值: true) + +## 在索引中忽略文件 + +Continue 遵守 `.gitignore` 文件,为了确定哪些文件不需要索引。如果你想要忽略更多的文件,你可以添加它们到 `.continueignore` 文件,它遵守和 `.gitignore` 完全相同的规则。 + +如果你想要查看哪些文件被 Continue 索引,元数据存储在 `~/.continue/index/index.sqlite` 。你可以使用工具,比如 [DB Browser for SQLite](https://sqlitebrowser.org/) 查看这个文件是的 `tag_catalog` 表。 + +如果你需要强制刷新索引,重新加载 VS Code 窗口使用 `cmd/ctrl + shift + p` + "Reload Window" 。 + +## 仓库 map + +Claude 3, Llama 3.1, Gemini 1.5 和 GPT-4o 家族的模型在代码库检索时会自动地使用 [仓库 map](../context-providers.md#repository-map) ,允许模型理解你的代码库的结构,并使用它回答问题。当前,仓库 map 仅包含代码库中的文件路径。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md new file mode 100644 index 000000000..79862b38f --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md @@ -0,0 +1,90 @@ +--- +description: 了解如何在 Continue 中访问和搜索你的项目文档 +keywords: [文档, 索引, 上下文提供者, 嵌入, 文档] +toc_max_heading_level: 5 +--- + +# @Docs + +[`@Docs` 上下文提供者](http://localhost:3000/customization/context-providers#documentation) 允许你直接通过 Continue 与自己的文档交互。这个特性运行你索引任何静态网站或 Github markdown 页面,让你在编码时访问和利用你的文档更方便。 + +## 启用 `@Docs` 上下文提供者 + +为了启用 `@Docs` 上下文提供者,你需要添加它到你的 `config.json` 文件中的上下文提供者列表。 + +```json +{ + "contextProviders": [ + { + "name": "docs" + } + ] +} +``` + +## 它是如何工作的 + +`@Docs` 上下文提供者通过爬取指定的文档网站工作,生成嵌入,把它们保存再本地。这个过程允许快速有效地访问你的文档内容。 + +1. 我们爬取指定的文档网站 +2. 生成内容的嵌入 +3. 本地保存嵌入在你的机器上 +4. 通过 `@Docs` 上下文提供者提供访问索引内容 + +## 预先索引文档网站 + +我们提供一个流行的框架和库的预先索引文档网站的选择。你可以 [在这里查看可用的预先索引网站和请求附加内容](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts) 列表。 + +## 索引你自己的文档 + +### 通过 `@Docs` 上下文提供者 + +为了添加一个单独的文档网站,我们推荐使用 `@Docs` 上下文提供者。 + +1. 在聊天面板输入 `@Docs` ,点击回车 +2. 输入 "add" 并选择 "Add Docs" 选项 +3. 输入需要的信息到对话框 + +索引将在提交之后开始。 + +### 通过 `config.json` + +为了添加多个文档网站,我们推荐批量添加它们到你的 `config.json` 文件中。索引将在文件保存后开始。 + +[docs 的配置 schema](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) 如下: + +```json +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +- `title`: 文档网站的名称,用来在 UI 中进行识别。 +- `startUrl`: 索引进程开始的 URL 。 +- `rootUrl`: 文档网站的基本 URL ,用来确定哪个页面索引。 +- `faviconUrl`: 网站 favicon 的 URL ,用来在 UI 中进行视觉识别。 + +## 使用 `useChromiumForDocsCrawling` 爬取动态生成的网站 + +默认情况下,我们使用一个轻量的工具爬取文档网站,它不能渲染使用 JavaScript 动态生成的网站。 + +If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`. + +如果你想要爬取一个动态生成的网站,或者当你爬取网站时得到一个错误,你可以在你的 `config.json` 启用试验性的 `useChromiumForDocsCrawling` 特性。这将下载并安装 Chromium 到 `~/.continue/.utils` 。 + +```json title="config.json" +"experimental": { + "useChromiumForDocsCrawling": true +} +``` + +## 常见问题 + +### 索引内容多长时间更新? + +当前,我们没有自动地重新索引你的文档。如果你想要强制重新刷新,你可以使用下面的命令: `Continue: Docs Force Re-Index` 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md new file mode 100644 index 000000000..bbcd0d36b --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/prompt-files.md @@ -0,0 +1,89 @@ +--- +title: 提示词文件 +--- + +提示词文件提供一个方便的方式,来标准化通用模式,并与你的团队分享一批 LLM 提示词。它们让构建和使用这些提示词更简单。 + +## 快速开始 + +:::tip[提示词库] +为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples)。我们鼓励社区贡献到这个仓库,所有请考虑为你的 prompt 创建一个拉取请求! +::: + +以下是一个快速示例,设置一个 prompt 文件使用 Jest 编写单元测试。 + +1. 创建一个名为 `.prompts/` 的目录,再你的工作区的最高层级。 +2. 添加一个名为 `test.prompt` 的文件到这个目录中。这个文件的名称将是斜杠命令的名称,你用来生成提示词。 +3. 写入以下内容到 `test.prompt` 并保存。 + +``` +temperature: 0.5 +maxTokens: 4096 +--- + +You are an expert programmer + + +{{{ input }}} + +Write unit tests for the above selected code, following each of these instructions: +- Use `jest` +- Properly set up and tear down +- Include important edge cases +- The tests should be complete and sophisticated +- Give the tests just as chat output, don't edit any file +- Don't explain how to set up `jest` +``` + +现在使用这个提示词,你可以高亮代码,并使用 `cmd/ctrl+L` 来选择它到 Continue 侧边栏中。 + +然后,输入 "/" 来查看斜杠命令列表,选择名为 "test" 的那个。按下 enter ,LLM 会响应你的 prompt 文件中给出的指令。 + +## 格式 + +格式来自 [HumanLoops 的 .prompt 文件](https://docs.humanloop.com/docs/prompt-file-format) ,并通过额外的模板,使用上下文提供者和内置的变量,使用 [Handlebars 语法](https://handlebarsjs.com/guide/) 。 + +:::info +这个格式的当前状态时试验性的,并且可能变更 +::: + +### preamble + +"preamble" 是 `---` 分隔符之上的任何东西,让你可以指定模型参数。它使用 YAML 语法,当前支持以下参数: + +- `name` +- `temperature` +- `topP` +- `topK` +- `minP` +- `presencePenalty` +- `frequencyPenalty` +- `mirostat` +- `stop` +- `maxTokens` +- `description` + +如果你不需要任何这些参数,你可以对 preamble 留空,不需要包含 `---` 分隔符。 + +### 系统信息 + +为了添加一个系统信息,使用 `` tag 开始 body ,例如上面的例子,并将你的系统信息放入其中。 + +### 内置变量 + +下面的内置变量当前是可用的: + +- `{{{ input }}}` - 侧边栏中输入框中与斜杠命令一起发送的全部文本 +- `{{{ currentFile }}}` - 当前在你的 IDE 中打开的文件 +- `{{{ ./path/to/file.js }}}` - 可以直接引用的任何文件 + +### 上下文提供者 + +任何你添加到配置中的 [上下文提供者](../context-providers.md) ,可以使用上下文提供者的名称引用。接收输入的上下文提供者也支持。 + +- `{{{ terminal }}}` - 终端的内容 +- `{{{ url "https://github.com/continuedev/continue" }}}` - URL 的内容 + +## 反馈 + +如果你有关于提高 `.prompt` 文件格式的想法,请在 [Discord](https://discord.gg/NWtdYexhMs) 提出。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/development-data.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/development-data.md new file mode 100644 index 000000000..c9541a4c4 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/development-data.md @@ -0,0 +1,9 @@ +--- +title: 开发数据 +description: 收集你如何构建软件的数据 +keywords: [开发数据, dev 数据, LLM-辅助开发] +--- + +当使用 Continue 时,你自动地收集如何构建软件的数据。默认情况下,这个开发数据保存在你本地机器上的 `.continue/dev_data` 。与你最终提交的代码结合,它可以用来提高你或你的团队使用的 LLM (如果你允许) 。 + +你可以了解更多关于开发数据是如何生成的,作为 LLM 辅助编程的副产品,以及为什么我们相信你应该现在开始收集它: [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/assets/watsonx2.gif b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/assets/watsonx2.gif new file mode 100644 index 000000000..e37443ad6 Binary files /dev/null and b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/assets/watsonx2.gif differ diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md new file mode 100644 index 000000000..79e142ca9 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md @@ -0,0 +1,18 @@ +# SambaNova Cloud + +SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](https://cloud.sambanova.ai/) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。 + +```json title="config.json" +{ + "models": [ + { + "title": "SambaNova Llama 3.1 405B", + "provider": "sambanova", + "model": "llama3.1-405b", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/SambaNova.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cloudflare.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cloudflare.md new file mode 100644 index 000000000..227539ff5 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cloudflare.md @@ -0,0 +1,46 @@ +# Cloudflare Workers AI + +Cloudflare Workers AI 可以在 Continue 中用来聊天或 tab 自动补全。要设置 Cloudflare Workers AI ,添加以下配置到你的 `config.json` 文件中: + +```json title="config.json" +{ + "models": [ + { + "accountId": "YOUR CLOUDFLARE ACCOUNT ID", + "apiKey": "YOUR CLOUDFLARE API KEY", + "contextLength": 2400, + "completionOptions": { + "maxTokens": 500 + }, + "model": "@cf/meta/llama-3-8b-instruct", // This can be the name of any model supported by Workers AI + "provider": "cloudflare", + "title": "Llama 3 8B" + }, + { + "accountId": "YOUR CLOUDFLARE ACCOUNT ID", + "apiKey": "YOUR CLOUDFLARE API KEY", + "contextLength": 2400, + "completionOptions": { + "maxTokens": 500 + }, + "model": "@hf/thebloke/deepseek-coder-6.7b-instruct-awq", + "provider": "cloudflare", + "title": "DeepSeek Coder 6.7b Instruct" + } + ... + "tabAutocompleteModel": { + "accountId": "YOUR CLOUDFLARE ACCOUNT ID", + "apiKey": "YOUR CLOUDFLARE API KEY", + "model": "@hf/thebloke/deepseek-coder-6.7b-base-awq", + "provider": "cloudflare", + "title": "DeepSeek 7b" + }, + ] +} +``` + +访问 [Cloudflare dashboard](https://dash.cloudflare.com/) 来 [创建 API key](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/) 。 + +在 Workers AI 重看 [可用的模型](https://developers.cloudflare.com/workers-ai/models/) + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Cloudflare.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md new file mode 100644 index 000000000..274c1942d --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/cohere.md @@ -0,0 +1,56 @@ +# Cohere + +在使用 Cohere 之前,访问 [Cohere dashboard](https://dashboard.cohere.com/api-keys) 创建 API key 。 + +## 聊天模型 + +我们推荐配置 **Command-R Plus** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Cohere", + "provider": "cohere", + "model": "command-r-plus", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +## 自动补全模型 + +Cohere 当前没有提供任何自动补全模型。 + +[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 + +## 嵌入模型 + +我们推荐配置 **embed-english-v3.0** 作为你的嵌入模型。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "cohere", + "model": "embed-english-v3.0", + "apiKey": "" + } +} +``` + +## 重排序模型 + +我们推荐配置 **rerank-english-v3.0** 作为你的重排序模型。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "cohere", + "params": { + "model": "rerank-english-v3.0", + "apiKey": "" + } + } +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/deepinfra.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/deepinfra.md new file mode 100644 index 000000000..990003ebb --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/deepinfra.md @@ -0,0 +1,18 @@ +# DeepInfra + +[DeepInfra](https://deepinfra.com) 提供很低费用的开源模型推理。要开始使用 DeepInfra ,在 [这里](https://deepinfra.com/dash) 获取你的 API key 。然后,在 [这里](https://deepinfra.com/models?type=text-generation) 找到你想要使用的模型,并复制模型的名称。 Continue 可以配置使用 `DeepInfra` LLM 类,比如这里的例子: + +```json title="config.json" +{ + "models": [ + { + "provider": "deepinfra", + "title": "DeepInfra", + "model": "mistralai/Mixtral-8x7B-Instruct-v0.1", + "apiKey": "" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/DeepInfra.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/flowise.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/flowise.md new file mode 100644 index 000000000..33a3290d7 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/flowise.md @@ -0,0 +1,18 @@ +# Flowise + +[Flowise](https://flowiseai.com/) 是一个 低代码/无代码 拖拽工具,目标是让人们更容易地可视化构建 LLM 应用。 Continue 可以配置使用 `Flowise` LLM 类,比如这里的例子: + +```json title="config.json" +{ + "models": [ + { + "provider": "flowise", + "title": "Flowise", + "model": "", + "apiBase": "" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Flowise.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/free-trial.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/free-trial.md new file mode 100644 index 000000000..746038bdf --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/free-trial.md @@ -0,0 +1,31 @@ +--- +title: 免费试用 +slug: ../free-trial +--- + +`"免费试用"` 提供者提供新用户在 Continue 快速尝试最好的体验,通过一个安全的代理服务器使用我们的 API key 。为了避免滥用,我们要求你使用 Github 登录,你可以在下面看到更多。 + +虽然 Continue 扩展总是免费使用,我们不能为所有用户提供无限免费 LLM 使用。你最终需要: + +1. 选择一个开源模型免费使用 [本地的](../top-level/ollama.md), 或者 +2. 添加你自己的 [Anthropic](../top-level/anthropic.md) API key 或者 [其他的 LLM 提供者](/customize/model-providers) + +## 试用的常见问题 + +Continue 要求免费试用用户登录,让我们可以避免我们的 API 端点滥用。如果你不使用免费试用,我们不会要求你登录。 + +### 我如何停止 Continue 询问我登录? + +移除 "models" 列表或 "tabAutocompleteModel" 中 `"provider": "free-trial"` 的所有模型,我们将不会再请求登录。 + +### 什么信息被收集? + +Continue 使用你的 GitHub 用户名,没有其他信息,唯一的目的是限制请求。 + +### 如果我没有登录,会发生什么? + +如果你没有登录,你仍然可以使用 Continue 的每个特性,你只需要提供自己的 LLM ,不论使用 API key 或运行本地的模型。 + +### 遥测与登录有什么关系? + +它没有。我们没有关联你的 GitHub 用户名到遥测数据。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/groq.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/groq.md new file mode 100644 index 000000000..a86a420f3 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/groq.md @@ -0,0 +1,19 @@ +# Groq + +Groq 提供开源语言模型最快的可用推理,包含整个 Llama 3.1 家族。 + +1. 从 [这里](https://console.groq.com/keys) 获取 API key +2. 像这样更新你的 Continue 配置文件: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "groq", + "model": "llama3.1-405b", + "apiKey": "" + } + ] +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/huggingfaceinferenceapi.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/huggingfaceinferenceapi.md new file mode 100644 index 000000000..450bfd365 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/huggingfaceinferenceapi.md @@ -0,0 +1,19 @@ +# HuggingFace 推理端点 + +Hugging Face 推理端点是一个在任何云上设置开源语言模型实例的简单的方式。在 [这里](https://huggingface.co/settings/billing)注册帐号并添加账单 , 在 [这里](https://ui.endpoints.huggingface.co) 访问推理端点,点击 "New endpoint" ,并填写表单,(例如,选择一个模型 [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)) ,然后通过点击 "Create Endpoint" 部署你的模型。修改 `~/.continue/config.json` 像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Hugging Face Inference API", + "provider": "huggingface-inference-api", + "model": "MODEL_NAME", + "apiKey": "YOUR_HF_TOKEN", + "apiBase": "INFERENCE_API_ENDPOINT_URL" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/HuggingFaceInferenceAPI.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/ipex_llm.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/ipex_llm.md new file mode 100644 index 000000000..b946d4dd5 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/ipex_llm.md @@ -0,0 +1,38 @@ +# IPEX-LLM + +:::info +[**IPEX-LLM**](https://github.com/intel-analytics/ipex-llm) 是一个 PyTorch 库,用来在 Intel CPU 和 GPU 上运行 LLM ,(例如,有 iGPU 的 PC ,独立 GPU ,比如, Arc A-Series, Flex 和 Max),有着很低的延迟。 +::: + +IPEX-LLM 支持加速托管在 Intel GPU 上的 Ollama 后端。从 IPEX-LLM 官方文档查看 [这个指南](https://ipex-llm.readthedocs.io/en/latest/doc/LLM/Quickstart/ollama_quickstart.html),关于如何安装和运行通过 IPEX-LLM 在 Intel GPU 上的 Ollama 服务加速。你可以如下配置 Continue 使用 IPEX-LLM 加速 `"ollama"` 提供者: + +```json title="config.json" +{ + "models": [ + { + "title": "IPEX-LLM", + "provider": "ollama", + "model": "AUTODETECT" + } + ] +} +``` + +如果你想要访问来自其他机器的 Ollama 服务,确保你在执行 `ollama serve` 命令之前, set 或 export 环境变量 `OLLAMA_HOST=0.0.0.0` 。然后,在 Continue 配置中,设置 `'apiBase'` 与远程机器的 IP 地址 / 端口一致。也就是, Continue 可以配置为: + +```json title="config.json" +{ + "models": [ + { + "title": "IPEX-LLM", + "provider": "ollama", + "model": "AUTODETECT", + "apiBase": "http://your-ollama-service-ip:11434" + } + ] +} +``` + +:::tip +如果你想要在 Continue 中第一次与模型交谈之前预加载模型,你需要查看 [这里](https://ipex-llm.readthedocs.io/en/latest/doc/LLM/Quickstart/continue_quickstart.html#pull-and-prepare-the-model) 获取更多信息。 +::: diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/kindo.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/kindo.md new file mode 100644 index 000000000..6129b47f2 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/kindo.md @@ -0,0 +1,43 @@ +# Kindo + +Kindo 对你的机构 AI 操作提供集中控制,当支持不同的商业和开源模型时,确保数据安全和内部原则兼容。要开始使用,在 [这里](https://app.kindo.ai/) 注册,在 [API keys 页面](https://app.kindo.ai/settings/api) 创建你的 API key ,在 [plugins 标签页](https://app.kindo.ai/plugins) 中,从支持的模型列表中选择一个模型。 + +## 配置示例 + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "kindo", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "" + } + ] +} +``` + +## tab 自动补全配置示例 + +```json title="config.json" +{ + "tabAutocompleteModel": [ + { + "title": "WhiteRabbitNeo", + "provider": "kindo", + "model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder", + "apiKey": "" + }, + { + "title": "DeepSeek", + "provider": "kindo", + "model": "deepseek-ai/deepseek-coder-33b-instruct", + "apiKey": "" + } + ] +} +``` + +## 安全性 + +要更新你的机构模型访问,在 [安全性设置](https://app.kindo.ai/security-settings) 中调整控制。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/llamacpp.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/llamacpp.md new file mode 100644 index 000000000..4ad70bd79 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/llamacpp.md @@ -0,0 +1,24 @@ +# LlamaCpp + +运行 llama.cpp server 二进制文件打开 API 服务器。如果你运行一个远程服务器,确保设置 host 为 0.0.0.0 : + +```shell +.\server.exe -c 4096 --host 0.0.0.0 -t 16 --mlock -m models\meta\llama\codellama-7b-instruct.Q8_0.gguf +``` + +在它设置和运行之后,修改 `~/.continue/config.json` 像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama CPP", + "provider": "llama.cpp", + "model": "MODEL_NAME", + "apiBase": "http://localhost:8080" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/LlamaCpp.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/llamafile.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/llamafile.md new file mode 100644 index 000000000..9c270ce5c --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/llamafile.md @@ -0,0 +1,17 @@ +# Llamafile + +[llamafile](https://github.com/Mozilla-Ocho/llamafile#readme) 是一个自包含的二进制文件,可以运行一个开源 LLM 。你可以像下面这样在 config.json 配置这个提供者: + +```json title="config.json" +{ + "models": [ + { + "title": "Llamafile", + "provider": "llamafile", + "model": "mistral-7b" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Llamafile.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/lmstudio.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/lmstudio.md new file mode 100644 index 000000000..faea201a8 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/lmstudio.md @@ -0,0 +1,32 @@ +# LM Studio + +[LM Studio](https://lmstudio.ai) 是一个 Mac, Windows 和 Linux 的应用,让本地运行开源模型更简单,并提供很好的 UI 。要开始使用 LM Studio ,从网站上下载它,使用 UI 下载一个模型,然后打开本地推理服务器。 Continue 可以配置来使用 `LMStudio` LLM 类: + +```json title="config.json" +{ + "models": [ + { + "title": "LM Studio", + "provider": "lmstudio", + "model": "llama2-7b" + } + ] +} +``` + +## 设置一个远程实例 + +要配置一个 LM Studio 的远程实例,在 config.json 中,添加 `"apiBase"` 属性到你的模型中: + +```json title="config.json" +{ + "title": "LM Studio", + "model": "codestral", + "provider": "lmstudio", + "apiBase": "http://x.x.x.x:1234/v1/" +} +``` + +`apiBase` 现在将会代替默认的 `http://localhost:1234/v1` 。 + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/LMStudio.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/msty.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/msty.md new file mode 100644 index 000000000..90a44f650 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/msty.md @@ -0,0 +1,49 @@ +# Msty + +[Msty](https://msty.app/) 是一个 Windows, Mac 和 Linux 的应用,让运行本地开源模型上线很容易,包括 Llama-2, DeepSeek Coder 等。不需要使用你的终端,运行命令或任何东西。只需要从网站下载应用,点击按钮,就会启动和运行。然后, Continue 可以配置使用 `Msty` LLM 类: + +```json title="config.json" +{ + "models": [ + { + "title": "Msty", + "provider": "msty", + "model": "deepseek-coder:6.7b", + "completionOptions": {} + } + ] +} +``` + +## 完成选项 + +除了模型类型,你还可以配置一些 Msty 运行模型的参数。 + +- temperature: options.temperature - 这是一个控制生成文本的随机性的参数。较高的值导致更有创造性,但是可能更少的有条理的输入,而更低的值导致更可预测和目标明确的输出。 +- top_p: options.topP - 这个设置一个阈值 (在 0 和 1 之前) ,用来控制预测 token 的多样性。模型生成 token ,通过它们的概率分布,但是也考虑 top-k 最可能的 token 。 +- top_k: options.topK - 这个参数限制唯一 token 的数量,当考虑生成序列的下一个 token 时。较高的值增加生成序列的多样性,而较低的值导致更明确的输出。 +- num_predict: options.maxTokens - 这个决定生成 token 的最大数量 (字或字符) ,对于给定的输入提示词。 +- num_thread: options.numThreads - 这是多线程配置选项,控制模型并发使用多少个线程。更到的值导致更快的生成时间,但是也会增加内存使用和复杂性。在本地运行模型时,设置这个为 1 或 2 ,低于你的 CPU 可以处理的线程数量,留给你的 GUI 一些。 + +## 认证 + +如果你需要发送自定义头来认证,你可以使用 `requestOptions.headers` 属性,像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Msty", + "provider": "msty", + "model": "deepseek-coder:6.7b", + "requestOptions": { + "headers": { + "Authorization": "Bearer xxx" + } + } + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Msty.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/openrouter.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/openrouter.md new file mode 100644 index 000000000..aa0e32a3b --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/openrouter.md @@ -0,0 +1,40 @@ +# OpenRouter + +OpenRouter 是一个对于商业的和开源的模型统一的接口,给你最好的模型,最好的价格。你可以在 [这里](https://openrouter.ai/signup) 注册,在 [keys 页面](https://openrouter.ai/keys) 创建你的 API key ,然后从 [支持模型列表](https://openrouter.ai/models) 中选择一个模型。 + +修改 `~/.continue/config.json` 如下: + +```json title="config.json" +{ + "models": [ + { + "title": "OpenRouter LLaMA 70 8B", + "provider": "openrouter", + "model": "meta-llama/llama-3-70b-instruct", + "apiBase": "https://openrouter.ai/api/v1", + "apiKey": "..." + } + ] +} +``` + +为了使用比如提供者推理或模型路由配置的特性,在你的插件配置中添加这些参数到 `models[].requestsOptions.extraBodyProperties` 字段。 + +例如,为了抑制额外的长提示词被压缩,你可以明确地关闭这个特性,像这样: + +```json title="config.json" +{ + "models": [ + { + ... + "requestOptions": { + "extraBodyProperties": { + "transforms": [] + } + } + } + ] +} +``` + +在 [这里](https://openrouter.ai/docs) 了解更多可用的设置。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/replicatellm.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/replicatellm.md new file mode 100644 index 000000000..dc4d6b80d --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/replicatellm.md @@ -0,0 +1,22 @@ +# ReplicateLLM + +Replicate 是一个很好的选项,对于新发布的语言模型或你通过他们的平台部署的模型。在 [这里](https://replicate.ai/) 注册一个帐号,复制你的 API key ,然后从 [Replicate Streaming 列表](https://replicate.com/collections/streaming-language-models) 选择任何模型。修改 `~/.continue/config.json` 看起来像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Replicate CodeLLama", + "provider": "replicate", + "model": "codellama-13b", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +If you don't specify the `model` parameter, it will default to `replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781`. + +如果你没有指定 `model` 参数,它将默认是 `replicate/llama-2-70b-chat:58d078176e02c219e11eb4da5a02a7830a283b14cf8f94537af893ccff5ee781`. + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Replicate.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/sagemaker.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/sagemaker.md new file mode 100644 index 000000000..5b804dedd --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/sagemaker.md @@ -0,0 +1,29 @@ +# AWS SageMaker + +SageMaker 提供者支持使用 [LMI](https://docs.djl.ai/docs/serving/serving/docs/lmi/index.html) 部署的 SageMaker 端点。 + +为了设置 SageMaker ,添加以下到你的 `config.json` 文件中: + +```json title="config.json" +{ + "models": [ + { + "title": "deepseek-6.7b-instruct", + "provider": "sagemaker", + "model": "lmi-model-deepseek-coder-xxxxxxx", + "region": "us-west-2" + } + ] +} +``` + +模型中的值是你部署的 SageMaker 端点名称。 + +认证可以通过临时的或长期的证书,在 `~/.aws/credentials` 中名为 "sagemaker" 的属性中设置。 + +```title="~/.aws/credentials +[sagemaker] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/textgenwebui.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/textgenwebui.md new file mode 100644 index 000000000..45768c776 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/textgenwebui.md @@ -0,0 +1,16 @@ +# TextGenWebUI + +TextGenWebUI 是一个综合的,开源语言模型 UI 和本地服务器。你可以使用 OpenAI-兼容服务器插件设置它,然后在你的 `config.json` 配置它,像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Text Generation WebUI", + "provider": "text-gen-webui", + "apiBase": "http://localhost:5000", + "model": "MODEL_NAME" + } + ] +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/together.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/together.md new file mode 100644 index 000000000..ba68e222c --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/together.md @@ -0,0 +1,18 @@ +# Together + +Together API 是一个运行大 AI 模型的云平台。你可以在 [这里](https://api.together.xyz/signup) 注册,在最初欢迎屏幕复制你的 API key ,然后在 [Together 模型列表](https://docs.together.ai/docs/models-inference) 的任何模型上点击 play 按钮。修改 `~/.continue/config.json` 像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Together CodeLlama", + "provider": "together", + "model": "codellama-13b", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Together.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/vllm.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/vllm.md new file mode 100644 index 000000000..28378cfe7 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/vllm.md @@ -0,0 +1,22 @@ +# vLLM + +通过 vLLM 使用 `vllm serve` 运行 OpenAI-兼用 服务器。查看他们的 [服务器文档](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) 和 [引擎参数文档](https://docs.vllm.ai/en/latest/models/engine_args.html) 。 + +```shell +vllm serve NousResearch/Meta-Llama-3-8B-Instruct --max-model-len 1024 +``` + +Continue 底层实现使用 [OpenAI](../top-level/openai.md) 并自动选择可用的模型。你只需要设置 `apiBase` ,像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "My vLLM OpenAI-compatible server", + "apiBase": "http://localhost:8000/v1" + } + ] +} +``` + +[查看代码](https://github.com/continuedev/continue/blob/main/core/llm/llms/Vllm.ts) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/watsonx.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/watsonx.md new file mode 100644 index 000000000..6924ae390 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/watsonx.md @@ -0,0 +1,84 @@ +# IBM watsonx + +watsonx, 由 IBM 开发,提供不同的预训练 AI 基础模型,可以用来自然语言处理 (NLP) ,计算机视觉和语音识别任务。 + +## 设置 + +为了访问 watsonx 模型,可以通过在 IBM 云的 watsonx SaaS 或者使用专有的 watsonx.ai 软件实例。 + +### watsonx.ai SaaS - IBM 云 + +为了开始使用 watsonx SaaS ,访问 [注册页面](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx) 。如果你没有已有的 IBM 云帐号,可以注册免费试用。 + +为了使用 Continue 认证 watsonx.ai SaaS ,你需要创建一个项目,然后 [设置 API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key) 。然后,在 Continue 中: + +- 设置 **watsonx URL** 为你的 watsonx SaaS 端点,例如 `https://us-south.ml.cloud.ibm.com` 使用 US 南方区域。 +- 设置 **watsonx Project ID** 为你的 watsonx 项目 ID 。 +- 设置 **watsonx API Key** 为你的 watsonx API Key 。 + +### watsonx.ai 软件 + +为了使用 Continue 认证你的 watsonx.ai 软件实例,你可以使用 `username/password` 或 `ZenApiKey` 方法: + +1. _选项 1_ (推荐): 使用 `ZenApiKey` 认证: + - 设置 **watsonx URL** 为你的 watsonx 软件端点,例如 `https://cpd-watsonx.apps.example.com` 。 + - 设置 **watsonx Project ID** 为你的 watsonx 项目 ID 。 + - 设置 **watsonx API Key** 为你的 watsonx Zen API Key 。要生成它: + 1. 登录到 CPD 网页客户端。 + 2. 在工具栏中,点击头像。 + 3. 点击 **简介和设置** 。 + 4. 点击 **API key** > **生成新的 key** 。 + 5. 点击 **生成** 。 + 6. 点击 **复制** 并保存你的 key 到安全的地方。如果丢失,你不能恢复这个 key 。 + 7. 生成你的 ZenApiKey ,通过在你喜欢的终端中运行下面的命令: `echo ":" | base64` ,替换 `` 为你的 CPD username 和 `` 为你刚刚创建的 API key 。 +2. _选项 2_: 使用 `username/password` 认证: + - 设置 **watsonx URL** 为你的 watsonx 软件端点,例如 `https://cpd-watsonx.apps.example.com` 。 + - 设置 **watsonx Project ID** 为你的 watsonx 项目 ID 。 + - 设置 **watsonx API Key** 为你的 watsonx 用户名和密码,使用 `username:password` 格式。 + +## 配置 + +添加下面的配置到你的 `config.json` 文件来使用 watsonx 提供者。填写 `watsonxCreds` ,使用你在设置步骤中获取的认证信息。 + +```json title="~/.continue/config.json" +{ + "models": [ + { + "model": "model ID", + "title": "watsonx - Model Name", + "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "watsonxProjectId": "PROJECT_ID", + "watsonxCreds": "API_KEY/ZENAPI_KEY/USERNAME:PASSWORD", + "watsonxApiVersion": "2023-05-29", + "provider": "watsonx" + } + ] +} +``` + +`watsonxAPIVersion` 是可选的,默认为最新版。 + +### 配置选项 + +如果你使用一个自定义的端点,添加完整的 watsonx URL 到 `watsonxFullUrl` 。当设置了 `watsonxFullUrl` , `watsonxUrl` 和 `watsonxApiVersion` 会被忽略。 + +```json title="~/.continue/config.json" +{ + "models": [ + { + "model": "model ID", + "title": "watsonx - Model Name", + "watsonxUrl": "watsonx endpoint e.g. https://us-south.ml.cloud.ibm.com", + "watsonxProjectId": "PROJECT_ID", + "watsonxCreds": "API_KEY", + "watsonxApiVersion": "2023-05-29", + "provider": "watsonx", + "watsonxFullUrl": "https://us-south.ml.cloud.ibm.com/m1/v1/text/generation" + } + ] +} +``` + +## 使用 + +![usage-gif](../assets/watsonx2.gif) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md new file mode 100644 index 000000000..7380e7673 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/anthropic.md @@ -0,0 +1,67 @@ +--- +title: Anthropic +slug: ../anthropic +--- + +:::info +你可以从 [Anthropic 控制台](https://console.anthropic.com/account/keys) 获取 API key 。 +::: + +## 聊天模型 + +我们推荐配置 **Claude 3.5 Sonnet** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "anthropic", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## 自动补全模型 + +Anthropic 当前没有提供任何自动补全模型。 + +[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 + +## 嵌入模型 + +Anthropic 当前没有提供任何嵌入模型。 + +[点击这里](../../model-types/embeddings.md) 查看嵌入模型提供者列表。 + +## 重排序模型 + +Anthropic 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 + +## 提示词缓存 + +Anthropic 提供 [Claude 的提示词缓存](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching) 。 + +为了打开系统消息和逐轮交谈的缓存,像下面这样更新你的模型配置: + +```json +{ + "models": [ + { + // Enable prompt caching + "cacheBehavior": { + "cacheSystemMessage": true, + "cacheConversation": true + }, + "title": "Anthropic", + "provider": "anthropic", + "model": "claude-3-5-sonnet-20240620", + "apiKey": "[API_KEY]" + } + ] +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md new file mode 100644 index 000000000..6fa50faaa --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/azure.md @@ -0,0 +1,91 @@ +--- +title: Azure OpenAI +slug: ../azure +--- + +## 聊天模型 + +我们推荐配置 **GPT-4o** 作为你的聊天模型。 + +```json title="config.json" +"models": [{ + "title": "GPT-4o", + "provider": "azure", + "model": "gpt-4o", + "apiBase": "", + "engine": "", + "apiVersion": "", + "apiType": "azure", + "apiKey": "" +}] +``` + +## 自动补全模型 + +我们推荐配置 **Codestral** 作为你的自动补全模型。 + +```json title="config.json" +"tabAutocompleteModel": [{ + "title": "Codestral", + "provider": "azure", + "model": "codestral-latest", + "apiBase": "", + "engine": "", + "apiVersion": "", + "apiType": "azure", + "apiKey": "" +}] +``` + +## 嵌入模型 + +我们推荐配置 **text-embedding-3-large** 作为你的嵌入模型。 + +```json title="config.json" +"embeddingsProvider": { + "provider": "azure", + "model": "text-embedding-3-large", + "apiBase": "", + "engine": "", + "apiVersion": "", + "apiType": "azure", + "apiKey": "" +} +``` + +## 重排序模型 + +Azure OpenAI 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型列表。 + +## 隐私 + +如果你想要使用 OpenAI 模型,但是担心隐私问题,你可以使用 Azure OpenAI 服务,它是符合 GDPR 和 HIPAA 的。 + +:::info[获取访问] +你需要申请 Azure OpenAI 服务的访问。响应时间通常是几天。 + +**[点击这里申请 Azure OpenAI 服务的访问](https://azure.microsoft.com/en-us/products/ai-services/openai-service)** +::: + +## 通用模型配置 + +Azure OpenAI 需要配置一些额外的参数,例如模型引擎和 API 版本。 + +要在 _Azure AI Studio_ 查找这个信息,首先选择你想要连接的模型。然后访问 _Endpoint_ > _Target URI_ 。 + +例如, Target URI `` 匹配以下配置: + +```json +{ + "title": "GPT-4o Azure", + "model": "gpt-4o", + "provider": "azure", + "apiBase": "https://just-an-example.openai.azure.com", + "apiType": "azure", + "engine": "gpt-4o", + "apiVersion": "2023-03-15-preview", + "apiKey": "" +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md new file mode 100644 index 000000000..a1a4d6234 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/bedrock.md @@ -0,0 +1,88 @@ +--- +title: Amazon Bedrock +slug: ../bedrock +--- + +## 聊天模型 + +我们推荐配置 **Claude 3.5 Sonnet** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "bedrock", + "model": "anthropic.claude-3-5-sonnet-20240620-v1:0", + "region": "us-east-1", + "profile": "bedrock" + } + ] +} +``` + +## 自动补全模型 + +Bedrock 当前不支持任何自动补全模型。 + +[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 + +## 嵌入模型 + +我们推荐配置 [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazon.com/bedrock/latest/devguide/models.html#amazon.titan-embed-text-v2-0) 作为你的嵌入模型。 + +```json title="~/.continue/config.json" +{ + "embeddingsProvider": { + "title": "Embeddings Model", + "provider": "bedrock", + "model": "amazon.titan-embed-text-v2:0", + "region": "us-west-2" + } +} +``` + +## 重排序模型 + +Bedrock 当前没有任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 + +## 认证 + +认证可以通过 `~/.aws/credentials` 配置属性中临时的或长期的证书,(例如 "bedrock") 。 + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` + +## 定制导入模型 + +为了设置 Bedrock 使用定制导入模型,将下面的配置添加到你的 `config.json` 文件中: + +```json title="config.json" +{ + "models": [ + { + "title": "AWS Bedrock deepseek-coder-6.7b-instruct", + "provider": "bedrockimport", + "model": "deepseek-coder-6.7b-instruct", + "modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX", + "region": "us-west-2", + "profile": "bedrock" + } + ] +} +``` + +认证可以通过 `~/.aws/credentials` 配置属性中临时的或长期的证书,(例如 "bedrock") 。 + +```title="~/.aws/credentials +[bedrock] +aws_access_key_id = abcdefg +aws_secret_access_key = hijklmno +aws_session_token = pqrstuvwxyz # Optional: means short term creds. +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md new file mode 100644 index 000000000..61e01e701 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/deepseek.md @@ -0,0 +1,51 @@ +--- +title: DeepSeek +slug: ../deepseek +--- + +:::info +你可以从 [DeepSeek 控制台](https://www.deepseek.com/) 获取 API key 。 +::: + +## 聊天模型 + +我们推荐配置 **DeepSeek Chat** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "DeepSeek Chat", + "provider": "deepseek", + "model": "deepseek-chat", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## 自动补全模型 + +我们推荐配置 **DeepSeek Coder** 作为你的自动补全模型。 + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "DeepSeek Coder", + "provider": "deepseek", + "model": "deepseek-coder" + } +} +``` + +## 嵌入模型 + +DeepSeek 当前没有提供任何嵌入模型。 + +[点击这里](../../model-types/embeddings.md) 查看嵌入模型提供者列表。 + +## 重排序模型 + +DeepSeek 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md new file mode 100644 index 000000000..13778e379 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/gemini.md @@ -0,0 +1,51 @@ +--- +title: Gemini +slug: ../gemini +--- + +:::info +你可以从 [Google AI Studio](https://aistudio.google.com/) 获取 API key 。 +::: + +## 聊天模型 + +我们推荐配置 **Gemini 1.5 Pro** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Gemini 1.5 Pro", + "provider": "gemini", + "model": "gemini-1.5-pro-latest", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## 自动补全模型 + +Gemini 当前没有提供任何自动补全模型。 + +[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 + +## 嵌入模型 + +我们推荐配置 **text-embedding-004** 作为你的嵌入模型。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "gemini", + "model": "models/text-embedding-004", + "apiKey": "[API_KEY]" + } +} +``` + +## 重排序模型 + +Gemini 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md new file mode 100644 index 000000000..2e853affc --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/mistral.md @@ -0,0 +1,60 @@ +--- +title: Mistral +slug: ../mistral +--- + +:::info +你可以从 [Mistral Dashboard](https://console.mistral.ai) 获取 API key 。注意 Codestral (codestral.mistral.ai) 的 API key 是与所有其他模型 (api.mistral.ai) 不同的。 +::: + +## 聊天模型 + +我们推荐配置 **Mistral Large** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Mistral Large", + "provider": "mistral", + "model": "mistral-large-latest", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## 自动补全模型 + +我们推荐配置 **Codestral** 作为你的自动补全模型。 + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest" + } +} +``` + +## 嵌入模型 + +我们推荐配置 **Mistral Embed** 作为你的嵌入模型。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "mistral", + "model": "mistral-embed", + "apiKey": "[API_KEY]", + "apiBase": "https://api.mistral.ai/v1" + } +} +``` + +## 重排序模型 + +Mistral 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md new file mode 100644 index 000000000..9119116ef --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/ollama.md @@ -0,0 +1,53 @@ +--- +title: Ollama +slug: ../ollama +--- + +## 聊天模型 + +我们推荐配置 **Llama3.1 8B** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "Llama3.1 8B", + "provider": "ollama", + "model": "llama3.1:8b" + } + ] +} +``` + +## 自动补全模型 + +我们推荐配置 **StarCoder2 3B** 作为你的自动补全模型。 + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "StarCoder2 3B", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +## 嵌入模型 + +我们推荐配置 **Nomic Embed Text** 作为你的嵌入模型。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "ollama", + "model": "nomic-embed-text" + } +} +``` + +## 重排序模型 + +Ollama 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md new file mode 100644 index 000000000..ba84723da --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/openai.md @@ -0,0 +1,90 @@ +--- +title: OpenAI +slug: ../openai +--- + +:::info +你可以从 [OpenAI 控制台](https://platform.openai.com/account/api-keys) 获取 API key +::: + +## 聊天模型 + +我们推荐配置 **GPT-4o** 作为你的聊天模型。 + +```json title="config.json" +{ + "models": [ + { + "title": "GPT-4o", + "provider": "openai", + "model": "gpt-4o", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## 自动补全模型 + +OpenAI 当前没有提供任何自动补全模型。 + +[点击这里](../../model-types/autocomplete.md) 查看自动补全模型提供者列表。 + +## 嵌入模型 + +我们推荐配置 **text-embedding-3-large** 作为你的嵌入模型。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-3-large", + "apiKey": "[API_KEY]" + } +} +``` + +## 重排序模型 + +OpenAI 当前没有提供任何重排序模型。 + +[点击这里](../../model-types/reranking.md) 查看重排序模型提供者列表。 + +## OpenAI 兼容服务器 / API + +OpenAI 兼容服务器 + +- [KoboldCpp](https://github.com/lostruins/koboldcpp) +- [text-gen-webui](https://github.com/oobabooga/text-generation-webui/tree/main/extensions/openai#setup--installation) +- [FastChat](https://github.com/lm-sys/FastChat/blob/main/docs/openai_api.md) +- [LocalAI](https://localai.io/basics/getting_started/) +- [llama-cpp-python](https://github.com/abetlen/llama-cpp-python#web-server) +- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) +- [vLLM](https://docs.vllm.ai/en/latest/serving/openai_compatible_server.html) + +OpenAI 兼容 API + +- [Anyscale Endpoints](https://github.com/continuedev/deploy-os-code-llm#others) +- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) + +如果你使用 OpenAI 兼容服务器 / API ,你可以像这样修改 `apiBase` : + +```json title="config.json" +{ + "models": [ + { + "title": "OpenAI-compatible server / API", + "provider": "openai", + "model": "MODEL_NAME", + "apiKey": "EMPTY", + "apiBase": "http://localhost:8000/v1" + } + ] +} +``` + +为了使用 `chat/completions` 代替 `completions` 端点,你可以设置 + +```json +"useLegacyCompletionsEndpoint": false +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/autocomplete.md new file mode 100644 index 000000000..174491438 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/autocomplete.md @@ -0,0 +1,16 @@ +--- +title: 自动补全模型 +description: 自动补全模型 +keywords: [自动补全] +sidebar_position: 1 +--- + +"自动补全模型" 是一个训练在称为中间填充 (FIM) 的特定的格式上的 LLM 。这种格式设计为,给出代码文件的前缀和后缀,预测中间是什么。这种任务很特殊,一方面意味着模型可以较小 (甚至一个 3B 参数模型可以表现很好)。另一方面,这意味着聊天模型,虽然更大,但是表现更差。 + +在 Continue 中,这些模型用来随着你的输入显示行内 [自动补全](../../autocomplete/how-to-use-it.md) 建议。 + +## 推荐的自动补全模型 + +如果你有使用任何模型的能力,我们推荐通过 [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) 使用 `Codestral` 。 + +如果你想要在本地运行模型,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#autocomplete-model) 使用 `Starcoder2-3B` 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/chat.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/chat.md new file mode 100644 index 000000000..c49051360 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/chat.md @@ -0,0 +1,18 @@ +--- +title: 聊天模型 +description: 聊天模型 +keywords: [聊天] +sidebar_position: 2 +--- + +"聊天模型" 是一个训练为在交谈格式中响应的 LLM 。因为它们应该回答通用问题和生成复杂代码,最好的聊天模型通常是很大的,通常 405B+ 参数。在 Continue 中,这些模型用来 [聊天](../../chat/how-to-use-it.md) , [编辑](../../edit/how-to-use-it.md) 和 [Actions](../../actions/how-to-use-it.md) 。 + +## 推荐的聊天模型 + +如果你有使用任何模型的能力,我们推荐 [Claude 3.5 Sonnet](../model-providers/top-level/anthropic.md) 。 + +否则,以下是一些最好的选择: + +- [GPT-4o](../model-providers/top-level/openai.md) +- [Gemini 1.5 Pro](../model-providers/top-level/gemini.md) +- [Llama3.1 405B](../tutorials/llama3.1.md) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md new file mode 100644 index 000000000..78cbc03c2 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/embeddings.md @@ -0,0 +1,71 @@ +--- +title: 嵌入模型 +description: 嵌入模型 +keywords: [嵌入] +sidebar_position: 3 +--- + +"嵌入模型" 是训练用来转换一部分文本为向量,可以在之后快速的与其他向量比较,决定部分文本的相似性。嵌入模型通常比 LLM 小得多,在比较中非常快速和便宜。 + +在 Continue 中,嵌入是在索引是生成的,然后由 [@Codebase](../deep-dives/codebase.md) 使用,来实现对你的代码库的相似性搜索。 + +## 推荐的嵌入模型 + +如果你有使用任何模型的能力,我们推荐 `voyage-code-2` ,它独立列在下面,和其他的嵌入模型选项一起。 + +如果你想本地生成嵌入,我们推荐通过 [Ollama](../model-providers/top-level/ollama.md#embeddings-model) 使用 `nomic-embed-text` 。 + +### Voyage AI + +在从 [这里](https://www.voyageai.com/) 获取 API key 后,你可以像这样配置: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "voyage", + "model": "voyage-code-2", + "apiKey": "" + } +} +``` + +### Ollama + +查看 [这个](../model-providers/top-level/ollama.md#embeddings-model) 获取如何使用 Ollama 来嵌入的指令。 + +### Transformers.js (当前只有 VS Code) + +[Transformers.js](https://huggingface.co/docs/transformers.js/index) 是流行的 [Transformers](https://huggingface.co/transformers/) 库一个 JavaScript 移植。它允许嵌入完全在本地计算。模型使用的是 `all-MiniLM-L6-v2` ,与 Continue 扩展一起,当你没有明确配置嵌入提供者时,作为默认使用。 + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "transformers.js" + } +} +``` + +### 文本嵌入推理 + +[Hugging Face 文本嵌入推理](https://huggingface.co/docs/text-embeddings-inference/en/index) 允许你托管自己的嵌入端点。你可以如下配置嵌入使用自己的端点: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "huggingface-tei", + "apiBase": "http://localhost:8080" + } +} +``` + +### OpenAI + +查看 [这里](../model-providers/top-level/openai.md#embeddings-model) 获取如何使用 OpenAI 嵌入的指令。 + +### Cohere + +查看 [这里](../model-providers/more/cohere.md#embeddings-model) 获取如何使用 Cohere 嵌入的指令。 + +### Gemini + +查看 [这里](../model-providers/top-level/gemini.md#embeddings-model) 获取如何使用 Gemini 嵌入的指令。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/reranking.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/reranking.md new file mode 100644 index 000000000..4e530b985 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-types/reranking.md @@ -0,0 +1,92 @@ +--- +title: 重排序模型 +description: 重排序模型 +keywords: [重排序] +sidebar_position: 4 +--- + +"重排序模型" 是训练为采用两部分文本(通常一个用户问题和一个文档)并返回 0 和 1 之间的相关性得分,估算文档回答问题的可用性。重排序通常远小于 LLM ,在比较中非常快速和便宜。 + +在 Continue 中,重排序用在 [@Codebase](../deep-dives/codebase.md) ,为了在向量搜索之后选择最想关的代码片断。 + +## 推荐的重排序模型 + +如果你有使用任何模型的能力,我们推荐 Voyage AI 的 `rerank-1` ,它独立列在下面,和其他的重排序选项一起。 + +### Voyage AI + +Voyage AI 提供代码最好的重排序模型, 使用他们的 `rerank-1` 模型。在从 [这里](https://www.voyageai.com/) 获取 API key 后,你可以像这样配置: + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-1", + "apiKey": "" + } + } +} +``` + +### Cohere + +在 [这里](https://docs.cohere.com/docs/rerank-2) 查看 Cohere 对于重排序的文档。 + +```json title="config.json" +{ + "reranker": { + "name": "cohere", + "params": { + "model": "rerank-english-v3.0", + "apiKey": "" + } + } +} +``` + +### LLM + +如果你只能访问一个单独的 LLM ,那么你可以使用它作为重排器。这是不推荐的,除非真正需要,因为它将会更昂贵,并且仍然比上面这些特殊任务训练的模型慢。注意,如果你使用本地的模型,这将不会工作,例如使用 Ollama ,因为会创建太多的并发请求。 + +```json title="config.json" +{ + "reranker": { + "name": "llm", + "params": { + "modelTitle": "My Model Title" + } + } +} +``` + +`"modelTitle"` 字段必须匹配在你的 `config.json` 中 "models" 列表中的一个模型。 + +### 文本嵌入推理 + +[Hugging Face 文本嵌入推理](https://huggingface.co/docs/text-embeddings-inference/en/index) 允许你托管自己的 [重排器端点](https://huggingface.github.io/text-embeddings-inference/#/Text%20Embeddings%20Inference/rerank) 。你可以像这样配置你的重排器: + +```json title="config.json" +{ + "reranker": { + "name": "huggingface-tei", + "params": { + "apiBase": "http://localhost:8080", + "truncate": true, + "truncation_direction": "Right" + } + } +} +``` + +### 免费试用 (Voyage AI) + +Continue 提供 Voyage AI 重排序模型的免费试用。 + +```json title="config.json" +{ + "reranker": { + "name": "free-trial" + } +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md new file mode 100644 index 000000000..784c0bd59 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/overview.md @@ -0,0 +1,23 @@ +--- +title: 概览 +description: 定制 Continue 简介 +keywords: [定制, 配置, 配置] +--- + +Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config.json` (MacOS / Linux) 或 `%USERPROFILE%\.continue\config.json` (Windows) 的本地文件实现。 `config.json` 在你第一次使用 Continue 时创建。 + +## 开始 + +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。 + +当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 + +## 每个工作区的配置 + +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。 + +## 可编程的配置 + +`config.json` 可以处理大多数需要的配置,所以我们推荐在可能的情况下使用它。不过,如果你需要可编程的配置 Continue ,你可以使用 `config.ts` ,它位于 `~/.continue/config.ts` (MacOS / Linux) 或 `%USERPROFILE%\.continue\config.ts` (Windows) 。 + +例如,如何使用 `config.ts` ,查看 [编写定制斜杠命令](./tutorials/build-your-own-slash-command.md#custom-slash-commands) 或者 [编写定制上下文提供者](./tutorials/build-your-own-context-provider.md) 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/slash-commands.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/slash-commands.md new file mode 100644 index 000000000..778a36522 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/slash-commands.md @@ -0,0 +1,153 @@ +--- +title: 斜杠命令 +description: 以 '/' 为开头激活的快捷方式 +keywords: [斜杠命令, 自定义命令, 步骤] +--- + +斜杠命令是可以通过输入 '/' 来激活,并从下拉框中选择的快捷方式。例如,内置的 '/edit' 斜杠命令,让你可以直接在你的编辑器中流式地编辑。 + +![slash-commands](/img/slash-commands.png) + +## 内置的斜杠命令 + +为了使用任何内置的斜杠命令,打开 `config.json` 并添加它到 `slashCommands` 列表中。 + +### `/Edit` + +使用 `ctrl/cmd + L` (VS Code) 或 `ctrl/cmd + J` (JetBrains) 选择代码,然后输入 `/Edit` ,跟着编辑的指令。 Continue 将会流式地在一个并排 diff 编辑器中修改。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "edit", + "description": "Edit highlighted code" + } + ] +} +``` + +### `/Comment` + +Comment 工作就像 `/Edit` ,除了它将自动地给 LLM 注释代码的提示词。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "comment", + "description": "Write comments for the highlighted code" + } + ] +} +``` + +### `/Share` + +生成一个关于你当前聊天历史的可分享的 markdown 副本。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "share", + "description": "Export the current chat session to markdown", + "params": { "outputDir": "~/.continue/session-transcripts" } + } + ] +} +``` + +使用 `outputDir` 参数指定你想要把 markdown 文件保存在哪里。 + +### `/Cmd` + +通过自然语言生成一个 shell 命令,并且(只在 VS Code 中)自动地粘贴它到终端中。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `/Commit` + +显示给 LLM 你当前的 git diff ,并询问生成一个 commit 消息。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message for the current changes" + } + ] +} +``` + +### `/Http` + +编写一个自定义的斜杠命令,在你自己的 HTTP 端点。在参数对象中对于你设置的端点设置 'url' 。端点应该返回一个字符串更新序列,将会流式地输出到 Continue 侧边栏。查看我们基本的 [FastAPI 示例](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) 作为参考。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "http", + "description": "Does something custom", + "params": { "url": "" } + } + ] +} +``` + +### `/Issue` + +描述你想要生成的 issue , Continue 会转换为格式良好的标题和正文,然后给你一个草稿的链接,让你可以提交。确保设置你想要生成 issue 的仓库的 URL 。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "issue", + "description": "Generate a link to a drafted GitHub issue", + "params": { "repositoryUrl": "https://github.com/continuedev/continue" } + } + ] +} +``` + +### `/So` + +StackOverflow 斜杠命令将会自动地拉取 StackOverflow 的结果来回答你的问题,引用链接和它的答案一起。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "so", + "description": "Reference StackOverflow to answer the question" + } + ] +} +``` + +### `/Onboard` + +Onboard 斜杠命令帮助你熟悉一个新的项目,通过分析项目结构, README 和依赖文件。它发现关键目录,解释它们的目的,并高亮使用的流行的包。另外,它提供对项目架构的了解。 + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "onboard", + "description": "Familiarize yourself with the codebase" + } + ] +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md new file mode 100644 index 000000000..735f405de --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-context-provider.md @@ -0,0 +1,250 @@ +--- +title: 构建你自己的上下文提供者 +--- + +## 入门示例 + +要编写你自己的上下文提供者,你只需要实现 `CustomContextProvider` 接口: + +```typescript +interface CustomContextProvider { + title: string; + displayTitle?: string; + description?: string; + renderInlineAs?: string; + type?: ContextProviderType; + getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise; + loadSubmenuItems?: ( + args: LoadSubmenuItemsArgs, + ) => Promise; +} +``` + +作为一个例子,比如你有一系列内部文件索引到一个向量数据库中。你设置了一个简单的 REST API ,允许内部用户查询和获取相关的片段。这个上下文提供者将会发送请求到这个服务器,并从向量数据库返回结果。返回的类型 `getContextItems` _必须_ 是一个包含所有以下属性的实例的列表: + +- `name`: 上下文条目的名称,将会展示为标题 +- `description`: 上下文条目的一个较长的描述 +- `content`: 上下文条目的实际内容,将会发送给 LLM 作为上下文 + +```typescript title="~/.continue/config.ts" +const RagContextProvider: CustomContextProvider = { + title: "rag", + displayTitle: "RAG", + description: + "Retrieve snippets from our vector database of internal documents", + + getContextItems: async ( + query: string, + extras: ContextProviderExtras, + ): Promise => { + const response = await fetch("https://internal_rag_server.com/retrieve", { + method: "POST", + body: JSON.stringify({ query }), + }); + + const results = await response.json(); + + return results.map((result) => ({ + name: result.title, + description: result.title, + content: result.contents, + })); + }, +}; +``` + +它可以被添加到 `config.ts` 像这样: + +```typescript title="~/.continue/config.ts" +export function modifyConfig(config: Config): Config { + if (!config.contextProviders) { + config.contextProviders = []; + } + config.contextProviders.push(RagContextProvider); + return config; +} +``` + +不需要对 `config.json` 做修改。 + +## 定制有 submenu 或 query 的上下文提供者 + +这里有 3 种类型的上下文提供者:"normal", "query" 和 "submenu" 。 "normal" 类型是默认的,就是你目前所看到的。 + +**"query"** 类型用来当你想要显示文本框给用户,然后使用那个文本框的内容生成上下文条目。内置示例包含 "search" 和 "google" 。这个文本是传递给 `getContextItems` 中的 "query" 参数。为了实现一个 "query" 上下文提供者,简单地设置 `"type": "query"` 在你的定制上下文提供者实例中。 + +**"submenu"** 类型用来当你想要在下拉框显示一个可搜索条目列表。内置示例包含 "issue" 和 "folder" 。为了实现一个 "submenu" 上下文提供者,设置 `"type": "submenu"` 并实现 `loadSubmenuItems` 和 `getContextItems` 函数。这是一个例子,显示当前工作区所有 README 文件的列表: + +```typescript title="~/.continue/config.ts" +const ReadMeContextProvider: CustomContextProvider = { + title: "readme", + displayTitle: "README", + description: "Reference README.md files in your workspace", + type: "submenu", + + getContextItems: async ( + query: string, + extras: ContextProviderExtras, + ): Promise => { + // 'query' is the filepath of the README selected from the dropdown + const content = await extras.ide.readFile(query); + return [ + { + name: getFolder(query), + description: getFolderAndBasename(query), + content, + }, + ]; + }, + + loadSubmenuItems: async ( + args: LoadSubmenuItemsArgs, + ): Promise => { + // Filter all workspace files for READMEs + const allFiles = await args.ide.listWorkspaceContents(); + const readmes = allFiles.filter((filepath) => + filepath.endsWith("README.md"), + ); + + // Return the items that will be shown in the dropdown + return readmes.map((filepath) => { + return { + id: filepath, + title: getFolder(filepath), + description: getFolderAndBasename(filepath), + }; + }); + }, +}; + +export function modifyConfig(config: Config): Config { + if (!config.contextProviders) { + config.contextProviders = []; + } + config.contextProviders.push(ReadMeContextProvider); + return config; +} + +function getFolder(path: string): string { + return path.split(/[\/\\]/g).slice(-2)[0]; +} + +function getFolderAndBasename(path: string): string { + return path + .split(/[\/\\]/g) + .slice(-2) + .join("/"); +} +``` + +以上示例的信息流如下: + +1. 用户输入 `@readme` 并从下拉框中选择,现在显示子菜单,他们可以搜索任何 `loadSubmenuItems` 返回的条目。 +2. 用户在子菜单中选择 README 之一,输入其他输入,并按下回车。 +3. 选择的 `ContextSubmenuItem` 的 id 传递给 `getContextItems` 作为 `query` 参数。在这个例子中,它是 README 的文件路径。 +4. 然后 `getContextItems` 函数使用 `query` 获取 README 的完整内容,并在返回上下文条目之前格式化内容,它会包含在提示词之中。 + +## 导入外部模块 + +为了包含外部的 Node 模块在你的 config.ts 中,在 `~/.continue` 文件夹运行 `npm install ` ,然后在 config.ts 中导入它们。 + +Continue 将使用 [esbuild](https://esbuild.github.io/) 打包你的 `config.ts` 和任何依赖到一个单独的 Javascript 文件。确切使用的配置可以在 [这里](https://github.com/continuedev/continue/blob/5c9874400e223bbc9786a8823614a2e501fbdaf7/extensions/vscode/src/ideProtocol.ts#L45-L52) 找到。 + +## `CustomContextProvider` 参考 + +- `title`: 上下文提供者的标识符 +- `displayTitle` (可选):在下拉框中显示的标题 +- `description` (可选):当鼠标悬停时,在下拉框中显示的较长的描述 +- `type` (可选):上下文提供者的类型。可选项是 "normal", "query" 和 "submenu" 。默认是 "normal" 。 +- `renderInlineAs` (可选):将会在提示词上面渲染的字符串。如果没有值提供, `displayTitle` 将会被sisyphus。可以提供空字符串来禁止渲染默认的 `displayTitle` 。 +- `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments: +- `getContextItems`: 一个返回包含在提示词中文档的函数。它应该返回一个 `ContextItem` 列表,并可以访问以下参数: + - `extras.fullInput`: 一个代表用户在文本框中完整输入的字符串。这可以用来生成嵌入,与一批其他的嵌入文档比较 + - `extras.embeddingsProvider`: 嵌入提供者有一个 `embed` 函数,将会转换文本 (例如 `fullInput`) 为嵌入 + - `extras.llm`: 当前默认的 LLM ,你可以用来创建补全请求 + - `extras.ide`: 一个 `IDE` 类的实例,让你可以收集来自 IDE 的不同来源的信息,包括终端的内容,打开文件的列表,或追额当前打开文件中的任何警告。 + - `query`: (not currently used) A string representing the query + - `query`: (当前没有使用) 代表 query 的字符串 +- `loadSubmenuItems` (可选): 一个返回 `ContextSubmenuItem` 列表的函数,显示在子菜单中。它可以访问 `IDE` ,同样传递给 `getContextItems` 。 + +## 使用其他语言编写上下文提供者 + +如果你想要用除了 TypeScript 的其他语言编写上下文提供者,你可以使用 "http" 上下文提供者,来调用一个托管你自己代码的服务器。添加上下文提供者到 `config.json` ,像这样: + +```json +{ + "name": "http", + "params": { + "url": "https://myserver.com/context-provider", + "title": "http", + "description": "Custom HTTP Context Provider", + "displayTitle": "My Custom Context" + } +} +``` + + + +## VSCode 的扩展 API + +Continue 暴露一个 API ,从第三方 VSCode 扩展注册上下文提供者。这是有用的,如果你有一个 VSCode 扩展,提供一些额外的上下文,你想要在 Continue 中使用。为了使用这个 API ,添加以下内容到你的 `package.json` : + +```json +{ + "extensionDependencies": ["continue.continue"] +} +``` + +或者复制 `~/.continue/type/core/index.d.ts` 到你的扩展仓库。 + +然后,你可以使用 `registerCustomContextProvider` 函数注册你的上下文提供者。你定制的上下文提供者必须实现 `IContextProvider` 接口。 +这是一个例子: + +```typescript +import * as vscode from "vscode"; + +class MyCustomProvider implements IContextProvider { + get description(): ContextProviderDescription { + return { + title: "custom", + displayTitle: "Custom", + description: "Custom description", + type: "normal", + }; + } + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + return [ + { + name: "Custom", + description: "Custom description", + content: "Custom content", + }, + ]; + } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + return []; + } +} + +// create an instance of your custom provider +const customProvider = new MyCustomProvider(); + +// get Continue extension using vscode API +const continueExt = vscode.extensions.getExtension("continue.continue"); + +// get the API from the extension +const continueApi = continueExt?.exports; + +// register your custom provider +continueApi?.registerCustomContextProvider(customProvider); +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md new file mode 100644 index 000000000..755bb2b14 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/build-your-own-slash-command.md @@ -0,0 +1,60 @@ +--- +title: 构建你自己的斜杠命令 +--- + +这里有两种方式可以添加自定义斜杠命令: + +1. 使用自然语言提示词 - 这个比较简单,只需要编写一个字符串或字符串模板。 +2. 使用一个自定义函数 - 这个给你完全访问 Continue SDK 并允许你编写任意的 Typescript 代码。 + +### "自定义命令" (使用自然语言) + +你可以添加自定义斜杠命令,通过添加到 `config.json` 中的 `customCommands` 属性。 + +- `name`: 命令的名称,使用 `/name` 触发 +- `description`: 命令的一个简短描述,会出现在下拉框中 +- `prompt`: 一个模板的提示词发送给 LLM + +当你频繁使用一个提示词时,自定义命令很好用。例如,如果你精心制作了一个很好的提示词,频繁地问 LLM 检查你代码中的错误,你可以添加一个命令,像这样: + +```json title="config.json" +customCommands=[{ + "name": "check", + "description": "Check for mistakes in my code", + "prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found." +}] +``` + +#### 模板 + +`prompt` 属性支持 Handlebars 语法的模板。你可以使用以下参数: + +- `input` (在上面的例子中使用): 斜杠命令的任何额外输入。例如,如果你输入 `/test only write one test` , `input` 将是 `only write one test` 。这还将包含高亮的代码块。 +- 文件名称: 你可以引用任何文件,通过提供绝对路径或当前工作目录的相对路径。 + +### 自定义斜杠命令 + +如果你想要比使用自然语言编写自定义命令更进一步,你可以编写一个自定义函数返回响应。这需要使用 `config.ts` 代替 `config.json` 。 + +为了做这个,放一个新的 `SlashCommand` 对象到 `slashCommands` 列表中。这个对象包含 "name" ,你用来触发斜杠命令的名称, "description" ,在下拉菜单中看到的描述,以及 "run" 。 `run` 函数是任何异步生成器,应该生成你想要流式输出到 UI 的字符串。作为函数的参数,你可以访问一个有实用工具的 `ContinueSDK` 对象,例如访问 IDE 中的当前信息/action ,当前语言模型,以及一些其他实用工具。例如,这是一个生成 commit 信息的斜杠命令: + +```typescript title="~/.continue/config.ts" +export function modifyConfig(config: Config): Config { + config.slashCommands?.push({ + name: "commit", + description: "Write a commit message", + run: async function* (sdk) { + const diff = await sdk.ide.getDiff(); + for await (const message of sdk.llm.streamComplete( + `${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`, + { + maxTokens: 20, + }, + )) { + yield message; + } + }, + }); + return config; +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md new file mode 100644 index 000000000..118e7945d --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/custom-code-rag.md @@ -0,0 +1,148 @@ +# 定制代码 RAG + +虽然 Continue 的 [@Codebase](../deep-dives/codebase.md) 开箱即用,你可能想要设置自己的向量数据库,并构建一个定制的检索增强生成(RAG)系统。这允许你访问不在本地可用的代码,对每个用户每次索引代码,或者包含定制的逻辑。在这个指南中,我们将展示构建这个的步骤。 + +## 步骤 1 :选择嵌入模型 + +如果可能,我们推荐使用 [`voyage-code-2`](https://docs.voyageai.com/docs/embeddings) ,它将给出最准确的答案,关于任何已存的代码嵌入模型。你可以在 [这里](https://dash.voyageai.com/api-keys) 获取 API key 。因为他门的 API 是 [OpenAI-兼容的](https://docs.voyageai.com/reference/embeddings-api) ,你可以使用任何 OpenAI 客户端换出 URL 。 + +## 步骤 2 :选择向量模型 + +这里有一些可用的向量数据库,但是因为大多数向量数据库能够良好地处理大的代码库,我们推荐选择设置和实验简单的一个。 + +[LanceDB](https://lancedb.github.io/lancedb/basic/) 是一个很好的选择,因为它可以在内存中运行,有 Python 和 Node.js 库。这意味着,在开始的时候,你可以专注于编写代码,而不是设置基础设施。如果你已经选择了向量数据库,那么使用这个代替 LanceDB 也是一个好的选择。 + +## 步骤 3 :选择一个 "分块" 策略 + +大多数嵌入模型只能一次处理有限的文本数量。为了解决这个问题,我们 "分块" 我们的代码到较小的部分。 + +如果你使用 `voyage-code-2` ,它可以有最大 16,000 token 上下文长度,足够容纳大多数文件。这意味着,在开始的时候,你可以使用更朴素的策略避免超过限制。为了最简单到最综合,你可以使用 3 分块策略: + +1. 截断文件,当它超过上下文长度:在这种情况下,你总是每个文件有 1 个分块。 +2. 拆分文件到一个固定长度的分块:从文件的最上面开始,添加你当前分块的行,直到它到达限制,然后开始一个新的分块。 +3. 使用一个递归的,基于抽象语法树(AST)的策略:这是最准确的,但是最复杂的。在大多数情况下,通过使用 (1) 或 (2) ,你可以获得好的质量结果,但是如果你想要尝试这个,你可以查找一个参考示例,在 [我们的代码 chunker](https://github.com/continuedev/continue/blob/main/core/indexing/chunk/code.ts) 或在 [LlamaIndex](https://docs.llamaindex.ai/en/stable/api_reference/node_parsers/code/) 。 + +像往常一样,在这个指南中,我们推荐开始的策略,使用 20% 的努力获得 80% 的收益。 + +## 步骤 4 :放在一起一个索引脚本 + +Indexing, in which we will insert your code into the vector database in a retrievable format, happens in three steps: + +索引,我们将以可检索的格式插入你的代码到向量数据库,有以下三个步骤: + +1. 分块 +2. 生成嵌入 +3. 插入到向量数据库 + +使用 LanceDB ,我们可以同时做步骤 2 和 3 ,像 [他门的文档](https://lancedb.github.io/lancedb/basic/#using-the-embedding-api) 所描述的。如果你使用 Voyage AI ,它可以配置像下面这样: + +```python +from lancedb.pydantic import LanceModel, Vector +from lancedb.embeddings import get_registry + +db = lancedb.connect("/tmp/db") +func = get_registry().get("openai").create( + name="voyage-code-2", + base_url="https://api.voyageai.com/v1/", + api_key=os.environ["VOYAGE_API_KEY"], +) + +class CodeChunks(LanceModel): + filename: str + text: str = func.SourceField() + # 1536 is the embedding dimension of the `voyage-code-2` model. + vector: Vector(1536) = func.VectorField() + +table = db.create_table("code_chunks", schema=CodeChunks, mode="overwrite") +table.add([ + {"text": "print('hello world!')", filename: "hello.py"}, + {"text": "print('goodbye world!')", filename: "goodbye.py"} +]) + +query = "greetings" +actual = table.search(query).limit(1).to_pydantic(CodeChunks)[0] +print(actual.text) +``` + +:::tip +如果你索引超过一个仓库,最好保存它们到不同的 "table" (LanceDB 使用的术语)或 "collection" (一些其他向量数据库使用的术语)。可替代的做法,添加一个 "repository" 字段,然后通过这个过滤是性能较低的。 +::: + +不管你选择的是哪个数据库或模型,你的脚本应该迭代你想要索引的所有文件,对它们分块,生成每个分块的嵌入,然后插入所有分块到你的向量数据库。 + +## 步骤 5 :运行你的索引脚本 + +:::tip +在一个完成的生产版本,你想要构建 "自动的,增量的索引" ,以便无论任何时候文件变更,那个文件没有别的自动重新索引。这有完全最新嵌入的收益和较低的花费。 + +也就是说,我们强烈推荐,在尝试这个之前,首先构建和测试流水线。除非你的代码库频繁地整个重写,一个完整的索引刷新,是足够的和合理的便宜。 +::: + +在这个点上,你编写了你的索引脚本,测试可以从你的向量数据库做查询。现在,你想要什么时候运行索引脚本的计划。 + +在开始的时候,你可能手动运行它。一旦你确认,你定制的 RAG 提供了值,准备好长期使用,那么你可以设置一个 cron 任务,定期地运行它。因为代码库在短的时间内不会大量变更,你不会想要重新索引超过一天一次。每周一次或每月一次甚至可能是足够的。 + +## 步骤 6 :设置你的服务器 + +为了 Continue 扩展能够访问你的定制 RAG 系统,你需要设置服务器。这个服务器负责接收来自扩展的查询,查询向量数据库,返回 Continue 想要的格式的结果。 + +这是一个使用 FastAPI 的参考实现,适用于处理来自 Continue 的 "http" 上下文提供者的请求。 + +```python +""" +This is an example of a server that can be used with the "http" context provider. +""" + +from fastapi import FastAPI +from pydantic import BaseModel + + +class ContextProviderInput(BaseModel): + query: str + fullInput: str + + +app = FastAPI() + + +@app.post("/retrieve") +async def create_item(item: ContextProviderInput): + results = [] # TODO: Query your vector database here. + + # Construct the "context item" format expected by Continue + context_items = [] + for result in results: + context_items.append({ + "name": result.filename, + "description": result.filename, + "content": result.text, + }) + + return context_items +``` + +在你设置服务器之后,你可以配置 Continue 使用它,通过添加 "http" 上下文提供者到你的 `config.json` 中的 `contextProviders` 列表: + +```json title="config.json" +{ + "name": "http", + "params": { + "url": "https://myserver.com/retrieve", + "title": "http", + "description": "Custom HTTP Context Provider", + "displayTitle": "My Custom Context" + } +} +``` + +## 步骤 7 (额外的):设置重排序 + +如果你想要提高你的结果的质量,一个好的首先的步骤是添加重排序。这涉及到获取一个更大的来自向量数据库的初始结果池,然后使用重排序模型对它们进行排序,从最高到最低相关性。这是有效的,因为重排序模型可以执行一个稍高的计算,在一个小的最高结果上,所以可以给出比相似性搜索更准确的排序,它需要搜索数据库中所有的条目。 + +例如,如果你想要对于每个查询返回 10 个完整的结果,那么你可以: + +1. 使用相似性搜索从向量数据库检索 ~50 个结果 +2. 发送所有这 50 个结果到重排器 API ,与查询一起,为了获取每个结果的相关性分数 +3. 通过相关性分数对结果进行排序,并返回最前面 10 个 + +我们推荐使用来自 Voyage AI 的 `rerank-1` 模型,它有使用示例 [在这里](https://docs.voyageai.com/docs/reranker) 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/how-to-self-host-a-model.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/how-to-self-host-a-model.md new file mode 100644 index 000000000..c9a611b19 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/how-to-self-host-a-model.md @@ -0,0 +1,76 @@ +--- +title: 如何自托管模型 +--- + +你可以在你的 [AWS](https://github.com/continuedev/deploy-os-code-llm#aws), [GCP](https://github.com/continuedev/deploy-os-code-llm#gcp), [Azure](https://github.com/continuedev/deploy-os-code-llm#azure), [Lambda](https://lambdalabs.com/) 或 [其他云](https://github.com/continuedev/deploy-os-code-llm#others-2) 上部署模型,使用: + +- [HuggingFace TGI](https://github.com/continuedev/deploy-os-code-llm#tgi) +- [vLLM](https://github.com/continuedev/deploy-os-code-llm#vllm) +- [SkyPilot](https://github.com/continuedev/deploy-os-code-llm#skypilot) +- [Anyscale Private Endpoints](https://github.com/continuedev/deploy-os-code-llm#anyscale-private-endpoints) (OpenAI 兼容 API) +- [Lambda](https://github.com/continuedev/deploy-os-code-llm#lambda) + +## 自托管开源模型 + +对于很多情况, Continue 内置的提供者或你使用的 API 是 OpenAI-兼容的,这种情况下,你可以使用 "openai" 提供者,修改 "baseUrl" 指向服务器。 + +不过,如果这些情况都不是,你需要编写一个新的 LLM 对象。 + +## 认证 + +对于任何提供者,基本认证可以通过使用 `apiKey` 字段完成: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "llama2-7b", + "apiKey": "xxx" + } + ] +} +``` + +这会转换为 header `"Authorization": "Bearer xxx"` 。 + +如果你需要发送定制的 header 来认证,你可能使用 `requestOptions.headers` 属性,比如这里例子中的 Ollama : + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "llama2-7b", + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } + } + ] +} +``` + +类似地,如果你的模型需要 Certificate 来认证,你可能使用 `requestOptions.clientCertificate` 属性,比如下面的例子: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "llama2-7b", + "requestOptions": { + "clientCertificate": { + "cert": "C:\tempollama.pem", + "key": "C:\tempollama.key", + "passphrase": "c0nt!nu3" + } + } + } + ] +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md new file mode 100644 index 000000000..2453fbd94 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md @@ -0,0 +1,113 @@ +--- +title: Continue 使用 Llama 3.1 +description: Continue 如何使用 Llama 3.1 +keywords: [llama, meta, togetherai, ollama, replicate] +--- + +Continue 让使用最新的开元模型编码变得简单,包括整个 Llama 3.1 家族模型。 + +如果你还没有安装 Continue ,你可以安装 [VS Code 在这里](https://marketplace.visualstudio.com/items?itemName=Continue.continue) 或者 [JetBrains 在这里](https://plugins.jetbrains.com/plugin/22707-continue) 。对于更通用的定制 Continue 的信息,查看 [我们的定制文档](../overview.md) 。 + +下面,我们分享一些最简单的配置和运行,基于你的使用情况。 + +## Ollama + +Ollama 是最快的配置和运行本地语言模型的方法。我们推荐尝试 Llama 3.1 8b ,它是令人印象深刻的,它的大小和在大多数硬件上表现良好。 + +1. 下载 Ollama [在这里](https://ollama.ai/) (它将带你通过其他的步骤) +2. 打开终端并运行 `ollama run llama3.1:8b` +3. 修改 Continue 配置文件像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 8b", + "provider": "ollama", + "model": "llama3.1-8b" + } + ] +} +``` + +## Groq + +Groq 提供最快的可用的开源语言模型推理,包括整个 Llama 3.1 家族。 + +1. 获取 API key [在这里](https://console.groq.com/keys) +2. 更新你的 Continue 配置文件像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "groq", + "model": "llama3.1-405b", + "apiKey": "" + } + ] +} +``` + +## Together AI + +Together AI 提供开源模型的快速和可信任的推理。你可以以良好的速度运行 405b 模型。 + +1. 创建账号 [在这里](https://api.together.xyz/signup) +2. 复制出现在欢迎屏幕上你的 API key +3. 更新你的 Continue 配置文件像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "together", + "model": "llama3.1-405b", + "apiKey": "" + } + ] +} +``` + +## Replicate + +Replicate 让使用 API 托管和运行开源 AI 变得简单。 + +1. 获取你的 Replicate API key [在这里](https://replicate.ai/) +2. 修改你的 Continue 配置文件像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Llama 3.1 405b", + "provider": "replicate", + "model": "llama3.1-405b", + "apiKey": "" + } + ] +} +``` + +## SambaNova + +SambaNova Cloud 提供 Llama3.1 70B/405B 服务的世界记录。 + +1. 创建账号 [在这里](https://cloud.sambanova.ai/) +2. 复制你的 API key +3. 更新你的 Continue 配置文件像这样: + +```json title="~/.continue/config.json" +{ + "models": [ + { + "title": "SambaNova Llama 3.1 405B", + "provider": "sambanova", + "model": "llama3.1-405b", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/running-continue-without-internet.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/running-continue-without-internet.md new file mode 100644 index 000000000..146394d76 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/running-continue-without-internet.md @@ -0,0 +1,12 @@ +--- +title: 不联网使用 Continue +description: 如何不联网使用 Continue +keywords: [不联网, air-gapped, 本地模型] +--- + +Continue 甚至可以运行在 air-gapped 计算机上,如果你使用本地模型。只需要少量的调整就可以工作。 + +1. 从 [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) 下载最新的 .vsix 文件,并 [安装它到 VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix) 。 +2. 打开 `~/.continue/config.json` 并设置 `"allowAnonymousTelemetry": false` 。这将停止 Continue 尝试请求 PostHog 获取 [匿名遥测](../../telemetry.md) 。 +3. 还在 `config.json` 中,设置默认的模型为本地模型。你可以 [在这里](../model-providers/) 看到可用的选项。 +4. 重启 VS Code 确保对 `config.json` 的变更生效。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/set-up-codestral.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/set-up-codestral.md new file mode 100644 index 000000000..583b128a0 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/set-up-codestral.md @@ -0,0 +1,69 @@ +--- +title: 如何设置 Codestral +description: 如何设置 Codestral +keywords: [codestral, mistral, 模型设置] +--- + +![mistral x continue](../../../../../../static/img/mistral-x-continue.png) + +**这是一个分步指南,关于如何在 Continue 设置 Codestral ,使用 Mistral AI API :** + +1. 安装 Continue VS Code 或 JetBrains 扩展,跟随 [这里](../../getting-started/install.md) 的指令 + +2. 点击 Continue 窗口右下角的齿轮图标,打开 `~/.continue/config.json` (MacOS) / `%userprofile%\.continue\config.json` (Windows) + +3. 登录并创建一个 API key ,在 [这里](https://console.mistral.ai/codestral) 的 Mistral AI's La Plateforme 。确保你从 "Codestral" 页面获得一个 API key ,一般的 "api.mistral.ai" API 的 API key 不能工作。 + +4. 为了使用 Codestral 作为你的 `自动补全` 和 `聊天` 模型,使用 Mistral API key 替换下面的 `[API_KEY]` ,并把它添加到你的 `config.json` 文件: + +```json title="config.json" +{ + "models": [ + { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "[API_KEY]" + } + ], + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "[API_KEY]" + } +} +``` + +5. 如果你遇到任何 issue 或有任何问题,请加入我们的 Discord 并在 [这里的](https://discord.gg/EfJEfdFnDQ) `#help` 频道发帖 + +## 故障排除 + +### JetBrains 的临时变通方法 + +Mistral AI 最近修改 API 端点,使用 `codestral.mistral.ai` 替换 `api.mistral.ai` ,我们更新的 JetBrains 扩展正在等待商店批准。在这个期间,你必须在 config.json 中指定 apiBase 为 `https://codestral.mistral.ai/v1` ,像这样: + +```json title="config.json" +{ + "models": [ + { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "[API_KEY]", + "apiBase": "https://codestral.mistral.ai/v1/" + } + ], + "tabAutocompleteModel": { + "title": "Codestral", + "provider": "mistral", + "model": "codestral-latest", + "apiKey": "[API_KEY]", + "apiBase": "https://codestral.mistral.ai/v1/" + } +} +``` + +### 在 Discord 寻求帮助 + +请加入我们的 Discord ,并在 [这里](https://discord.gg/EfJEfdFnDQ) 的 `#help` 频道发帖,如果你使用 Codestral 有任何问题 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/context-selection.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/context-selection.md new file mode 100644 index 000000000..6690976f5 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/context-selection.md @@ -0,0 +1,18 @@ +--- +title: 上下文选择 +sidebar_position: 3 +description: 如何选择编辑的上下文 +keywords: [编辑, cmd i, 工作] +--- + +## 输入 + +你提供的输入包含在提示词中。 + +## 高亮代码 + +你选择的高亮代码包含在提示词中。这是唯一模型会尝试编辑的代码块。 + +## 当前文件 + +包含你的高亮代码块的文件的整个内容都作为额外的上下文。这给了模型一个关于代码环境的全面的理解。如果文件太大不能放在上下文窗口中,我们将截断文件内容放入。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-it-works.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-it-works.md new file mode 100644 index 000000000..06e81fd24 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-it-works.md @@ -0,0 +1,14 @@ +--- +title: 编辑是如何工作的 +sidebar_position: 4 +description: 编辑是如何工作的 +keywords: [编辑, cmd l, 工作] +--- + +使用高亮代码,包含你的高亮代码的文件内容,以及你的输入指令,我们提示模型根据你的指令编辑代码。没有更多的上下文提供给模型。 + +模型响应会直接流式地返回到你的代码高亮范围中,我们使用一个 diff 格式来显示建议的变更。 + +如果你接受 diff ,我们移除之前的高亮行,如果你拒绝 diff ,我们移除建议的变更。 + +如果你想查看在编辑中发送给模型的确切的提示词,你可以 [在提示词日志中查看这个](troubleshooting.md#check-the-logs) 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-to-customize.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-to-customize.md new file mode 100644 index 000000000..648d1a335 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-to-customize.md @@ -0,0 +1,16 @@ +--- +title: 如何定制 +sidebar_position: 5 +description: 如何定制编辑 +keywords: [编辑, cmd i, 工作] +--- + +你可以配置编辑使用指定的模型,使用 `inlineEdit` 属性。 + +```json title="config.json" +"experimental": { + "modelRoles": { + "inlineEdit": "MODEL_TITLE", + } +} +``` diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-to-use-it.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-to-use-it.md new file mode 100644 index 000000000..850fdf95e --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/how-to-use-it.md @@ -0,0 +1,37 @@ +--- +title: 编辑 +sidebar_position: 1 +sidebar_label: 如何使用它 +description: 如何使用编辑 +keywords: [编辑, cmd l, 使用] +--- + +![edit](/img/edit.gif) + +## 如何使用它 + +编辑是一种不用离开你的当前文件来修改代码的方便的方式。高亮一个代码块,描述你的代码变更,一个 diff 会流式地出现在你的文件行内,你可以接受或拒绝。 + +编辑最好用在小的,快速的变更上,比如: + +- 编写注释 +- 生成单元测试 +- 重构函数或方法 + +## 高亮代码并激活 + +高亮你想要修改的代码块,按下 `cmd/ctrl + i` 来激活编辑输入。 + +## 描述代码变更 + +描述你想要模型对你的高亮代码所做的变更。对于编辑,一个好的提示词应该是相对较短且简洁的。对于长的,更复杂的任务,我们推荐使用 [聊天](chat/how-to-use-it.md) 。 + +## 接受和拒绝变更 + +建议的变更作为行内 diff 出现在你的高亮文本中。 + +你可以导航到每个建议变更,接受或拒绝它们,使用 `cmd/ctrl + opt + y` (接受) 或 `cmd/ctrl + opt + n` (拒绝) 。 + +你也可以一次性接受或拒绝所有变更,使用 `cmd/ctrl + shift + enter` (接受) 或 `cmd/ctrl + shift + delete` (拒绝) 。 + +如果你想要对于相同的高亮代码块请求一个新的建议,你可以使用 `cmd/ctrl + i` 重新提示模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md new file mode 100644 index 000000000..f96a8fe6d --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/edit/model-setup.md @@ -0,0 +1,10 @@ +--- +title: 模型设置 +sidebar_position: 2 +description: 如何设置一个编辑模型 +keywords: [编辑, cmd l, 模型] +--- + +默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 + +你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/getting-started/install.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/getting-started/install.md new file mode 100644 index 000000000..169b2061c --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/getting-started/install.md @@ -0,0 +1,33 @@ +--- +title: 安装 +description: 开发者的开源 AI 代码助手 +keywords: [安装, 开始, vs code, jetbrains] +--- + +## VS Code + +1. 点击 [Visual Studio 市场中 Continue 扩展页面](https://marketplace.visualstudio.com/items?itemName=Continue.continue) 的 `安装` 按钮 + +2. 这会打开 VS Code 中的 Continue 扩展页面,你需要再次点击 `安装` + +3. Continue 标志会出现在左侧边栏中。为了获得更好的体验,可以把 Continue 移动到右侧边栏 + +![move-to-right-sidebar](/img/move-to-right-sidebar.gif) + +:::info[故障排除] +如果你有任何问题,查看 [故障排除指南](troubleshooting.md) 或者在 [我们的 Discord](https://discord.gg/NWtdYexhMs) 寻求帮助 +::: + +## JetBrains + +1. 打开你的 JetBrains IDE 并使用 `cmd/ctrl + ,` 打开 **设置** + +2. 在侧边栏中选择 **插件** 并在市场中查找 "Continue" + +3. 点击 `安装`, 随后 Continue 标志会出现在右侧边栏 + +![jetbrains-getting-started.png](/img/jetbrains-getting-started.png) + +:::info[故障排除] +如果你有任何问题,查看 [故障排除指南](troubleshooting.md) 或者在 [我们的 Discord](https://discord.com/invite/EfJEfdFnDQ) 寻求帮助 +::: diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/getting-started/overview.mdx b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/getting-started/overview.mdx new file mode 100644 index 000000000..e3ee2af29 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/getting-started/overview.mdx @@ -0,0 +1,58 @@ +--- +title: 概览 +description: 开始使用 Continue +keywords: [快速开始, 开始, 概览, 聊天, 自动补全, 编辑, actions] +--- + +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; +import Admonition from "@theme/Admonition"; + +为了快速理解你可以在 Continue 做的事,查看下面的每个标签页。 + + + + + [聊天](../chat/how-to-use-it.md#how-to-use-it) 让你方便向 LLM 寻求帮助,而不需要离开 IDE + + ![chat](/img/chat.gif) + + + 了解更多关于 [聊天](../chat/how-to-use-it.md#how-to-use-it) + + + + + + [自动补全](../autocomplete/how-to-use-it.md#how-to-use-it) 随着你的输入提供行内代码建议 + + ![autocomplete](/img/autocomplete.gif) + + + 了解更多关于 [自动补全](../autocomplete/how-to-use-it.md#how-to-use-it) + + + + + + [编辑](../edit/how-to-use-it.md#how-to-use-it) 是一种编辑代码的方便的方式,不需要离开你的当前文件 + + ![edit](/img/edit.gif) + + + 了解更多关于 [编辑](../edit/how-to-use-it.md#how-to-use-it) + + + + + + [Actions](../actions/how-to-use-it.md#how-to-use-it) 是常用情况的快捷方式 + + ![actions](/img/actions.gif) + + + 了解更多关于如何使用 [Actions](../actions/how-to-use-it.md#how-to-use-it) + + + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/introduction.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/introduction.md new file mode 100644 index 000000000..9248b0bb2 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/introduction.md @@ -0,0 +1,25 @@ +--- +title: 简介 +description: 开发者的开源 AI 代码助手 +slug: / +keywords: + [ + continue, + AI, + 代码助手, + 自动补全, + 聊天, + VS Code, + JetBrains, + 简介, + ] +--- + +![Continue Logo](/img/intro.png) + +**Continue 是 [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) 和 [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) 中领先的开源 AI 代码助手** + +- [聊天](chat/how-to-use-it.md) 在侧边栏中理解和迭代代码 +- [自动补全](autocomplete/how-to-use-it.md) 在你输入时获取行内代码建议 +- [编辑](edit/how-to-use-it.md) 在不需要离开当前文件的情况下修改代码 +- [Actions](actions/how-to-use-it.md) 对于常用情况建立快捷方式 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/telemetry.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/telemetry.md new file mode 100644 index 000000000..319c45445 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/telemetry.md @@ -0,0 +1,50 @@ +--- +title: 遥测 +description: 了解 Continue 如何收集匿名使用信息,以及你如何选择退出 +keywords: [遥测, 匿名, 使用信息, 选择退出] +--- + +## 概述 +Continue 收集并报告 **匿名** 使用信息,来帮助我们提高产品。这个数据允许我们有效地理解用户交互,并优化用户体验。你可以在任何时候选择退出遥测收集,如果你倾向与不分享你的使用信息。 + +我们使用 [Posthog](https://posthog.com/) ,一个产品分析的开源平台,来收集并存储这个数据。为了透明,你可以 [在这里](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) 检查实现代码,或者查看我们的 [官方隐私策略](https://continue.dev/privacy) 。 + +## 跟踪策略 + +所有 Continue 收集的数据是匿名的,在发送到 PostHog 之前,除去个人可识别信息 (PII) 。我们承诺维护你的数据的隐私和安全。 + +## 我们跟踪什么 + +以下使用信息被收集和报告: + +- **建议交互:** 你是否接受或拒绝建议(不包括涉及的实际代码或提示词)。 +- **模型和命令信息:** 使用的模型和命令的名称。 +- **token 指标:** 生成的 token 的数量。 +- **系统信息:** 你的操作系统 (OS) 和集成开发环境 (IDE) 的名称。 +- **页面浏览量:** 一般页面浏览量统计。 + +## 如何退出 + +你可以通过修改位于 `~/.continue` 目录中 `config.json` 文件禁用匿名遥测。这个文件通常包含以下条目: + +```json title="config.json" +{ + "allowAnonymousTelemetry": true +} +``` + +为了退出,修改 `allowAnonymousTelemetry` 的值为 `false` 。另外,你可以通过 VS Code 设置禁用遥测,通过取消勾选 "Continue: Telemetry Enabled" 选择框。 + +### 通过配置文件禁用遥测的步骤 + +1. 用你的文件编辑器打开 `~/.continue/config.json` 文件。 +2. 定位到 `"allowAnonymousTelemetry"` 设置。 +3. 将值从 `true` 修改为 `false` 。 +4. 保存文件。 + +### 通过 VS Code 设置禁用遥测 + +1. 打开 VS Code 。 +2. 导航到 `File` > `Preferences` > `Settings` (或在 Windows/Linux 上使用快捷键 `Ctrl + ,` 或在 macOS 上使用 `Cmd + ,` )。 +3. 在搜索栏中,输入 "Continue: Telemetry Enabled" 。 +4. 取消勾选 "Continue: Telemetry Enabled" 选择框。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md new file mode 100644 index 000000000..9f1ceab6a --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/troubleshooting.md @@ -0,0 +1,131 @@ +--- +title: 故障排除 +description: 故障排除,在等待 beta / alpha 测试帮助时 +keywords: [重新加载, 删除, 手动, 日志, 服务器, 控制台] +--- + +Continue VS Code 扩展现在是 beta , JetBrains 扩展现在是 Alpha 。如果你有问题,请跟随下面的步骤。 + +1. [检查日志](#check-the-logs) +2. [尝试最新的预览版](#download-the-latest-pre-release) +3. [下载较老的版本](#download-an-older-version) +4. [解析快件键问题](#keyboard-shortcuts-not-resolving) +5. [检查常见问题的 FAQ](#faqs) + +## 检查日志 + +解决很多问题,第一步是阅读日志找到相关的错误信息。要做这个,跟随下面的步骤: + +### VS Code + +#### 控制台日志 + +:::info +为了查看调试日志,它包含额外的信息,点击最上面是 "Default levels" 的下拉框并选择 "Verbose" 。 +::: + +1. `cmd+shift+p` (MacOS) / `ctrl+shift+p` (Windows) +2. 查找,然后选择 "Developer: Toggle Developer Tools" +3. 这将打开 [Chrome DevTools window](https://developer.chrome.com/docs/devtools/) +4. 选择 `Console` 标签 +5. 查看控制台日志 + +#### LLM 提示词日志 + +如果你从 LLM 获得的响应看起来是不合理的,你可以 + +1. 打开 "Output" 面板 (终端的下一个) +2. 在下拉框中,选择 "Continue - LLM Prompts/Completions" +3. 查看发送给 LLM ,补全所接受的确切的提示词 + +### JetBrains + +打开 `~/.continue/logs/core.log` 。最近的日志可以在文件的底部找到。 + +## 下载最新的预览版 + +### VS Code + +我们不断地修复和改进 Continue ,但是最新的修改停留在 "预览" 版大概一周,让我们可以测试它们的稳定性。如果你遇到问题,你可以尝试预览版,通过去 VS Code 的 Continue 扩展页面,并选择 "切换到预览版" ,像下面显示的这样。 + +![Pre-Release](../../../../static/img/prerelease.png) + +### JetBrains + +在 JetBrains 上, "预览版" 出现在他们的抢先体验计划 (EAP) 频道。要下载最新的 EAP 版本,启用 EAP 频道: + +1. 打开 JetBrains 设置 (`cmd/ctrl + ,`) 并导航到 "插件" +2. 点击顶部的齿轮图标 +3. 选择 "管理插件仓库..." +4. 添加 "[https://plugins.jetbrains.com/plugins/eap/list](https://plugins.jetbrains.com/plugins/eap/list)" 到列表中 +5. 你现在总是可以在市场下载最新的 EAP 版本 + +## 下载一个较老的版本 + +如果你尝试了所有东西,报告一个错误,知道一个之前的版本对你有效,并等待回复,你可以尝试下载一个扩展的比较老的版本。 + +对于 VS Code ,所有版本都托管在 [这里](https://open-vsx.org/extension/Continue/continue) 的 Open VSX Registry 。一旦你下载了扩展,它是一个 .vsix 文件,你可以通过 [在这里](https://code.visualstudio.com/docs/editor/extension-gallery#_install-from-a-vsix) 的以下指令手动安装它。 + +你可以在他们的 [市场](https://plugins.jetbrains.com/plugin/22707-continue) 中找到较老版本的 JetBrains 扩展,这将允许你从磁盘上安装。 + +## 快捷键无法解析 + +如果你的快捷键无法解析,你可能有其他命令优先于 Continue 快捷键。你可以看看是否是这种情况,在你的 IDE 的配置中修改你的快捷键绑定。 + +- [VSCode 快捷键文档](https://code.visualstudio.com/docs/getstarted/keybindings) +- [IntelliJ 快捷键文档](https://www.jetbrains.com/help/idea/configuring-keyboard-and-mouse-shortcuts.html) + +## 常见问题 + +### 网络问题 + +#### 配置证书 + +如果你看到 `fetch failed` 错误,并且你的网络需要自定义证书,你需要在 `config.json` 配置它们。在 `"models"` 列表的每个对象中,添加 `requestOptions.caBundlePath` ,像这样: + +```json +{ + "models": [ + { + "title": "My Model", + ... + "requestOptions": { + "caBundlePath": "/path/to/cert.pem" + } + } + ], + ... +} +``` + +你可能也需要为多个证书设置 `requestOptions.caBundlePath` 到路径列表。 + +#### VS Code 代理设置 + +如果你使用 VS Code ,需要通过代理进行请求,你可能已经通过 VS Code 的 [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support) 设置。为了检查这个是否启用,使用 `cmd/ctrl+,` 打开设置并查找 "Proxy Support" ,除非它设置为 "off" ,那么 VS Code 将会负责对代理进行请求。 + +#### code-server + +Continue 可以在 [code-server](https://coder.com/) 中使用,但是如果你运行,日志中错误包含 "This is likely because the editor is not running in a secure context" ,请查看 [他们的关于安全暴露 code-server 的文档](https://coder.com/docs/code-server/latest/guide#expose-code-server) 。 + +### 我安装了 Continue ,但是没有看到侧边栏窗口 + +默认情况下, VS Code 中的 Continue 窗口在左边,但是它也可以拖动到右边,这在我们的入门教程中是推荐的。在你已经安装 Continue 并将它移动到右边的情况下,它可能仍然在那里。你可以显示 Continue ,通过使用 `cmd/ctrl+L` 或点击 VS Code 右上方的按钮打开右侧边栏。 + +### 我得到一个 OpenAI 的 404 错误 + +如果你输入一个有效的 API key 和模型,但是仍然得到 OpenAI 的 404 错误,这可能是因为你需要添加信用卡到你的账单账户。你可以在 [账单控制台](https://platform.openai.com/settings/organization/billing/overview)这样做。如果你只想要检查这确实是错误的原因,你可以尝试添加 1 美元到你的账户,再检查错误是否仍然存在。 + +### 索引问题 + +如果你有持续的索引问题,我们的推荐是重新构建你的索引。注意,对于大的代码库,这可能需要一些时间。 + +这可以通过以下命令实现: `Continue: Rebuild codebase index` 。 + +### Android Studio - "Nothing to show" 在聊天中 + +这可以修复,通过选择 `Actions > Choose Boot runtime for the IDE` ,然后选择最新的版本,然后重启 Android Studio 。[查看这个线索](https://github.com/continuedev/continue/issues/2280#issuecomment-2365231567) 获得详情。 + +## 仍然有问题? + +你还可以 [在这里](https://discord.gg/vapESyrFmJ) 加入我们的 Discord 社区,获得更多的支持和讨论。另外,你可以 [在这里](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=) 创建一个 GitHub issue ,提供你的问题的详情,我们将能更快的帮助你。 diff --git a/docs/i18n/zh-CN/docusaurus-theme-classic/footer.json b/docs/i18n/zh-CN/docusaurus-theme-classic/footer.json new file mode 100644 index 000000000..381e52193 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-theme-classic/footer.json @@ -0,0 +1,42 @@ +{ + "link.title.Extensions": { + "message": "扩展", + "description": "The title of the footer links column with title=Extensions in the footer" + }, + "link.title.Community": { + "message": "社区", + "description": "The title of the footer links column with title=Community in the footer" + }, + "link.title.Follow Us": { + "message": "关注我们", + "description": "The title of the footer links column with title=Follow Us in the footer" + }, + "link.item.label.VS Code": { + "message": "VS Code", + "description": "The label of footer link with label=VS Code linking to https://marketplace.visualstudio.com/items?itemName=Continue.continue" + }, + "link.item.label.JetBrains": { + "message": "JetBrains", + "description": "The label of footer link with label=JetBrains linking to https://plugins.jetbrains.com/plugin/22707-continue-extension" + }, + "link.item.label.Discord": { + "message": "Discord", + "description": "The label of footer link with label=Discord linking to https://discord.gg/vapESyrFmJ" + }, + "link.item.label.GitHub": { + "message": "GitHub", + "description": "The label of footer link with label=GitHub linking to https://github.com/continuedev/continue" + }, + "link.item.label.Twitter": { + "message": "Twitter", + "description": "The label of footer link with label=Twitter linking to https://twitter.com/continuedev" + }, + "link.item.label.LinkedIn": { + "message": "LinkedIn", + "description": "The label of footer link with label=LinkedIn linking to https://linkedin.com/company/continuedev" + }, + "copyright": { + "message": "Copyright © 2024 Continue Dev, Inc.", + "description": "The footer copyright" + } +} diff --git a/docs/i18n/zh-CN/docusaurus-theme-classic/navbar.json b/docs/i18n/zh-CN/docusaurus-theme-classic/navbar.json new file mode 100644 index 000000000..872b8559d --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-theme-classic/navbar.json @@ -0,0 +1,26 @@ +{ + "title": { + "message": "Continue", + "description": "The title in the navbar" + }, + "logo.alt": { + "message": "Continue Logo", + "description": "The alt text of navbar logo" + }, + "item.label.Docs": { + "message": "文档", + "description": "Navbar item with label Docs" + }, + "item.label.Customize": { + "message": "定制", + "description": "Navbar item with label Customize" + }, + "item.label.GitHub": { + "message": "GitHub", + "description": "Navbar item with label GitHub" + }, + "item.label.Discord": { + "message": "Discord", + "description": "Navbar item with label Discord" + } +} diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 953db6d20..a0535391f 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -204,7 +204,8 @@ "askSage", "nebius", "vertexai", - "xAI" + "xAI", + "kindo" ], "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)", @@ -240,7 +241,8 @@ "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", "### 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/)" + "### 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//)" ], "type": "string" }, @@ -467,7 +469,8 @@ "cloudflare", "sambanova", "nebius", - "xAI" + "xAI", + "kindo" ] } }, diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 76b93351e..30828f300 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -559,6 +559,7 @@ "tsc-watch": "tsc -watch -p ./", "rebuild": "electron-rebuild -v 19.1.8 node-pty", "lint": "eslint src --ext ts", + "lint:fix": "eslint . --ext ts --fix", "build-test": "npm run esbuild && node esbuild.test.mjs", "test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", "quick-test": "npm run build-test && node ./out/runTestOnVSCodeHost.js", diff --git a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts index b84d921f7..8c8c399a7 100644 --- a/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts +++ b/extensions/vscode/src/ContinueGUIWebviewViewProvider.ts @@ -1,18 +1,24 @@ -import type { FileEdit } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { EXTENSION_NAME } from "core/control-plane/env"; import * as vscode from "vscode"; + import { getTheme } from "./util/getTheme"; import { getExtensionVersion } from "./util/util"; import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode"; import { VsCodeWebviewProtocol } from "./webviewProtocol"; +import type { FileEdit } from "core"; + export class ContinueGUIWebviewViewProvider implements vscode.WebviewViewProvider { public static readonly viewType = "continue.continueGUIView"; public webviewProtocol: VsCodeWebviewProtocol; + public get isReady(): boolean { + return !!this.webview; + } + private updateDebugLogsStatus() { const settings = vscode.workspace.getConfiguration(EXTENSION_NAME); this.enableDebugLogs = settings.get("enableDebugLogs", false); diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index eabb2fec8..217f33e6d 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -2,6 +2,28 @@ import * as child_process from "node:child_process"; import { exec } from "node:child_process"; import * as path from "node:path"; +import { Range } from "core"; +import { EXTENSION_NAME } from "core/control-plane/env"; +import { walkDir } from "core/indexing/walkDir"; +import { GetGhTokenArgs } from "core/protocol/ide"; +import { + editConfigJson, + getConfigJsonPath, + getContinueGlobalPath, +} from "core/util/paths"; +import * as vscode from "vscode"; + +import { executeGotoProvider } from "./autocomplete/lsp"; +import { DiffManager } from "./diff/horizontal"; +import { Repository } from "./otherExtensions/git"; +import { VsCodeIdeUtils } from "./util/ideUtils"; +import { + getExtensionUri, + openEditorAndRevealRange, + uriFromFilePath, +} from "./util/vscode"; +import { VsCodeWebviewProtocol } from "./webviewProtocol"; + import type { ContinueRcJson, FileType, @@ -14,26 +36,6 @@ import type { RangeInFile, Thread, } from "core"; -import { Range } from "core"; -import { EXTENSION_NAME } from "core/control-plane/env"; -import { walkDir } from "core/indexing/walkDir"; -import { GetGhTokenArgs } from "core/protocol/ide"; -import { - editConfigJson, - getConfigJsonPath, - getContinueGlobalPath, -} from "core/util/paths"; -import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; -import { DiffManager } from "./diff/horizontal"; -import { Repository } from "./otherExtensions/git"; -import { VsCodeIdeUtils } from "./util/ideUtils"; -import { - getExtensionUri, - openEditorAndRevealRange, - uriFromFilePath, -} from "./util/vscode"; -import { VsCodeWebviewProtocol } from "./webviewProtocol"; class VsCodeIde implements IDE { ideUtils: VsCodeIdeUtils; @@ -487,12 +489,14 @@ class VsCodeIde implements IDE { } async getCurrentFile() { - if (!vscode.window.activeTextEditor) return undefined + if (!vscode.window.activeTextEditor) { + return undefined; + } return { isUntitled: vscode.window.activeTextEditor.document.isUntitled, path: vscode.window.activeTextEditor.document.uri.fsPath, - contents: vscode.window.activeTextEditor.document.getText() - } + contents: vscode.window.activeTextEditor.document.getText(), + }; } async getPinnedFiles(): Promise { @@ -627,4 +631,3 @@ class VsCodeIde implements IDE { } export { VsCodeIde }; - diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 864b07cc4..7aa0ae4a9 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -1,9 +1,11 @@ import { getContinueRcPath, getTsConfigPath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; + import { VsCodeExtension } from "../extension/VsCodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; + import { VsCodeContinueApi } from "./api"; import { setupInlineTips } from "./inlineTips"; diff --git a/extensions/vscode/src/activation/api.ts b/extensions/vscode/src/activation/api.ts index 9d8f5d0db..5c54bf418 100644 --- a/extensions/vscode/src/activation/api.ts +++ b/extensions/vscode/src/activation/api.ts @@ -1,4 +1,5 @@ import { IContextProvider } from "core"; + import { VsCodeExtension } from "../extension/VsCodeExtension"; export class VsCodeContinueApi { diff --git a/extensions/vscode/src/activation/inlineTips.ts b/extensions/vscode/src/activation/inlineTips.ts index 7cd1ef2bc..49a8adf29 100644 --- a/extensions/vscode/src/activation/inlineTips.ts +++ b/extensions/vscode/src/activation/inlineTips.ts @@ -1,5 +1,6 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import * as vscode from "vscode"; + import { getMetaKeyName } from "../util/util"; const inlineTipDecoration = vscode.window.createTextEditorDecorationType({ diff --git a/extensions/vscode/src/activation/languageClient.ts b/extensions/vscode/src/activation/languageClient.ts index 98663bdc3..c3b4b96c5 100644 --- a/extensions/vscode/src/activation/languageClient.ts +++ b/extensions/vscode/src/activation/languageClient.ts @@ -3,8 +3,8 @@ */ import * as path from "node:path"; -import { type ExtensionContext, extensions, workspace } from "vscode"; +import { type ExtensionContext, extensions, workspace } from "vscode"; import { LanguageClient, type LanguageClientOptions, @@ -13,6 +13,7 @@ import { type StateChangeEvent, TransportKind, } from "vscode-languageclient/node"; + import { getExtensionUri } from "../util/vscode"; let client: LanguageClient; @@ -65,7 +66,7 @@ function startPythonLanguageServer(context: ExtensionContext): LanguageClient { configurationSection: "pyls", }, }; - return new LanguageClient(command, serverOptions, clientOptions) + return new LanguageClient(command, serverOptions, clientOptions); } async function startPylance(context: ExtensionContext) { diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 131d61ffa..b6b04297f 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,4 +1,3 @@ -import type { IDE } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { type AutocompleteInput, @@ -7,9 +6,10 @@ import { import { ConfigHandler } from "core/config/ConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; -import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; + import { showFreeTrialLoginMessage } from "../util/messages"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; + import { getDefinitionsFromLsp } from "./lsp"; import { RecentlyEditedTracker } from "./recentlyEdited"; import { @@ -19,6 +19,9 @@ import { stopStatusBarLoading, } from "./statusBar"; +import type { TabAutocompleteModel } from "../util/loadAutocompleteModel"; +import type { IDE } from "core"; + interface VsCodeCompletionInput { document: vscode.TextDocument; position: vscode.Position; diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index 41ae1d973..f900058ab 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,4 +1,3 @@ -import type { IDE, Range, RangeInFile } from "core"; import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; @@ -10,6 +9,8 @@ import { } from "core/indexing/chunk/code"; import { intersection } from "core/util/ranges"; import * as vscode from "vscode"; + +import type { IDE, Range, RangeInFile } from "core"; import type Parser from "web-tree-sitter"; type GotoProviderName = @@ -133,7 +134,7 @@ async function crawlTypes( // Parse AST const ast = await getAst(rif.filepath, contents); - if (!ast) return results; + if (!ast) {return results;} const astLineCount = ast.rootNode.text.split("\n").length; // Find type identifiers @@ -342,10 +343,10 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( ): Promise => { try { const ast = await getAst(filepath, contents); - if (!ast) return []; + if (!ast) {return [];} const treePath = await getTreePathAtCursor(ast, cursorIndex); - if (!treePath) return []; + if (!treePath) {return [];} const results: RangeInFileWithContents[] = []; for (const node of treePath.reverse()) { diff --git a/extensions/vscode/src/autocomplete/statusBar.ts b/extensions/vscode/src/autocomplete/statusBar.ts index df7ae1dad..faa85338f 100644 --- a/extensions/vscode/src/autocomplete/statusBar.ts +++ b/extensions/vscode/src/autocomplete/statusBar.ts @@ -1,6 +1,7 @@ import { ILLM } from "core"; import { EXTENSION_NAME } from "core/control-plane/env"; import * as vscode from "vscode"; + import { Battery } from "../util/battery"; import { CONTINUE_WORKSPACE_KEY, diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 560413db3..4733dee6f 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,4 +1,8 @@ /* eslint-disable @typescript-eslint/naming-convention */ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + import { ContextMenuConfig } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { RangeInFileWithContents } from "core/commands/util"; @@ -11,11 +15,9 @@ import { walkDirAsync } from "core/indexing/walkDir"; import { GlobalContext } from "core/util/GlobalContext"; import { getConfigJsonPath, getDevDataFilePath } from "core/util/paths"; import { Telemetry } from "core/util/posthog"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; import readLastLines from "read-last-lines"; import * as vscode from "vscode"; + import { StatusBarStatus, getAutocompleteStatusBarDescription, @@ -34,6 +36,7 @@ import { Battery } from "./util/battery"; import { getFullyQualifiedPath } from "./util/util"; import { uriFromFilePath } from "./util/vscode"; import { VsCodeIde } from "./VsCodeIde"; + import type { VsCodeWebviewProtocol } from "./webviewProtocol"; let fullScreenPanel: vscode.WebviewPanel | undefined; @@ -363,6 +366,14 @@ const commandsMap: ( core.invoke("context/indexDocs", { reIndex: true }); }, "continue.focusContinueInput": async () => { + // This is a temporary fix—sidebar.webviewProtocol.request is blocking + // when the GUI hasn't yet been setup and we should instead be + // immediately throwing an error, or returning a Result object + if (!sidebar.isReady) { + focusGUI(); + return; + } + const historyLength = await sidebar.webviewProtocol.request( "getWebviewHistoryLength", undefined, @@ -385,6 +396,14 @@ const commandsMap: ( } }, "continue.focusContinueInputWithoutClear": async () => { + // This is a temporary fix—sidebar.webviewProtocol.request is blocking + // when the GUI hasn't yet been setup and we should instead be + // immediately throwing an error, or returning a Result object + if (!sidebar.isReady) { + focusGUI(); + return; + } + const isContinueInputFocused = await sidebar.webviewProtocol.request( "isContinueInputFocused", undefined, diff --git a/extensions/vscode/src/debug/debug.ts b/extensions/vscode/src/debug/debug.ts index 27a2be28e..ff762fd22 100644 --- a/extensions/vscode/src/debug/debug.ts +++ b/extensions/vscode/src/debug/debug.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode"; + import type { VsCodeIde } from "../VsCodeIde"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -33,29 +34,29 @@ export function registerDebugTracker( case "continued": case "stopped": if (typeof message.body.threadId !== "undefined") - threadStopped.set( + {threadStopped.set( Number(message.body.threadId), message.event === "stopped", - ); + );} if (message.body.allThreadsStopped) - threadStopped.forEach((_, key) => + {threadStopped.forEach((_, key) => threadStopped.set(key, true), - ); + );} if (message.body.allThreadsContinued) - threadStopped.forEach((_, key) => + {threadStopped.forEach((_, key) => threadStopped.set(key, false), - ); + );} updateThreads(); break; case "thread": if (message.body.reason === "exited") - threadStopped.delete(Number(message.body.threadId)); + {threadStopped.delete(Number(message.body.threadId));} else if (message.body.reason === "started") - threadStopped.set(Number(message.body.threadId), false); + {threadStopped.set(Number(message.body.threadId), false);} // somehow the threadId does not respect the specification in my vscodium (debugging C++) // expecting a number but got a string instead break; diff --git a/extensions/vscode/src/decorations.ts b/extensions/vscode/src/decorations.ts index 9ac6a49ca..6547c2986 100644 --- a/extensions/vscode/src/decorations.ts +++ b/extensions/vscode/src/decorations.ts @@ -1,5 +1,7 @@ import * as path from "node:path"; + import * as vscode from "vscode"; + import { uriFromFilePath } from "./util/vscode"; export function showAnswerInTextEditor( diff --git a/extensions/vscode/src/diff/horizontal.ts b/extensions/vscode/src/diff/horizontal.ts index 6313f0bfa..65c411265 100644 --- a/extensions/vscode/src/diff/horizontal.ts +++ b/extensions/vscode/src/diff/horizontal.ts @@ -1,10 +1,13 @@ -import { devDataPath } from "core/util/paths"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; + +import { devDataPath } from "core/util/paths"; import * as vscode from "vscode"; + import { getMetaKeyLabel, getPlatform } from "../util/util"; import { uriFromFilePath } from "../util/vscode"; + import type { VsCodeWebviewProtocol } from "../webviewProtocol"; interface DiffInfo { diff --git a/extensions/vscode/src/diff/vertical/handler.ts b/extensions/vscode/src/diff/vertical/handler.ts index fe643b1bb..323c8caaf 100644 --- a/extensions/vscode/src/diff/vertical/handler.ts +++ b/extensions/vscode/src/diff/vertical/handler.ts @@ -1,6 +1,6 @@ -import type { DiffLine } from "core"; import { ApplyState } from "core/protocol/ideWebview"; import * as vscode from "vscode"; + import { DecorationTypeRangeManager, belowIndexDecorationType, @@ -8,7 +8,9 @@ import { indexDecorationType, redDecorationType, } from "./decorations"; + import type { VerticalDiffCodeLens } from "./manager"; +import type { DiffLine } from "core"; export interface VerticalDiffHandlerOptions { input?: string; diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index 80aa54be1..f4b762d35 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -4,8 +4,10 @@ import { streamDiffLines } from "core/edit/streamDiffLines"; import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens"; import { getMarkdownLanguageTagForFile } from "core/util"; import * as vscode from "vscode"; + import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; + import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -178,6 +180,8 @@ export class VerticalDiffManager { // Re-enable listener for user changes to file this.enableDocumentChangeListener(); } + + this.refreshCodeLens(); } async streamDiffLines( @@ -267,13 +271,13 @@ export class VerticalDiffManager { onlyOneInsertion?: boolean, quickEdit?: string, range?: vscode.Range, - ) { + ): Promise { vscode.commands.executeCommand("setContext", "continue.diffVisible", true); let editor = vscode.window.activeTextEditor; if (!editor) { - return; + return undefined; } const filepath = editor.document.uri.fsPath; @@ -348,7 +352,7 @@ export class VerticalDiffManager { if (!diffHandler) { console.warn("Issue occured while creating new vertical diff handler"); - return; + return undefined; } let selectedRange = diffHandler.range; @@ -398,8 +402,10 @@ export class VerticalDiffManager { this.editDecorationManager.clear(); try { - this.logDiffs = await diffHandler.run( - streamDiffLines( + const streamedLines: string[] = []; + + async function* recordedStream() { + const stream = streamDiffLines( prefix, rangeContent, suffix, @@ -407,14 +413,26 @@ export class VerticalDiffManager { input, getMarkdownLanguageTagForFile(filepath), onlyOneInsertion, - ), - ); + ); + + for await (const line of stream) { + if (line.type === "new" || line.type === "same") { + streamedLines.push(line.line); + } + yield line; + } + } + + this.logDiffs = await diffHandler.run(recordedStream()); // enable a listener for user edits to file while diff is open this.enableDocumentChangeListener(); + + return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + return undefined; } finally { vscode.commands.executeCommand( "setContext", diff --git a/extensions/vscode/src/extension.ts b/extensions/vscode/src/extension.ts index 9fa7cfb49..f1aa3f3e4 100644 --- a/extensions/vscode/src/extension.ts +++ b/extensions/vscode/src/extension.ts @@ -6,6 +6,7 @@ import { setupCa } from "core/util/ca"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; + import { getExtensionVersion } from "./util/util"; async function dynamicImportAndActivate(context: vscode.ExtensionContext) { diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index faee3cc06..f8bc7c556 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -1,3 +1,5 @@ +import fs from "fs"; + import { IContextProvider } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import { controlPlaneEnv, EXTENSION_NAME } from "core/control-plane/env"; @@ -5,9 +7,9 @@ import { Core } from "core/core"; import { FromCoreProtocol, ToCoreProtocol } from "core/protocol"; import { InProcessMessenger } from "core/util/messenger"; import { getConfigJsonPath, getConfigTsPath } from "core/util/paths"; -import fs from "fs"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; + import { ContinueCompletionProvider } from "../autocomplete/completionProvider"; import { monitorBatteryChanges, @@ -32,9 +34,11 @@ import { Battery } from "../util/battery"; import { FileSearch } from "../util/FileSearch"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; import { VsCodeIde } from "../VsCodeIde"; -import type { VsCodeWebviewProtocol } from "../webviewProtocol"; + import { VsCodeMessenger } from "./VsCodeMessenger"; +import type { VsCodeWebviewProtocol } from "../webviewProtocol"; + export class VsCodeExtension { // Currently some of these are public so they can be used in testing (test/test-suites) @@ -293,15 +297,15 @@ export class VsCodeExtension { // Reindex the file this.core.invoke("index/forceReIndex", { dirs: [filepath] - }) + }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { this.core.invoke("index/forceReIndex", { dirs: event.files.map((file) => file.fsPath.split("/").slice(0, -1).join("/")) - }) - }) + }); + }); // When GitHub sign-in status changes, reload config vscode.authentication.onDidChangeSessions(async (e) => { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index e1356a9c1..ff60b13c8 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -1,3 +1,6 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; + import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; import { applyCodeBlock } from "core/edit/lazy/applyCodeBlock"; @@ -17,19 +20,18 @@ import { import { getBasename } from "core/util"; import { InProcessMessenger, Message } from "core/util/messenger"; import { getConfigJsonPath } from "core/util/paths"; -import * as fs from "node:fs"; -import * as path from "node:path"; import * as vscode from "vscode"; + import { VerticalDiffManager } from "../diff/vertical/manager"; import EditDecorationManager from "../quickEdit/EditDecorationManager"; import { getControlPlaneSessionInfo, WorkOsAuthProvider, } from "../stubs/WorkOsAuthProvider"; +import { getFullyQualifiedPath } from "../util/util"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; -import { getFullyQualifiedPath } from "../util/util"; /** * A shared messenger class between Core and Webview @@ -318,7 +320,7 @@ export class VsCodeMessenger { "getDefaultModelTitle", undefined, ); - await verticalDiffManager.streamEdit( + const fileAfterEdit = await verticalDiffManager.streamEdit( stripImages(prompt), modelTitle, "edit", @@ -332,6 +334,7 @@ export class VsCodeMessenger { this.webviewProtocol.request("setEditStatus", { status: "accepting", + fileAfterEdit, }); }); this.onWebview("edit/acceptReject", async (msg) => { diff --git a/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts index c3f374c48..80225874c 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/ConfigPyCodeLensProvider.ts @@ -1,6 +1,7 @@ -import * as vscode from "vscode"; import * as os from "os"; +import * as vscode from "vscode"; + export class ConfigPyCodeLensProvider implements vscode.CodeLensProvider { public provideCodeLenses( document: vscode.TextDocument, diff --git a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts index b67db0e52..f3ef5c67a 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/DiffViewerCodeLensProvider.ts @@ -1,5 +1,7 @@ import path from "path"; + import * as vscode from "vscode"; + import { DiffManager, DIFF_DIRECTORY } from "../../../diff/horizontal"; import { getMetaKeyLabel } from "../../../util/util"; diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts index 08decb215..b4c30350b 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -1,6 +1,7 @@ import { ContinueConfig, QuickActionConfig } from "core"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; + import { QuickEditShowParams } from "../../../quickEdit/QuickEditQuickPick"; import { CONTINUE_WORKSPACE_KEY, diff --git a/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts index d0541d228..e66749084 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/SuggestionsCodeLensProvider.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode"; + import { editorToSuggestions } from "../../../suggestions"; import { getMetaKeyLabel } from "../../../util/util"; diff --git a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts index a96cf5660..5d07e6ce2 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/VerticalPerLineCodeLensProvider.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode"; + import { VerticalDiffCodeLens } from "../../../diff/vertical/manager"; import { getMetaKeyLabel } from "../../../util/util"; diff --git a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts index b70ade262..292999f7b 100644 --- a/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts +++ b/extensions/vscode/src/lang-server/codeLens/registerAllCodeLensProviders.ts @@ -1,7 +1,9 @@ import { ContinueConfig } from "core"; import * as vscode from "vscode"; + import { DiffManager } from "../../diff/horizontal"; import { VerticalDiffCodeLens } from "../../diff/vertical/manager"; + import * as providers from "./providers"; import { getQuickActionsConfig, diff --git a/extensions/vscode/src/lang-server/promptFileCompletions.ts b/extensions/vscode/src/lang-server/promptFileCompletions.ts index da620f700..ef873b44d 100644 --- a/extensions/vscode/src/lang-server/promptFileCompletions.ts +++ b/extensions/vscode/src/lang-server/promptFileCompletions.ts @@ -1,6 +1,7 @@ import { IDE } from "core"; import { getBasename, getLastNPathParts } from "core/util"; import vscode from "vscode"; + import { FileSearch } from "../util/FileSearch"; class PromptFilesCompletionItemProvider @@ -140,6 +141,12 @@ class YamlKeysCompletionItemProvider implements vscode.CompletionItemProvider { const lineText = document.lineAt(position).text; const textBeforeCursor = lineText.substring(0, position.character); + // 0. If no delimiter in the file, return no completions + const fullContent = document.getText(); + if (!fullContent.includes("---")) { + return undefined; + } + // 1. Check if the cursor is in YAML section (before --- delimiter) const beforeDelimiter = isCursorBeforeDelimiter(document, position); @@ -159,7 +166,7 @@ class YamlKeysCompletionItemProvider implements vscode.CompletionItemProvider { vscode.CompletionItemKind.Property, ); item.documentation = new vscode.MarkdownString(key.description); - item.insertText = key + ": "; + item.insertText = key.key + ": "; return item; }); diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index e4274230e..355c02de6 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,19 +1,22 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { IDE } from "core"; +import { ConfigHandler } from "core/config/ConfigHandler"; +import { getModelByRole } from "core/config/util"; +import { logDevData } from "core/util/devdata"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; + import { VerticalDiffManager } from "../diff/vertical/manager"; +import { FileSearch } from "../util/FileSearch"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; + import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick"; import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick"; import { getModelQuickPickVal } from "./ModelSelectionQuickPick"; // @ts-ignore - error finding typings -import { ConfigHandler } from "core/config/ConfigHandler"; // @ts-ignore -import { getModelByRole } from "core/config/util"; -import { logDevData } from "core/util/devdata"; -import { FileSearch } from "../util/FileSearch"; + /** * Used to track what action to take after a user interacts diff --git a/extensions/vscode/src/stubs/SecretStorage.ts b/extensions/vscode/src/stubs/SecretStorage.ts index 4c85dfb01..202713cbd 100644 --- a/extensions/vscode/src/stubs/SecretStorage.ts +++ b/extensions/vscode/src/stubs/SecretStorage.ts @@ -1,6 +1,7 @@ import * as crypto from "crypto"; import * as fs from "fs"; import * as path from "path"; + import * as vscode from "vscode"; const ENCRYPTION_KEY_NAME = "dev.continue.continue"; diff --git a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts index c8f5ee79a..4e9eb3054 100644 --- a/extensions/vscode/src/stubs/WorkOsAuthProvider.ts +++ b/extensions/vscode/src/stubs/WorkOsAuthProvider.ts @@ -14,6 +14,7 @@ import { UriHandler, window, } from "vscode"; + import { PromiseAdapter, promiseFromEvent } from "./promiseUtils"; const AUTH_NAME = "Continue"; @@ -28,7 +29,9 @@ class UriEventHandler extends EventEmitter implements UriHandler { import { ControlPlaneSessionInfo } from "core/control-plane/client"; import { controlPlaneEnv } from "core/control-plane/env"; + import crypto from "crypto"; + import { SecretStorage } from "./SecretStorage"; // Function to generate a random string of specified length diff --git a/extensions/vscode/src/stubs/activation.ts b/extensions/vscode/src/stubs/activation.ts index bcec4b5a6..60e889c83 100644 --- a/extensions/vscode/src/stubs/activation.ts +++ b/extensions/vscode/src/stubs/activation.ts @@ -1,5 +1,6 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import * as vscode from "vscode"; + import { getUserToken } from "./auth"; import { RemoteConfigSync } from "./remoteConfig"; diff --git a/extensions/vscode/src/stubs/remoteConfig.ts b/extensions/vscode/src/stubs/remoteConfig.ts index eb3cba824..719d52db4 100644 --- a/extensions/vscode/src/stubs/remoteConfig.ts +++ b/extensions/vscode/src/stubs/remoteConfig.ts @@ -1,11 +1,13 @@ +import * as fs from "fs"; + import { ContinueServerClient } from "core/continueServer/stubs/client"; import { EXTENSION_NAME } from "core/control-plane/env"; import { getConfigJsPathForRemote, getConfigJsonPathForRemote, } from "core/util/paths"; -import * as fs from "fs"; import * as vscode from "vscode"; + import { CONTINUE_WORKSPACE_KEY } from "../util/workspaceConfig"; export class RemoteConfigSync { diff --git a/extensions/vscode/src/suggestions.ts b/extensions/vscode/src/suggestions.ts index 8021809a4..f4acb9be7 100644 --- a/extensions/vscode/src/suggestions.ts +++ b/extensions/vscode/src/suggestions.ts @@ -1,4 +1,5 @@ import * as vscode from "vscode"; + import { openEditorAndRevealRange, translate } from "./util/vscode"; export interface SuggestionRanges { diff --git a/extensions/vscode/src/terminal/terminalEmulator.ts b/extensions/vscode/src/terminal/terminalEmulator.ts index b2a7a99a9..d8518035d 100644 --- a/extensions/vscode/src/terminal/terminalEmulator.ts +++ b/extensions/vscode/src/terminal/terminalEmulator.ts @@ -1,7 +1,8 @@ /* Terminal emulator - commented because node-pty is causing problems. */ -import { longestCommonSubsequence } from "core/util/lcs"; import * as os from "node:os"; + +import { longestCommonSubsequence } from "core/util/lcs"; import stripAnsi from "strip-ansi"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/test/runner/mochaRunner.ts b/extensions/vscode/src/test/runner/mochaRunner.ts index 66d61a77f..1056ed6b7 100644 --- a/extensions/vscode/src/test/runner/mochaRunner.ts +++ b/extensions/vscode/src/test/runner/mochaRunner.ts @@ -1,4 +1,5 @@ import * as path from "node:path"; + import * as glob from "glob"; import Mocha from "mocha"; diff --git a/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts b/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts index 13fe2f404..f6174e087 100644 --- a/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts +++ b/extensions/vscode/src/test/runner/runTestOnVSCodeHost.ts @@ -1,8 +1,9 @@ -import { runTests } from "@vscode/test-electron"; -import { defaultConfig } from "core/config/default"; import fs from "node:fs"; import * as path from "node:path"; +import { runTests } from "@vscode/test-electron"; +import { defaultConfig } from "core/config/default"; + export const testWorkspacePath = path.resolve( __dirname, "..", diff --git a/extensions/vscode/src/test/test-suites/ideUtils.test.ts b/extensions/vscode/src/test/test-suites/ideUtils.test.ts index f994b3810..99a0532ae 100644 --- a/extensions/vscode/src/test/test-suites/ideUtils.test.ts +++ b/extensions/vscode/src/test/test-suites/ideUtils.test.ts @@ -1,9 +1,12 @@ -import { describe, test } from "mocha"; import assert from "node:assert"; import path from "node:path"; + +import { describe, test } from "mocha"; import * as vscode from "vscode"; + import { VsCodeIdeUtils } from "../../util/ideUtils"; import { testWorkspacePath } from "../runner/runTestOnVSCodeHost"; + const util = require("node:util"); const asyncExec = util.promisify(require("node:child_process").exec); diff --git a/extensions/vscode/src/test/test-suites/main.test.ts b/extensions/vscode/src/test/test-suites/main.test.ts index 01945f804..2cd1945fa 100644 --- a/extensions/vscode/src/test/test-suites/main.test.ts +++ b/extensions/vscode/src/test/test-suites/main.test.ts @@ -1,6 +1,8 @@ -import { describe, test } from "mocha"; import assert from "node:assert"; + +import { describe, test } from "mocha"; import * as vscode from "vscode"; + import { VsCodeExtension } from "../../extension/VsCodeExtension"; describe("Extension Test Suite", () => { diff --git a/extensions/vscode/src/util/cleanSlate.ts b/extensions/vscode/src/util/cleanSlate.ts index 09703f481..9d00f3e65 100644 --- a/extensions/vscode/src/util/cleanSlate.ts +++ b/extensions/vscode/src/util/cleanSlate.ts @@ -1,6 +1,7 @@ +import fs from "fs"; + import { getContinueGlobalPath } from "core/util/paths"; import { ExtensionContext } from "vscode"; -import fs from "fs"; /** * Clear all Continue-related artifacts to simulate a brand new user diff --git a/extensions/vscode/src/util/expandSnippet.ts b/extensions/vscode/src/util/expandSnippet.ts index 10d1cda5b..3b9c45bb1 100644 --- a/extensions/vscode/src/util/expandSnippet.ts +++ b/extensions/vscode/src/util/expandSnippet.ts @@ -3,9 +3,11 @@ import { languageForFilepath } from "core/autocomplete/constants/AutocompleteLan import { DEFAULT_IGNORE_DIRS } from "core/indexing/ignore"; import { deduplicateArray } from "core/util"; import { getParserForFile } from "core/util/treeSitter"; -import type { SyntaxNode } from "web-tree-sitter"; + import { getDefinitionsForNode } from "../autocomplete/lsp"; +import type { SyntaxNode } from "web-tree-sitter"; + export async function expandSnippet( filepath: string, startLine: number, diff --git a/extensions/vscode/src/util/getTheme.ts b/extensions/vscode/src/util/getTheme.ts index 26bb042e0..3d0d3f795 100644 --- a/extensions/vscode/src/util/getTheme.ts +++ b/extensions/vscode/src/util/getTheme.ts @@ -1,8 +1,10 @@ import * as fs from "node:fs"; import * as path from "node:path"; + import mergeJson from "core/util/merge"; import { convertTheme } from "monaco-vscode-textmate-theme-converter/lib/cjs"; import * as vscode from "vscode"; + import { getExtensionUri } from "./vscode"; const builtinThemes: any = { diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 2dd9cd330..60fc6b72d 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -1,6 +1,9 @@ -import type { FileEdit, RangeInFile, Thread } from "core"; import path from "node:path"; + +import { EXTENSION_NAME } from "core/control-plane/env"; +import _ from "lodash"; import * as vscode from "vscode"; + import { threadStopped } from "../debug/debug"; import { VsCodeExtension } from "../extension/VsCodeExtension"; import { GitExtension, Repository } from "../otherExtensions/git"; @@ -11,14 +14,15 @@ import { rejectSuggestionCommand, showSuggestion as showSuggestionInEditor, } from "../suggestions"; + import { getUniqueId, openEditorAndRevealRange, uriFromFilePath, } from "./vscode"; -import { EXTENSION_NAME } from "core/control-plane/env"; -import _ from "lodash"; + +import type { FileEdit, RangeInFile, Thread } from "core"; const util = require("node:util"); const asyncExec = util.promisify(require("node:child_process").exec); diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index 4d3484040..f4f4c87b3 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -1,8 +1,9 @@ -import type { ILLM } from "core"; import { ConfigHandler } from "core/config/ConfigHandler"; import Ollama from "core/llm/llms/Ollama"; import { GlobalContext } from "core/util/GlobalContext"; +import type { ILLM } from "core"; + export class TabAutocompleteModel { private _llm: ILLM | undefined; private defaultTag = "starcoder2:3b"; diff --git a/extensions/vscode/src/util/util.ts b/extensions/vscode/src/util/util.ts index 60836a735..48777fa07 100644 --- a/extensions/vscode/src/util/util.ts +++ b/extensions/vscode/src/util/util.ts @@ -1,7 +1,9 @@ -const os = require("node:os"); import * as vscode from "vscode"; + import { VsCodeIde } from "../VsCodeIde"; +const os = require("node:os"); + function charIsEscapedAtIndex(index: number, str: string): boolean { if (index === 0) { return false; @@ -124,7 +126,7 @@ export function getExtensionVersion(): string { } export function getFullyQualifiedPath(ide: VsCodeIde, filepath: string) { - if (ide.ideUtils.path.isAbsolute(filepath)) return filepath; + if (ide.ideUtils.path.isAbsolute(filepath)) {return filepath;} const workspaceFolders = vscode.workspace.workspaceFolders; diff --git a/extensions/vscode/src/util/vscode.ts b/extensions/vscode/src/util/vscode.ts index 9f9dd2093..16c15bb19 100644 --- a/extensions/vscode/src/util/vscode.ts +++ b/extensions/vscode/src/util/vscode.ts @@ -1,5 +1,6 @@ -import { machineIdSync } from "node-machine-id"; import * as path from "node:path"; + +import { machineIdSync } from "node-machine-id"; import * as vscode from "vscode"; export function translate(range: vscode.Range, lines: number): vscode.Range { diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index be309e390..17b72af8b 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -1,13 +1,16 @@ +import fs from "node:fs"; +import path from "path"; + import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol"; import { WebviewMessengerResult } from "core/protocol/util"; import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo"; import { Message } from "core/util/messenger"; import { Telemetry } from "core/util/posthog"; -import fs from "node:fs"; -import path from "path"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; + import { IMessenger } from "../../../core/util/messenger"; + import { showFreeTrialLoginMessage } from "./util/messages"; import { getExtensionUri } from "./util/vscode"; diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/typescript.scm new file mode 100644 index 000000000..bf38152b7 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/typescript.scm @@ -0,0 +1,19 @@ +( + (class_declaration + (class_heritage + (extends_clause + (identifier) @base-class + ) + ) + ) +) + +( + (class_declaration + (class_heritage + (implements_clause + (type_identifier) @interface + ) + ) + ) +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/class_definition/python.scm b/extensions/vscode/tree-sitter/root-path-context-queries/class_definition/python.scm new file mode 100644 index 000000000..5a9e34b86 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/class_definition/python.scm @@ -0,0 +1,5 @@ +( + (class_definition + superclasses: (argument_list + (identifier) @superclass)) +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm index c0d936f5e..ab10968a3 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm @@ -2,8 +2,9 @@ (function_declaration (formal_parameters (_ - (type_annotation) @type + (type_annotation) @param_type ) ) + (type_annotation) @return_type ) ) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm index 10ee28346..727db5090 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm @@ -2,8 +2,9 @@ (method_definition (formal_parameters (_ - (type_annotation) @type + (type_annotation) @param_type ) ) + (type_annotation) @return_type ) -) \ No newline at end of file +) diff --git a/gui/index.html b/gui/index.html index 017e27848..f54eae839 100644 --- a/gui/index.html +++ b/gui/index.html @@ -1,4 +1,4 @@ - + diff --git a/gui/postcss.config.cjs b/gui/postcss.config.cjs index 33ad091d2..12a703d90 100644 --- a/gui/postcss.config.cjs +++ b/gui/postcss.config.cjs @@ -3,4 +3,4 @@ module.exports = { tailwindcss: {}, autoprefixer: {}, }, -} +}; diff --git a/gui/public/logos/qwen.png b/gui/public/logos/qwen.png new file mode 100644 index 000000000..4f5a292bc Binary files /dev/null and b/gui/public/logos/qwen.png differ diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx index 8ff095926..4a5744e7d 100644 --- a/gui/src/components/AddModelButtonSubtext.tsx +++ b/gui/src/components/AddModelButtonSubtext.tsx @@ -9,7 +9,7 @@ function AddModelButtonSubtext() { This will update your{" "} ideMessenger.post("openConfigJson", undefined)} > config file diff --git a/gui/src/components/InfoHover.tsx b/gui/src/components/InfoHover.tsx index d51e90fdb..aa6541c5b 100644 --- a/gui/src/components/InfoHover.tsx +++ b/gui/src/components/InfoHover.tsx @@ -8,7 +8,7 @@ const InfoHover = ({ msg }: { msg: string }) => { <> diff --git a/gui/src/components/Layout.tsx b/gui/src/components/Layout.tsx index 5974c00cd..cc09881a3 100644 --- a/gui/src/components/Layout.tsx +++ b/gui/src/components/Layout.tsx @@ -202,8 +202,8 @@ const Layout = () => { [navigate], ); - useWebviewListener("setEditStatus", async ({ status }) => { - dispatch(setEditStatus(status)); + useWebviewListener("setEditStatus", async ({ status, fileAfterEdit }) => { + dispatch(setEditStatus({ status, fileAfterEdit })); }); useWebviewListener("exitEditMode", async () => { diff --git a/gui/src/components/OnboardingCard/OnboardingCard.tsx b/gui/src/components/OnboardingCard/OnboardingCard.tsx index aba23e14a..14a840456 100644 --- a/gui/src/components/OnboardingCard/OnboardingCard.tsx +++ b/gui/src/components/OnboardingCard/OnboardingCard.tsx @@ -10,7 +10,8 @@ const StyledCard = styled.div` margin: auto; border-radius: ${defaultBorderRadius}; background-color: ${vscInputBackground}; - box-shadow: 0 20px 25px -5px rgb(0 0 0 / 0.1), + box-shadow: + 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); `; @@ -42,13 +43,13 @@ export function OnboardingCard(props: OnboardingCardProps) { } return ( - + - +
    {renderTabContent()}
    diff --git a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx index 44c5c5caa..1b2cbea0a 100644 --- a/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx +++ b/gui/src/components/OnboardingCard/components/OllamaCompletedStep.tsx @@ -6,8 +6,8 @@ interface OllamaCompletedStepProps { function OllamaCompletedStep({ text }: OllamaCompletedStepProps) { return ( -
    -

    {text}

    +
    +

    {text}

    ); diff --git a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx index d44524cb5..fa76279d2 100644 --- a/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx +++ b/gui/src/components/OnboardingCard/components/OnboardingCardTabs.tsx @@ -71,7 +71,7 @@ export function OnboardingCardTabs({ }: OnboardingCardTabsProps) { return (
    -
    +
    {Object.entries(TabTitles).map(([tabType, titles]) => { if (hasPassedFTL() && tabType === "Quickstart") { @@ -80,21 +80,21 @@ export function OnboardingCardTabs({ return ( onTabClick(tabType as TabTitle)} > -

    +

    {titles.default}

    -

    {titles.md}

    +

    {titles.md}

    ); })}
    -
    +
    onTabClick(e.target.value as TabTitle)} diff --git a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx index d5b372245..f4c02cefd 100644 --- a/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx +++ b/gui/src/components/OnboardingCard/tabs/OnboardingBestTab.tsx @@ -7,7 +7,7 @@ function OnboardingBestTab() { return (
    -
    +
    diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index 3089803da..266a09cd8 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -1,19 +1,19 @@ -import { - useRef, - useEffect, - useState, - RefObject, - useCallback, - useMemo, -} from "react"; -import { RootState } from "../../redux/store"; -import { useSelector } from "react-redux"; -import { HeaderButton, Input } from ".."; import { ArrowDownIcon, ArrowUpIcon, XMarkIcon, } from "@heroicons/react/24/outline"; +import { + RefObject, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { useSelector } from "react-redux"; +import { HeaderButton, Input } from ".."; +import { RootState } from "../../redux/store"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; interface SearchMatch { @@ -119,7 +119,7 @@ export const useFindWidget = (searchRef: RefObject) => { // Handle keyboard shortcuts for navigation useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { - if (event.metaKey && event.key.toLowerCase() === "f") { + if (event.metaKey && event.key.toLowerCase() === "f" && !event.shiftKey) { event.preventDefault(); event.stopPropagation(); openWidget(); diff --git a/gui/src/components/gui/Alert.tsx b/gui/src/components/gui/Alert.tsx index 1e72e6386..cc1e5c9d1 100644 --- a/gui/src/components/gui/Alert.tsx +++ b/gui/src/components/gui/Alert.tsx @@ -1,8 +1,8 @@ import { - InformationCircleIcon, - ExclamationTriangleIcon, CheckCircleIcon, ExclamationCircleIcon, + ExclamationTriangleIcon, + InformationCircleIcon, } from "@heroicons/react/24/solid"; import { ReactNode } from "react"; import { vscBackground } from ".."; @@ -39,10 +39,10 @@ function Alert({ children, type = "info" }: AlertProps) { const { Icon } = ALERT_CONFIGS[type]; return ( -
    +
    diff --git a/gui/src/components/gui/HeaderButtonWithToolTip.tsx b/gui/src/components/gui/HeaderButtonWithToolTip.tsx index 4a64c6283..f83bca318 100644 --- a/gui/src/components/gui/HeaderButtonWithToolTip.tsx +++ b/gui/src/components/gui/HeaderButtonWithToolTip.tsx @@ -1,7 +1,7 @@ import React from "react"; import { type PlacesType } from "react-tooltip"; -import { HeaderButton } from ".."; import { v4 as uuidv4 } from "uuid"; +import { HeaderButton } from ".."; import { ToolTip } from "./Tooltip"; interface HeaderButtonWithToolTipProps { diff --git a/gui/src/components/index.ts b/gui/src/components/index.ts index 7a04bf43a..3a384c995 100644 --- a/gui/src/components/index.ts +++ b/gui/src/components/index.ts @@ -109,7 +109,6 @@ export function parseColorForHex(colorVar: string): string { colorVar, ); if (value.startsWith("#")) { - console.log("OAIJFIOJOOJOIO", colorVar, value, value.slice(0, 7)); return value.slice(0, 7); } diff --git a/gui/src/components/loaders/FreeTrialProgressBar.tsx b/gui/src/components/loaders/FreeTrialProgressBar.tsx index 81c7a0477..99a2d9b69 100644 --- a/gui/src/components/loaders/FreeTrialProgressBar.tsx +++ b/gui/src/components/loaders/FreeTrialProgressBar.tsx @@ -37,7 +37,7 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) { return ( <>
    @@ -54,11 +54,11 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) { return ( <>
    -
    +
    Free trial requests @@ -68,9 +68,9 @@ function FreeTrialProgressBar({ completed, total }: FreeTrialProgressBarProps) {
    -
    +
    0.75 ? "bg-amber-500" : "bg-stone-500" }`} style={{ diff --git a/gui/src/components/loaders/RingLoader.tsx b/gui/src/components/loaders/RingLoader.tsx index 687d2990e..c72b70a30 100644 --- a/gui/src/components/loaders/RingLoader.tsx +++ b/gui/src/components/loaders/RingLoader.tsx @@ -46,7 +46,7 @@ const RingLoader = (props: { return (
    ({ mergeAttributes( { "data-type": this.name }, this.options.HTMLAttributes, - HTMLAttributes + HTMLAttributes, ), this.options.renderText({ options: this.options, @@ -155,7 +155,7 @@ export const SlashCommand = Node.create({ tr.insertText( this.options.suggestion.char || "", pos, - pos + node.nodeSize + pos + node.nodeSize, ); return false; diff --git a/gui/src/components/mainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/ContextItemsPeek.tsx index 2d7409b26..3ae178abf 100644 --- a/gui/src/components/mainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/ContextItemsPeek.tsx @@ -52,7 +52,7 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { if (contextItem.icon) { return ( +
    @@ -96,16 +96,16 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { return (
    -
    +
    {getContextItemIcon()}
    -
    +
    {contextItem.name}
    {contextItem.uri?.type === "file" ? getBasename(contextItem.description) @@ -134,18 +134,18 @@ function ContextItemsPeek({ return (
    setOpen((prev) => !prev)} > -
    +
    diff --git a/gui/src/components/mainInput/resolveInput.ts b/gui/src/components/mainInput/resolveInput.ts index 4b2d606d6..64acba85a 100644 --- a/gui/src/components/mainInput/resolveInput.ts +++ b/gui/src/components/mainInput/resolveInput.ts @@ -62,7 +62,10 @@ async function resolveEditorContent( let extName = relativePath.split(".").slice(-1)[0]; const text = "\n\n" + - "```" + extName + " " + p.attrs.item.description + + "```" + + extName + + " " + + p.attrs.item.description + "\n" + p.attrs.item.content + "\n```"; diff --git a/gui/src/components/modelSelection/ModelSelectionListbox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx index a28410eb4..12d62c200 100644 --- a/gui/src/components/modelSelection/ModelSelectionListbox.tsx +++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx @@ -79,7 +79,7 @@ export const StyledListboxOptions = styled(Listbox.Options)` } `; -export const StyledListboxOption = styled(Listbox.Option) <{ +export const StyledListboxOption = styled(Listbox.Option)<{ selected: boolean; }>` background-color: ${({ selected }) => @@ -121,7 +121,7 @@ function ModelSelectionListbox({ {window.vscMediaUrl && selectedProvider.icon && ( )} {selectedProvider.title} @@ -150,13 +150,13 @@ function ModelSelectionListbox({ {({ selected }) => ( <> {option.title === "Autodetect" ? ( - + ) : ( window.vscMediaUrl && option.icon && ( ) )} diff --git a/gui/src/hooks/useAppendedString.ts b/gui/src/hooks/useAppendedString.ts index 18eb08217..54d1c5f71 100644 --- a/gui/src/hooks/useAppendedString.ts +++ b/gui/src/hooks/useAppendedString.ts @@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react"; export function useAppendedString( fullString: string, - append: (chunk: string, lineCount: number) => void + append: (chunk: string, lineCount: number) => void, ) { // Queue of fullString updated versions to be processed atomically const [updateQueue, setUpdateQueue] = useState([]); diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index 0390f1110..e5199ea88 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -5,10 +5,11 @@ import { stripImages } from "core/llm/images"; import { useCallback, useContext } from "react"; import { useSelector } from "react-redux"; import { IdeMessengerContext } from "../context/IdeMessenger"; +import { useLastSessionContext } from "../context/LastSessionContext"; +import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { newSession } from "../redux/slices/stateSlice"; import { RootState } from "../redux/store"; import { getLocalStorage, setLocalStorage } from "../util/localStorage"; -import { useLastSessionContext } from "../context/LastSessionContext"; const MAX_TITLE_LENGTH = 100; @@ -21,6 +22,7 @@ function truncateText(text: string, maxLength: number) { function useHistory(dispatch: Dispatch) { const state = useSelector((state: RootState) => state.state); + const defaultModel = useSelector(defaultModelSelector); const ideMessenger = useContext(IdeMessengerContext); const { lastSessionId, setLastSessionId } = useLastSessionContext(); @@ -48,11 +50,17 @@ function useHistory(dispatch: Dispatch) { return result.status === "success" ? result.content : undefined; } - async function getSessionTitle(stateCopy: typeof state): Promise { - if ( - state.config?.experimental?.getChatTitles && - stateCopy.title === "New Session" - ) { + async function saveSession(openNewSession: boolean = true) { + if (state.history.length === 0) return; + + const stateCopy = { ...state }; + if (openNewSession) { + dispatch(newSession()); + updateLastSessionId(stateCopy.sessionId); + } + await new Promise((resolve) => setTimeout(resolve, 10)); + + if (state.config?.ui?.getChatTitles && stateCopy.title === "New Session") { try { // Check if we have first assistant response let assistantResponse = stateCopy.history @@ -60,40 +68,26 @@ function useHistory(dispatch: Dispatch) { ?.message?.content?.toString(); if (assistantResponse) { - return await getChatTitle(assistantResponse); + stateCopy.title = await getChatTitle(assistantResponse); } } catch (e) { - console.error("Unable to get chat title:", e); + throw new Error("Unable to get chat title"); } } // Fallback if we get an error above or if the user has not set getChatTitles - return stateCopy.title === "New Session" - ? truncateText( - stripImages(stateCopy.history[0].message.content) - .split("\n") - .filter((l) => l.trim() !== "") - .slice(-1)[0] || "", - MAX_TITLE_LENGTH, - ) - : stateCopy.title?.length > 0 - ? stateCopy.title - : (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page. - } - - async function saveSession(openNewSession = true) { - if (state.history.length === 0) return; - - const stateCopy = { ...state }; - - if (openNewSession) { - dispatch(newSession()); - updateLastSessionId(stateCopy.sessionId); - } - - await new Promise((resolve) => setTimeout(resolve, 10)); - - const title = await getSessionTitle(stateCopy); + let title = + stateCopy.title === "New Session" + ? truncateText( + stripImages(stateCopy.history[0].message.content) + .split("\n") + .filter((l) => l.trim() !== "") + .slice(-1)[0] || "", + MAX_TITLE_LENGTH, + ) + : stateCopy.title?.length > 0 + ? stateCopy.title + : (await getSession(stateCopy.sessionId)).title; // to ensure titles are synced with updates from history page. const sessionInfo: PersistedSessionInfo = { history: stateCopy.history, diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index f7c9fdf10..2fed805da 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -88,9 +88,13 @@ function useSetup(dispatch: Dispatch) { // IDE event listeners const history = useSelector((store: RootState) => store.state.history); - useWebviewListener("getWebviewHistoryLength", async () => { - return history.length; - }, [history]); + useWebviewListener( + "getWebviewHistoryLength", + async () => { + return history.length; + }, + [history], + ); useWebviewListener("setInactive", async () => { dispatch(setInactive()); diff --git a/gui/src/pages/AddNewModel/AddNewModel.tsx b/gui/src/pages/AddNewModel/AddNewModel.tsx index ed06ccdce..b361732c7 100644 --- a/gui/src/pages/AddNewModel/AddNewModel.tsx +++ b/gui/src/pages/AddNewModel/AddNewModel.tsx @@ -63,9 +63,9 @@ function AddNewModel() { const [providersSelected, setProvidersSelected] = React.useState(true); return ( -
    +
    navigate("/")} - className="inline-block ml-4 cursor-pointer" + className="ml-4 inline-block cursor-pointer" /> -

    Add a new model

    +

    Add a new model


    @@ -113,7 +113,7 @@ function AddNewModel() { {providersSelected ? ( <> -
    +

    Providers

    Select a provider below, or configure your own in{" "} @@ -142,7 +142,7 @@ function AddNewModel() { ) : ( <> -

    +

    Models

    Select a model from the most popular options below, or configure @@ -152,8 +152,8 @@ function AddNewModel() { {Object.entries(modelsByProvider).map( ([providerTitle, modelConfigsByProviderTitle]) => ( -

    -
    +
    +

    {providerTitle}


    -

    - +

    + Open config.json

    diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index 87bdfc546..67c3547a7 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -69,6 +69,7 @@ export const models: { [key: string]: ModelPackage } = { "replicate", "sambanova", "cerebras", + "nebius", ], isOpenSource: true, }, @@ -190,6 +191,10 @@ export const models: { [key: string]: ModelPackage } = { model: "mistral-8x7b", title: "Mixtral", }, + "8x22b (MoE)": { + model: "mistral-8x22b", + title: "Mixtral", + }, }, }, ], @@ -1005,52 +1010,23 @@ export const models: { [key: string]: ModelPackage } = { icon: "openai.png", isOpenSource: false, }, - MetaLlama3Large: { - title: "Llama 3.1 405b", - description: - "Llama 3 is an auto-regressive language model that uses an optimized transformer architecture.", - params: { - title: "Llama 3.1 405b", - model: "meta-llama/Meta-Llama-3.1-405B-Instruct", - contextLength: 128_000, - }, - icon: "meta.png", - dimensions: [ - { - name: "Parameter Count", - description: "The number of parameters in the model", - options: { - "70b": { - model: "meta-llama/Meta-Llama-3.1-70B-Instruct", - title: "Llama 3.1 70b", - }, - "405bb": { - model: "meta-llama/Meta-Llama-3.1-405B-Instruct", - title: "Llama 3.1 405b", - }, - }, - }, - ], - providerOptions: ["nebius"], - isOpenSource: true, - }, Qwen2Coder: { title: "Qwen 2.5 Coder 7b", description: "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", params: { title: "Qwen 2.5 Coder 7b", - model: "Qwen/Qwen2.5-Coder-7B-Instruct", + model: "qwen-coder2.5-7b", contextLength: 32_000, }, - icon: "meta.png", + icon: "qwen.png", dimensions: [ { name: "Parameter Count", description: "The number of parameters in the model", options: { "7b": { - model: "Qwen/Qwen2.5-Coder-7B-Instruct", + model: "qwen-coder2.5-7b", title: "Qwen 2.5 Coder 7b", }, }, diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index dd1c3fbdb..39613731b 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -356,8 +356,10 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n title: "xAI", provider: "xAI", icon: "xAI.png", - description: "xAI is a company working on building artificial intelligence to accelerate human scientific discovery", - longDescription: "To get started with xAI, obtain an API key from their [console](https://console.x.ai/).", + description: + "xAI is a company working on building artificial intelligence to accelerate human scientific discovery", + longDescription: + "To get started with xAI, obtain an API key from their [console](https://console.x.ai/).", tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], collectInputFor: [ { @@ -368,9 +370,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n required: true, }, ], - packages: [ - models.grokBeta, - ], + packages: [models.grokBeta], apiKeyUrl: "https://console.x.ai/", }, lmstudio: { @@ -657,8 +657,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo packages: [ models.VertexGemini15Pro, models.VertexGemini15Flash, - models.mistralLarge - + models.mistralLarge, ], collectInputFor: [ { @@ -727,7 +726,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo nebius: { title: "Nebius AI Studio", provider: "nebius", - refPage: "nebiusllm", + refPage: "nebius", description: "Use the Nebius API to run open-source models", longDescription: `Nebius AI Studio is a cheap hosted service with $100 trial. To get started with Nebius AI Studio:\n1. Obtain an API key from [here](https://studio.nebius.ai)\n2. Paste below\n3. Select a model preset`, params: { @@ -745,7 +744,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ], icon: "nebius.png", tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], - packages: [models.MetaLlama3Large, models.Qwen2Coder], + packages: [models.llama31Chat, models.Qwen2Coder, models.mistralOs], apiKeyUrl: "https://studio.nebius.ai/settings/api-keys", }, }; diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx index 910b45c54..f3d4fea55 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgress.tsx @@ -108,8 +108,8 @@ function IndexingProgress() { } return ( -
    -
    +
    +
    {update.status !== "loading" && ( diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx index f8e395468..5de74fb3f 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressBar.tsx @@ -9,9 +9,9 @@ function IndexingProgressBar({ update }: IndexingProgressBarProps) { const progressPercentage = getProgressPercentage(update.progress); return ( -
    +
    https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx index 852cdf845..944fdc917 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressIndicator.tsx @@ -27,13 +27,16 @@ function IndexingProgressIndicator({ update }: IndexingProgressIndicatorProps) { return (
    - {showProgress && {progressPercentage.toFixed(0)}%} + {showProgress && ( + {progressPercentage.toFixed(0)}% + )} {Icon && (
    )} diff --git a/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx b/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx index 67ba96054..6c07babb0 100644 --- a/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx +++ b/gui/src/pages/More/IndexingProgress/IndexingProgressSubtext.tsx @@ -26,7 +26,7 @@ function IndexingProgressSubtext({ return (
    {showIndexingDesc && ( - + {update.desc} )} diff --git a/gui/src/pages/More/More.tsx b/gui/src/pages/More/More.tsx index 4e6f3cd0f..4824c9535 100644 --- a/gui/src/pages/More/More.tsx +++ b/gui/src/pages/More/More.tsx @@ -31,7 +31,10 @@ function MorePage() { backgroundColor: vscBackground, }} > -
    navigate("/")}> +
    navigate("/")} + > Chat
    diff --git a/gui/src/pages/config-error/index.tsx b/gui/src/pages/config-error/index.tsx index 230a45204..aa0e22f22 100644 --- a/gui/src/pages/config-error/index.tsx +++ b/gui/src/pages/config-error/index.tsx @@ -20,37 +20,37 @@ export default function ConfigErrorPage() {
    navigate(ROUTES.HOME)} - className="items-center flex m-0 p-0 sticky top-0 cursor-pointer border-0 border-b border-solid border-b-zinc-700 bg-inherit" + className="sticky top-0 m-0 flex cursor-pointer items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0" style={{ backgroundColor: vscBackground, }} > - - Chat + + Chat
    -
    +
    -

    Config Errors

    -

    +

    Config Errors

    +

    Please resolve the following errors in your config.json file.

    {sortedErrors.length > 0 ? ( -
      +
        {sortedErrors.map((error, index) => (
      • {error.fatal ? ( - + ) : ( - + )}

        @@ -62,7 +62,7 @@ export default function ConfigErrorPage() { ))}

      ) : ( -

      +

      No configuration errors found.

      )} diff --git a/gui/src/pages/edit/EditInputHeader.tsx b/gui/src/pages/edit/EditInputHeader.tsx new file mode 100644 index 000000000..b7b66de8c --- /dev/null +++ b/gui/src/pages/edit/EditInputHeader.tsx @@ -0,0 +1,114 @@ +import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { getBasename } from "core/util"; +import { useContext, useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import FileIcon from "../../components/FileIcon"; +import HeaderButtonWithToolTip from "../../components/gui/HeaderButtonWithToolTip"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { setEditDone, setEditStatus } from "../../redux/slices/editModeState"; +import { RootState } from "../../redux/store"; + +interface EditInputHeaderParams {} + +/** + * @description This is a class that represents an edit input header. + */ +export function EditInputHeader(editInputHeaderParams: EditInputHeaderParams) { + const dispatch = useDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const editModeState = useSelector((state: RootState) => state.editModeState); + + const [showCode, setShowCode] = useState(false); + + function onClick() { + ideMessenger.ide.showLines( + editModeState.highlightedCode.filepath, + editModeState.highlightedCode.range.start.line, + editModeState.highlightedCode.range.end.line, + ); + setShowCode(!showCode); + } + + async function showFullDiff() { + await ideMessenger.ide.showDiff( + editModeState.highlightedCode.filepath, + editModeState.fileAfterEdit, + 0, + ); + dispatch(setEditStatus({ status: "accepting:full-diff" })); + } + + return ( + <> +
      +
      +
      + + {getBasename(editModeState.highlightedCode.filepath)} ( + {editModeState.highlightedCode.range.start.line}- + {editModeState.highlightedCode.range.end.line}) +
      + {editModeState.editStatus === "accepting" || + editModeState.editStatus === "accepting:full-diff" ? ( +
      + {/* {editModeState.editStatus === "accepting" ? ( + <> + + + + + N diffs remaining + + + ) : ( +
      hi
      + )} */} + +
      + + { + ideMessenger.request("edit/acceptReject", { + accept: false, + onlyFirst: false, + filepath: editModeState.highlightedCode.filepath, + }); + dispatch(setEditDone()); + }} + > + + + { + ideMessenger.request("edit/acceptReject", { + accept: true, + onlyFirst: false, + filepath: editModeState.highlightedCode.filepath, + }); + dispatch(setEditDone()); + }} + > + +
      +
      + ) : null} +
      +
      + + ); +} diff --git a/gui/src/pages/edit.tsx b/gui/src/pages/edit/index.tsx similarity index 54% rename from gui/src/pages/edit.tsx rename to gui/src/pages/edit/index.tsx index e608c8d73..e69be0d14 100644 --- a/gui/src/pages/edit.tsx +++ b/gui/src/pages/edit/index.tsx @@ -1,28 +1,23 @@ import { ArrowLeftIcon } from "@heroicons/react/24/outline"; import { Editor, JSONContent } from "@tiptap/core"; import { InputModifiers } from "core"; -import { getBasename } from "core/util"; -import { usePostHog } from "posthog-js/react"; -import { useContext, useEffect, useState } from "react"; +import { stripImages } from "core/llm/images"; +import { useContext, useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; import { defaultBorderRadius, lightGray, - parseColorForHex, - VSC_DIFF_INSERTED_LINE_BACKGROUND_VAR, - VSC_DIFF_REMOVED_LINE_BACKGROUND_VAR, vscForeground, -} from "../components"; -import FileIcon from "../components/FileIcon"; -import { NewSessionButton } from "../components/mainInput/NewSessionButton"; -import resolveEditorContent from "../components/mainInput/resolveInput"; -import TipTapEditor from "../components/mainInput/TipTapEditor"; -import { IdeMessengerContext } from "../context/IdeMessenger"; -import { setEditDone, submitEdit } from "../redux/slices/editModeState"; -import { RootState } from "../redux/store"; -import { getMetaKeyLabel } from "../util"; +} from "../../components"; +import { NewSessionButton } from "../../components/mainInput/NewSessionButton"; +import resolveEditorContent from "../../components/mainInput/resolveInput"; +import TipTapEditor from "../../components/mainInput/TipTapEditor"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { setEditDone, submitEdit } from "../../redux/slices/editModeState"; +import { RootState } from "../../redux/store"; +import { EditInputHeader } from "./EditInputHeader"; const TopDiv = styled.div` overflow-y: auto; @@ -33,6 +28,13 @@ const TopDiv = styled.div` } `; +const ToolbarDiv = styled.div` + padding: 8px; + border-bottom: 1px solid ${lightGray}; + border-radius: ${defaultBorderRadius}; + display: flex; +`; + const AcceptRejectButton = styled.div<{ backgroundColor: string; disabled: boolean; @@ -71,10 +73,19 @@ const EditHistoryDiv = styled.div` } `; -const EDIT_ALLOWS_CONTEXT_PROVIDERS = ["file", "code"]; +const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ + "codebase", + "tree", + "open", + "web", + "diff", + "folder", + "search", + "debugger", + "repo-map", +]; function Edit() { - const posthog = usePostHog(); const dispatch = useDispatch(); const navigate = useNavigate(); const ideMessenger = useContext(IdeMessengerContext); @@ -84,8 +95,6 @@ function Edit() { ); useEffect(() => {}, []); - const [showCode, setShowCode] = useState(false); - // Reusing the applyState logic which was just the fastest way to get this working useEffect(() => { if (editModeState.editStatus === "done") { @@ -126,35 +135,7 @@ function Edit() {
      -
      { - ideMessenger.ide.showLines( - editModeState.highlightedCode.filepath, - editModeState.highlightedCode.range.start.line, - editModeState.highlightedCode.range.end.line, - ); - setShowCode(!showCode); - }} - > - - {getBasename(editModeState.highlightedCode.filepath)} ( - {editModeState.highlightedCode.range.start.line}- - {editModeState.highlightedCode.range.end.line}) -
      -
      - } + header={} toolbarOptions={{ hideAddContext: true, hideImageUpload: true, @@ -168,13 +149,13 @@ function Edit() { }} placeholder={ ["streaming", "accepting"].includes(editModeState.editStatus) - ? "Enter instructions for edit" - : "Enter instructions for edit" + ? "Describe how to modify code" + : "Describe how to modify code" } border={`1px solid #aa0`} availableContextProviders={availableContextProviders.filter( (provider) => - EDIT_ALLOWS_CONTEXT_PROVIDERS.includes(provider.title), + !EDIT_DISALLOWED_CONTEXT_PROVIDERS.includes(provider.title), )} historyKey="edit" availableSlashCommands={[]} @@ -184,15 +165,21 @@ function Edit() { modifiers: InputModifiers, editor: Editor, ): Promise { - const [_, __, prompt] = await resolveEditorContent( - editorState, - { - noContext: true, - useCodebase: false, - }, - ideMessenger, - [], - ); + const [contextItems, __, userInstructions] = + await resolveEditorContent( + editorState, + { + noContext: true, + useCodebase: false, + }, + ideMessenger, + [], + ); + + const prompt = [ + ...contextItems.map((item) => item.content), + stripImages(userInstructions), + ].join("\n\n"); ideMessenger.request("edit/sendPrompt", { prompt, range: editModeState.highlightedCode, @@ -206,43 +193,6 @@ function Edit() {
    - {["accepting", "streaming"].includes(editModeState.editStatus) && ( -
    - { - ideMessenger.request("edit/acceptReject", { - accept: false, - onlyFirst: false, - filepath: editModeState.highlightedCode.filepath, - }); - dispatch(setEditDone()); - }} - > - {getMetaKeyLabel()}⇧⌫ Reject all - - { - ideMessenger.request("edit/acceptReject", { - accept: true, - onlyFirst: false, - filepath: editModeState.highlightedCode.filepath, - }); - dispatch(setEditDone()); - }} - > - {getMetaKeyLabel()}⇧⏎ Accept all - -
    - )} -
    { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 3701b753e..21ed79f04 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -309,7 +309,8 @@ export function Chat() { [state.history], ); - const showScrollbar = state.config.ui?.showChatScrollbar || false; + const showScrollbar = + state.config.ui?.showChatScrollbar || window.innerHeight > 5000; return ( <> @@ -368,18 +369,6 @@ export function Chat() { index={index} isLast={index === state.history.length - 1} item={item} - onContinueGeneration={() => { - window.postMessage( - { - messageType: "userInput", - data: { - input: - "Continue your response exactly where you left off:", - }, - }, - "*", - ); - }} />
    diff --git a/gui/src/pages/history/HistoryHeader.tsx b/gui/src/pages/history/HistoryHeader.tsx index e93a68520..4dbdf90bb 100644 --- a/gui/src/pages/history/HistoryHeader.tsx +++ b/gui/src/pages/history/HistoryHeader.tsx @@ -19,7 +19,10 @@ export const HistoryHeader = () => { borderBottom: `0.5px solid ${lightGray}`, }} > -
    navigate("/")}> +
    navigate("/")} + >
    -

    Settings

    +

    Settings

    { ideMessenger.post("showFile", { @@ -191,7 +191,7 @@ function Settings() { predictable.`} />

    -
    +

    0

    -
    +
    { navigate("/"); diff --git a/gui/src/redux/slices/editModeState.ts b/gui/src/redux/slices/editModeState.ts index 4c5defeef..38091ccbf 100644 --- a/gui/src/redux/slices/editModeState.ts +++ b/gui/src/redux/slices/editModeState.ts @@ -1,12 +1,13 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { MessageContent } from "core"; import { RangeInFileWithContents } from "core/commands/util"; -import { EditModeArgs } from "core/protocol/ideWebview"; -type EditStatus = "not-started" | "streaming" | "accepting" | "done"; +import { EditModeArgs, EditStatus } from "core/protocol/ideWebview"; + interface EditModeState { highlightedCode?: RangeInFileWithContents; editStatus: EditStatus; previousInputs: MessageContent[]; + fileAfterEdit?: string; } const initialState: EditModeState = { @@ -22,22 +23,47 @@ export const editModeStateSlice = createSlice({ state.highlightedCode = payload.highlightedCode; state.editStatus = "not-started"; state.previousInputs = []; + state.fileAfterEdit = undefined; }, submitEdit: (state, { payload }: PayloadAction) => { state.previousInputs.push(payload); state.editStatus = "streaming"; }, - setEditStatus: (state, { payload }: PayloadAction) => { + setEditStatus: ( + state, + { + payload, + }: PayloadAction<{ status: EditStatus; fileAfterEdit?: string }>, + ) => { // Only allow valid transitions const currentStatus = state.editStatus; - if (currentStatus === "not-started" && payload === "streaming") { - state.editStatus = payload; - } else if (currentStatus === "streaming" && payload === "accepting") { - state.editStatus = payload; - } else if (currentStatus === "accepting" && payload === "done") { - state.editStatus = payload; - } else if (currentStatus === "done" && payload === "not-started") { - state.editStatus = payload; + if (currentStatus === "not-started" && payload.status === "streaming") { + state.editStatus = payload.status; + } else if ( + currentStatus === "streaming" && + payload.status === "accepting" + ) { + state.editStatus = payload.status; + state.fileAfterEdit = payload.fileAfterEdit; + } else if (currentStatus === "accepting" && payload.status === "done") { + state.editStatus = payload.status; + } else if ( + currentStatus === "accepting:full-diff" && + payload.status === "done" + ) { + state.editStatus = payload.status; + } else if ( + currentStatus === "accepting" && + payload.status === "accepting:full-diff" + ) { + state.editStatus = payload.status; + } else if ( + currentStatus === "accepting:full-diff" && + payload.status === "accepting" + ) { + state.editStatus = payload.status; + } else if (currentStatus === "done" && payload.status === "not-started") { + state.editStatus = payload.status; } }, addPreviousInput: (state, { payload }: PayloadAction) => { diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 261eaf090..f782f1c78 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -73,6 +73,11 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi { ...config, apiBase: "https://api.sambanova.ai/v1/", }); + case "nebius": + return new OpenAIApi({ + ...config, + apiBase: "https://api.studio.nebius.ai/v1/", + }); default: throw new Error(`Unsupported LLM API format: ${config.provider}`); } diff --git a/packages/openai-adapters/test/main.test.ts b/packages/openai-adapters/test/main.test.ts index a0d55097f..efe8cc7c5 100644 --- a/packages/openai-adapters/test/main.test.ts +++ b/packages/openai-adapters/test/main.test.ts @@ -273,6 +273,12 @@ const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [ apiKey: process.env.SAMBANOVA_API_KEY!, chatOnly: true, }, + { + provider: "nebius", + model: "llama3.1-8b", + apiKey: process.env.NEBIUS_API_KEY!, + chatOnly: true, + }, ]; const FIM_TESTS: LlmApiConfig[] = [ @@ -311,6 +317,11 @@ const EMBEDDINGS_TESTS: LlmApiConfig[] = [ model: "models/text-embedding-004", apiKey: process.env.GEMINI_API_KEY!, }, + { + provider: "nebius", + model: "BAAI/bge-en-icl", + apiKey: process.env.NEBIUS_API_KEY!, + }, ]; const RERANK_TESTS: LlmApiConfig[] = [