From 2869cf50781317eddf55dde8248a247953f53d99 Mon Sep 17 00:00:00 2001 From: lkyu <67578466+lkyu-ly@users.noreply.github.com> Date: Thu, 20 Feb 2025 01:07:24 +0800 Subject: [PATCH 01/20] Update domain in docusaurus.config.js Change site url from `continue.dev` to `docs.continue.dev` so as to generate a correct sitemap. --- docs/docusaurus.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index c97113a0a..0ca029806 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -19,7 +19,7 @@ const config = { favicon: "img/favicon.ico", // Set the production url of your site here - url: "https://continue.dev", + url: "https://docs.continue.dev", // Set the // pathname under which your site is served // For GitHub pages deployment, it is often '//' baseUrl: "/", From dbdf72ea84215e59caa5fe9ea159248a56413118 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 13 Feb 2025 12:10:19 +0100 Subject: [PATCH 02/20] Pull missing ollama models Signed-off-by: Fred Bricon --- core/index.d.ts | 4 ++ core/llm/index.ts | 22 ++++++- core/llm/llms/Ollama.ts | 37 +++++++++++- core/util/ollamaHelper.ts | 60 ++++++++++++++++++- .../src/autocomplete/completionProvider.ts | 21 +++++-- extensions/vscode/src/commands.ts | 44 +++++++++++++- extensions/vscode/src/webviewProtocol.ts | 50 ++++++++++------ gui/src/pages/gui/StreamError.tsx | 12 ++-- 8 files changed, 214 insertions(+), 36 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 7cbf0e25b..c0c7e1453 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -163,6 +163,10 @@ export interface ILLM extends LLMOptions { ): string | ChatMessage[]; } +export interface ModelInstaller { + installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise; +} + export type ContextProviderType = "normal" | "query" | "submenu"; export interface ContextProviderDescription { diff --git a/core/llm/index.ts b/core/llm/index.ts index ccbad6699..3abed5f0b 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -19,6 +19,7 @@ import { LLMFullCompletionOptions, LLMOptions, ModelCapability, + ModelInstaller, PromptLog, PromptTemplate, RequestOptions, @@ -58,6 +59,17 @@ import { toFimBody, } from "./openaiTypeConverters.js"; + +export class LLMError extends Error { + constructor(message: string, public llm: ILLM) { + super(message); + } +} + +export function isModelInstaller(provider: any): provider is ModelInstaller { + return provider && typeof provider.installModel === 'function'; +} + export abstract class BaseLLM implements ILLM { static providerName: string; static defaultOptions: Partial | undefined = undefined; @@ -380,9 +392,11 @@ export abstract class BaseLLM implements ILLM { if (!resp.ok) { let text = await resp.text(); if (resp.status === 404 && !resp.url.includes("/v1")) { - if (text.includes("try pulling it first")) { - const model = JSON.parse(text).error.split(" ")[1].slice(1, -1); + const error = JSON.parse(text)?.error?.replace(/"/g, "'"); + let model = error?.match(/model '(.*)' not found/)?.[1]; + if (model && resp.url.match("127.0.0.1:11434")) { text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`; + throw new LLMError(text, this);// No need to add HTTP status details } else if (text.includes("/api/chat")) { text = "The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue."; @@ -442,6 +456,10 @@ export abstract class BaseLLM implements ILLM { throw new Error(message); } } + //if e instance of LLMError, rethrow + if (e instanceof LLMError) { + throw e; + } throw new Error(e.message); } }; diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index ee822eb27..675fd8663 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,9 +1,10 @@ import { JSONSchema7, JSONSchema7Object } from "json-schema"; -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { ChatMessage, CompletionOptions, ModelInstaller, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +import { getRemoteModelInfo } from "../../util/ollamaHelper.js"; type OllamaChatMessage = { role: "tool" | "user" | "assistant" | "system"; @@ -123,7 +124,7 @@ interface OllamaTool { }; } -class Ollama extends BaseLLM { +class Ollama extends BaseLLM implements ModelInstaller{ static providerName = "ollama"; static defaultOptions: Partial = { apiBase: "http://localhost:11434/", @@ -574,6 +575,38 @@ class Ollama extends BaseLLM { } return embedding; } + + public async installModel(modelName: string, signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void): Promise { + const modelInfo = await getRemoteModelInfo(modelName, signal); + if (!modelInfo) { + throw new Error(`'${modelName}' not found in the Ollama registry!`); + } + const response = await fetch(this.getEndpoint("api/pull"), { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ name: modelName }), + signal + }); + + const reader = response.body?.getReader(); + //TODO: generate proper progress based on modelInfo size + while (true) { + const { done, value } = await reader?.read() || { done: true, value: undefined }; + if (done) { + break; + } + + const chunk = new TextDecoder().decode(value); + const lines = chunk.split('\n').filter(Boolean); + for (const line of lines) { + const data = JSON.parse(line); + progressReporter?.(data.status, data.completed, data.total); + } + } + } } export default Ollama; diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts index a00e869dd..2d5266318 100644 --- a/core/util/ollamaHelper.ts +++ b/core/util/ollamaHelper.ts @@ -1,6 +1,13 @@ +import crypto from "crypto"; +import { exec } from "node:child_process"; import path from "node:path"; import { IDE } from ".."; -import { exec } from "node:child_process"; + +export interface ModelInfo { + id: string; + size: number; + digest: string; +} export async function isOllamaInstalled(): Promise { return new Promise((resolve, _reject) => { @@ -39,3 +46,54 @@ export async function startLocalOllama(ide: IDE): Promise { }); } } + +export async function getRemoteModelInfo( + modelId: string, + signal?: AbortSignal, + ): Promise { + const start = Date.now(); + const [modelName, tag = "latest"] = modelId.split(":"); + const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`; + try { + const sig = signal ? signal : AbortSignal.timeout(3000); + const response = await fetch(url, { signal: sig }); + + if (!response.ok) { + throw new Error(`Failed to fetch the model page: ${response.statusText}`); + } + + // First, read the response body as an ArrayBuffer to compute the digest + const buffer = await response.arrayBuffer(); + const digest = getDigest(buffer); + + // Then, decode the ArrayBuffer into a string and parse it as JSON + const text = new TextDecoder().decode(buffer); + const manifest = JSON.parse(text) as { + config: { size: number }; + layers: { size: number }[]; + }; + const modelSize = + manifest.config.size + + manifest.layers.reduce((sum, layer) => sum + layer.size, 0); + + const data: ModelInfo = { + id: modelId, + size: modelSize, + digest, + }; + // Cache the successful result + return data; + } catch (error) { + console.error(`Error fetching or parsing model info: ${error}`); + } finally { + const elapsed = Date.now() - start; + console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`); + } + return undefined; + } + + function getDigest(buffer: ArrayBuffer): string { + const hash = crypto.createHash("sha256"); + hash.update(new Uint8Array(buffer)); + return hash.digest("hex"); + } \ No newline at end of file diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 497de3875..8c0721d53 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -21,8 +21,8 @@ import { stopStatusBarLoading, } from "./statusBar"; -import { startLocalOllama } from "core/util/ollamaHelper"; import type { IDE } from "core"; +import { startLocalOllama } from "core/util/ollamaHelper"; const Diff = require("diff"); @@ -44,15 +44,22 @@ export class ContinueCompletionProvider { private onError(e: any) { let options = ["Documentation"]; - if (e.message.includes("Ollama may not be installed")) { + let message = e.message; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { options.push("Download Ollama"); - } else if (e.message.includes("Ollama may not be running")) { + } else if (message.includes("Ollama may not be running")) { options = ["Start Ollama"]; // We want "Start" to be the only choice + } else if (message.includes("ollama run") && e.llm) { + //extract model name from error message matching the pattern "ollama run " + modelName = message.match(/`ollama run (.*)`/)?.[1]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; } - if (e.message.includes("Please sign in with GitHub")) { + if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( - e.message, + message, this.configHandler.reloadConfig.bind(this.configHandler), () => { void this.webviewProtocol.request("openOnboardingCard", undefined); @@ -60,7 +67,7 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(e.message, ...options).then((val) => { + vscode.window.showErrorMessage(message, ...options).then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( @@ -71,6 +78,8 @@ export class ContinueCompletionProvider vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); } else if (val === "Start Ollama") { startLocalOllama(this.ide); + } else if (val === "Install Model" && e.llm) { + vscode.commands.executeCommand("continue.installModel", modelName, e.llm); } }); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index fa6b44c2a..697768d4c 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, RangeInFileWithContents } from "core"; +import { ContextMenuConfig, ILLM, ModelInstaller, RangeInFileWithContents } from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -14,13 +14,13 @@ import readLastLines from "read-last-lines"; import * as vscode from "vscode"; import { - StatusBarStatus, getAutocompleteStatusBarDescription, getAutocompleteStatusBarTitle, getStatusBarStatus, getStatusBarStatusFromQuickPickItemLabel, quickPickStatusText, setupStatusBar, + StatusBarStatus, } from "./autocomplete/statusBar"; import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider"; @@ -32,6 +32,7 @@ import { getMetaKeyLabel } from "./util/util"; import { VsCodeIde } from "./VsCodeIde"; import { LOCAL_DEV_DATA_VERSION } from "core/data/log"; +import { isModelInstaller } from "core/llm"; import { startLocalOllama } from "core/util/ollamaHelper"; import type { VsCodeWebviewProtocol } from "./webviewProtocol"; @@ -996,6 +997,19 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, + "continue.installModel": async (modelName: string, llmProvider: ILLM | undefined) => { + try { + if (!isModelInstaller(llmProvider)) { + const msg = llmProvider ? `LLM provider '${llmProvider.providerName}' does not support installing models` : + 'Missing LLM Provider'; + throw new Error(msg); + } + await installModelWithProgress(modelName, llmProvider); + } catch (e) { + const message = e instanceof Error ? e.message : String(e); + vscode.window.showErrorMessage(`Failed to install '${modelName}': ${message}`); + } + } }; }; @@ -1037,6 +1051,32 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; +async function installModelWithProgress(modelName: string, modelInstaller: ModelInstaller) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = (details: string, worked?: number, total?: number) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; + } + windowProgress.report({ message: details, increment }); + } + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); + }); + await modelInstaller.installModel(modelName, abortController.signal, progressWrapper); + }); +} + export function registerAllCommands( context: vscode.ExtensionContext, ide: VsCodeIde, diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 14854f1c3..3f2c6ea44 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,6 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; +import { ILLM } from "core"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -87,27 +88,40 @@ export class VsCodeWebviewProtocol } } catch (e: any) { let message = e.message; + let llmProvider: ILLM | undefined; //Intercept Ollama errors for special handling - if (message.includes("Ollama may not")) { - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); + if (message.includes("Ollama may not") || message.includes("`ollama run")) { + let modelName : string | undefined; + const options = []; + if (message.includes("be installed")) { + options.push("Download Ollama"); + } else if (message.includes("be running")) { + options.push("Start Ollama"); + } else if (message.includes("`ollama run")) { + modelName = e.message.match(/`ollama run (.*)`/)?.[1]; + if (e.llm) { + llmProvider = e.llm; } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(e.message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } - }); - return; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + if (modelName) { + options.push("Install Model"); } + } + if (options.length > 0) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); + // Show native vscode error message instead, with options to download/start Ollama + vscode.window.showErrorMessage(message, ...options).then(async (val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model") { + vscode.commands.executeCommand("continue.installModel", modelName, llmProvider); + } + }); + return; + } } respond({ done: true, error: e.message, status: "error" }); diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 36d3853b1..635a9ae3e 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -66,11 +66,13 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ) { message = error["message"]; const parts = message?.split(" ") ?? []; - const status = parts[0] === "HTTP" ? parts[1] : parts[0]; - if (status) { - const code = Number(status); - if (!Number.isNaN(statusCode)) { - statusCode = code; + if (parts.length > 1) { + const status = parts[0] === "HTTP" ? parts[1] : parts[0]; + if (status) { + const code = Number(status); + if (!Number.isNaN(code)) { + statusCode = code; + } } } } From d9c3d447b9d20b447489d4d147490e5ad60957a5 Mon Sep 17 00:00:00 2001 From: Fred Bricon Date: Thu, 6 Mar 2025 15:20:25 +0100 Subject: [PATCH 03/20] Refactor Ollama error management Signed-off-by: Fred Bricon --- .../src/autocomplete/completionProvider.ts | 26 ++---- extensions/vscode/src/commands.ts | 80 ++++++++++++------- .../vscode/src/diff/vertical/manager.ts | 9 ++- extensions/vscode/src/util/errorHandling.ts | 49 ++++++++++++ extensions/vscode/src/webviewProtocol.ts | 44 ++-------- 5 files changed, 119 insertions(+), 89 deletions(-) create mode 100644 extensions/vscode/src/util/errorHandling.ts diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 8c0721d53..f74de8409 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -22,7 +22,7 @@ import { } from "./statusBar"; import type { IDE } from "core"; -import { startLocalOllama } from "core/util/ollamaHelper"; +import { handleLLMError } from "../util/errorHandling"; const Diff = require("diff"); @@ -43,20 +43,10 @@ export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { private onError(e: any) { - let options = ["Documentation"]; - let message = e.message; - let modelName = undefined; - if (message.includes("Ollama may not be installed")) { - options.push("Download Ollama"); - } else if (message.includes("Ollama may not be running")) { - options = ["Start Ollama"]; // We want "Start" to be the only choice - } else if (message.includes("ollama run") && e.llm) { - //extract model name from error message matching the pattern "ollama run " - modelName = message.match(/`ollama run (.*)`/)?.[1]; - message = `Model "${modelName}" is not found in Ollama. You need to install it.`; - options = [`Install Model`]; + if (handleLLMError(e)) { + return; } - + let message = e.message; if (message.includes("Please sign in with GitHub")) { showFreeTrialLoginMessage( message, @@ -67,19 +57,13 @@ export class ContinueCompletionProvider ); return; } - vscode.window.showErrorMessage(message, ...options).then((val) => { + vscode.window.showErrorMessage(message, "Documentation").then((val) => { if (val === "Documentation") { vscode.env.openExternal( vscode.Uri.parse( "https://docs.continue.dev/features/tab-autocomplete", ), ); - } else if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - startLocalOllama(this.ide); - } else if (val === "Install Model" && e.llm) { - vscode.commands.executeCommand("continue.installModel", modelName, e.llm); } }); } diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 697768d4c..e9b973a2a 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,7 +1,12 @@ /* eslint-disable @typescript-eslint/naming-convention */ import * as os from "node:os"; -import { ContextMenuConfig, ILLM, ModelInstaller, RangeInFileWithContents } from "core"; +import { + ContextMenuConfig, + ILLM, + ModelInstaller, + RangeInFileWithContents, +} from "core"; import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { ConfigHandler } from "core/config/ConfigHandler"; import { ContinueServerClient } from "core/continueServer/stubs/client"; @@ -997,19 +1002,25 @@ const getCommandsMap: ( "continue.startLocalOllama": () => { startLocalOllama(ide); }, - "continue.installModel": async (modelName: string, llmProvider: ILLM | undefined) => { + "continue.installModel": async ( + modelName: string, + llmProvider: ILLM | undefined, + ) => { try { if (!isModelInstaller(llmProvider)) { - const msg = llmProvider ? `LLM provider '${llmProvider.providerName}' does not support installing models` : - 'Missing LLM Provider'; + const msg = llmProvider + ? `LLM provider '${llmProvider.providerName}' does not support installing models` + : "Missing LLM Provider"; throw new Error(msg); } await installModelWithProgress(modelName, llmProvider); } catch (e) { const message = e instanceof Error ? e.message : String(e); - vscode.window.showErrorMessage(`Failed to install '${modelName}': ${message}`); + vscode.window.showErrorMessage( + `Failed to install '${modelName}': ${message}`, + ); } - } + }, }; }; @@ -1051,30 +1062,43 @@ const registerCopyBufferSpy = ( context.subscriptions.push(typeDisposable); }; -async function installModelWithProgress(modelName: string, modelInstaller: ModelInstaller) { - return vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: `Installing model '${modelName}'`, - cancellable: true, - }, async (windowProgress, token) => { - let currentProgress: number = 0; - const progressWrapper = (details: string, worked?: number, total?: number) => { - let increment = 0; - if (worked && total) { - const progressValue = Math.round((worked / total) * 100); - increment = progressValue - currentProgress; - currentProgress = progressValue; - } - windowProgress.report({ message: details, increment }); +async function installModelWithProgress( + modelName: string, + modelInstaller: ModelInstaller, +) { + return vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Installing model '${modelName}'`, + cancellable: true, + }, + async (windowProgress, token) => { + let currentProgress: number = 0; + const progressWrapper = ( + details: string, + worked?: number, + total?: number, + ) => { + let increment = 0; + if (worked && total) { + const progressValue = Math.round((worked / total) * 100); + increment = progressValue - currentProgress; + currentProgress = progressValue; } - const abortController = new AbortController(); - token.onCancellationRequested(() => { - console.log(`Pulling ${modelName} model was cancelled`); - abortController.abort(); - }); - await modelInstaller.installModel(modelName, abortController.signal, progressWrapper); + windowProgress.report({ message: details, increment }); + }; + const abortController = new AbortController(); + token.onCancellationRequested(() => { + console.log(`Pulling ${modelName} model was cancelled`); + abortController.abort(); }); + await modelInstaller.installModel( + modelName, + abortController.signal, + progressWrapper, + ); + }, + ); } export function registerAllCommands( diff --git a/extensions/vscode/src/diff/vertical/manager.ts b/extensions/vscode/src/diff/vertical/manager.ts index a62406b00..b51462a3c 100644 --- a/extensions/vscode/src/diff/vertical/manager.ts +++ b/extensions/vscode/src/diff/vertical/manager.ts @@ -9,6 +9,7 @@ import * as vscode from "vscode"; import EditDecorationManager from "../../quickEdit/EditDecorationManager"; import { VsCodeWebviewProtocol } from "../../webviewProtocol"; +import { handleLLMError } from "../../util/errorHandling"; import { VerticalDiffHandler, VerticalDiffHandlerOptions } from "./handler"; export interface VerticalDiffCodeLens { @@ -255,7 +256,9 @@ export class VerticalDiffManager { this.enableDocumentChangeListener(); } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } } finally { vscode.commands.executeCommand( "setContext", @@ -446,7 +449,9 @@ export class VerticalDiffManager { return `${prefix}${streamedLines.join("\n")}${suffix}`; } catch (e) { this.disableDocumentChangeListener(); - vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + if (!handleLLMError(e)) { + vscode.window.showErrorMessage(`Error streaming diff: ${e}`); + } return undefined; } finally { vscode.commands.executeCommand( diff --git a/extensions/vscode/src/util/errorHandling.ts b/extensions/vscode/src/util/errorHandling.ts new file mode 100644 index 000000000..de68f0ce2 --- /dev/null +++ b/extensions/vscode/src/util/errorHandling.ts @@ -0,0 +1,49 @@ +import * as vscode from "vscode"; + +function supportSpecialHandling(error: any): boolean { + let message: string | undefined = error.message; + return message !== undefined && message.toLowerCase().includes("ollama"); +} + +/** + * @param error Handles common LLM errors. Currently only handles Ollama-related errors. + * @returns true if error is handled, false otherwise + */ +export function handleLLMError(error: any): boolean { + if (!supportSpecialHandling(error)) { + return false; + } + let message: string = error.message; + let options: string[] | undefined; + let modelName = undefined; + if (message.includes("Ollama may not be installed")) { + options = ["Download Ollama"]; + } else if (message.includes("Ollama may not be running")) { + options = ["Start Ollama"]; // We want "Start" to be the only choice + } else if (message.includes("ollama run") && error.llm) { + //extract model name from error message matching the pattern "ollama run " + modelName = message.match(/`ollama run (.*)`/)?.[1]; + message = `Model "${modelName}" is not found in Ollama. You need to install it.`; + options = [`Install Model`]; + } + if (options === undefined) { + console.log("Found an unhandled Ollama error: ", message); + return false; + } + + vscode.window.showErrorMessage(message, ...options).then((val) => { + if (val === "Download Ollama") { + vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); + } else if (val === "Start Ollama") { + vscode.commands.executeCommand("continue.startLocalOllama"); + } else if (val === "Install Model" && error.llm) { + //Eventually, we might be able to support installing models for other LLM providers than Ollama + vscode.commands.executeCommand( + "continue.installModel", + modelName, + error.llm, + ); + } + }); + return true; +} diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 3f2c6ea44..0d58532ae 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -7,7 +7,7 @@ import * as vscode from "vscode"; import { IMessenger } from "../../../core/protocol/messenger"; -import { ILLM } from "core"; +import { handleLLMError } from "./util/errorHandling"; import { showFreeTrialLoginMessage } from "./util/messages"; export class VsCodeWebviewProtocol @@ -87,44 +87,12 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { - let message = e.message; - let llmProvider: ILLM | undefined; - //Intercept Ollama errors for special handling - if (message.includes("Ollama may not") || message.includes("`ollama run")) { - let modelName : string | undefined; - const options = []; - if (message.includes("be installed")) { - options.push("Download Ollama"); - } else if (message.includes("be running")) { - options.push("Start Ollama"); - } else if (message.includes("`ollama run")) { - modelName = e.message.match(/`ollama run (.*)`/)?.[1]; - if (e.llm) { - llmProvider = e.llm; - } - message = `Model "${modelName}" is not found in Ollama. You need to install it.`; - if (modelName) { - options.push("Install Model"); - } - } - if (options.length > 0) { - // Respond without an error, so the UI doesn't show the error component - respond({ done: true, status: "error" }); - // Show native vscode error message instead, with options to download/start Ollama - vscode.window.showErrorMessage(message, ...options).then(async (val) => { - if (val === "Download Ollama") { - vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai/download")); - } else if (val === "Start Ollama") { - vscode.commands.executeCommand("continue.startLocalOllama"); - } else if (val === "Install Model") { - vscode.commands.executeCommand("continue.installModel", modelName, llmProvider); - } - }); - return; - } + if (handleLLMError(e)) { + // Respond without an error, so the UI doesn't show the error component + respond({ done: true, status: "error" }); } - - respond({ done: true, error: e.message, status: "error" }); + let message = e.message; + respond({ done: true, error: message, status: "error" }); const stringified = JSON.stringify({ msg }, null, 2); console.error( From 954d91cfe8d3d9a684213d6aba9b513dd5ddc2a9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 6 Mar 2025 11:59:46 -0800 Subject: [PATCH 04/20] better autodetect names --- core/config/load.ts | 3 ++- core/config/yaml/models.ts | 3 ++- core/util/text.ts | 6 ++++++ gui/src/components/modelSelection/ModelSelectionListbox.tsx | 3 +-- 4 files changed, 11 insertions(+), 4 deletions(-) create mode 100644 core/util/text.ts diff --git a/core/config/load.ts b/core/config/load.ts index 873577d8c..8005ff555 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -71,6 +71,7 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; +import { capitalizeFirstLetter } from "../util/text"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -272,7 +273,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${llm.title} - ${modelName}`, + title: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, }, ide.readFile.bind(ide), uniqueId, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index c6916b010..240a7044e 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,6 +3,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; +import { capitalizeFirstLetter } from "../../util/text"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -127,7 +128,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${llm.title} - ${modelName}`, + name: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, }, uniqueId, ideSettings, diff --git a/core/util/text.ts b/core/util/text.ts new file mode 100644 index 000000000..e4870dfa0 --- /dev/null +++ b/core/util/text.ts @@ -0,0 +1,6 @@ +export const capitalizeFirstLetter = (val: string) => { + if (val.length === 0) { + return ""; + } + return val[0].toUpperCase() + val.slice(1); +}; diff --git a/gui/src/components/modelSelection/ModelSelectionListbox.tsx b/gui/src/components/modelSelection/ModelSelectionListbox.tsx index d48ffceed..596cddb9b 100644 --- a/gui/src/components/modelSelection/ModelSelectionListbox.tsx +++ b/gui/src/components/modelSelection/ModelSelectionListbox.tsx @@ -1,11 +1,10 @@ -import { Transition } from "@headlessui/react"; +import { Listbox, Transition } from "@headlessui/react"; import { CheckIcon, ChevronUpDownIcon, CubeIcon, } from "@heroicons/react/24/outline"; import { Fragment } from "react"; -import { Listbox } from "@headlessui/react"; import styled from "styled-components"; import { defaultBorderRadius, From 0917ddf9a534891c267d659de7f776df59bad65d Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 7 Mar 2025 22:53:42 -0800 Subject: [PATCH 05/20] remove "Autodetect" --- core/config/load.ts | 3 +-- core/config/yaml/models.ts | 3 +-- extensions/vscode/package-lock.json | 4 ++-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index 8005ff555..3636b4bf8 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -71,7 +71,6 @@ import { } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; -import { capitalizeFirstLetter } from "../util/text"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -273,7 +272,7 @@ async function intermediateToFinalConfig( { ...desc, model: modelName, - title: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, + title: modelName, }, ide.readFile.bind(ide), uniqueId, diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 240a7044e..b4392d519 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,7 +3,6 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; -import { capitalizeFirstLetter } from "../../util/text"; import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -128,7 +127,7 @@ async function autodetectModels( { ...model, model: modelName, - name: `${modelName} - ${llm.title?.toUpperCase() === "AUTODETECT" ? capitalizeFirstLetter(llm.providerName) : llm.title} (Autodetect)`, + name: modelName, }, uniqueId, ideSettings, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index cbcebc34e..ed46978a0 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.3", + "version": "1.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.3", + "version": "1.1.4", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From c0fc96945d26670105d4652e3d751879cd2213e7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 08:21:49 -0800 Subject: [PATCH 06/20] ignore ssh tests on forks --- .github/workflows/pr_checks.yaml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 5fe472a10..7ed61ec89 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -303,7 +303,13 @@ jobs: cd extensions/vscode npm ci npm run e2e:compile - FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" || "${{ github.actor }}" == "dependabot[bot]" ]]; then + # Exclude SSH tests for forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | grep -v "SSH" | jq -R . | jq -s .) + else + # Include all tests for non-forks + FILES=$(ls -1 e2e/_output/tests/*.test.js | jq -R . | jq -s .) + fi echo "test_file_matrix<> $GITHUB_OUTPUT echo "$FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT From 98739c63eccca5b3177935510d5196c20486e2f4 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 09:29:00 -0800 Subject: [PATCH 07/20] fix ignore api key tests --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 7ed61ec89..da4d69970 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -275,7 +275,7 @@ jobs: cd core npm test env: - IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true && github.actor == 'dependabot[bot]' }} + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} From 1be8ed69ecab06faced15882e425c562cfae3dd1 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 09:42:12 -0800 Subject: [PATCH 08/20] attempt to fix flaky walkdir test --- core/indexing/walkDir.test.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8ded86670..50d21c778 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -192,12 +192,7 @@ describe("walkDir functions", () => { it("should skip symlinks", async () => { const filePath = path.join(TEST_DIR_PATH, "real.ts"); addToTestDir([["real.ts", "content"]]); - fs.symlink( - filePath, - path.join(TEST_DIR_PATH, "symlink.ts"), - "file", - () => {}, - ); + fs.symlinkSync(filePath, path.join(TEST_DIR_PATH, "symlink.ts"), "file"); const files = await walkDirs(testIde); From 6bc7c5560e6a003b208a363deb38a65e5b4adb73 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 11:54:09 -0800 Subject: [PATCH 09/20] load .continue/assistants profiles --- core/config/ConfigHandler.ts | 48 ++++++++++++++-- core/config/getSystemPromptDotFile.ts | 55 +++++++++++++++++++ .../profile/ControlPlaneProfileLoader.ts | 1 + core/config/profile/LocalProfileLoader.ts | 2 + core/config/profile/PlatformProfileLoader.ts | 1 + core/config/profile/doLoadConfig.ts | 3 +- core/util/paths.ts | 4 ++ extensions/vscode/package-lock.json | 4 +- 8 files changed, 110 insertions(+), 8 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index b9a0f0896..96b5fc6da 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -20,6 +20,7 @@ import { GlobalContext } from "../util/GlobalContext.js"; import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; import { localPathToUri } from "../util/pathToUri.js"; +import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, LOCAL_ONBOARDING_PROVIDER_TITLE, @@ -86,6 +87,25 @@ export class ConfigHandler { }); } + /** + * Users can define as many local assistants as they want in a `.continue/assistants` folder + */ + private async getLocalAssistantProfiles() { + const assistantFiles = await getAllAssistantFiles(this.ide); + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + assistant.path, + ); + }); + return profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + } + /** * Retrieves the titles of additional context providers that are of type "submenu". * @@ -98,13 +118,20 @@ export class ConfigHandler { } private async init() { + try { + await this.loadLocalProfilesOnly(); + } catch (e) { + console.error("Failed to load local assistants: ", e); + } + try { await this.fetchControlPlaneProfiles(); } catch (e) { // If this fails, make sure at least local profile is loaded console.error("Failed to fetch control plane profiles in init: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } + try { const configResult = await this.loadConfig(); this.notifyConfigListeners(configResult); @@ -189,7 +216,8 @@ export class ConfigHandler { if (selectedOrgId === null) { // Personal - profiles = [...hubProfiles, this.localProfileManager]; + const allLocalProfiles = await this.getAllLocalProfiles(); + profiles = [...hubProfiles, ...allLocalProfiles]; } else { // Organization profiles = hubProfiles; @@ -199,6 +227,16 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } + private async getAllLocalProfiles() { + const localAssistantProfiles = await this.getLocalAssistantProfiles(); + return [this.localProfileManager, ...localAssistantProfiles]; + } + + private async loadLocalProfilesOnly() { + const allLocalProfiles = await this.getAllLocalProfiles(); + await this.updateAvailableProfiles(allLocalProfiles); + } + private async updateAvailableProfiles(profiles: ProfileLifecycleManager[]) { this.profiles = profiles; @@ -278,7 +316,7 @@ export class ConfigHandler { } else { try { const workspaces = await this.controlPlaneClient.listWorkspaces(); - const profiles = [this.localProfileManager]; + const profiles = await this.getAllLocalProfiles(); workspaces.forEach((workspace) => { const profileLoader = new ControlPlaneProfileLoader( workspace.id, @@ -296,7 +334,7 @@ export class ConfigHandler { await this.updateAvailableProfiles(profiles); } catch (e: any) { console.error("Failed to load profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); } } } @@ -355,7 +393,7 @@ export class ConfigHandler { ); this.fetchControlPlaneProfiles().catch(async (e) => { console.error("Failed to fetch control plane profiles: ", e); - await this.updateAvailableProfiles([this.localProfileManager]); + await this.loadLocalProfilesOnly(); await this.reloadConfig(); }); } diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 550144cd8..1bfc6d1a1 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,4 +1,6 @@ import { IDE } from ".."; +import { walkDir } from "../indexing/walkDir"; +import { getGlobalAssistantsPath } from "../util/paths"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -24,3 +26,56 @@ export async function getSystemPromptDotFile(ide: IDE): Promise { return prompts.join("\n\n"); } + +export const ASSISTANTS_FOLDER = ".continue/assistants"; + +export async function getAssistantFilesFromDir( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const uris = await walkDir(dir, ide); + const assistantFilePaths = uris.filter( + (p) => p.endsWith(".yaml") || p.endsWith(".yml"), + ); + const results = assistantFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} + +export async function getAllAssistantFiles( + ide: IDE, +): Promise<{ path: string; content: string }[]> { + const workspaceDirs = await ide.getWorkspaceDirs(); + let assistantFiles: { path: string; content: string }[] = []; + + let dirsToCheck = [ASSISTANTS_FOLDER]; + const fullDirs = workspaceDirs + .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) + .flat(); + + fullDirs.push(getGlobalAssistantsPath()); + + assistantFiles = ( + await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + ).flat(); + + return await Promise.all( + assistantFiles.map(async (file) => { + const content = await ide.readFile(file.path); + return { path: file.path, content }; + }), + ); +} diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 6df837cf4..fa62d042f 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -68,6 +68,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { undefined, undefined, this.workspaceId, + undefined, ); return { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 9ccf5c812..921a6170d 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -27,6 +27,7 @@ export default class LocalProfileLoader implements IProfileLoader { private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, + private overrideConfigYamlByPath?: string | undefined, ) {} async doLoadConfig(): Promise> { @@ -39,6 +40,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, + this.overrideConfigYamlByPath, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index c0fa4c5cc..0a36d7492 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -70,6 +70,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, + undefined ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 0ec9b4137..2e3e403ef 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -36,6 +36,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, + overrideConfigYamlByPath: string | undefined ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -50,7 +51,7 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = getConfigYamlPath(ideInfo.ideType); + const configYamlPath = overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; diff --git a/core/util/paths.ts b/core/util/paths.ts index 31ed8bb02..fc537ed63 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -353,6 +353,10 @@ export function getGlobalPromptsPath(): string { return path.join(getContinueGlobalPath(), "prompts"); } +export function getGlobalAssistantsPath(): string { + return path.join(getContinueGlobalPath(), "assistants"); +} + export function readAllGlobalPromptFiles( folderPath: string = getGlobalPromptsPath(), ): { path: string; content: string }[] { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index ed46978a0..43750054e 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.4", + "version": "1.1.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.4", + "version": "1.1.5", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", From edcf5b321cb201c328ed640c13f8e99ac7559137 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:09:08 -0800 Subject: [PATCH 10/20] load multiple local assistants --- core/config/ConfigHandler.ts | 56 +++++++++---------- core/config/ProfileLifecycleManager.ts | 1 + .../profile/ControlPlaneProfileLoader.ts | 2 + core/config/profile/LocalProfileLoader.ts | 52 +++++++++++------ core/config/profile/PlatformProfileLoader.ts | 46 ++++++++++++--- core/config/profile/doLoadConfig.ts | 10 +++- core/config/yaml/loadYaml.ts | 6 +- core/control-plane/env.ts | 2 +- core/util/paths.ts | 10 +++- gui/src/components/AddModelButtonSubtext.tsx | 2 +- .../components/modelSelection/ModelSelect.tsx | 14 ++--- .../modelSelection/platform/utils.ts | 3 +- gui/src/pages/AddNewModel/AddNewModel.tsx | 2 +- gui/src/pages/config/index.tsx | 2 +- gui/src/util/index.ts | 2 +- 15 files changed, 134 insertions(+), 76 deletions(-) diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 96b5fc6da..d50e63235 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,5 +1,3 @@ -import * as fs from "node:fs"; - import { ConfigResult, FullSlug } from "@continuedev/config-yaml"; import { @@ -17,8 +15,6 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { localPathToUri } from "../util/pathToUri.js"; import { getAllAssistantFiles } from "./getSystemPromptDotFile.js"; import { @@ -98,7 +94,7 @@ export class ConfigHandler { this.ideSettingsPromise, this.controlPlaneClient, this.writeLog, - assistant.path, + assistant, ); }); return profiles.map( @@ -162,14 +158,12 @@ export class ConfigHandler { async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; - if (openProfileId === "local") { + const profile = this.profiles?.find( + (p) => p.profileDescription.id === openProfileId, + ); + if (profile?.profileDescription.profileType === "local") { const ideInfo = await this.ide.getIdeInfo(); - const configYamlPath = getConfigYamlPath(ideInfo.ideType); - if (fs.existsSync(configYamlPath)) { - await this.ide.openFile(localPathToUri(configYamlPath)); - } else { - await this.ide.openFile(localPathToUri(getConfigJsonPath())); - } + await this.ide.openFile(profile.profileDescription.uri); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); @@ -194,25 +188,27 @@ export class ConfigHandler { const assistants = await this.controlPlaneClient.listAssistants(selectedOrgId); - const hubProfiles = assistants.map((assistant) => { - const profileLoader = new PlatformProfileLoader( - { - ...assistant.configResult, - config: assistant.configResult.config, - }, - assistant.ownerSlug, - assistant.packageSlug, - assistant.iconUrl, - assistant.configResult.config?.version ?? "latest", - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + const profileLoader = await PlatformProfileLoader.create( + { + ...assistant.configResult, + config: assistant.configResult.config, + }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.iconUrl, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); - return new ProfileLifecycleManager(profileLoader, this.ide); - }); + return new ProfileLifecycleManager(profileLoader, this.ide); + }), + ); if (selectedOrgId === null) { // Personal diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index deaf5f40e..b7946ed7d 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -21,6 +21,7 @@ export interface ProfileDescription { id: string; iconUrl: string; errors: ConfigValidationError[] | undefined; + uri: string; } export interface OrganizationDescription { diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index fa62d042f..cce940ab7 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -10,6 +10,7 @@ import { } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { PRODUCTION_ENV } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -40,6 +41,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { }, title: workspaceTitle, errors: undefined, + uri: `${PRODUCTION_ENV.APP_URL}workspaces/${workspaceId}`, }; setInterval(async () => { diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 921a6170d..13a1480c9 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,34 +1,54 @@ -import { ConfigResult } from "@continuedev/config-yaml"; +import { ConfigResult, parseConfigYaml } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getPrimaryConfigFilePath } from "../../util/paths.js"; +import { localPathToUri } from "../../util/pathToUri.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - description: ProfileDescription = { - id: LocalProfileLoader.ID, - profileType: "local", - fullSlug: { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - iconUrl: "", - title: "Local Config", - errors: undefined, - }; constructor( private ide: IDE, private ideSettingsPromise: Promise, private controlPlaneClient: ControlPlaneClient, private writeLog: (message: string) => Promise, - private overrideConfigYamlByPath?: string | undefined, - ) {} + private overrideAssistantFile?: + | { path: string; content: string } + | undefined, + ) { + const description: ProfileDescription = { + id: overrideAssistantFile?.path ?? LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + iconUrl: "", + title: overrideAssistantFile?.path ?? "Local Config", + errors: undefined, + uri: + overrideAssistantFile?.path ?? + localPathToUri(getPrimaryConfigFilePath()), + }; + this.description = description; + if (overrideAssistantFile?.content) { + try { + const parsedAssistant = parseConfigYaml( + overrideAssistantFile?.content ?? "", + ); + this.description.title = parsedAssistant.name; + } catch (e) { + console.error("Failed to parse assistant file: ", e); + } + } + } + description: ProfileDescription; async doLoadConfig(): Promise> { const result = await doLoadConfig( @@ -40,7 +60,7 @@ export default class LocalProfileLoader implements IProfileLoader { undefined, undefined, this.description.id, - this.overrideConfigYamlByPath, + this.overrideAssistantFile?.path, ); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 0a36d7492..329a7a59e 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -5,6 +5,7 @@ import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; @@ -21,21 +22,35 @@ export interface PlatformConfigMetadata { export default class PlatformProfileLoader implements IProfileLoader { static RELOAD_INTERVAL = 1000 * 5; // 5 seconds - description: ProfileDescription; - - constructor( + private constructor( private configResult: ConfigResult, private readonly ownerSlug: string, private readonly packageSlug: string, private readonly iconUrl: string, - versionSlug: string, + private readonly versionSlug: string, private readonly controlPlaneClient: ControlPlaneClient, private readonly ide: IDE, private ideSettingsPromise: Promise, private writeLog: (message: string) => Promise, private readonly onReload: () => void, - ) { - this.description = { + readonly description: ProfileDescription, + ) {} + + static async create( + configResult: ConfigResult, + ownerSlug: string, + packageSlug: string, + iconUrl: string, + versionSlug: string, + controlPlaneClient: ControlPlaneClient, + ide: IDE, + ideSettingsPromise: Promise, + writeLog: (message: string) => Promise, + onReload: () => void, + ): Promise { + const controlPlaneEnv = await getControlPlaneEnv(ideSettingsPromise); + + const description: ProfileDescription = { id: `${ownerSlug}/${packageSlug}`, profileType: "platform", fullSlug: { @@ -45,8 +60,23 @@ export default class PlatformProfileLoader implements IProfileLoader { }, title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`, errors: configResult.errors, - iconUrl: this.iconUrl, + iconUrl: iconUrl, + uri: `${controlPlaneEnv}${ownerSlug}/${packageSlug}`, }; + + return new PlatformProfileLoader( + configResult, + ownerSlug, + packageSlug, + iconUrl, + versionSlug, + controlPlaneClient, + ide, + ideSettingsPromise, + writeLog, + onReload, + description, + ); } async doLoadConfig(): Promise> { @@ -70,7 +100,7 @@ export default class PlatformProfileLoader implements IProfileLoader { packageSlug: this.packageSlug, }, this.description.id, - undefined + undefined, ); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 2e3e403ef..224b7b64e 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -19,13 +19,14 @@ import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; +import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; +import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; import { PlatformConfigMetadata } from "./PlatformProfileLoader"; -import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; export default async function doLoadConfig( ide: IDE, @@ -36,7 +37,7 @@ export default async function doLoadConfig( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, profileId: string, - overrideConfigYamlByPath: string | undefined + overrideConfigYamlByPath: string | undefined, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); @@ -51,7 +52,9 @@ export default async function doLoadConfig( migrateJsonSharedConfig(configJsonPath, ide); } - const configYamlPath = overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType); + const configYamlPath = localPathOrUriToPath( + overrideConfigYamlByPath || getConfigYamlPath(ideInfo.ideType), + ); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; @@ -69,6 +72,7 @@ export default async function doLoadConfig( overrideConfigYaml, platformConfigMetadata, controlPlaneClient, + configYamlPath, ); newConfig = result.config; errors = result.errors; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index b008092e9..8d0ebf60a 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -366,10 +366,14 @@ export async function loadContinueConfigFromYaml( overrideConfigYaml: AssistantUnrolled | undefined, platformConfigMetadata: PlatformConfigMetadata | undefined, controlPlaneClient: ControlPlaneClient, + configYamlPath: string | undefined, ): Promise> { const rawYaml = overrideConfigYaml === undefined - ? fs.readFileSync(getConfigYamlPath(ideInfo.ideType), "utf-8") + ? fs.readFileSync( + configYamlPath ?? getConfigYamlPath(ideInfo.ideType), + "utf-8", + ) : ""; const configYamlResult = await loadConfigYaml( diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 288901cab..8995dca7e 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -18,7 +18,7 @@ const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; const WORKOS_ENV_ID_PRODUCTION = "continue"; const WORKOS_ENV_ID_STAGING = "continue-staging"; -const PRODUCTION_ENV: ControlPlaneEnv = { +export const PRODUCTION_ENV: ControlPlaneEnv = { DEFAULT_CONTROL_PLANE_PROXY_URL: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", CONTROL_PLANE_URL: diff --git a/core/util/paths.ts b/core/util/paths.ts index fc537ed63..02d2f43b5 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -103,7 +103,7 @@ export function getConfigJsonPath(ideType: IdeType = "vscode"): string { return p; } -export function getConfigYamlPath(ideType: IdeType): string { +export function getConfigYamlPath(ideType?: IdeType): string { const p = path.join(getContinueGlobalPath(), "config.yaml"); // if (!fs.existsSync(p)) { // if (ideType === "jetbrains") { @@ -115,6 +115,14 @@ export function getConfigYamlPath(ideType: IdeType): string { return p; } +export function getPrimaryConfigFilePath(): string { + const configYamlPath = getConfigYamlPath(); + if (fs.existsSync(configYamlPath)) { + return configYamlPath; + } + return getConfigJsonPath(); +} + export function getConfigTsPath(): string { const p = path.join(getContinueGlobalPath(), "config.ts"); if (!fs.existsSync(p)) { diff --git a/gui/src/components/AddModelButtonSubtext.tsx b/gui/src/components/AddModelButtonSubtext.tsx index 0ebb2ed9d..aa7ef99b5 100644 --- a/gui/src/components/AddModelButtonSubtext.tsx +++ b/gui/src/components/AddModelButtonSubtext.tsx @@ -12,7 +12,7 @@ function AddModelButtonSubtext() { className="cursor-pointer underline" onClick={() => ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }) } > diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index d99ced546..7cf854e4d 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -19,14 +19,10 @@ import { setDefaultModel, } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { - getFontSize, - getMetaKeyLabel, - isMetaEquivalentKeyPressed, -} from "../../util"; +import { getFontSize, isMetaEquivalentKeyPressed } from "../../util"; import ConfirmationDialog from "../dialogs/ConfirmationDialog"; +import Shortcut from "../gui/Shortcut"; import { Divider } from "./platform/shared"; -import Shortcut from '../gui/Shortcut'; interface ModelOptionProps { option: Option; @@ -166,9 +162,7 @@ function ModelOption({ e.stopPropagation(); e.preventDefault(); - ideMessenger.post("config/openProfile", { - profileId: "local", - }); + ideMessenger.post("config/openProfile", { profileId: undefined }); } function handleOptionClick(e: any) { @@ -351,7 +345,7 @@ function ModelSelect() {
- {selectedProfile?.id === "local" && ( + {selectedProfile?.profileType === "local" && ( <> { ideMessenger.post("config/openProfile", { - profileId: "local", + profileId: undefined, }); }} > diff --git a/gui/src/pages/config/index.tsx b/gui/src/pages/config/index.tsx index 79c81a221..f82443531 100644 --- a/gui/src/pages/config/index.tsx +++ b/gui/src/pages/config/index.tsx @@ -297,7 +297,7 @@ function ConfigPage() {
{selectedProfile && ( - {selectedProfile.id === "local" + {selectedProfile.profileType === "local" ? "Open Config File" : hubEnabled ? "Open Assistant" diff --git a/gui/src/util/index.ts b/gui/src/util/index.ts index eb5fc2324..2636a3b67 100644 --- a/gui/src/util/index.ts +++ b/gui/src/util/index.ts @@ -108,5 +108,5 @@ export function updatedObj(old: any, pathToValue: { [key: string]: any }) { } export function isLocalProfile(profile: ProfileDescription): boolean { - return profile.id === "local"; + return profile.profileType === "local"; } From 5dfc9110c6f22104a16920e19f82ce21b84c9d7f Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:18:51 -0800 Subject: [PATCH 11/20] ignore .continue folder --- .continueignore | 3 ++- .gitignore | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.continueignore b/.continueignore index 79e924012..50684c187 100644 --- a/.continueignore +++ b/.continueignore @@ -5,4 +5,5 @@ docs/docs/languages .vscode/ .archive/ **/*.scm -**/*.diff \ No newline at end of file +**/*.diff +.continue/ \ No newline at end of file diff --git a/.gitignore b/.gitignore index f331ec68c..94efa5983 100644 --- a/.gitignore +++ b/.gitignore @@ -168,4 +168,5 @@ extensions/.continue-debug/ *.vsix -.continuerules \ No newline at end of file +.continuerules +.continue/ \ No newline at end of file From 693540155b719e5059d838a0cc82fa487690fb43 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 8 Mar 2025 16:19:05 -0800 Subject: [PATCH 12/20] hot reload local assistants --- core/core.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/core/core.ts b/core/core.ts index d5b0f6d8e..4861013bf 100644 --- a/core/core.ts +++ b/core/core.ts @@ -30,12 +30,7 @@ import { ChatDescriber } from "./util/chatDescriber"; import { clipboardCache } from "./util/clipboardCache"; import { GlobalContext } from "./util/GlobalContext"; import historyManager from "./util/history"; -import { - editConfigJson, - getConfigJsonPath, - migrateV1DevDataFiles, -} from "./util/paths"; -import { localPathToUri } from "./util/pathToUri"; +import { editConfigJson, migrateV1DevDataFiles } from "./util/paths"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; @@ -860,7 +855,10 @@ export class Core { for (const uri of data.uris) { // Listen for file changes in the workspace // URI TODO is this equality statement valid? - if (URI.equal(uri, localPathToUri(getConfigJsonPath()))) { + const currentProfileUri = + this.configHandler.currentProfile?.profileDescription.uri ?? ""; + + if (URI.equal(uri, currentProfileUri)) { // Trigger a toast notification to provide UI feedback that config has been updated const showToast = this.globalContext.get("showConfigUpdateToast") ?? true; @@ -874,6 +872,8 @@ export class Core { this.globalContext.update("showConfigUpdateToast", false); } } + await this.configHandler.reloadConfig(); + continue; } if ( From 7e0b3d93870ad10ecb7f8f1e4092511af74fa7dc Mon Sep 17 00:00:00 2001 From: "Owen W. Taylor" Date: Sun, 9 Mar 2025 06:25:23 -0400 Subject: [PATCH 13/20] Fix logic for setting IGNORE_SSH_TESTS The logic for checking for dependabot introduced in fda4cc8096 skip ssh on dependabot PRs was somewhat confused; this was partially fixed in 98739c63ec fix ignore api key tests Make IGNORE_SSH_TESTS match. --- .github/workflows/pr_checks.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index da4d69970..6dbae92a6 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -460,7 +460,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == false && github.actor != 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} + IGNORE_SSH_TESTS="${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}" TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 From ba80343cabe080e6098eee39004f48b3725070d1 Mon Sep 17 00:00:00 2001 From: Daniel Barduhn Date: Sun, 9 Mar 2025 16:33:17 +0100 Subject: [PATCH 14/20] added tools support for fireworks.ai --- core/llm/llms/OpenAI.ts | 12 +++++++++++- core/llm/toolSupport.ts | 13 +++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 92f0aca08..139d033ab 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -97,6 +97,10 @@ class OpenAI extends BaseLLM { return !!model && (model.startsWith("o1") || model.startsWith("o3")); } + private isFireworksAiModel(model?: string): boolean { + return !!model && model.startsWith("accounts/fireworks/models"); + } + protected supportsPrediction(model: string): boolean { const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; return SUPPORTED_MODELS.some((m) => model.includes(m)); @@ -274,7 +278,13 @@ class OpenAI extends BaseLLM { body.max_completion_tokens = undefined; } - if (body.tools?.length && !body.model?.startsWith("o3")) { + if (body.tools?.length) { + if (this.isFireworksAiModel(body.model)) { + // fireworks.ai does not support parallel tool calls, but their api expects this to be true anyway otherwise they return an error. + // tooling works with them as a inference provider once this is set to true. + // https://docs.fireworks.ai/guides/function-calling#openai-compatibility + body.parallel_tool_calls = true; + } // To ensure schema adherence: https://platform.openai.com/docs/guides/function-calling#parallel-function-calling-and-structured-outputs // In practice, setting this to true and asking for multiple tool calls // leads to "arguments" being something like '{"file": "test.ts"}{"file": "test.js"}' diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index ebe6599f8..06994ec93 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -39,6 +39,19 @@ export const PROVIDER_TOOL_SUPPORT: Record< ) { return true; } + // firworks-ai https://docs.fireworks.ai/guides/function-calling + if (model.startsWith("accounts/fireworks/models/")) { + switch (model.substring(26)) { + case "llama-v3p1-405b-instruct": + case "llama-v3p1-70b-instruct": + case "qwen2p5-72b-instruct": + case "firefunction-v1": + case "firefunction-v2": + return true; + default: + return false; + } + } }, gemini: (model) => { // All gemini models support function calling From d7b30155c2b139a3c11c9c9db85c4be2d86c038c Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 10:51:37 -0700 Subject: [PATCH 15/20] fix bug in codebase retrieval --- core/indexing/LanceDbIndex.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 168a4ff07..2b2f23a77 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -24,6 +24,7 @@ import { } from "./types"; import type * as LanceType from "vectordb"; +import { localPathToUri } from "../util/pathToUri"; interface LanceDbRow { uuid: string; @@ -498,7 +499,7 @@ export class LanceDbIndex implements CodebaseIndex { return data.map((d) => { return { digest: d.cacheKey, - filepath: d.path, + filepath: localPathToUri(d.path), startLine: d.startLine, endLine: d.endLine, index: 0, From 91426f233cbdbb04c9af894d8b3340031257df88 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 10:54:58 -0700 Subject: [PATCH 16/20] isolate errors in the different codebase retrieval steps --- .../pipelines/BaseRetrievalPipeline.ts | 27 ++++------ .../pipelines/NoRerankerRetrievalPipeline.ts | 46 ++++++++++++----- .../pipelines/RerankerRetrievalPipeline.ts | 51 ++++++++++++++----- 3 files changed, 81 insertions(+), 43 deletions(-) diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index d91931327..a3dcc0f7e 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -80,24 +80,19 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { args: RetrievalPipelineRunArguments, n: number, ): Promise { - try { - if (args.query.trim() === "") { - return []; - } - - const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); - const tokens = this.escapeFtsQueryString(tokensRaw); - - return await this.ftsIndex.retrieve({ - n, - text: tokens, - tags: args.tags, - directory: args.filterDirectory, - }); - } catch (e) { - console.warn("Error retrieving from FTS:", e); + if (args.query.trim() === "") { return []; } + + const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); + const tokens = this.escapeFtsQueryString(tokensRaw); + + return await this.ftsIndex.retrieve({ + n, + text: tokens, + tags: args.tags, + directory: args.filterDirectory, + }); } protected async retrieveAndChunkRecentlyEditedFiles( diff --git a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts index 889005414..f35809fed 100644 --- a/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/NoRerankerRetrievalPipeline.ts @@ -19,22 +19,42 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, ftsNFinal); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, ftsNFinal); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, embeddingsNFinal) - : []; + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, embeddingsNFinal) + : []; + } catch (error) { + console.error("Error retrieving embeddings:", error); + } - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal); + } catch (error) { + console.error("Error retrieving recently edited files:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, diff --git a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts index 5fc4f240b..a3e4d830f 100644 --- a/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/RerankerRetrievalPipeline.ts @@ -16,20 +16,42 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { let retrievalResults: Chunk[] = []; - const ftsChunks = await this.retrieveFts(args, nRetrieve); - const embeddingsChunks = !!config.selectedModelByRole.embed - ? await this.retrieveEmbeddings(input, nRetrieve) - : []; - const recentlyEditedFilesChunks = - await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + let ftsChunks: Chunk[] = []; + try { + ftsChunks = await this.retrieveFts(args, nRetrieve); + } catch (error) { + console.error("Error retrieving FTS chunks:", error); + } - const repoMapChunks = await requestFilesFromRepoMap( - this.options.llm, - this.options.config, - this.options.ide, - input, - filterDirectory, - ); + let embeddingsChunks: Chunk[] = []; + try { + embeddingsChunks = !!config.selectedModelByRole.embed + ? await this.retrieveEmbeddings(input, nRetrieve) + : []; + } catch (error) { + console.error("Error retrieving embeddings chunks:", error); + } + + let recentlyEditedFilesChunks: Chunk[] = []; + try { + recentlyEditedFilesChunks = + await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve); + } catch (error) { + console.error("Error retrieving recently edited files chunks:", error); + } + + let repoMapChunks: Chunk[] = []; + try { + repoMapChunks = await requestFilesFromRepoMap( + this.options.llm, + this.options.config, + this.options.ide, + input, + filterDirectory, + ); + } catch (error) { + console.error("Error retrieving repo map chunks:", error); + } retrievalResults.push( ...recentlyEditedFilesChunks, @@ -41,7 +63,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline { if (filterDirectory) { // Backup if the individual retrieval methods don't listen retrievalResults = retrievalResults.filter( - (chunk) => !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, + (chunk) => + !!findUriInDirs(chunk.filepath, [filterDirectory]).foundInDir, ); } From 26d7eb4631b2b41f1b38c180cd4d6f376a8b52f0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 11:57:14 -0700 Subject: [PATCH 17/20] anthropic tool call fix in openai-adapters --- packages/openai-adapters/package.json | 2 +- .../openai-adapters/src/apis/Anthropic.ts | 26 ++++++++ packages/openai-adapters/src/apis/Gemini.ts | 42 ++++++++++++- packages/openai-adapters/src/test/util.ts | 59 +++++++++++++++++++ packages/openai-adapters/src/types.ts | 1 + 5 files changed, 128 insertions(+), 2 deletions(-) diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index b2d293852..f11313bad 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.15", + "version": "1.0.16", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index d8c5b0c44..04b0fbce9 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -71,6 +71,32 @@ export class AnthropicApi implements BaseLlmApi { msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[], ): any[] { const messages = msgs.map((message) => { + if (message.role === "tool") { + return { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: message.tool_call_id, + content: + typeof message.content === "string" + ? message.content + : message.content.map((part) => part.text).join(""), + }, + ], + }; + } else if (message.role === "assistant" && message.tool_calls) { + return { + role: "assistant", + content: message.tool_calls.map((toolCall) => ({ + type: "tool_use", + id: toolCall.id, + name: toolCall.function?.name, + input: JSON.parse(toolCall.function?.arguments || "{}"), + })), + }; + } + if (!Array.isArray(message.content)) { return message; } diff --git a/packages/openai-adapters/src/apis/Gemini.ts b/packages/openai-adapters/src/apis/Gemini.ts index ae2235d25..c17527674 100644 --- a/packages/openai-adapters/src/apis/Gemini.ts +++ b/packages/openai-adapters/src/apis/Gemini.ts @@ -86,11 +86,50 @@ export class GeminiApi implements BaseLlmApi { } const isV1API = url.includes("/v1/"); + + const toolCallIdToNameMap = new Map(); const contents = oaiBody.messages .map((msg) => { if (msg.role === "system" && !isV1API) { return null; // Don't include system message in contents } + + if (msg.role == "assistant" && msg.tool_calls?.length) { + for (const toolCall of msg.tool_calls) { + toolCallIdToNameMap.set(toolCall.id, toolCall.function.name); + } + + return { + role: "model", + parts: msg.tool_calls.map((toolCall) => ({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments || "{}"), + }, + })), + }; + } + + if (msg.role === "tool") { + return { + role: "user", + parts: [ + { + functionResponse: { + name: msg.tool_call_id, + response: { + name: toolCallIdToNameMap.get(msg.tool_call_id), + content: + typeof msg.content === "string" + ? msg.content + : msg.content.map((part) => part.text).join(""), + }, + }, + }, + ], + }; + } + if (!msg.content) { return null; } @@ -246,9 +285,10 @@ export class GeminiApi implements BaseLlmApi { `models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`, this.apiBase, ).toString(); + const convertedBody = this._convertBody(body, apiURL); const resp = await customFetch(this.config.requestOptions)(apiURL, { method: "POST", - body: JSON.stringify(this._convertBody(body, apiURL)), + body: JSON.stringify(convertedBody), signal, }); diff --git a/packages/openai-adapters/src/test/util.ts b/packages/openai-adapters/src/test/util.ts index 5b1b52ab1..ba4490f2a 100644 --- a/packages/openai-adapters/src/test/util.ts +++ b/packages/openai-adapters/src/test/util.ts @@ -260,6 +260,65 @@ export function testChat(api: BaseLlmApi, model: string) { const parsedArgs = JSON.parse(args); expect(parsedArgs.name).toBe("Nate"); }); + + test("Tool Call second message works", async () => { + let response = ""; + for await (const chunk of api.chatCompletionStream( + { + messages: [ + { + role: "user", + content: + "Hi, my name is Nate. Please call the say_hello function to respond to me, then respond to me again.", + }, + { + role: "assistant", + tool_calls: [ + { + function: { + arguments: '{"name":"Nate"}', + name: "say_hello", + }, + id: "tool_call_1", + type: "function", + }, + ], + }, + { + role: "tool", + tool_call_id: "tool_call_1", + content: "Nate was greeted", + }, + ], + tools: [ + { + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, + }, + }, + }, + type: "function", + }, + ], + stream: true, + model, + }, + new AbortController().signal, + )) { + console.log(JSON.stringify(chunk, null, 2)); + response += chunk.choices[0].delta.content ?? ""; + } + + expect(response.length).toBeGreaterThan(0); + }); } export function testCompletion(api: BaseLlmApi, model: string) { diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index c59c8c8f7..30fd2cef0 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -54,6 +54,7 @@ export const OpenAIConfigSchema = BasePlusConfig.extend({ z.literal("vllm"), z.literal("x-ai"), z.literal("scaleway"), + z.literal("ncompass"), ]), }); export type OpenAIConfig = z.infer; From 21934981cd90594c5d75ce9cbada90d6b37115a0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 18:10:15 -0700 Subject: [PATCH 18/20] only ignore assistants --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 94efa5983..b24d52983 100644 --- a/.gitignore +++ b/.gitignore @@ -169,4 +169,4 @@ extensions/.continue-debug/ *.vsix .continuerules -.continue/ \ No newline at end of file +.continue/assistants/ \ No newline at end of file From 81511a10640aa5a5eca40a253e5fc8bff6b117cd Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 18:13:31 -0700 Subject: [PATCH 19/20] fix uri bug --- core/config/getSystemPromptDotFile.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index 1bfc6d1a1..de2c25db8 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,6 +1,7 @@ import { IDE } from ".."; import { walkDir } from "../indexing/walkDir"; import { getGlobalAssistantsPath } from "../util/paths"; +import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; @@ -34,7 +35,7 @@ export async function getAssistantFilesFromDir( dir: string, ): Promise<{ path: string; content: string }[]> { try { - const exists = await ide.fileExists(dir); + const exists = await ide.fileExists(localPathToUri(dir)); if (!exists) { return []; From fc306c736374661f56fb73204f1149ffb05865a0 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 9 Mar 2025 19:55:19 -0700 Subject: [PATCH 20/20] bump --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index caa49d1dc..347351b00 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": "1.1.5", + "version": "1.1.6", "repository": { "type": "git", "url": "https://github.com/continuedev/continue"