diff --git a/.gitignore b/.gitignore index 106cef892..9621811de 100644 --- a/.gitignore +++ b/.gitignore @@ -142,7 +142,7 @@ codeql .tiktoken_cache -# IntelliJ Plugin +# IntelliJ Plugin **/**/.gradle **/**/.qodana **/**/build @@ -168,4 +168,6 @@ extensions/intellij/.idea/** **/.idea/shelf/ extensions/intellij/bin -extensions/.continue-debug/ \ No newline at end of file +extensions/.continue-debug/ + +*.vsix \ No newline at end of file diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 000000000..d59df2ef6 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx prettier --write . \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index db326191f..15619929d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,4 +1,17 @@ +binary/bin +binary/build +binary/out +binary/tmp +core/.continue-test +docs/.docusaurus +extensions/.continue-debug extensions/vscode/continue_rc_schema.json +extensions/vscode/.vscode-test +extensions/vscode/bin +extensions/vscode/build +extensions/vscode/out +gui/dist **/.continueignore CHANGELOG.md **/continue_tutorial.py +**/node_modules \ No newline at end of file diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 381dc63b7..3cc1ce65c 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -29,6 +29,7 @@ const autocompleteCache = AutocompleteLruCache.get(); const ERRORS_TO_IGNORE = [ // From Ollama "unexpected server status", + "operation was aborted" ]; export type GetLspDefinitionsFunction = ( @@ -176,17 +177,18 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let snippets = await aggregateSnippets( - helper, - extraSnippets, - this.contextRetrievalService, - ); + const [snippets, diff, workspaceDirs] = await Promise.all([ + aggregateSnippets(helper, extraSnippets, this.contextRetrievalService), + this.ide.getDiff(true), + this.ide.getWorkspaceDirs(), + ]); - const { prompt, prefix, suffix, completionOptions } = renderPrompt( + const { prompt, prefix, suffix, completionOptions } = renderPrompt({ snippets, - await this.ide.getWorkspaceDirs(), + diff, + workspaceDirs, helper, - ); + }); // Completion let completion: string | undefined = ""; diff --git a/core/autocomplete/aggregateSnippets.ts b/core/autocomplete/aggregateSnippets.ts index 90196de87..f47b9021f 100644 --- a/core/autocomplete/aggregateSnippets.ts +++ b/core/autocomplete/aggregateSnippets.ts @@ -1,10 +1,7 @@ -import { Position, Range } from "../index.js"; - import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, rankAndOrderSnippets, - removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; import { HelperVars } from "./util/HelperVars.js"; @@ -21,29 +18,6 @@ function filterSnippetsAlreadyInCaretWindow( ); } -function getRangeOfPrefixAndSuffixWithBuffer( - prefix: string, - suffix: string, - caretPos: Position, -): Range { - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: caretPos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: caretPos.line + suffixLines + buffer, - character: 0, - }, - }; - - return prefixSuffixRangeWithBuffer; -} - export async function aggregateSnippets( helper: HelperVars, extraSnippets: AutocompleteSnippet[], @@ -61,24 +35,7 @@ export async function aggregateSnippets( const scoredSnippets = rankAndOrderSnippets(snippets, helper); - // This might be redundant with filterSnippetsAlreadyInCaretWindow - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - getRangeOfPrefixAndSuffixWithBuffer( - helper.prunedPrefix, - helper.prunedSuffix, - helper.pos, - ), - ); - - // Filter snippets below similarity threshold - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - - finalSnippets = fillPromptWithSnippets( + const finalSnippets = fillPromptWithSnippets( scoredSnippets, helper.maxSnippetTokens, helper.modelName, diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index e761d994e..3e83afca5 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -153,24 +153,6 @@ export function fillPromptWithSnippets( return keptSnippets; } -function rangeIntersectionByLines(a: Range, b: Range): Range | null { - const startLine = Math.max(a.start.line, b.start.line); - const endLine = Math.min(a.end.line, b.end.line); - if (startLine >= endLine) { - return null; - } - return { - start: { - line: startLine, - character: 0, - }, - end: { - line: endLine, - character: 0, - }, - }; -} - /** * Remove one range from another range, which may lead to returning two disjoint ranges */ @@ -225,31 +207,3 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] { } return [orig]; } - -export function removeRangeFromSnippets( - snippets: Required[], - filepath: string, - range: Range, -): Required[] { - const finalSnippets: Required[] = []; - for (const snippet of snippets) { - if (snippet.filepath !== filepath) { - finalSnippets.push(snippet); - continue; - } - - const intersection = rangeIntersectionByLines(range, snippet.range); - if (!intersection) { - finalSnippets.push(snippet); - } else { - finalSnippets.push( - ...rangeDifferenceByLines(snippet.range, intersection).map((range) => ({ - ...snippet, - range, - })), - ); - } - } - - return finalSnippets; -} diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index f516ad04b..d44957d15 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -25,10 +25,10 @@ export class CompletionStreamer { // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, - () => + (abortSignal: AbortSignal) => llm.supportsFim() - ? llm.streamFim(prefix, suffix, completionOptions) - : llm.streamComplete(prompt, { + ? llm.streamFim(prefix, suffix, abortSignal, completionOptions) + : llm.streamComplete(prompt, abortSignal, { ...completionOptions, raw: true, }), diff --git a/core/autocomplete/generation/GeneratorReuseManager.test.ts b/core/autocomplete/generation/GeneratorReuseManager.test.ts index 2454377d3..039059903 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.test.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.test.ts @@ -4,7 +4,7 @@ import { GeneratorReuseManager } from "./GeneratorReuseManager"; function createMockGenerator( data: string[], delay: number = 0, -): () => AsyncGenerator { +): (abortSignal: AbortSignal) => AsyncGenerator { const mockGenerator = async function* () { for (const chunk of data) { yield chunk; diff --git a/core/autocomplete/generation/GeneratorReuseManager.ts b/core/autocomplete/generation/GeneratorReuseManager.ts index 0b19183ce..e099b92f4 100644 --- a/core/autocomplete/generation/GeneratorReuseManager.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -8,12 +8,13 @@ export class GeneratorReuseManager { constructor(private readonly onError: (err: any) => void) {} private _createListenableGenerator( + abortController: AbortController, gen: AsyncGenerator, prefix: string, ) { this.currentGenerator?.cancel(); - const listenableGen = new ListenableGenerator(gen, this.onError); + const listenableGen = new ListenableGenerator(gen, this.onError, abortController); listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? "")); this.pendingGeneratorPrefix = prefix; @@ -35,13 +36,14 @@ export class GeneratorReuseManager { async *getGenerator( prefix: string, - newGenerator: () => AsyncGenerator, + newGenerator: (abortSignal: AbortSignal) => AsyncGenerator, multiline: boolean, ): AsyncGenerator { // If we can't reuse, then create a new generator if (!this.shouldReuseExistingGenerator(prefix)) { // Create a wrapper over the current generator to fix the prompt - this._createListenableGenerator(newGenerator(), prefix); + const abortController = new AbortController(); + this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix); } // Already typed characters are those that are new in the prefix from the old generator diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts index 0cc9f664e..e6b36019b 100644 --- a/core/autocomplete/generation/ListenableGenerator.ts +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -3,16 +3,20 @@ export class ListenableGenerator { private _buffer: T[] = []; private _listeners: Set<(value: T) => void> = new Set(); private _isEnded = false; + private _abortController: AbortController constructor( source: AsyncGenerator, private readonly onError: (e: any) => void, + abortController: AbortController ) { this._source = source; + this._abortController = abortController; this._start(); } public cancel() { + this._abortController.abort(); this._isEnded = true; } diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index bc3b3bcaa..40ffa5384 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,5 +1,7 @@ import path from "node:path"; +import ignore from "ignore"; + import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; @@ -31,7 +33,7 @@ async function isDisabledForFile( } // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); + const pattern = ignore.default().add(disableInFiles); if (pattern.ignores(filepath)) { return true; } diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index d0d67db85..f847e3b2a 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -11,6 +11,7 @@ import { getTemplateForModel, } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; +import { countTokens } from "../../llm/countTokens"; export function formatExternalSnippet( filepath: string, @@ -33,25 +34,17 @@ function getContextComments( snippets: AutocompleteSnippet[], lang: AutocompleteLanguageInfo, filepath: string, - prefix: string, - suffix: string, ) { - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - return `${formattedSnippets}\n\n`; - } + const fileNameSnippet = `\n\n${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n\n`; - const isEmptyFile = prefix.trim().length === 0 && suffix.trim().length === 0; - if (isEmptyFile) { - // Include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts(filepath, 2)}\n`; - } + const formattedSnippets = + snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n") + fileNameSnippet; - return ""; + return formattedSnippets; } function getTemplate(helper: HelperVars): AutocompleteTemplate { @@ -85,11 +78,29 @@ function renderStringTemplate( }); } -export function renderPrompt( - snippets: AutocompleteSnippet[], - workspaceDirs: string[], - helper: HelperVars, -): { +const formatDiff = (helper: HelperVars, diff?: string) => { + if (!diff) return ""; + + const tokenCount = countTokens(diff, helper.modelName); + + if (tokenCount > helper.maxDiffTokens) { + return ""; + } + + return `${diff}\n\n`; +}; + +export function renderPrompt({ + snippets, + workspaceDirs, + helper, + diff, +}: { + snippets: AutocompleteSnippet[]; + workspaceDirs: string[]; + helper: HelperVars; + diff?: string; +}): { prompt: string; prefix: string; suffix: string; @@ -119,10 +130,10 @@ export function renderPrompt( snippets, helper.lang, helper.filepath, - prefix, - suffix, ); - prefix = `${contextComments}${prefix}`; + const formattedDiff = formatDiff(helper, diff); + + prefix = `${formattedDiff}${contextComments}${prefix}`; } const prompt = diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 2d9f74ab5..190e9b8ec 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -39,7 +39,9 @@ export class HelperVars { private async init() { // Don't do anything if already initialized - if (this._fileContents !== undefined) {return;} + if (this._fileContents !== undefined) { + return; + } this._fileContents = this.input.manuallyPassFileContents ?? @@ -115,6 +117,11 @@ export class HelperVars { get maxSnippetTokens() { return this.options.maxPromptTokens * this.options.maxSnippetPercentage; } + + get maxDiffTokens() { + return this.options.maxPromptTokens * this.options.maxDiffPercentage; + } + get prunedCaretWindow() { return this.prunedPrefix + this.prunedSuffix; } diff --git a/core/commands/index.ts b/core/commands/index.ts index 806e918db..cb5e162f7 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -58,7 +58,7 @@ export function slashFromCustomCommand( } } - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/cmd.ts b/core/commands/slash/cmd.ts index 00ba5b0de..1c3968172 100644 --- a/core/commands/slash/cmd.ts +++ b/core/commands/slash/cmd.ts @@ -24,7 +24,9 @@ const GenerateTerminalCommand: SlashCommand = { "${input}" -Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`); +Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`, + new AbortController().signal + ); const lines = streamLines(gen); let cmd = ""; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 034e07e5e..7d5f22a90 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -16,7 +16,7 @@ const CommitMessageCommand: SlashCommand = { const prompt = `${diff}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`; for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/draftIssue.ts b/core/commands/slash/draftIssue.ts index 25da6b559..268c68384 100644 --- a/core/commands/slash/draftIssue.ts +++ b/core/commands/slash/draftIssue.ts @@ -30,7 +30,7 @@ const DraftIssueCommand: SlashCommand = { return; } let title = await llm.complete( - `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, + `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `, new AbortController().signal, { maxTokens: 20 }, ); @@ -43,7 +43,7 @@ const DraftIssueCommand: SlashCommand = { { role: "user", content: PROMPT(input, title) }, ]; - for await (const chunk of llm.streamChat(messages)) { + for await (const chunk of llm.streamChat(messages, new AbortController().signal)) { body += chunk.content; yield stripImages(chunk.content); } diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index fc71838df..78d86beee 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -478,7 +478,7 @@ const EditSlashCommand: SlashCommand = { messages = rendered; } - const completion = llm.streamComplete(rendered as string, { + const completion = llm.streamComplete(rendered as string, new AbortController().signal, { maxTokens: Math.min(maxTokens, Math.floor(llm.contextLength / 2), 4096), raw: true, }); @@ -494,7 +494,7 @@ const EditSlashCommand: SlashCommand = { ); } else { async function* gen() { - for await (const chunk of llm.streamChat(messages, { + for await (const chunk of llm.streamChat(messages, new AbortController().signal,{ temperature: 0.5, // TODO maxTokens: Math.min( maxTokens, @@ -609,7 +609,7 @@ ${lines.join("\n")} Please briefly explain the changes made to the code above. Give no more than 2-3 sentences, and use markdown bullet points:`; - for await (const update of llm.streamComplete(prompt)) { + for await (const update of llm.streamComplete(prompt, new AbortController().signal)) { yield update; } } diff --git a/core/commands/slash/multifileEdit.ts b/core/commands/slash/multifileEdit.ts index 740243a5a..c8cf64679 100644 --- a/core/commands/slash/multifileEdit.ts +++ b/core/commands/slash/multifileEdit.ts @@ -39,7 +39,7 @@ const MultiFileEditSlashCommand: SlashCommand = { const content = createPrompt(filesToEditStr, additionalContextStr, input); - for await (const chunk of llm.streamChat([{ role: "user", content }])) { + for await (const chunk of llm.streamChat([{ role: "user", content }], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index 8d3433c25..4d8aa3a38 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -47,7 +47,7 @@ const OnboardSlashCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: prompt }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, @@ -134,7 +134,7 @@ function createOnboardingPrompt(context: string): string { Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole. Here is an example of a valid response: - + ## Important folders ### /folder1 diff --git a/core/commands/slash/review.ts b/core/commands/slash/review.ts index 34859d94c..77357647a 100644 --- a/core/commands/slash/review.ts +++ b/core/commands/slash/review.ts @@ -45,7 +45,7 @@ const ReviewMessageCommand: SlashCommand = { for await (const chunk of llm.streamChat([ { role: "user", content: content }, - ])) { + ], new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index aa19f3b0c..1ec963513 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -125,7 +125,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } diff --git a/core/config/types.ts b/core/config/types.ts index ad80cdeab..370689dde 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -836,7 +836,7 @@ declare global { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/context/providers/GitHubIssuesContextProvider.ts b/core/context/providers/GitHubIssuesContextProvider.ts index ef34ad621..7bd64d860 100644 --- a/core/context/providers/GitHubIssuesContextProvider.ts +++ b/core/context/providers/GitHubIssuesContextProvider.ts @@ -21,11 +21,12 @@ class GitHubIssuesContextProvider extends BaseContextProvider { ): Promise { const issueId = query; const { Octokit } = await import("@octokit/rest"); - const domain = this.options?.domain ?? "github.com"; const octokit = new Octokit({ auth: this.options?.githubToken, - baseUrl: `https://${domain}/api/v3`, + baseUrl: this.options?.domain + ? `https://${this.options.domain}/api/v3` + : undefined, request: { fetch: extras.fetch, }, diff --git a/core/context/rerankers/llm.ts b/core/context/rerankers/llm.ts index 5396c8d9b..a673f5dc4 100644 --- a/core/context/rerankers/llm.ts +++ b/core/context/rerankers/llm.ts @@ -6,7 +6,7 @@ const RERANK_PROMPT = ( documentId: string, document: string, ) => `You are an expert software developer responsible for helping detect whether the retrieved snippet of code is relevant to the query. For a given input, you need to output a single word: "Yes" or "No" indicating the retrieved snippet is relevant to the query. - + Query: Where is the FastAPI server? Snippet: \`\`\`/Users/andrew/Desktop/server/main.py @@ -17,7 +17,7 @@ const RERANK_PROMPT = ( return {{"Hello": "World"}} \`\`\` Relevant: Yes - + Query: Where in the documentation does it talk about the UI? Snippet: \`\`\`/Users/andrew/Projects/bubble_sort/src/lib.rs @@ -32,13 +32,13 @@ const RERANK_PROMPT = ( }} \`\`\` Relevant: No - + Query: ${query} Snippet: \`\`\`${documentId} ${document} \`\`\` - Relevant: + Relevant: `; export class LLMReranker implements Reranker { @@ -49,6 +49,7 @@ export class LLMReranker implements Reranker { async scoreChunk(chunk: Chunk, query: string): Promise { const completion = await this.llm.complete( RERANK_PROMPT(query, getBasename(chunk.filepath), chunk.content), + new AbortController().signal, { maxTokens: 1, model: diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index e4b3e072e..8dc55df9d 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -61,7 +61,7 @@ This is the question that you should select relevant files for: "${input}"`; const response = await llm.chat([ { role: "user", content: prompt }, { role: "assistant", content: "" }, - ]); + ], new AbortController().signal); const content = stripImages(response.content); console.debug("Repo map retrieval response: ", content); diff --git a/core/core.ts b/core/core.ts index 14db3517d..18ae323c6 100644 --- a/core/core.ts +++ b/core/core.ts @@ -387,6 +387,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamChat( msg.data.messages, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -428,6 +429,7 @@ export class Core { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); let next = await gen.next(); @@ -460,6 +462,7 @@ export class Core { const model = await this.configHandler.llmFromTitle(msg.data.title); const completion = await model.complete( msg.data.prompt, + new AbortController().signal, msg.data.completionOptions, ); return completion; diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index e6c3183f0..26e174c17 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -86,7 +86,7 @@ export async function* getReplacementWithLlm( const completion = await llm.streamChat([ { role: "user", content: userPrompt }, { role: "assistant", content: assistantPrompt }, - ]); + ], new AbortController().signal); let lines = streamLines(completion); lines = filterLeadingNewline(lines); diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index 135aa3170..a5c85ee4d 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -23,7 +23,7 @@ export async function* streamLazyApply( } const promptMessages = promptFactory(oldCode, filename, newCode); - const lazyCompletion = llm.streamChat(promptMessages); + const lazyCompletion = llm.streamChat(promptMessages, new AbortController().signal); // Do find and replace over the lazy edit response async function* replacementFunction( diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index ca47f010d..5ecf273c5 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -96,8 +96,8 @@ export async function* streamDiffLines( const completion = typeof prompt === "string" - ? llm.streamComplete(prompt, { raw: true, prediction }) - : llm.streamChat(prompt, { + ? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction }) + : llm.streamChat(prompt, new AbortController().signal, { prediction, }); diff --git a/core/index.d.ts b/core/index.d.ts index c30119968..392a9e11c 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -78,26 +78,34 @@ export interface ILLM extends LLMOptions { region?: string; projectId?: string; - complete(prompt: string, options?: LLMFullCompletionOptions): Promise; + complete( + prompt: string, + signal: AbortSignal, + options?: LLMFullCompletionOptions + ): Promise; streamComplete( prompt: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamFim( prefix: string, suffix: string, + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; streamChat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): AsyncGenerator; chat( messages: ChatMessage[], + signal: AbortSignal, options?: LLMFullCompletionOptions, ): Promise; @@ -388,11 +396,13 @@ export interface CustomLLMWithOptionals { options: LLMOptions; streamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; streamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; @@ -937,7 +947,7 @@ export interface TabAutocompleteOptions { slidingWindowPrefixPercentage: number; slidingWindowSize: number; maxSnippetPercentage: number; - recentlyEditedSimilarityThreshold: number; + maxDiffPercentage: number; useCache: boolean; onlyMyCode: boolean; useOtherFiles: boolean; diff --git a/core/indexing/docs/preIndexedDocs.ts b/core/indexing/docs/preIndexedDocs.ts index 01935af9e..99a8ddc8a 100644 --- a/core/indexing/docs/preIndexedDocs.ts +++ b/core/indexing/docs/preIndexedDocs.ts @@ -330,6 +330,12 @@ const preIndexedDocs: Record< startUrl: "https://llama-stack.readthedocs.io/", rootUrl: "https://llama-stack.readthedocs.io/", }, + "https://go.dev/doc": { + title: "Go", + startUrl: "https://go.dev/doc", + rootUrl: "https://go.dev", + faviconUrl: "https://go.dev/favicon.ico", + }, }; export default preIndexedDocs; diff --git a/core/llm/index.ts b/core/llm/index.ts index d3148f833..1156120a6 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -372,10 +372,11 @@ export abstract class BaseLLM implements ILLM { `HTTP ${e.response.status} ${e.response.statusText} from ${e.response.url}\n\n${e.response.body}`, ); } else { - console.debug( - `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, - ); - + if (e.name !== "AbortError") { // Don't pollute console with abort errors. Check on name instead of instanceof, to avoid importing node-fetch here + console.debug( + `${e.message}\n\nCode: ${e.code}\nError number: ${e.errno}\nSyscall: ${e.erroredSysCall}\nType: ${e.type}\n\n${e.stack}`, + ); + } if ( e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") @@ -424,6 +425,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -432,6 +434,7 @@ export abstract class BaseLLM implements ILLM { async *streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log } = this._parseCompletionOptions(options); @@ -452,6 +455,7 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamFim( prefix, suffix, + signal, completionOptions, )) { completion += chunk; @@ -477,6 +481,7 @@ export abstract class BaseLLM implements ILLM { async *streamComplete( _prompt: string, + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ) { const { completionOptions, log, raw } = @@ -506,6 +511,7 @@ export abstract class BaseLLM implements ILLM { try { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -527,7 +533,7 @@ export abstract class BaseLLM implements ILLM { }; } - async complete(_prompt: string, options: LLMFullCompletionOptions = {}) { + async complete(_prompt: string, signal: AbortSignal, options: LLMFullCompletionOptions = {}) { const { completionOptions, log, raw } = this._parseCompletionOptions(options); @@ -551,7 +557,7 @@ export abstract class BaseLLM implements ILLM { } } - const completion = await this._complete(prompt, completionOptions); + const completion = await this._complete(prompt, signal, completionOptions); this._logTokensGenerated(completionOptions.model, prompt, completion); @@ -562,9 +568,9 @@ export abstract class BaseLLM implements ILLM { return completion; } - async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) { + async chat(messages: ChatMessage[], signal: AbortSignal, options: LLMFullCompletionOptions = {}) { let completion = ""; - for await (const chunk of this.streamChat(messages, options)) { + for await (const chunk of this.streamChat(messages, signal, options)) { completion += chunk.content; } return { role: "assistant" as ChatMessageRole, content: completion }; @@ -572,6 +578,7 @@ export abstract class BaseLLM implements ILLM { async *streamChat( _messages: ChatMessage[], + signal: AbortSignal, options: LLMFullCompletionOptions = {}, ): AsyncGenerator { const { completionOptions, log, raw } = @@ -597,6 +604,7 @@ export abstract class BaseLLM implements ILLM { if (this.templateMessages) { for await (const chunk of this._streamComplete( prompt, + signal, completionOptions, )) { completion += chunk; @@ -605,6 +613,7 @@ export abstract class BaseLLM implements ILLM { } else { for await (const chunk of this._streamChat( messages, + signal, completionOptions, )) { completion += chunk.content; @@ -633,6 +642,7 @@ export abstract class BaseLLM implements ILLM { // biome-ignore lint/correctness/useYield: Purposefully not implemented protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { throw new Error("Not implemented"); @@ -640,6 +650,7 @@ export abstract class BaseLLM implements ILLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.templateMessages) { @@ -650,15 +661,16 @@ export abstract class BaseLLM implements ILLM { for await (const chunk of this._streamComplete( this.templateMessages(messages), + signal, options, )) { yield { role: "assistant", content: chunk }; } } - protected async _complete(prompt: string, options: CompletionOptions) { + protected async _complete(prompt: string, signal: AbortSignal, options: CompletionOptions) { let completion = ""; - for await (const chunk of this._streamComplete(prompt, options)) { + for await (const chunk of this._streamComplete(prompt, signal, options)) { completion += chunk; } return completion; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index dfb3065cd..5033658c7 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -97,16 +97,18 @@ class Anthropic extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const shouldCacheSystemMessage = @@ -139,6 +141,7 @@ class Anthropic extends BaseLLM { ] : systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 85fb19184..74b1ddc27 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -98,6 +98,7 @@ class Asksage extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): Promise { if (typeof prompt !== "string" || prompt.trim() === "") { @@ -126,14 +127,16 @@ class Asksage extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { - const completion = await this._complete(prompt, options); + const completion = await this._complete(prompt, signal, options); yield completion; } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions ): AsyncGenerator { const args = this._convertArgs(options, messages); @@ -142,6 +145,7 @@ class Asksage extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(args), + signal }); if (!response.ok) { diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts index 0daec0850..d563ca78e 100644 --- a/core/llm/llms/Azure.ts +++ b/core/llm/llms/Azure.ts @@ -5,6 +5,10 @@ import OpenAI from "./OpenAI.js"; class Azure extends OpenAI { static providerName: ModelProvider = "azure"; + protected supportsPrediction(model: string): boolean { + return false; + } + static defaultOptions: Partial = { apiVersion: "2024-02-15-preview", apiType: "azure", diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts index 67d8a4167..01a0201eb 100644 --- a/core/llm/llms/Bedrock.ts +++ b/core/llm/llms/Bedrock.ts @@ -37,16 +37,18 @@ class Bedrock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -84,7 +86,7 @@ class Bedrock extends BaseLLM { const input = this._generateConverseInput(messages, options); const command = new ConverseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal}); if (response.stream) { for await (const chunk of response.stream) { diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts index 44a57205e..5726cd91e 100644 --- a/core/llm/llms/BedrockImport.ts +++ b/core/llm/llms/BedrockImport.ts @@ -37,6 +37,7 @@ class BedrockImport extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -51,7 +52,7 @@ class BedrockImport extends BaseLLM { const input = this._generateInvokeModelCommandInput(prompt, options); const command = new InvokeModelWithResponseStreamCommand(input); - const response = await client.send(command); + const response = await client.send(command, {abortSignal: signal}); if (response.body) { for await (const item of response.body) { diff --git a/core/llm/llms/Cloudflare.ts b/core/llm/llms/Cloudflare.ts index 93b9c4433..07e2e427c 100644 --- a/core/llm/llms/Cloudflare.ts +++ b/core/llm/llms/Cloudflare.ts @@ -16,6 +16,7 @@ export default class Cloudflare extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -35,6 +36,7 @@ export default class Cloudflare extends BaseLLM { model: this.model, ...this._convertArgs(options), }), + signal }); for await (const value of streamSse(resp)) { @@ -46,10 +48,12 @@ export default class Cloudflare extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); diff --git a/core/llm/llms/Cohere.ts b/core/llm/llms/Cohere.ts index 83f255904..98135c7cc 100644 --- a/core/llm/llms/Cohere.ts +++ b/core/llm/llms/Cohere.ts @@ -46,16 +46,18 @@ class Cohere extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const messages = [{ role: "user" as const, content: prompt }]; - for await (const update of this._streamChat(messages, options)) { + for await (const update of this._streamChat(messages, signal, options)) { yield stripImages(update.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -73,6 +75,7 @@ class Cohere extends BaseLLM { chat_history: this._convertMessages(messages), preamble: this.systemMessage, }), + signal }); if (options.stream === false) { diff --git a/core/llm/llms/CustomLLM.ts b/core/llm/llms/CustomLLM.ts index d35dfabde..81d038f9d 100644 --- a/core/llm/llms/CustomLLM.ts +++ b/core/llm/llms/CustomLLM.ts @@ -13,12 +13,14 @@ class CustomLLMClass extends BaseLLM { private customStreamCompletion?: ( prompt: string, + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; private customStreamChat?: ( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; @@ -31,18 +33,20 @@ class CustomLLMClass extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamChat) { for await (const content of this.customStreamChat( messages, + signal, options, (...args) => this.fetch(...args), )) { yield { role: "assistant", content }; } } else { - for await (const update of super._streamChat(messages, options)) { + for await (const update of super._streamChat(messages, signal, options)) { yield update; } } @@ -50,11 +54,13 @@ class CustomLLMClass extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.customStreamCompletion) { for await (const content of this.customStreamCompletion( prompt, + signal, options, (...args) => this.fetch(...args), )) { @@ -63,6 +69,7 @@ class CustomLLMClass extends BaseLLM { } else if (this.customStreamChat) { for await (const content of this.customStreamChat( [{ role: "user", content: prompt }], + signal, options, (...args) => this.fetch(...args), )) { diff --git a/core/llm/llms/Deepseek.ts b/core/llm/llms/Deepseek.ts index cfba34e85..177ac7efa 100644 --- a/core/llm/llms/Deepseek.ts +++ b/core/llm/llms/Deepseek.ts @@ -23,6 +23,7 @@ class Deepseek extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("beta/completions", this.apiBase); @@ -45,6 +46,7 @@ class Deepseek extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].text; diff --git a/core/llm/llms/Flowise.ts b/core/llm/llms/Flowise.ts index 0d9e617a0..ecca89d16 100644 --- a/core/llm/llms/Flowise.ts +++ b/core/llm/llms/Flowise.ts @@ -121,16 +121,18 @@ class Flowise extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const message: ChatMessage = { role: "user", content: prompt }; - for await (const chunk of this._streamChat([message], options)) { + for await (const chunk of this._streamChat([message], signal, options)) { yield stripImages(chunk.content); } } protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const requestBody = this._getRequestBody(messages, options); @@ -139,6 +141,7 @@ class Flowise extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), + signal }).then((res) => res.json()); while (await socketInfo.hasNextToken()) { diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 9f307d125..8f80c7418 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -60,6 +60,7 @@ class FreeTrial extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -73,6 +74,7 @@ class FreeTrial extends BaseLLM { prompt, ...args, }), + signal }); let completion = ""; @@ -103,6 +105,7 @@ class FreeTrial extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -120,6 +123,7 @@ class FreeTrial extends BaseLLM { messages: messages.map(this._convertMessage), ...args, }), + signal }); let completion = ""; @@ -140,6 +144,7 @@ class FreeTrial extends BaseLLM { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(this.collectArgs(options)); @@ -153,6 +158,7 @@ class FreeTrial extends BaseLLM { suffix, ...args, }), + signal }); let completion = ""; diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 2e33968d5..ada603240 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -46,10 +46,12 @@ class Gemini extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -72,6 +74,7 @@ class Gemini extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { // Ensure this.apiBase is used if available, otherwise use default @@ -89,6 +92,7 @@ class Gemini extends BaseLLM { if (options.model.includes("gemini")) { for await (const message of this.streamChatGemini( convertedMsgs, + signal, options, )) { yield message; @@ -96,6 +100,7 @@ class Gemini extends BaseLLM { } else { for await (const message of this.streamChatBison( convertedMsgs, + signal, options, )) { yield message; @@ -118,6 +123,7 @@ class Gemini extends BaseLLM { private async *streamChatGemini( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiURL = new URL( @@ -159,6 +165,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); let buffer = ""; @@ -211,6 +218,7 @@ class Gemini extends BaseLLM { } private async *streamChatBison( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const msgList = []; @@ -226,6 +234,7 @@ class Gemini extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); const data = await response.json(); yield { role: "assistant", content: data.candidates[0].content }; diff --git a/core/llm/llms/HuggingFaceInferenceAPI.ts b/core/llm/llms/HuggingFaceInferenceAPI.ts index 21b607163..7e8d11c56 100644 --- a/core/llm/llms/HuggingFaceInferenceAPI.ts +++ b/core/llm/llms/HuggingFaceInferenceAPI.ts @@ -16,6 +16,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (!this.apiBase) { @@ -36,6 +37,7 @@ class HuggingFaceInferenceAPI extends BaseLLM { stream: true, parameters: this._convertArgs(options), }), + signal }); async function* stream() { diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index 9636dbc63..df84083dc 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -48,6 +48,7 @@ class HuggingFaceTGI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args = this._convertArgs(options, prompt); @@ -60,6 +61,7 @@ class HuggingFaceTGI extends BaseLLM { "Content-Type": "application/json", }, body: JSON.stringify({ inputs: prompt, parameters: args }), + signal }, ); diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index e37b445e6..80ada3fdf 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -26,6 +26,7 @@ class LlamaCpp extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const headers = { @@ -42,6 +43,7 @@ class LlamaCpp extends BaseLLM { stream: true, ...this._convertArgs(options, prompt), }), + signal }); for await (const value of streamSse(resp)) { diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index e6097a60d..5f3880e3c 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -7,6 +7,7 @@ class Mock extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { yield this.completion; @@ -14,6 +15,7 @@ class Mock extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for (const char of this.completion) { diff --git a/core/llm/llms/Moonshot.ts b/core/llm/llms/Moonshot.ts index 022fa8af2..5a015dcca 100644 --- a/core/llm/llms/Moonshot.ts +++ b/core/llm/llms/Moonshot.ts @@ -23,6 +23,7 @@ class Moonshot extends OpenAI { async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("v1/chat/completions", this.apiBase); @@ -49,6 +50,7 @@ class Moonshot extends OpenAI { Accept: "application/json", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index a9ac7ab75..dcaa078ba 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -30,7 +30,7 @@ interface ModelFileParams { min_p?: number; // deprecated? num_thread?: number; - use_mmap?: boolean; + use_mmap?: boolean; num_gqa?: number; num_gpu?: number; } @@ -77,7 +77,6 @@ class Ollama extends BaseLLM { if (options.model === "AUTODETECT") { return; } - this.fetch(this.getEndpoint("api/show"), { method: "POST", headers: { @@ -262,6 +261,7 @@ class Ollama extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/generate"), { @@ -271,6 +271,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prompt)), + signal }); let buffer = ""; @@ -301,6 +302,7 @@ class Ollama extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const response = await this.fetch(this.getEndpoint("api/chat"), { @@ -310,6 +312,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getChatOptions(options, messages)), + signal }); let buffer = ""; @@ -348,8 +351,10 @@ class Ollama extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const response = await this.fetch(this.getEndpoint("api/generate"), { method: "POST", headers: { @@ -357,6 +362,7 @@ class Ollama extends BaseLLM { Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify(this._getGenerateOptions(options, prefix, suffix)), + signal }); let buffer = ""; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 168e0afff..36abb746d 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -95,11 +95,8 @@ class OpenAI extends BaseLLM { ); } - private supportsPrediction(model: string): boolean { - return [ - "gpt-4o-mini", - "gpt-4o" - ].includes(model); + protected supportsPrediction(model: string): boolean { + return ["gpt-4o-mini", "gpt-4o"].includes(model); } protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]) { @@ -120,9 +117,9 @@ class OpenAI extends BaseLLM { : url.host === "api.deepseek.com" ? options.stop?.slice(0, 16) : url.port === "1337" || - url.host === "api.openai.com" || - url.host === "api.groq.com" || - this.apiType === "azure" + url.host === "api.openai.com" || + url.host === "api.groq.com" || + this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, }; @@ -143,10 +140,12 @@ class OpenAI extends BaseLLM { } if (options.prediction && this.supportsPrediction(options.model)) { - if (finalOptions.presence_penalty) { // prediction doesn't support > 0 + if (finalOptions.presence_penalty) { + // prediction doesn't support > 0 finalOptions.presence_penalty = undefined; } - if (finalOptions.frequency_penalty) { // prediction doesn't support > 0 + if (finalOptions.frequency_penalty) { + // prediction doesn't support > 0 finalOptions.frequency_penalty = undefined; } finalOptions.max_completion_tokens = undefined; @@ -167,11 +166,13 @@ class OpenAI extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -200,10 +201,12 @@ class OpenAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -212,6 +215,7 @@ class OpenAI extends BaseLLM { protected async *_legacystreamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const args: any = this._convertArgs(options, []); @@ -225,6 +229,7 @@ class OpenAI extends BaseLLM { ...args, stream: true, }), + signal }); for await (const value of streamSse(response)) { @@ -236,6 +241,7 @@ class OpenAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if ( @@ -247,6 +253,7 @@ class OpenAI extends BaseLLM { ) { for await (const content of this._legacystreamComplete( stripImages(messages[messages.length - 1]?.content || ""), + signal, options, )) { yield { @@ -267,6 +274,7 @@ class OpenAI extends BaseLLM { method: "POST", headers: this._getHeaders(), body: JSON.stringify(body), + signal }); // Handle non-streaming response @@ -286,6 +294,7 @@ class OpenAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("fim/completions", this.apiBase); @@ -309,6 +318,7 @@ class OpenAI extends BaseLLM { "x-api-key": this.apiKey ?? "", Authorization: `Bearer ${this.apiKey}`, }, + signal }); for await (const chunk of streamSse(resp)) { yield chunk.choices[0].delta.content; diff --git a/core/llm/llms/Replicate.ts b/core/llm/llms/Replicate.ts index 414975ac4..59994cec1 100644 --- a/core/llm/llms/Replicate.ts +++ b/core/llm/llms/Replicate.ts @@ -41,11 +41,13 @@ class Replicate extends BaseLLM { private _convertArgs( options: CompletionOptions, prompt: string, - ): [`${string}/${string}:${string}`, { input: any }] { + signal: AbortSignal + ): [`${string}/${string}:${string}`, { input: any, signal: AbortSignal }] { return [ Replicate.MODEL_IDS[options.model] || (options.model as any), { input: { prompt, message: prompt }, + signal }, ]; } @@ -57,9 +59,10 @@ class Replicate extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); const response = await this._replicate.run(model, args); return (response as any)[0]; @@ -67,9 +70,10 @@ class Replicate extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - const [model, args] = this._convertArgs(options, prompt); + const [model, args] = this._convertArgs(options, prompt, signal); for await (const event of this._replicate.stream(model, args)) { if (event.event === "output") { yield event.data; diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index c88261941..edbda4d34 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -32,6 +32,7 @@ class SageMaker extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -45,7 +46,7 @@ class SageMaker extends BaseLLM { }); const toolkit = new CompletionAPIToolkit(this); const command = toolkit.generateCommand([], prompt, options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { @@ -82,6 +83,7 @@ class SageMaker extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const credentials = await this._getCredentials(); @@ -96,7 +98,7 @@ class SageMaker extends BaseLLM { const toolkit = new MessageAPIToolkit(this); const command = toolkit.generateCommand(messages, "", options); - const response = await client.send(command); + const response = await client.send(command, { abortSignal: signal }); if (response.Body) { let buffer = ""; for await (const rawValue of response.Body) { diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index f5b5f0bac..b0044c4a8 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -41,9 +41,10 @@ class Together extends OpenAI { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { - for await (const chunk of this._legacystreamComplete(prompt, options)) { + for await (const chunk of this._legacystreamComplete(prompt,signal, options)) { yield chunk; } } diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index e945831e6..c17aac90d 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -49,7 +49,7 @@ class VertexAI extends BaseLLM { "unknown"; this.anthropicInstance = new Anthropic(_options); this.geminiInstance = new Gemini(_options); - + } async fetch(url: RequestInfo | URL, init?: RequestInit) { @@ -307,6 +307,7 @@ class VertexAI extends BaseLLM { protected async *StreamFimMistral( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const apiBase = this.apiBase!; @@ -329,6 +330,7 @@ class VertexAI extends BaseLLM { const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), + signal }); for await (const chunk of streamSse(response)) { @@ -342,6 +344,7 @@ class VertexAI extends BaseLLM { protected async *streamFimGecko( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const endpoint = new URL("publishers/google/models/code-gecko:predict", this.apiBase); @@ -363,6 +366,7 @@ class VertexAI extends BaseLLM { } }), + signal }); // Streaming is not supported by code-gecko // TODO: convert to non-streaming fim method when one exist in continue. @@ -373,6 +377,7 @@ class VertexAI extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { const isV1API = this.apiBase.includes("/v1/"); @@ -396,10 +401,12 @@ class VertexAI extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const message of this._streamChat( [{ content: prompt, role: "user" }], + signal, options, )) { yield stripImages(message.content); @@ -409,15 +416,16 @@ class VertexAI extends BaseLLM { protected async *_streamFim( prefix: string, suffix: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { if (this.model === "code-gecko") { - yield* this.streamFimGecko(prefix, suffix, options); + yield* this.streamFimGecko(prefix, suffix, signal, options); } else if (this.model.includes("codestral")) { - yield* this.StreamFimMistral(prefix, suffix, options); + yield* this.StreamFimMistral(prefix, suffix, signal, options); } else { throw new Error(`Unsupported model: ${this.model}`); } diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index 89a2d13dc..808557692 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -140,11 +140,13 @@ class WatsonX extends BaseLLM { protected async _complete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): Promise { let completion = ""; for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { completion += chunk.content; @@ -155,10 +157,12 @@ class WatsonX extends BaseLLM { protected async *_streamComplete( prompt: string, + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { for await (const chunk of this._streamChat( [{ role: "user", content: prompt }], + signal, options, )) { yield stripImages(chunk.content); @@ -167,6 +171,7 @@ class WatsonX extends BaseLLM { protected async *_streamChat( messages: ChatMessage[], + signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { var now = new Date().getTime() / 1000; @@ -219,6 +224,7 @@ class WatsonX extends BaseLLM { method: "POST", headers: headers, body: JSON.stringify(payload), + signal }); if (!response.ok || response.body === null) { diff --git a/core/promptFiles/v1/slashCommandFromPromptFile.ts b/core/promptFiles/v1/slashCommandFromPromptFile.ts index 4b77360fe..9e4f0c194 100644 --- a/core/promptFiles/v1/slashCommandFromPromptFile.ts +++ b/core/promptFiles/v1/slashCommandFromPromptFile.ts @@ -90,7 +90,7 @@ export function slashCommandFromPromptFile( systemMessage, ); - for await (const chunk of context.llm.streamChat(messages)) { + for await (const chunk of context.llm.streamChat(messages, new AbortController().signal)) { yield stripImages(chunk.content); } }, diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 5f3d1bdc1..b8ca609a2 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -52,6 +52,7 @@ export class ChatDescriber { content: ChatDescriber.prompt + message, }, ], + new AbortController().signal, completionOptions, ); diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 7a94abc03..269f3489e 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -11,8 +11,8 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { multilineCompletions: "auto", slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, - maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. + maxSnippetPercentage: 0.5, + maxDiffPercentage: 0.5, useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/docs/docs/customize/model-providers/top-level/vertexai.md b/docs/docs/customize/model-providers/top-level/vertexai.md index 1778ce3c6..50958cae0 100644 --- a/docs/docs/customize/model-providers/top-level/vertexai.md +++ b/docs/docs/customize/model-providers/top-level/vertexai.md @@ -27,7 +27,6 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. } ``` - ## Autocomplete model We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. @@ -43,6 +42,7 @@ We recommend configuring **Codestral** or **code-gecko** as your autocomplete mo } } ``` + ## Embeddings model We recommend configuring **text-embedding-004** as your embeddings model. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 09dd150a6..f39e68998 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -1,5 +1,5 @@ --- -title: Reference +title: config.json Reference description: Reference for the Continue _config.json_ configuration file keywords: [config, config_schema.json, json] --- 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 index 940fedc65..095d75918 100644 --- 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 @@ -7,7 +7,7 @@ sidebar_position: 5 ## 内置的斜杠命令 -Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。 +Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../reference.md) 并添加它们到 `slashCommands` 列表中。 ## 定制斜杠命令 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 index 5e7b8fad2..aa2a04d5f 100644 --- 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 @@ -5,7 +5,7 @@ keywords: [定制] sidebar_position: 5 --- -Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: +Continue 在 [`config.json`](../reference.md) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡: ```json title="config.json" "tabAutocompleteOptions": { 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 index fe24f18fb..b95d976f1 100644 --- 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 @@ -9,7 +9,7 @@ import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; :::info -这个页面推荐聊天的模型和提供者。在 [这里](../customize/config.mdx) 了解更多关于如何设置你的 `config.json` 。 +这个页面推荐聊天的模型和提供者。在 [这里](../reference.md) 了解更多关于如何设置你的 `config.json` 。 ::: ## 最好的总体体验 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 index ea07525ee..b85cfe323 100644 --- 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 @@ -44,7 +44,7 @@ ollama run starcoder2:3b } ``` -如果你对可用选项不熟悉,你可以在 [这里](../config.mdx) 查找完整的参考。 +如果你对可用选项不熟悉,你可以在 [这里](../../reference.md) 查找完整的参考。 ## 配置选项 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md new file mode 100644 index 000000000..049ff7754 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/nvidia.md @@ -0,0 +1,52 @@ +--- +title: NVIDIA +--- + +:::info + +[View the docs](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog) to learn how to get an API key. + +::: + +## Chat model + +We recommend configuring **Nemotron-4-340B-Instruct** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Nemotron-4-340B-Instruct", + "provider": "nvidia", + "model": "nvidia-nemotron-4-340b-instruct", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +NVIDIA currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +We recommend configuring **NVIDIA Retrieval QA Mistral 7B** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "nvidia", + "model": "nvidia/nv-embedqa-mistral-7b-v2", + "apiKey": "[API_KEY]" + } +} +``` + +## Reranking model + +NVIDIA currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md new file mode 100644 index 000000000..daf966d9e --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/vertexai.md @@ -0,0 +1,65 @@ +--- +title: Vertex AI +slug: ../vertexai +--- + +:::info + +You need to enable the [Vertex AI API](https://console.cloud.google.com/marketplace/product/google/aiplatform.googleapis.com) and set up the [Google Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc). + +::: + +## Chat model + +We recommend configuring **Claude 3.5 Sonnet** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Claude 3.5 Sonnet", + "provider": "vertexai", + "model": "claude-3-5-sonnet-20240620", + "projectId": "[PROJECT_ID]", + "region": "us-east5" + } + ] +} +``` + +## Autocomplete model + +We recommend configuring **Codestral** or **code-gecko** as your autocomplete model. + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "Codestral (Vertex AI)", + "provider": "vertexai", + "model": "codestral", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Embeddings model + +We recommend configuring **text-embedding-004** as your embeddings model. + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "vertexai", + "model": "text-embedding-004", + "projectId": "[PROJECT_ID]", + "region": "us-central1" + } +} +``` + +## Reranking model + + diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md new file mode 100644 index 000000000..fbdfa83ad --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/top-level/xai.md @@ -0,0 +1,53 @@ +--- +title: xAI +slug: ../xai +--- + +:::info + +You can get an API key from the [xAI console](https://console.x.ai/) + +::: + +## Chat model + +We recommend configuring **grok-beta** as your chat model. + +```json title="config.json" +{ + "models": [ + { + "title": "Grok Beta", + "provider": "xAI", + "model": "grok-beta", + "apiKey": "[API_KEY]" + } + ] +} +``` + +## Autocomplete model + +xAI currently does not offer any autocomplete models. + +[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. + +## Embeddings model + +xAI currently does not offer any embeddings models. + +[Click here](../../model-types/embeddings.md) to see a list of embeddings model providers. + +## Reranking model + +xAI currently does not offer any reranking models. + +[Click here](../../model-types/reranking.md) to see a list of reranking model providers. + +## Legacy Completions + +To force usage of `chat/completions` instead of `completions` endpoint you can set + +```json +"useLegacyCompletionsEndpoint": false +``` 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 index 784c0bd59..f95574dae 100644 --- 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 @@ -8,13 +8,13 @@ Continue 可以深度定制。这个主要通过编辑位于 `~/.continue/config ## 开始 -要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](./config.mdx) 。 +要打开 `config.json` ,在 Continue 聊天侧边栏的右下角点击 "齿轮" 图标。当编辑这个文件时,你可以使用 IntelliSense ,随着你的输入来查看有效的选项,或者你可以查看 [完整参考](../reference.md) 。 当你保存 `config.json` 时, Continue 会自动地刷新,应用你的变更。 ## 每个工作区的配置 -如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](./config.mdx) ,会自动地应用到本地 `config.json` 之上。 +如果你想要限制指定的配置到一个特定的工作区,你可以添加一个 `.continuerc.json` 到你的项目根目录。它有和 `config.json` 相同的 [定义](../reference.md) ,会自动地应用到本地 `config.json` 之上。 ## 可编程的配置 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 index f96a8fe6d..07a0a6c65 100644 --- 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 @@ -5,6 +5,6 @@ description: 如何设置一个编辑模型 keywords: [编辑, cmd l, 模型] --- -默认情况下,编辑使用 [与聊天相同的模型](chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 +默认情况下,编辑使用 [与聊天相同的模型](../chat/model-setup.mdx) ,所以对于代码编辑,我们推荐相同的 400B+ 参数模型或者领先的模型之一。 -你可以通过更新你的 [`config.json`](../customize/config.mdx) 为编辑配置一个不同的模型。 +你可以通过更新你的 [`config.json`](../reference.md) 为编辑配置一个不同的模型。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md new file mode 100644 index 000000000..09dd150a6 --- /dev/null +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -0,0 +1,446 @@ +--- +title: Reference +description: Reference for the Continue _config.json_ configuration file +keywords: [config, config_schema.json, json] +--- + +Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). + +**All properties at all levels are optional unless explicitly marked required** + +### `models` + +Your **chat** models are defined here, which are used for [Chat](./chat/how-to-use-it.md), [Edit](./edit/how-to-use-it.md), and [Actions](./actions/how-to-use-it.md). +Each model has specific configuration options tailored to its provider and functionality, which can be seen as suggestions while editing the json. + +**Properties:** + +- `title` (**required**): The title to assign to your model, shown in dropdowns, etc. +- `provider` (**required**): The provider of the model, which determines the type and interaction method. Options inclued `openai`, `ollama`, etc., see intelliJ suggestions. +- `model` (**required**): The name of the model, used for prompt template auto-detection. +- `apiKey`: API key required by providers like OpenAI, Anthropic, and Cohere. +- `apiBase`: The base URL of the LLM API. +- `contextLength`: Maximum context length of the model, typically in tokens (default: 2048). +- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists. +- `template`: Chat template to format messages. Auto-detected for most models but can be overridden. See intelliJ suggestions. +- `promptTemplates`: A mapping of prompt template names (e.g., `edit`) to template strings. [Customization Guide](https://docs.continue.dev/model-setup/configuration#customizing-the-edit-prompt). +- `completionOptions`: Model-specific completion options, same format as top-level [`completionOptions`](#completionoptions), which they override. +- `systemMessage`: A system message that will precede responses from the LLM. +- `requestOptions`: Model-specific HTTP request options, same format as top-level [`requestOptions`](#requestoptions), which they override. +- `apiType`: Specifies the type of API (`openai` or `azure`). +- `apiVersion`: Azure API version (e.g., `2023-07-01-preview`). +- `engine`: Engine for Azure OpenAI requests. +- `capabilities`: Override auto-detected capabilities: + - `uploadImage`: Boolean indicating if the model supports image uploads. + +_(AWS Only)_ + +- `profile`: AWS security profile for authorization. +- `modelArn`: AWS ARN for imported models (e.g., for `bedrockimport` provider). +- `region`: Region where the model is hosted (e.g., `us-east-1`, `eu-central-1`). + +Example: + +```json title="config.json" +{ + "models": [ + { + "title": "Ollama", + "provider": "ollama", + "model": "AUTODETECT" + }, + { + "model": "gpt-4o", + "contextLength": 128000, + "title": "GPT-4o", + "provider": "openai", + "apiKey": "YOUR_API_KEY" + } + ] +} +``` + +### `tabAutocompleteModel` + +Specifies the model or models for tab autocompletion, defaulting to an Ollama instance. This property uses the same format as `models`. Can be an array of models or an object for one model. + +Example + +```json title="config.json" +{ + "tabAutocompleteModel": { + "title": "My Starcoder", + "provider": "ollama", + "model": "starcoder2:3b" + } +} +``` + +### `tabAutocompleteOptions` + +Specifies options for tab autocompletion behavior. + +**Properties:** + +- `disable`: If `true`, disables tab autocomplete (default: `false`). +- `useCopyBuffer`: If `true`, includes the copy buffer in the prompt. +- `useFileSuffix`: If `true`, includes file suffix in the prompt. +- `maxPromptTokens`: Maximum number of tokens for the prompt. +- `debounceDelay`: Delay (in ms) before triggering autocomplete. +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. +- `prefixPercentage`: Percentage of input for prefix. +- `template`: Template string for autocomplete, using Mustache templating. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). +- `useCache`: If `true`, caches completions. +- `onlyMyCode`: If `true`, only includes code within the repository. +- `useOtherFiles`: If `true`, includes snippets from other files (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. + +Example + +```json title="config.json" +{ + "tabAutocompleteOptions": { + "debounceDelay": 500, + "maxPromptTokens": 1500, + "disableInFiles": ["*.md"] + } +} +``` + +### `embeddingsProvider` + +Embeddings model settings - the model used for @Codebase and @docs. + +**Properties:** + +- `provider` (**required**): Specifies the embeddings provider, with options including `transformers.js`, `ollama`, `openai`, `cohere`, `free-trial`, `gemini`, etc +- `model`: Model name for embeddings. +- `apiKey`: API key for the provider. +- `apiBase`: Base URL for API requests. +- `requestOptions`: Additional HTTP request settings specific to the embeddings provider. +- `maxChunkSize`: Maximum tokens per document chunk. Minimum is 128 tokens. +- `maxBatchSize`: Maximum number of chunks per request. Minimum is 1 chunk. + +(AWS ONLY) + +- `region`: Specifies the region hosting the model. +- `profile`: AWS security profile. + +Example: + +```json title="config.json" +{ + "embeddingsProvider": { + "provider": "openai", + "model": "text-embedding-ada-002", + "apiKey": "", + "maxChunkSize": 256, + "maxBatchSize": 5 + } +} +``` + +### `completionOptions` + +Parameters that control the behavior of text generation and completion settings. Top-level `completionOptions` apply to all models, _unless overridden at the model level_. + +**Properties:** + +- `stream`: Whether to stream the LLM response. Currently only respected by the `anthropic` and `ollama` providers; other providers will always stream (default: `true`). +- `temperature`: Controls the randomness of the completion. Higher values result in more diverse outputs. +- `topP`: The cumulative probability for nucleus sampling. Lower values limit responses to tokens within the top probability mass. +- `topK`: The maximum number of tokens considered at each step. Limits the generated text to tokens within this probability. +- `presencePenalty`: Discourages the model from generating tokens that have already appeared in the output. +- `frequencePenalty`: Penalizes tokens based on their frequency in the text, reducing repetition. +- `mirostat`: Enables Mirostat sampling, which controls the perplexity during text generation. Supported by Ollama, LM Studio, and llama.cpp providers (default: `0`, where `0` = disabled, `1` = Mirostat, and `2` = Mirostat 2.0). +- `stop`: An array of stop tokens that, when encountered, will terminate the completion. Allows specifying multiple end conditions. +- `maxTokens`: The maximum number of tokens to generate in a completion (default: `2048`). +- `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. +- `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). +- `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. + +Example + +```json title="config.json" +{ + "completionOptions": { + "stream": false, + "temperature": 0.5 + } +} +``` + +### `requestOptions` + +Default HTTP request options that apply to all models and context providers, unless overridden at the model level. + +**Properties:** + +- `timeout`: Timeout for each request to the LLM (default: 7200 seconds). +- `verifySsl`: Whether to verify SSL certificates for requests. +- `caBundlePath`: Path to a custom CA bundle for HTTP requests - path to `.pem` file (or array of paths) +- `proxy`: Proxy URL to use for HTTP requests. +- `headers`: Custom headers for HTTP requests. +- `extraBodyProperties`: Additional properties to merge with the HTTP request body. +- `noProxy`: List of hostnames that should bypass the specified proxy. +- `clientCertificate`: Client certificate for HTTP requests. + + - `cert`: Path to the client certificate file. + - `key`: Path to the client certificate key file. + - `passphrase`: Optional passphrase for the client certificate key file. + +Example + +```json title="config.json" +{ + "requestOptions": { + "headers": { + "X-Auth-Token": "xxx" + } + } +} +``` + +### `reranker` + +Configuration for the reranker model used in response ranking. + +**Properties:** + +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `params`: + - `model`: Model name + - `apiKey`: Api key + +Example + +```json title="config.json" +{ + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + } +} +``` + +### `docs` + +List of documentation sites to index. + +**Properties:** + +- `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. +- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs +- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL +- `maxDepth`: Maximum depth for crawling. Default `3` +- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). + +Example + +```json title="config.json" +"docs": [ + { + "title": "Continue", + "startUrl": "https://docs.continue.dev/intro", + "rootUrl": "https://docs.continue.dev", + "faviconUrl": "https://docs.continue.dev/favicon.ico", + } +] +``` + +### `analytics` + +Configuration for analytics tracking. + +**Properties:** + +- `provider`: Analytics provider (`"posthog"` or `"logstash"`). +- `url`: URL for analytics data. +- `clientKey`: Client key for analytics. + +### `slashCommands` + +Custom commands initiated by typing "/" in the sidebar. Commands include predefined functionality or may be user-defined. + +**Properties:** + +- `name`: The command name. Options include "issue", "share", "cmd", "http", "commit", and "review". +- `description`: Brief description of the command. +- `step`: (Deprecated) Used for built-in commands; set the name for pre-configured options. +- `params`: Additional parameters to configure command behavior (command-specific - see code for command) + +Example: + +```json title="config.json" +{ + "slashCommands": [ + { + "name": "commit", + "description": "Generate a commit message" + }, + { + "name": "share", + "description": "Export this session as markdown" + }, + { + "name": "cmd", + "description": "Generate a shell command" + } + ] +} +``` + +### `customCommands` + +User-defined commands for prompt shortcuts in the sidebar, allowing quick access to common actions. + +**Properties:** + +- `name`: The name of the custom command. +- `prompt`: Text prompt for the command. +- `description`: Brief description explaining the command's function. + +Example: + +```json title="config.json" +{ + "customCommands": [ + { + "name": "test", + "prompt": "Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.", + "description": "Write unit tests for highlighted code" + } + ] +} +``` + +### `contextProviders` + +List of the pre-defined context providers that will show up as options while typing in the chat, and their customization with `params`. + +**Properties:** + +- `name`: Name of the context provider, e.g. `docs` or `web` +- `params`: A context-provider-specific record of params to configure the context behavior + +Example + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "code", + "params": {} + }, + { + "name": "docs", + "params": {} + }, + { + "name": "diff", + "params": {} + }, + { + "name": "open", + "params": {} + } + ] +} +``` + +### `disableSessionTitles` + +Prevents generating summary titles for each chat session when set to `true`. + +### `ui` + +Customizable UI settings to control interface appearance and behavior. + +**Properties:** + +- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. +- `fontSize`: Specifies font size for UI elements. +- `displayRawMarkdown`: If `true`, shows raw markdown in responses. +- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. + +Example: + +```json title="config.json" +{ + "ui": { + "codeBlockToolbarPosition": "bottom", + "fontSize": 14, + "displayRawMarkdown": false + } +} +``` + +### `allowAnonymousTelemetry` + +When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. + +### `userToken` + +An optional token that identifies the user, primarily for authenticated services. + +### `systemMessage` + +Defines a system message that appears before every response from the language model, providing guidance or context. + +### `disableIndexing` + +Prevents indexing of the codebase, useful primarily for debugging purposes. + +### `experimental` + +Several experimental config parameters are available, as described below: + +`experimental`: + +- `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= +- `modelRoles`: + - `inlineEdit`: Model title for inline edits. + - `applyCodeBlock`: Model title for applying code blocks. + - `repoMapFileSelection`: Model title for repo map selections. +- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. +- `promptPath`: Change the path to custom prompt files from the default ".prompts" +- `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. + - `prompt` (**required**): Prompt for quick action. + - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. +- `contextMenuPrompts`: + - `comment`: Prompt for commenting code. + - `docstring`: Prompt for adding docstrings. + - `fix`: Prompt for fixing code. + - `optimize`: Prompt for optimizing code. + - `fixGrammar`: Prompt for fixing grammar or spelling. +- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. + +Example + +```json title="config.json" +{ + "experimental": { + "modelRoles": { + "inlineEdit": "Edit Model" + }, + "promptPath": "custom/.prompts", + "quickActions": [ + { + "title": "Tags", + "prompt": "Return a list of any function and class names from the included code block", + "sendToChat": true + } + ], + "contextMenuPrompts": { + "fixGrammar": "Fix grammar in the above but allow for typos." + }, + "readResponseTTS": false, + "useChromiumForDocsCrawling": true + } +} +``` diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 21fe76ccf..7761b605f 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -771,6 +771,9 @@ "starcoder-1b", "starcoder-3b", "starcoder2-3b", + "mistral-tiny", + "mistral-small", + "mistral-medium", "qwen2.5-coder:1.5b", "qwen2.5-coder:3b", "qwen2.5-coder:7b", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 697bf61c1..ef2d12c82 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.231", + "version": "0.9.232", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 60fc6b72d..2ce332f02 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -21,7 +21,6 @@ import { uriFromFilePath, } from "./vscode"; - import type { FileEdit, RangeInFile, Thread } from "core"; const util = require("node:util"); @@ -181,7 +180,8 @@ export class VsCodeIdeUtils { vscode.workspace .openTextDocument( vscode.Uri.parse( - `${VsCodeExtension.continueVirtualDocumentScheme + `${ + VsCodeExtension.continueVirtualDocumentScheme }:${encodeURIComponent(name)}?${encodeURIComponent(contents)}`, ), ) @@ -305,8 +305,8 @@ export class VsCodeIdeUtils { return `${lines .slice(range.start.line, range.end.line) .join("\n")}\n${lines[ - range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 - ].slice(0, range.end.character)}`; + range.end.line < lines.length - 1 ? range.end.line : lines.length - 1 + ].slice(0, range.end.character)}`; } async getTerminalContents(commands = -1): Promise { @@ -572,7 +572,6 @@ export class VsCodeIdeUtils { async getDiff(includeUnstaged: boolean): Promise { let diffs: string[] = []; - let repos = []; for (const dir of this.getWorkspaceDirectories()) { const repo = await this.getRepo(vscode.Uri.file(dir)); @@ -580,20 +579,16 @@ export class VsCodeIdeUtils { continue; } - repos.push(repo.state.HEAD?.name); - const staged = await repo.diff(true); - diffs.push(`${staged}`); + diffs.push(staged); if (includeUnstaged) { const unstaged = await repo.diff(false); - diffs.push(`\n${unstaged}`); + diffs.push(unstaged); } } const fullDiff = diffs.join("\n\n"); - if (fullDiff.trim() === "") { - console.log(`Diff empty for repos: ${repos}`); - } + return fullDiff; } diff --git a/gui/src/hooks/useChatHandler.ts b/gui/src/hooks/useChatHandler.ts index 02f44e1be..be32c5ee8 100644 --- a/gui/src/hooks/useChatHandler.ts +++ b/gui/src/hooks/useChatHandler.ts @@ -23,6 +23,7 @@ import resolveEditorContent, { import { IIdeMessenger } from "../context/IdeMessenger"; import { defaultModelSelector } from "../redux/selectors/modelSelectors"; import { + abortStream, addPromptCompletionPair, clearLastEmptyResponse, initNewActiveMessage, @@ -52,6 +53,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const history = useSelector((store: RootState) => store.state.history); const active = useSelector((store: RootState) => store.state.active); + const streamAborter = useSelector( + (store: RootState) => store.state.streamAborter, + ); const activeRef = useRef(active); const { saveSession } = useHistory(dispatch); @@ -66,6 +70,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { }, [active]); async function _streamNormalInput(messages: ChatMessage[]) { +<<<<<<< HEAD const abortController = new AbortController(); const cancelToken = abortController.signal; @@ -90,6 +95,37 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { let returnVal = next.value as PromptLog; if (returnVal) { dispatch(addPromptCompletionPair([returnVal])); +======= + try { + if (!defaultModel) { + throw new Error("Default model not defined"); + } + const gen = ideMessenger.llmStreamChat( + defaultModel.title, + streamAborter.signal, + messages, + ); + let next = await gen.next(); + + while (!next.done) { + if (!activeRef.current) { + dispatch(abortStream()); + break; + } + dispatch( + streamUpdate(stripImages((next.value as ChatMessage).content)), + ); + next = await gen.next(); + } + + let returnVal = next.value as PromptLog; + if (returnVal) { + dispatch(addPromptCompletionPair([returnVal])); + } + } catch (e) { + // If there's an error, we should clear the response so there aren't two input boxes + dispatch(clearLastResponse()); +>>>>>>> e60341647fcf9834844ad7ef4d5aa44fe1edf801 } } @@ -126,9 +162,6 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { selectedCode: RangeInFile[], contextItems: ContextItemWithId[], ) { - const abortController = new AbortController(); - const cancelToken = abortController.signal; - if (!defaultModel) { throw new Error("Default model not defined"); } @@ -137,7 +170,7 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { const checkActiveInterval = setInterval(() => { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); clearInterval(checkActiveInterval); } }, 100); @@ -155,10 +188,10 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { historyIndex, selectedCode, }, - cancelToken, + streamAborter.signal, )) { if (!activeRef.current) { - abortController.abort(); + dispatch(abortStream()); clearInterval(checkActiveInterval); break; } @@ -321,7 +354,9 @@ function useChatHandler(dispatch: Dispatch, ideMessenger: IIdeMessenger) { } } - return { streamResponse }; + return { + streamResponse, + }; } export default useChatHandler; diff --git a/gui/src/hooks/useHistory.tsx b/gui/src/hooks/useHistory.tsx index f159ffea3..bb5935653 100644 --- a/gui/src/hooks/useHistory.tsx +++ b/gui/src/hooks/useHistory.tsx @@ -122,9 +122,9 @@ function useHistory(dispatch: Dispatch) { if (result.status === "error") { throw new Error(result.error); } - const persistedSessionInfo = result.content; - dispatch(newSession(persistedSessionInfo)); - return persistedSessionInfo; + const sessionContent = result.content; + dispatch(newSession(sessionContent)); + return sessionContent; } async function loadLastSession(): Promise { diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index 2d98b1011..eae4b0acc 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -126,6 +126,7 @@ function useSetup(dispatch: Dispatch) { dispatch(setConfigError(error)); }); + // TODO - remove? useWebviewListener("submitMessage", async (data) => { streamResponse( data.message, diff --git a/gui/src/redux/slices/stateSlice.ts b/gui/src/redux/slices/stateSlice.ts index 9c3292c1a..5fba54889 100644 --- a/gui/src/redux/slices/stateSlice.ts +++ b/gui/src/redux/slices/stateSlice.ts @@ -4,7 +4,6 @@ import { ChatHistoryItem, ChatMessage, Checkpoint, - ContextItemId, ContextItemWithId, PersistedSessionInfo, PromptLog, @@ -12,9 +11,7 @@ import { import { BrowserSerializedContinueConfig } from "core/config/load"; import { ConfigValidationError } from "core/config/validation"; import { stripImages } from "core/llm/images"; -import { createSelector } from "reselect"; import { v4 as uuidv4, v4 } from "uuid"; -import { RootState } from "../store"; import { ApplyState } from "core/protocol/ideWebview"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. @@ -36,9 +33,10 @@ type State = { configError: ConfigValidationError[] | undefined; checkpoints: Checkpoint[]; curCheckpointIndex: number; - isMultifileEdit: boolean; applyStates: ApplyState[]; nextCodeBlockToApplyIndex: number; + streamAborter: AbortController; + isMultifileEdit: boolean; }; const initialState: State = { @@ -70,6 +68,7 @@ const initialState: State = { curCheckpointIndex: 0, nextCodeBlockToApplyIndex: 0, applyStates: [], + streamAborter: new AbortController(), }; export const stateSlice = createSlice({ @@ -252,6 +251,10 @@ export const stateSlice = createSlice({ state.isGatheringContext = false; state.active = false; }, + abortStream: (state) => { + state.streamAborter.abort(); + state.streamAborter = new AbortController(); + }, streamUpdate: (state, action: PayloadAction) => { if (state.history.length) { state.history[state.history.length - 1].message.content += @@ -262,6 +265,12 @@ export const stateSlice = createSlice({ state, { payload }: PayloadAction, ) => { + state.streamAborter.abort(); + state.streamAborter = new AbortController(); + + state.active = false; + state.isGatheringContext = false; + state.isMultifileEdit = false; if (payload) { state.history = payload.history as any; state.title = payload.title; @@ -270,7 +279,6 @@ export const stateSlice = createSlice({ state.curCheckpointIndex = 0; } else { state.history = []; - state.active = false; state.title = "New Session"; state.sessionId = v4(); state.checkpoints = []; @@ -393,6 +401,7 @@ export const { setCurCheckpointIndex, resetNextCodeBlockToApplyIndex, updateApplyState, + abortStream, } = stateSlice.actions; export default stateSlice.reducer; diff --git a/package-lock.json b/package-lock.json index c147efa72..42ecd2cd8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,6 +7,7 @@ "devDependencies": { "@typescript-eslint/parser": "^7.8.0", "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", "prettier": "^3.3.3", "prettier-plugin-tailwindcss": "^0.6.8" } @@ -1645,6 +1646,21 @@ "node": ">= 0.4" } }, + "node_modules/husky": { + "version": "9.1.7", + "resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz", + "integrity": "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA==", + "dev": true, + "bin": { + "husky": "bin.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/typicode" + } + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", diff --git a/package.json b/package.json index 6d93be403..e5dbe76f2 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,12 @@ { "devDependencies": { - "prettier": "^3.3.3", - "prettier-plugin-tailwindcss": "^0.6.8", "@typescript-eslint/parser": "^7.8.0", - "eslint-plugin-import": "^2.29.1" + "eslint-plugin-import": "^2.29.1", + "husky": "^9.1.7", + "prettier": "^3.3.3", + "prettier-plugin-tailwindcss": "^0.6.8" + }, + "scripts": { + "prepare": "husky" } } diff --git a/packages/config-types/src/index.ts b/packages/config-types/src/index.ts index 4d989c127..a4ba53b8e 100644 --- a/packages/config-types/src/index.ts +++ b/packages/config-types/src/index.ts @@ -142,7 +142,7 @@ export const tabAutocompleteOptionsSchema = z.object({ slidingWindowPrefixPercentage: z.number(), slidingWindowSize: z.number(), maxSnippetPercentage: z.number(), - recentlyEditedSimilarityThreshold: z.number(), + maxDiffPercentage: z.number(), useCache: z.boolean(), onlyMyCode: z.boolean(), useOtherFiles: z.boolean(),