diff --git a/.eslintrc.shared.json b/.eslintrc.shared.json index f4b9c4c78..f62954280 100644 --- a/.eslintrc.shared.json +++ b/.eslintrc.shared.json @@ -6,6 +6,7 @@ }, "plugins": ["@typescript-eslint", "import"], "rules": { + "@typescript-eslint/naming-convention": "off", "@typescript-eslint/semi": "warn", "curly": "warn", "eqeqeq": "warn", diff --git a/.github/ISSUE_TEMPLATE/docs_issue_report.yml b/.github/ISSUE_TEMPLATE/docs_issue_report.yml index d04f976f4..cef2fae0f 100644 --- a/.github/ISSUE_TEMPLATE/docs_issue_report.yml +++ b/.github/ISSUE_TEMPLATE/docs_issue_report.yml @@ -58,26 +58,3 @@ body: label: Expected Content description: If applicable, provide the content you believe should be added or updated. placeholder: "Suggested details or changes for the documentation..." - - - type: textarea - id: additional-info - attributes: - label: Additional Information - description: Add any other relevant information that may help us understand and resolve your issue. - placeholder: "Additional context, screenshots, or related links..." - - - type: input - id: related-issue - attributes: - label: Related Issue - description: If this issue is related to an existing GitHub issue, provide the issue number. - placeholder: "#123" - - - type: checkboxes - id: terms - attributes: - label: Code of Conduct - description: By submitting this issue, you agree to follow our [Code of Conduct](https://github.com/continuedev/continue/blob/main/CODE_OF_CONDUCT.md) - options: - - label: I agree to follow this project's Code of Conduct - required: true \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eddf7b45b..ca26d38fe 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -188,7 +188,7 @@ After you've written your context provider, make sure to complete the following: ### Adding an LLM Provider -Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, Novita AI, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps: +Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps: 1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example. @@ -209,7 +209,7 @@ While any model that works with a supported provider can be used with Continue, 1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file 2. Add the model within its provider's array to [AddNewModel.tsx](./gui/src/pages/AddNewModel/AddNewModel.tsx) (add provider if needed) - [index.d.ts](./core/index.d.ts) - This file defines the TypeScript types used throughout Continue. You'll find a `ModelName` type. Be sure to add the name of your model to this. -- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), [Novita AI](./core/llm/llms/Novita.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Novita AI](https://novita.ai/llm-api?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link), [Replicate](https://replicate.com/collections/streaming-language-models). +- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models). - [Prompt Templates](./core/llm/index.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates. ### Adding Pre-indexed Documentation diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 41a35db07..6533074b9 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -59,8 +59,8 @@ export async function testAutocompleteFiltering( line, character, }, - recentlyEditedFiles: [], recentlyEditedRanges: [], + recentlyVisitedRanges: [], }; // Generate a completion diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 5ff4a7d60..198bf16c6 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -3,6 +3,7 @@ import { findUriInDirs } from "../../util/uri"; import { ContextRetrievalService } from "../context/ContextRetrievalService"; import { GetLspDefinitionsFunction } from "../types"; import { HelperVars } from "../util/HelperVars"; + import { AutocompleteClipboardSnippet, AutocompleteCodeSnippet, @@ -15,6 +16,7 @@ export interface SnippetPayload { importDefinitionSnippets: AutocompleteCodeSnippet[]; ideSnippets: AutocompleteCodeSnippet[]; recentlyEditedRangeSnippets: AutocompleteCodeSnippet[]; + recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[]; diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; } @@ -135,5 +137,6 @@ export const getAllSnippets = async ({ recentlyEditedRangeSnippets, diffSnippets, clipboardSnippets, + recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, }; }; diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index e3f087102..8f7bbd66d 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -111,13 +111,13 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { return snippet.content; } - return `+++++ ${relativePaths[i]}\n${snippet.content}`; + return `+++++ ${relativePaths[i].uri} \n${snippet.content}`; }) .join("\n\n"); return [ `${otherFiles}\n\n+++++ ${ - relativePaths[relativePaths.length - 1] + relativePaths[relativePaths.length - 1].uri }\n${prefix}`, suffix, ]; diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index a6cdf0957..c741dedc8 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -5,6 +5,7 @@ import { AutocompleteSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; + import { isValidSnippet } from "./validation"; const getRemainingTokenCount = (helper: HelperVars): number => { @@ -44,6 +45,7 @@ export const getSnippets = ( const snippets = [ ...payload.diffSnippets, ...payload.clipboardSnippets, + ...payload.recentlyVisitedRangesSnippets, ...shuffleArray( filterSnippetsAlreadyInCaretWindow( [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index c11d8c2d9..b6379dd61 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -5,6 +5,7 @@ import { RangeInFileWithContents, TabAutocompleteOptions, } from "../.."; +import { AutocompleteCodeSnippet } from "../snippets/types"; export type RecentlyEditedRange = RangeInFile & { timestamp: number; @@ -17,7 +18,7 @@ export interface AutocompleteInput { completionId: string; filepath: string; pos: Position; - recentlyEditedFiles: RangeInFileWithContents[]; + recentlyVisitedRanges: AutocompleteCodeSnippet[]; recentlyEditedRanges: RecentlyEditedRange[]; // Used for notebook files manuallyPassFileContents?: string; diff --git a/core/config/load.ts b/core/config/load.ts index 99c701141..b7ce400eb 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -46,6 +46,8 @@ import CustomLLMClass from "../llm/llms/CustomLLM"; import FreeTrial from "../llm/llms/FreeTrial"; import { LLMReranker } from "../llm/llms/llm"; import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider"; +import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; +import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; import { allTools } from "../tools"; import { copyOf } from "../util"; import { GlobalContext } from "../util/GlobalContext"; @@ -61,8 +63,6 @@ import { getEsbuildBinaryPath, } from "../util/paths"; -import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile"; -import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -70,6 +70,7 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; +import { isSupportedLanceDbCpuTarget } from "./util"; import { ConfigValidationError, validateConfig } from "./validation.js"; export interface ConfigResult { @@ -112,6 +113,7 @@ function loadSerializedConfig( ideSettings: IdeSettings, ideType: IdeType, overrideConfigJson: SerializedContinueConfig | undefined, + ide: IDE, ): ConfigResult { const configPath = getConfigJsonPath(ideType); let config: SerializedContinueConfig = overrideConfigJson!; @@ -174,6 +176,10 @@ function loadSerializedConfig( ? [...defaultSlashCommandsVscode] : [...defaultSlashCommandsJetBrains]; + if (!isSupportedLanceDbCpuTarget(ide)) { + config.disableIndexing = true; + } + return { config, errors, configLoadInterrupted: false }; } @@ -767,6 +773,7 @@ async function loadFullConfigNode( ideSettings, ideType, overrideConfigJson, + ide, ); if (!serialized || configLoadInterrupted) { diff --git a/core/config/types.ts b/core/config/types.ts index 6c7e580dd..aa1873894 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -717,7 +717,6 @@ declare global { type ContextProviderName = | "diff" - | "github" | "terminal" | "debugger" | "open" diff --git a/core/config/util.ts b/core/config/util.ts index 0247aa25d..6d28dcbcb 100644 --- a/core/config/util.ts +++ b/core/config/util.ts @@ -1,10 +1,15 @@ +import { execSync } from "child_process"; +import os from "os"; + import { ContextProviderWithParams, ContinueConfig, + IDE, ILLM, ModelDescription, ModelRoles, } from "../"; +import { GlobalContext } from "../util/GlobalContext"; import { editConfigJson } from "../util/paths"; function stringify(obj: any, indentation?: number): string { @@ -96,3 +101,84 @@ export function getModelByRole( return matchingModel; } + +/** + * This check is to determine if the user is on an unsupported CPU + * target for our Lance DB binaries. + * + * See here for details: https://github.com/continuedev/continue/issues/940 + */ +export function isSupportedLanceDbCpuTarget(ide: IDE) { + const CPU_FEATURES_TO_CHECK = ["avx2", "fma"] as const; + + const globalContext = new GlobalContext(); + const globalContextVal = globalContext.get("isSupportedLanceDbCpuTarget"); + + // If we've already checked the CPU target, return the cached value + if (globalContextVal !== undefined) { + return globalContextVal; + } + + const arch = os.arch(); + const platform = os.platform(); + + // This check only applies to x64 + //https://github.com/lancedb/lance/issues/2195#issuecomment-2057841311 + if (arch !== "x64") { + globalContext.update("isSupportedLanceDbCpuTarget", true); + return true; + } + + try { + const cpuFlags = (() => { + switch (platform) { + case "darwin": + return execSync("sysctl -n machdep.cpu.features") + .toString() + .toLowerCase(); + case "linux": + return execSync("cat /proc/cpuinfo").toString().toLowerCase(); + case "win32": + return execSync("wmic cpu get caption /format:list") + .toString() + .toLowerCase(); + default: + return ""; + } + })(); + + const isSupportedLanceDbCpuTarget = cpuFlags + ? CPU_FEATURES_TO_CHECK.every((feature) => cpuFlags.includes(feature)) + : true; + + // If it's not a supported CPU target, and it's the first time we are checking, + // show a toast to inform the user that we are going to disable indexing. + if (!isSupportedLanceDbCpuTarget) { + // We offload our async toast to `showUnsupportedCpuToast` to prevent making + // our config loading async upstream of `isSupportedLanceDbCpuTarget` + void showUnsupportedCpuToast(ide); + } + + globalContext.update( + "isSupportedLanceDbCpuTarget", + isSupportedLanceDbCpuTarget, + ); + + return isSupportedLanceDbCpuTarget; + } catch (error) { + // If we can't determine CPU features, default to true + return true; + } +} + +async function showUnsupportedCpuToast(ide: IDE) { + const shouldOpenLink = await ide.showToast( + "warning", + "Codebase indexing is disabled due to CPU incompatibility", + "Learn more", + ); + + if (shouldOpenLink) { + void ide.openUrl("https://github.com/continuedev/continue/pull/3551"); + } +} diff --git a/core/context/providers/DebugLocalsProvider.ts b/core/context/providers/DebugLocalsProvider.ts index 19efa4347..53c093b13 100644 --- a/core/context/providers/DebugLocalsProvider.ts +++ b/core/context/providers/DebugLocalsProvider.ts @@ -11,7 +11,7 @@ class DebugLocalsProvider extends BaseContextProvider { static description: ContextProviderDescription = { title: "debugger", displayTitle: "Debugger", - description: "Reference the contents of the local variables in the debugger", + description: "Local variables", type: "submenu", renderInlineAs: "", }; diff --git a/core/context/providers/DiffContextProvider.ts b/core/context/providers/DiffContextProvider.ts index ef5823580..cbb9cf530 100644 --- a/core/context/providers/DiffContextProvider.ts +++ b/core/context/providers/DiffContextProvider.ts @@ -17,7 +17,9 @@ class DiffContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const diff = await extras.ide.getDiff(this.options.includeUnstaged ?? true); + const diff = await extras.ide.getDiff( + this.options?.includeUnstaged ?? true, + ); return [ { description: "The current git diff", diff --git a/core/context/providers/DiscordContextProvider.ts b/core/context/providers/DiscordContextProvider.ts index f341be6ab..a180c64a4 100644 --- a/core/context/providers/DiscordContextProvider.ts +++ b/core/context/providers/DiscordContextProvider.ts @@ -32,7 +32,7 @@ class DiscordContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { title: "discord", displayTitle: "Discord", - description: "Reference Discord messages from a channel", + description: "Select a channel", type: "submenu", }; diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 9ee50c256..00e193354 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -80,6 +80,8 @@ class DocsContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + const useReranking = this.options?.useReranking ?? true; + // Get docs service const docsService = DocsService.getSingleton(); if (!docsService) { @@ -101,8 +103,8 @@ class DocsContextProvider extends BaseContextProvider { // We found chunks, so check if there's a favicon for the docs page const favicon = await docsService.getFavicon(query); - // Rerank if there's a rerankder - if (extras.reranker) { + // Rerank if there's a reranker + if (useReranking && extras.reranker) { chunks = await this._rerankChunks( chunks, extras.reranker, diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index ae7d92bf9..0805d341e 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -38,7 +38,10 @@ class RepoMapContextProvider extends BaseContextProvider { content: await generateRepoMap(extras.llm, extras.ide, { dirUris: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query], outputRelativeUriPaths: true, - includeSignatures: false, + // Doesn't ALWAYS depend on indexing, so not setting dependsOnIndexing = true, just checking for it + includeSignatures: extras.config.disableIndexing + ? false + : (this.options?.includeSignatures ?? false), }), }, ]; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 3d1d7cc55..920e13687 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,7 +1,7 @@ import { BaseContextProvider } from "../"; import { ContextProviderName } from "../../"; -import ClipboardContextProvider from "./ClipboardContextProvider"; +import ClipboardContextProvider from "./ClipboardContextProvider"; import CodeContextProvider from "./CodeContextProvider"; import ContinueProxyContextProvider from "./ContinueProxyContextProvider"; import CurrentFileContextProvider from "./CurrentFileContextProvider"; diff --git a/core/core.ts b/core/core.ts index af05f7d96..7316f9aac 100644 --- a/core/core.ts +++ b/core/core.ts @@ -2,10 +2,12 @@ import path from "path"; import { fetchwithRequestOptions } from "@continuedev/fetch"; import ignore from "ignore"; +import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; +import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; import { setupBestConfig, setupLocalConfig, @@ -26,6 +28,7 @@ import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; import { callTool } from "./tools/callTool"; import { ChatDescriber } from "./util/chatDescriber"; +import { clipboardCache } from "./util/clipboardCache"; import { logDevData } from "./util/devdata"; import { DevDataSqliteDb } from "./util/devdataSqlite"; import { GlobalContext } from "./util/GlobalContext"; @@ -35,18 +38,15 @@ import { getConfigJsonPath, setupInitialDotContinueDirectory, } from "./util/paths"; +import { localPathToUri } from "./util/pathToUri"; import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; import { type ContextItemId, type IDE, type IndexingProgressUpdate } from "."; -import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; -import * as URI from "uri-js"; -import { SYSTEM_PROMPT_DOT_FILE } from "./config/getSystemPromptDotFile"; +import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; -import { localPathToUri } from "./util/pathToUri"; -import { clipboardCache } from "./util/clipboardCache"; export class Core { // implements IMessenger @@ -299,7 +299,6 @@ export class Core { }); on("context/loadSubmenuItems", async (msg) => { - console.log("Load SUMBENU ITEMS", msg); const config = await this.config(); if (!config) { return []; @@ -384,9 +383,12 @@ export class Core { }); on("clipboardCache/add", (msg) => { - console.log("ADD TO CLIPBOARD", msg); - clipboardCache.add(uuidv4(), msg.data.content); - this.messenger.send("refreshSubmenuItems", undefined); + const added = clipboardCache.add(uuidv4(), msg.data.content); + if (added) { + this.messenger.send("refreshSubmenuItems", { + providers: ["clipboard"], + }); + } }); async function* llmStreamChat( @@ -665,7 +667,6 @@ export class Core { abortedMessageIds.delete(msg.messageId); break; } - console.log(diffLine); yield { content: diffLine }; } @@ -948,7 +949,9 @@ export class Core { } } - this.messenger.send("refreshSubmenuItems", undefined); + this.messenger.send("refreshSubmenuItems", { + providers: "dependsOnIndexing", + }); this.indexingCancellationController = undefined; } @@ -979,7 +982,9 @@ export class Core { } } - this.messenger.send("refreshSubmenuItems", undefined); + this.messenger.send("refreshSubmenuItems", { + providers: "dependsOnIndexing", + }); } // private diff --git a/core/index.d.ts b/core/index.d.ts index e4f3ff143..132c657ad 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -216,6 +216,10 @@ export interface ContextSubmenuItem { metadata?: any; } +export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem { + providerTitle: string; +} + export interface SiteIndexingConfig { title: string; startUrl: string; @@ -630,7 +634,7 @@ export interface IDE { openUrl(url: string): Promise; - runCommand(command: string): Promise; + runCommand(command: string, options?: TerminalOptions): Promise; saveFile(fileUri: string): Promise; @@ -724,7 +728,6 @@ export type StepName = export type ContextProviderName = | "diff" - | "github" | "terminal" | "debugger" | "open" @@ -751,6 +754,8 @@ export type ContextProviderName = | "issue" | "repo-map" | "url" + | "web" + | "discord" | "clipboard" | string; @@ -1066,7 +1071,6 @@ export interface ExperimentalConfig { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - useTools?: boolean; modelContextProtocolServers?: MCPOptions[]; } @@ -1230,4 +1234,9 @@ export type PackageDocsResult = { } & ( | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } -); + ); + +export interface TerminalOptions { + reuseTerminal?: boolean, + terminalName?: string, +} diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 1f56de495..105d24b9e 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -580,9 +580,9 @@ export default class DocsService { void this.ide.showToast("info", `Successfully indexed ${startUrl}`); - if (this.messenger) { - this.messenger.send("refreshSubmenuItems", undefined); - } + this.messenger?.send("refreshSubmenuItems", { + providers: ["docs"], + }); } catch (e) { console.error("Error indexing docs", e); this.handleStatusUpdate({ @@ -1055,6 +1055,8 @@ export default class DocsService { this.abort(startUrl); await this.deleteIndexes(startUrl); this.deleteFromConfig(startUrl); - this.messenger?.send("refreshSubmenuItems", undefined); + this.messenger?.send("refreshSubmenuItems", { + providers: ["docs"], + }); } } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 2a9986e6c..8232f8288 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -35,6 +35,7 @@ import { xWinCoderEditPrompt, zephyrEditPrompt, } from "./templates/edit.js"; +import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js"; const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", @@ -87,11 +88,11 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ ]; function modelSupportsTools(modelName: string, provider: string) { - return ( - provider === "anthropic" && - modelName.includes("claude") && - (modelName.includes("3-5") || modelName.includes("3.5")) - ); + const providerSupport = PROVIDER_TOOL_SUPPORT[provider]; + if (!providerSupport) { + return false; + } + return providerSupport(modelName) ?? false; } function modelSupportsImages( diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 24f44279d..5b0d1b60b 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -71,20 +71,17 @@ function constructSystemPrompt( provider: string, useTools: boolean, ): string | null { - if ( - useTools && - CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family)) - ) { - return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES; - } else if ( - CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family)) - ) { - return SYSTEM_MESSAGE; - } else if (useTools && modelSupportsTools(model, provider)) { - return TOOL_USE_RULES; + let systemMessage = ""; + if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) { + systemMessage = SYSTEM_MESSAGE; } - - return null; + if (useTools && modelSupportsTools(model, provider)) { + if (systemMessage) { + systemMessage += "\n\n"; + } + systemMessage += TOOL_USE_RULES; + } + return systemMessage || null; } const CANCELED_TOOL_CALL_MESSAGE = diff --git a/core/llm/index.ts b/core/llm/index.ts index 5c0253e86..0b48d867c 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -55,6 +55,7 @@ import { toCompleteBody, toFimBody, } from "./openaiTypeConverters.js"; +import { isOllamaInstalled } from "../util/ollamaHelper.js"; export abstract class BaseLLM implements ILLM { static providerName: string; @@ -414,9 +415,11 @@ export abstract class BaseLLM implements ILLM { e.code === "ECONNREFUSED" && e.message.includes("http://127.0.0.1:11434") ) { - throw new Error( - "Failed to connect to local Ollama instance, please ensure Ollama is both installed and running. You can download Ollama from https://ollama.ai.", - ); + const message = (await isOllamaInstalled()) ? + "Unable to connect to local Ollama instance. Ollama may not be running." : + "Unable to connect to local Ollama instance. Ollama may not be installed or may not running." + ; + throw new Error(message); } } throw new Error(e.message); diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 3e9af9d38..16f71cf15 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,12 +1,24 @@ +import { JSONSchema7Object, JSONSchema7Type } from "json-schema"; + import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; -type OllamaChatMessage = ChatMessage & { images?: string[] }; +type OllamaChatMessage = { + role: "tool" | "user" | "assistant" | "system"; + content: string; + images?: string[] | null; + tool_calls?: { + function: { + name: string; + arguments: Record; + }; + }[]; +}; // See https://github.com/ollama/ollama/blob/main/docs/modelfile.md for details on each parameter -interface ModelFileParams { +interface OllamaModelFileParams { mirostat?: number; mirostat_eta?: number; mirostat_tau?: number; @@ -21,23 +33,35 @@ interface ModelFileParams { top_k?: number; top_p?: number; min_p?: number; - // deprecated? + + // deprecated or not directly supported here: num_thread?: number; use_mmap?: boolean; num_gqa?: number; num_gpu?: number; + num_keep?: number; + typical_p?: number; + presence_penalty?: number; + frequency_penalty?: number; + penalize_newline?: boolean; + numa?: boolean; + num_batch?: number; + main_gpu?: number; + low_vram?: boolean; + vocab_only?: boolean; + use_mlock?: boolean; } // See https://github.com/ollama/ollama/blob/main/docs/api.md -interface BaseOptions { +interface OllamaBaseOptions { model: string; // the model name - options?: ModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature + options?: OllamaModelFileParams; // additional model parameters listed in the documentation for the Modelfile such as temperature format?: "json"; // the format to return a response in. Currently, the only accepted value is json stream?: boolean; // if false the response will be returned as a single response object, rather than a stream of objects keep_alive?: number; // controls how long the model will stay loaded into memory following the request (default: 5m) } -interface GenerateOptions extends BaseOptions { +interface OllamaRawOptions extends OllamaBaseOptions { prompt: string; // the prompt to generate a response for suffix?: string; // the text after the model response images?: string[]; // a list of base64-encoded images (for multimodal models such as llava) @@ -47,12 +71,58 @@ interface GenerateOptions extends BaseOptions { raw?: boolean; // if true no formatting will be applied to the prompt. You may choose to use the raw parameter if you are specifying a full templated prompt in your request to the API } -interface ChatOptions extends BaseOptions { +interface OllamaChatOptions extends OllamaBaseOptions { messages: OllamaChatMessage[]; // the messages of the chat, this can be used to keep a chat memory + tools?: OllamaTool[]; // the tools of the chat, this can be used to keep a tool memory // Not supported yet - tools: tools for the model to use if supported. Requires stream to be set to false // And correspondingly, tool calls in OllamaChatMessage } +type OllamaBaseResponse = { + model: string; + created_at: string; +} & ( + | { + done: false; + } + | { + done: true; + done_reason: string; + total_duration: number; // Time spent generating the response in nanoseconds + load_duration: number; // Time spent loading the model in nanoseconds + prompt_eval_count: number; // Number of tokens in the prompt + prompt_eval_duration: number; // Time spent evaluating the prompt in nanoseconds + eval_count: number; // Number of tokens in the response + eval_duration: number; // Time spent generating the response in nanoseconds + context: number[]; // An encoding of the conversation used in this response; can be sent in the next request to keep conversational memory + } +); + +type OllamaErrorResponse = { + error: string; +}; + +type OllamaRawResponse = + | OllamaErrorResponse + | (OllamaBaseResponse & { + response: string; // the generated response + }); + +type OllamaChatResponse = + | OllamaErrorResponse + | (OllamaBaseResponse & { + message: OllamaChatMessage; + }); + +interface OllamaTool { + type: "function"; + function: { + name: string; + description?: string; + parameters?: JSONSchema7Object; + }; +} + class Ollama extends BaseLLM { static providerName = "ollama"; static defaultOptions: Partial = { @@ -130,56 +200,59 @@ class Ollama extends BaseLLM { }); } + // Map of "continue model name" to Ollama actual model name + private modelMap: Record = { + "mistral-7b": "mistral:7b", + "mixtral-8x7b": "mixtral:8x7b", + "llama2-7b": "llama2:7b", + "llama2-13b": "llama2:13b", + "codellama-7b": "codellama:7b", + "codellama-13b": "codellama:13b", + "codellama-34b": "codellama:34b", + "codellama-70b": "codellama:70b", + "llama3-8b": "llama3:8b", + "llama3-70b": "llama3:70b", + "llama3.1-8b": "llama3.1:8b", + "llama3.1-70b": "llama3.1:70b", + "llama3.1-405b": "llama3.1:405b", + "llama3.2-1b": "llama3.2:1b", + "llama3.2-3b": "llama3.2:3b", + "llama3.2-11b": "llama3.2:11b", + "llama3.2-90b": "llama3.2:90b", + "phi-2": "phi:2.7b", + "phind-codellama-34b": "phind-codellama:34b-v2", + "qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b", + "qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b", + "qwen2.5-coder-3b": "qwen2.5-coder:3b", + "qwen2.5-coder-7b": "qwen2.5-coder:7b", + "qwen2.5-coder-14b": "qwen2.5-coder:14b", + "qwen2.5-coder-32b": "qwen2.5-coder:32b", + "wizardcoder-7b": "wizardcoder:7b-python", + "wizardcoder-13b": "wizardcoder:13b-python", + "wizardcoder-34b": "wizardcoder:34b-python", + "zephyr-7b": "zephyr:7b", + "codeup-13b": "codeup:13b", + "deepseek-1b": "deepseek-coder:1.3b", + "deepseek-7b": "deepseek-coder:6.7b", + "deepseek-33b": "deepseek-coder:33b", + "neural-chat-7b": "neural-chat:7b-v3.3", + "starcoder-1b": "starcoder:1b", + "starcoder-3b": "starcoder:3b", + "starcoder2-3b": "starcoder2:3b", + "stable-code-3b": "stable-code:3b", + "granite-code-3b": "granite-code:3b", + "granite-code-8b": "granite-code:8b", + "granite-code-20b": "granite-code:20b", + "granite-code-34b": "granite-code:34b", + }; + private _getModel() { - return ( - { - "mistral-7b": "mistral:7b", - "mixtral-8x7b": "mixtral:8x7b", - "llama2-7b": "llama2:7b", - "llama2-13b": "llama2:13b", - "codellama-7b": "codellama:7b", - "codellama-13b": "codellama:13b", - "codellama-34b": "codellama:34b", - "codellama-70b": "codellama:70b", - "llama3-8b": "llama3:8b", - "llama3-70b": "llama3:70b", - "llama3.1-8b": "llama3.1:8b", - "llama3.1-70b": "llama3.1:70b", - "llama3.1-405b": "llama3.1:405b", - "llama3.2-1b": "llama3.2:1b", - "llama3.2-3b": "llama3.2:3b", - "llama3.2-11b": "llama3.2:11b", - "llama3.2-90b": "llama3.2:90b", - "phi-2": "phi:2.7b", - "phind-codellama-34b": "phind-codellama:34b-v2", - "qwen2.5-coder-0.5b": "qwen2.5-coder:0.5b", - "qwen2.5-coder-1.5b": "qwen2.5-coder:1.5b", - "qwen2.5-coder-3b": "qwen2.5-coder:3b", - "qwen2.5-coder-7b": "qwen2.5-coder:7b", - "qwen2.5-coder-14b": "qwen2.5-coder:14b", - "qwen2.5-coder-32b": "qwen2.5-coder:32b", - "wizardcoder-7b": "wizardcoder:7b-python", - "wizardcoder-13b": "wizardcoder:13b-python", - "wizardcoder-34b": "wizardcoder:34b-python", - "zephyr-7b": "zephyr:7b", - "codeup-13b": "codeup:13b", - "deepseek-1b": "deepseek-coder:1.3b", - "deepseek-7b": "deepseek-coder:6.7b", - "deepseek-33b": "deepseek-coder:33b", - "neural-chat-7b": "neural-chat:7b-v3.3", - "starcoder-1b": "starcoder:1b", - "starcoder-3b": "starcoder:3b", - "starcoder2-3b": "starcoder2:3b", - "stable-code-3b": "stable-code:3b", - "granite-code-3b": "granite-code:3b", - "granite-code-8b": "granite-code:8b", - "granite-code-20b": "granite-code:20b", - "granite-code-34b": "granite-code:34b", - }[this.model] ?? this.model - ); + return this.modelMap[this.model] ?? this.model; } - private _getModelFileParams(options: CompletionOptions): ModelFileParams { + private _getModelFileParams( + options: CompletionOptions, + ): OllamaModelFileParams { return { temperature: options.temperature, top_p: options.topP, @@ -194,50 +267,38 @@ class Ollama extends BaseLLM { }; } - private _convertMessage(message: ChatMessage) { - if (message.role === "tool") { - return null; - } + private _convertToOllamaMessage(message: ChatMessage): OllamaChatMessage { + const ollamaMessage: OllamaChatMessage = { + role: message.role, + content: "", + }; if (typeof message.content === "string") { - return message; - } - const images: string[] = []; - message.content.forEach((part) => { - if (part.type === "imageUrl" && part.imageUrl) { - const image = part.imageUrl?.url.split(",").at(-1); - if (image) { - images.push(image); + ollamaMessage.content = message.content; + } else { + ollamaMessage.content = renderChatMessage(message); + const images: string[] = []; + message.content.forEach((part) => { + if (part.type === "imageUrl" && part.imageUrl) { + const image = part.imageUrl?.url.split(",").at(-1); + if (image) { + images.push(image); + } } + }); + if (images.length > 0) { + ollamaMessage.images = images; } - }); + } - return { - role: message.role, - content: renderChatMessage(message), - images, - }; - } - - private _getChatOptions( - options: CompletionOptions, - messages: ChatMessage[], - ): ChatOptions { - return { - model: this._getModel(), - messages: messages.map(this._convertMessage).filter(Boolean) as any, - options: this._getModelFileParams(options), - keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes - stream: options.stream, - // format: options.format, // Not currently in base completion options - }; + return ollamaMessage; } private _getGenerateOptions( options: CompletionOptions, prompt: string, suffix?: string, - ): GenerateOptions { + ): OllamaRawOptions { return { model: this._getModel(), prompt, @@ -286,12 +347,11 @@ class Ollama extends BaseLLM { const chunk = chunks[i]; if (chunk.trim() !== "") { try { - const j = JSON.parse(chunk); - if ("response" in j) { - yield j.response; - } else if ("error" in j) { + const j = JSON.parse(chunk) as OllamaRawResponse; + if ("error" in j) { throw new Error(j.error); } + yield j.response; } catch (e) { throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); } @@ -305,39 +365,91 @@ class Ollama extends BaseLLM { signal: AbortSignal, options: CompletionOptions, ): AsyncGenerator { + const chatOptions: OllamaChatOptions = { + model: this._getModel(), + messages: messages.map(this._convertToOllamaMessage), + options: this._getModelFileParams(options), + keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes + stream: options.stream, + // format: options.format, // Not currently in base completion options + }; + if (options.tools?.length) { + chatOptions.tools = options.tools.map((tool) => ({ + type: "function", + function: { + name: tool.function.name, + description: tool.function.description, + parameters: tool.function.parameters, + }, + })); + chatOptions.stream = false; // Cannot set stream = true for tools calls + } + const response = await this.fetch(this.getEndpoint("api/chat"), { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, - body: JSON.stringify(this._getChatOptions(options, messages)), + body: JSON.stringify(chatOptions), signal, }); - let buffer = ""; - for await (const value of streamResponse(response)) { - // Append the received chunk to the buffer - buffer += value; - // Split the buffer into individual JSON chunks - const chunks = buffer.split("\n"); - buffer = chunks.pop() ?? ""; + function convertChatMessage(res: OllamaChatResponse): ChatMessage { + if ("error" in res) { + throw new Error(res.error); + } + if (res.message.role === "tool") { + throw new Error( + "Unexpected message received from ollama with role = tool", + ); + } + if (res.message.role === "assistant") { + const chatMessage: ChatMessage = { + role: "assistant", + content: res.message.content, + }; + if (res.message.tool_calls) { + // Continue handles the response as a tool call delta but + // But ollama returns the full object in one response with no streaming + chatMessage.toolCalls = res.message.tool_calls.map((tc) => ({ + type: "function", + function: { + name: tc.function.name, + arguments: JSON.stringify(tc.function.arguments), + }, + })); + } + return chatMessage; + } else { + return { + role: res.message.role, + content: res.message.content, + }; + } + } - for (let i = 0; i < chunks.length; i++) { - const chunk = chunks[i]; - if (chunk.trim() !== "") { - try { - const j = JSON.parse(chunk); - if (j.message?.content) { - yield { - role: "assistant", - content: j.message.content, - }; - } else if (j.error) { - throw new Error(j.error); + if (chatOptions.stream === false) { + const json = (await response.json()) as OllamaChatResponse; + yield convertChatMessage(json); + } else { + let buffer = ""; + for await (const value of streamResponse(response)) { + // Append the received chunk to the buffer + buffer += value; + // Split the buffer into individual JSON chunks + const chunks = buffer.split("\n"); + buffer = chunks.pop() ?? ""; + + for (let i = 0; i < chunks.length; i++) { + const chunk = chunks[i]; + if (chunk.trim() !== "") { + try { + const j = JSON.parse(chunk) as OllamaChatResponse; + const chatMessage = convertChatMessage(j); + } catch (e) { + throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); } - } catch (e) { - throw new Error(`Error parsing Ollama response: ${e} ${chunk}`); } } } diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts new file mode 100644 index 000000000..da15aacc8 --- /dev/null +++ b/core/llm/toolSupport.ts @@ -0,0 +1,46 @@ +export const PROVIDER_TOOL_SUPPORT: Record< + string, + (model: string) => boolean | undefined +> = { + anthropic: (model) => { + if ( + ["claude-3-5", "claude-3.5"].some((part) => + model.toLowerCase().startsWith(part), + ) + ) { + return true; + } + }, + // https://ollama.com/search?c=tools + ollama: (model) => { + if ( + ["vision", "math", "guard", "mistrallite", "mistral-openorca"].some( + (part) => model.toLowerCase().includes(part), + ) + ) { + return false; + } + if ( + [ + "llama3.3", + "qwq", + "llama3.2", + "llama3.1", + "qwen2", + "mixtral", + "command-r", + "smollm2", + "hermes3", + "athene-v2", + "nemotron", + "llama3-groq", + "granite3", + "aya-expanse", + "firefunction-v2", + "mistral", + ].some((part) => model.toLowerCase().startsWith(part)) + ) { + return true; + } + }, +}; diff --git a/core/package-lock.json b/core/package-lock.json index 4117d99cf..18a318596 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -83,6 +83,7 @@ "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", "@types/jsdom": "^21.1.6", + "@types/json-schema": "^7.0.15", "@types/mozilla-readability": "^0.2.1", "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", @@ -5311,6 +5312,12 @@ "parse5": "^7.0.0" } }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, "node_modules/@types/json5": { "version": "0.0.29", "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", diff --git a/core/package.json b/core/package.json index eb805363b..e865e0ddb 100644 --- a/core/package.json +++ b/core/package.json @@ -22,6 +22,7 @@ "@types/jest": "^29.5.12", "@types/jquery": "^3.5.29", "@types/jsdom": "^21.1.6", + "@types/json-schema": "^7.0.15", "@types/mozilla-readability": "^0.2.1", "@types/mustache": "^4.2.5", "@types/node-fetch": "^2.6.11", diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 4df3cb95b..8c0d2557c 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -14,6 +14,7 @@ import type { Range, RangeInFile, Thread, + TerminalOptions } from "../"; export interface GetGhTokenArgs { @@ -28,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { showVirtualFile: [{ name: string; content: string }, void]; openFile: [{ path: string }, void]; openUrl: [string, void]; - runCommand: [{ command: string }, void]; + runCommand: [{ command: string, options?: TerminalOptions }, void]; getSearchResults: [{ query: string }, string]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 586afedf4..9cc19504d 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -62,10 +62,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { setInactive: [undefined, void]; submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap - updateSubmenuItems: [ - { provider: string; submenuItems: ContextSubmenuItem[] }, - void, - ]; newSessionWithPrompt: [{ prompt: string }, void]; userInput: [{ input: string }, void]; focusContinueInput: [undefined, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 9f46602c1..aaa567f39 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -13,6 +13,7 @@ import type { Problem, Range, RangeInFile, + TerminalOptions, Thread, } from "../.."; @@ -151,8 +152,8 @@ export class MessageIde implements IDE { await this.request("openUrl", url); } - async runCommand(command: string): Promise { - await this.request("runCommand", { command }); + async runCommand(command: string, options?: TerminalOptions): Promise { + await this.request("runCommand", { command, options }); } async saveFile(fileUri: string): Promise { diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 11512fa2c..5e22faae6 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -4,6 +4,8 @@ import { ConfigValidationError } from "../config/validation.js"; import type { BrowserSerializedContinueConfig, ContextItemWithId, + ContextProviderName, + ContextSubmenuItem, IndexingProgressUpdate, IndexingStatus, PackageDocsResult, @@ -21,7 +23,12 @@ export type ToWebviewFromIdeOrCoreProtocol = { getDefaultModelTitle: [undefined, string]; indexProgress: [IndexingProgressUpdate, void]; // Codebase "indexing/statusUpdate": [IndexingStatus, void]; // Docs, etc. - refreshSubmenuItems: [undefined, void]; + refreshSubmenuItems: [ + { + providers: "all" | "dependsOnIndexing" | ContextProviderName[]; + }, + void, + ]; isContinueInputFocused: [undefined, boolean]; addContextItem: [ { diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 5e4f7c6d7..336dc8293 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -15,6 +15,7 @@ export type GlobalContextType = { hasDismissedConfigTsNoticeJetBrains: boolean; hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; + isSupportedLanceDbCpuTarget: boolean; }; /** diff --git a/core/util/clipboardCache.ts b/core/util/clipboardCache.ts index 4ecd16afc..5e0f5ac85 100644 --- a/core/util/clipboardCache.ts +++ b/core/util/clipboardCache.ts @@ -8,10 +8,28 @@ class ClipboardCache { this.order = []; } - add(id: string, content: string): void { + /* + Returns true if added, false if not. + */ + add(id: string, content: string): boolean { if (!content) { - return; + return false; } + + // Check if the content already exists in the cache + for (const [existingId, existingContent] of this.cache.entries()) { + if (existingContent === content) { + // Remove the existing entry with the same content + this.cache.delete(existingId); + const index = this.order.indexOf(existingId); + if (index > -1) { + this.order.splice(index, 1); + } + return false; + } + } + + // Remove the oldest entry if the cache exceeds the maximum size if (this.order.length >= this.maxSize) { const oldest = this.order.pop(); if (oldest) { @@ -19,14 +37,13 @@ class ClipboardCache { } } + // Add the new entry to the cache and update the order this.cache.set(id, content); this.order.unshift(id); + return true; } - getNItems(count: number): { - id: string; - content: string; - }[] { + getNItems(count: number): { id: string; content: string }[] { return this.order.slice(0, count).map((id) => ({ id, content: this.cache.get(id) || "", diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 45ac7a7c5..b4297f7bc 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -13,6 +13,7 @@ import { Problem, Range, RangeInFile, + TerminalOptions, Thread, ToastType, } from "../index.js"; @@ -190,7 +191,7 @@ class FileSystemIde implements IDE { return Promise.resolve(); } - runCommand(command: string): Promise { + runCommand(command: string, options?: TerminalOptions): Promise { return Promise.resolve(); } diff --git a/core/util/ollamaHelper.ts b/core/util/ollamaHelper.ts new file mode 100644 index 000000000..1e9c52490 --- /dev/null +++ b/core/util/ollamaHelper.ts @@ -0,0 +1,41 @@ +import path from "node:path"; +import { IDE } from ".."; +import { exec } from "node:child_process"; + +export async function isOllamaInstalled(): Promise { + return new Promise((resolve, _reject) => { + const command = process.platform === "win32" ? "where.exe ollama" : "which ollama"; + exec(command, (error, _stdout, _stderr) => { + resolve(!error); + }); + }); +} + +export async function startLocalOllama(ide: IDE): Promise { + let startCommand: string | undefined; + + switch (process.platform) { + case "darwin"://MacOS + startCommand = "open -a Ollama.app\n"; + break; + + case "win32"://Windows + startCommand = `& "ollama app.exe"\n`; + break; + + default: //Linux... + const start_script_path = path.resolve(__dirname, './start_ollama.sh'); + if (await ide.fileExists(`file:/${start_script_path}`)) { + startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`; + console.log(`Ollama Linux startup script at : ${start_script_path}`); + } else { + ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`) + } + } + if (startCommand) { + return ide.runCommand(startCommand, { + reuseTerminal: true, + terminalName: "Start Ollama" + }); + } +} diff --git a/core/util/posthog.ts b/core/util/posthog.ts index 09a0d9e10..198041207 100644 --- a/core/util/posthog.ts +++ b/core/util/posthog.ts @@ -2,15 +2,17 @@ import os from "node:os"; import { TeamAnalytics } from "../control-plane/TeamAnalytics.js"; import { IdeInfo } from "../index.js"; + import type { PostHog as PostHogType } from "posthog-node"; export enum PosthogFeatureFlag { AutocompleteTimeout = "autocomplete-timeout", + RecentlyVisitedRangesNumSurroundingLines = "recently-visited-ranges-num-surrounding-lines", } export const EXPERIMENTS: { [key in PosthogFeatureFlag]: { - [key: string]: { value: number }; + [key: string]: { value: any }; }; } = { [PosthogFeatureFlag.AutocompleteTimeout]: { @@ -19,6 +21,13 @@ export const EXPERIMENTS: { "350": { value: 350 }, "450": { value: 450 }, }, + [PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: { + control: { value: null }, + "5": { value: 5 }, + "10": { value: 10 }, + "15": { value: 15 }, + "20": { value: 20 }, + }, }; export class Telemetry { diff --git a/core/util/start_ollama.sh b/core/util/start_ollama.sh new file mode 100755 index 000000000..ead153d2e --- /dev/null +++ b/core/util/start_ollama.sh @@ -0,0 +1,84 @@ +#!/bin/bash + +# Timeout for waiting for Ollama to start (in seconds) +readonly TIMEOUT=60 +readonly OLLAMA_API_URL="http://localhost:11434/api/version" + +# Check if a command exists +command_exists() { + command -v "$1" >/dev/null 2>&1 +} + +# Check if Ollama is already running +ollama_is_running() { + VERSION=$(curl -s --fail --max-time 1 "$OLLAMA_API_URL" | grep '"version"' | awk -F: '{ print $2 }' | sed -e 's/.*"\([^"]*\)".*/\1/') + test -n "$VERSION" +} + +# Determine if running in a container environment +in_container() { + [[ -f /.dockerenv || -f /run/.containerenv ]] +} + +# Start Ollama service or background process +start_ollama() { + local start_method="${1:-background}" + echo "Starting Ollama ($start_method)..." + + if [[ "$start_method" == "service" ]]; then + if in_container; then + service ollama start || return $? + else + sudo systemctl start ollama || return $? + fi + else + nohup ollama serve >/dev/null 2>&1 & + fi + + # Wait for Ollama to start. TIMEOUT * 4, since we sleep 1/4 sec on each iteration + for _ in $(seq 1 $((TIMEOUT * 4))); do + if ollama_is_running; then + echo -e "\nOllama started successfully." + return 0 + fi + (( _ % 2 == 0 )) && printf "." + sleep 0.25 + done + + echo -e "\nTimeout: Failed to start Ollama." + return 1 +} + +# Main script execution +main() { + # Early exit if Ollama is already running + if ollama_is_running; then + echo "Ollama is already running." + return 0 + fi + + # Try starting via service if possible + if in_container; then + if service --status-all 2>&1 | grep -qw 'ollama'; then + start_ollama service || return $? + return 0 + fi + elif command_exists systemctl; then + if systemctl list-unit-files ollama.service >/dev/null 2>&1; then + start_ollama service || return $? + return 0 + fi + fi + + # Fallback to background process + if command_exists ollama; then + start_ollama || return 1 + else + echo "Error: Ollama is not installed or not in the PATH." >&2 + return 1 + fi +} + +# Run the main function and exit with its status +main +exit $? diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md index 4ec425e81..e4c35ddc5 100644 --- a/docs/docs/chat/context-selection.md +++ b/docs/docs/chat/context-selection.md @@ -15,7 +15,7 @@ The highlighted code you’ve selected by pressing cmd/ctrl + L< ## Active file -You can include the currently open file as context by pressing cmd + opt + enter (Mac) or alt + enter (Windows) when you send your request at Chat window(Prompt can't be empty). +You can include the currently open file as context by pressing opt + enter (Mac) or alt + enter (Windows) when you send your request at Chat window(Prompt can't be empty). ## Specific file diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index 832f2f837..eb7dc5430 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -33,7 +33,7 @@ Our current top recommendation is Claude Sonnet 3.5 from [Anthropic](../customiz ### Llama 3.1 405B from Meta -If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Novita AI](../customize/model-providers/more/novita.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)). +If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your best option right now. You will need to decide if you use it through a SaaS model provider (e.g. [Together](../customize/model-providers/more/together.md) or [Groq](../customize/model-providers/more/groq.md)) or self-host it (e.g. using [vLLM](../customize/model-providers//more/vllm.md) or [Ollama](../customize/model-providers/top-level/ollama.md)). @@ -48,18 +48,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your ] ``` - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "novita", - "model": "meta-llama/llama-3.1-405b-instruct", - "apiKey": "[NOVITA_API_KEY]" - } - ] - ``` - ```json title="config.json" "models": [ @@ -94,18 +82,6 @@ If you prefer to use an open-weight model, then Llama 3.1 405B from Meta is your ] ``` - - ```json title="config.json" - "models": [ - { - "title": "Llama 3.1 405B", - "provider": "nebius", - "model": "llama3.1-405b", - "apiKey": "[NEBIUS_API_KEY]" - } - ] - ``` - ### GPT-4o from OpenAI diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 0b48c386b..f28824000 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -123,11 +123,16 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to Reference relevant pages from across the web, automatically determined from your input. +Optionally, set "n" to limit the number of results returned (default 6). + ```json title="config.json" { "contextProviders": [ { - "name": "web" + "name": "web", + "params": { + "n": 5 + } } ] } @@ -193,6 +198,20 @@ Reference the markdown converted contents of a given URL. } ``` +### `@Clipboard` + +Reference recent clipboard items + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "clipboard" + } + ] +} +``` + ### `@Tree` Reference the structure of your current workspace. @@ -207,26 +226,103 @@ Reference the structure of your current workspace. } ``` -### `@Google` +### `@Problems` -Reference the results of a Google search. +Get Problems from the current file. ```json title="config.json" { "contextProviders": [ { - "name": "google", + "name": "problems" + } + ] +} +``` + +### `@Debugger` + +Reference the contents of the local variables in the debugger. Currently only available in VS Code. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "debugger", "params": { - "serperApiKey": "" + "stackDepth": 3 } } ] } ``` -For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python. +Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. -Note: You can get an API key for free at [serper.dev](https://serper.dev). +### `@Repository Map` + +Reference the outline of your codebase. + +`includeSignatures` params can be used to include signatures for all files in the repo. Use with caution as will increase context size significantly. `includeSignatures` will not work if indexing is disabled. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "repo-map", + "params": { + "includeSignatures": false + } + } + ] +} +``` + +Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. + +In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. + +This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). + +### `@Operating System` + +Reference the architecture and platform of your current operating system. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "os" + } + ] +} +``` + +### Model Context Protocol + +The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: + +```json +{ + "experimental": { + "modelContextProtocolServers": [ + { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + ] + } +} +``` + +You'll then be able to type "@" and see "MCP" in the context providers dropdown. + +### Prompt Files + +See [Prompt Files](/customize/deep-dives/prompt-files). Prompt files are not added directly to the config file; prompt files are parsed and injected into the config automatically, to be used like other context providers. ### `@Issue` @@ -253,6 +349,110 @@ Reference the conversation in a GitHub issue. Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited. +### `@Database` + +Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "database", + "params": { + "connections": [ + { + "name": "examplePostgres", + "connection_type": "postgres", + "connection": { + "user": "username", + "host": "localhost", + "database": "exampleDB", + "password": "yourPassword", + "port": 5432 + } + }, + { + "name": "exampleMssql", + "connection_type": "mssql", + "connection": { + "user": "username", + "server": "localhost", + "database": "exampleDB", + "password": "yourPassword" + } + }, + { + "name": "exampleSqlite", + "connection_type": "sqlite", + "connection": { + "filename": "/path/to/your/sqlite/database.db" + } + } + ] + } + } + ] +} +``` + +Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type. + +Available connection types: + +- `postgres` +- `mysql` +- `sqlite` + +### `@Postgres` + +Reference the schema of a table, and some sample rows + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "postgres", + "params": { + "host": "localhost", + "port": 5436, + "user": "myuser", + "password": "catsarecool", + "database": "animals", + "schema": "public", + "sampleRows": 3 + } + } + ] +} +``` + +The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`. + +By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas. + +[Here is a short demo.](https://github.com/continuedev/continue/pull/859) + +### `@Google` + +Reference the results of a Google search. + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "google", + "params": { + "serperApiKey": "" + } + } + ] +} +``` + +For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python. + +Note: You can get an API key for free at [serper.dev](https://serper.dev). + ### `@Gitlab Merge Request` Reference an open MR for this branch on GitLab. @@ -373,164 +573,6 @@ Reference the messages in a Discord channel. Make sure to include your own [Bot Token](https://discord.com/developers/applications), and join it to your related server . If you want more granular control over which channels are searched, you can specify a list of channel IDs to search in. If you don't want to specify any channels, just include the guild id(Server ID) and all channels will be included. The provider only reads text channels. -### `@Postgres` - -Reference the schema of a table, and some sample rows - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "postgres", - "params": { - "host": "localhost", - "port": 5436, - "user": "myuser", - "password": "catsarecool", - "database": "animals", - "schema": "public", - "sampleRows": 3 - } - } - ] -} -``` - -The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`. - -By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas. - -[Here is a short demo.](https://github.com/continuedev/continue/pull/859) - -### `@Database` - -Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "database", - "params": { - "connections": [ - { - "name": "examplePostgres", - "connection_type": "postgres", - "connection": { - "user": "username", - "host": "localhost", - "database": "exampleDB", - "password": "yourPassword", - "port": 5432 - } - }, - { - "name": "exampleMssql", - "connection_type": "mssql", - "connection": { - "user": "username", - "server": "localhost", - "database": "exampleDB", - "password": "yourPassword" - } - }, - { - "name": "exampleSqlite", - "connection_type": "sqlite", - "connection": { - "filename": "/path/to/your/sqlite/database.db" - } - } - ] - } - } - ] -} -``` - -Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type. - -Available connection types: - -- `postgres` -- `mysql` -- `sqlite` - -### `@Debugger` - -Reference the contents of the local variables in the debugger. Currently only available in VS Code. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "debugger", - "params": { - "stackDepth": 3 - } - } - ] -} -``` - -Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. - -### `@Repository Map` - -Reference the outline of your codebase. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "repo-map" - } - ] -} -``` - -Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase. - -In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from. - -This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html). - -### `@Operating System` - -Reference the architecture and platform of your current operating system. - -```json title="config.json" -{ - "contextProviders": [ - { - "name": "os" - } - ] -} -``` - -### Model Context Protocol - -The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a standard proposed by Anthropic to unify prompts, context, and tool use. Continue supports any MCP server with the MCP context provider. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: - -```json -{ - "experimental": { - "modelContextProtocolServers": [ - { - "transport": { - "type": "stdio", - "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] - } - } - ] - } -} -``` - -You'll then be able to type "@" and see "MCP" in the context providers dropdown. - ### `@HTTP` The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems. @@ -550,7 +592,7 @@ The HttpContextProvider makes a POST request to the url passed in the configurat The receiving URL should expect to receive the following parameters: -```json title="POST parameters" +```js title="POST parameters" { query: string, fullInput: string @@ -576,15 +618,19 @@ The response 200 OK should be a JSON object with the following structure: } ``` -### `@Clipboard` +### `@Greptile` -Reference recent clipboard items +Query a [Greptile](https://www.greptile.com/) index of the current repo/branch. ```json title="config.json" { "contextProviders": [ { - "name": "clipboard" + "name": "greptile", + "params": { + "GreptileToken": "...", + "GithubToken": "..." + } } ] } diff --git a/docs/docs/customize/tools.md b/docs/docs/customize/tools.md index 878432c11..020c38459 100644 --- a/docs/docs/customize/tools.md +++ b/docs/docs/customize/tools.md @@ -4,7 +4,12 @@ description: Tool use and customization keywords: [tool, use, function calling, claude, automatic] --- -Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported with [Anthropic](./model-providers/top-level/anthropic.md). To use tools, click on the icon in the input toolbar like below. +Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported for the following providers: + +- [Anthropic](./model-providers/top-level/anthropic.md) - see recommended models [here](https://docs.anthropic.com/en/docs/build-with-claude/tool-use#choosing-a-model). +- [Ollama](./model-providers/top-level/ollama.md) - see recommended models [here](https://ollama.com/search?c=tools). + +To use tools, click on the icon in the input toolbar like below. ![tools](/img/tool-use-example.png) diff --git a/docs/docs/customize/tutorials/llama3.1.md b/docs/docs/customize/tutorials/llama3.1.md index 38e90bee9..e2ac72986 100644 --- a/docs/docs/customize/tutorials/llama3.1.md +++ b/docs/docs/customize/tutorials/llama3.1.md @@ -71,28 +71,6 @@ Together AI provides fast and reliable inference of open-source models. You'll b } ``` - -## Novita AI - -[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) offers an affordable, reliable, and simple inference platform with scalable [LLM API](https://novita.ai/docs/model-api/reference/introduction.html), empowering developers to build AI applications. Try the [Novita AI Llama 3 API Demo](https://novita.ai/model-api/product/llm-api/playground/meta-llama-llama-3.1-70b-instruct?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) today! - -1. Create an account [here](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) -2. Copy your API key that appears on the welcome screen -3. Update your Continue config file like this: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "novita", - "model": "meta-llama/llama-3.1-405b-instruct", - "apiKey": "" - } - ] -} -``` - ## Replicate Replicate makes it easy to host and run open-source AI with an API. 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 4ef37a41e..cbbef8761 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 @@ -33,7 +33,7 @@ import TabItem from "@theme/TabItem"; ### 来自 Meta 的 Llama 3.1 405B -如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md) 、[Novita AI](../customize/model-providers/more/novita.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。 +如果你倾向于使用开放权重模型,那么来自 Meta 的 Llama 3.1 405B 是你当前的最好选择。你需要决定,通过 SaaS 模型提供者使用它(比如 [Together](../customize/model-providers/more/together.md)或 [Groq](../customize/model-providers/more/groq.md))或者自托管使用它(比如使用 [vLLM](../customize/model-providers//more/vllm.md) 或 [Ollama](../customize/model-providers/top-level/ollama.md)) 。 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md index dc285627a..e02ba6741 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md @@ -71,27 +71,6 @@ Together AI 提供开源模型的快速和可信任的推理。你可以以良 } ``` -## Novita AI - -[Novita AI](https://novita.ai?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) 提供了一个经济实惠、可靠且简单的推理平台。你可以以良好的速度运行 405b 模型。 - -1. 创建账号 [在这里](https://novita.ai/user/login?&redirect=/&utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link) -2. 复制[Key Management](https://novita.ai/settings/key-management?utm_source=github_continuedev&utm_medium=github_readme&utm_campaign=github_link)中的你的 API key -3. 更新你的 Continue 配置文件,像这样: - -```json title="config.json" -{ - "models": [ - { - "title": "Llama 3.1 405b", - "provider": "novita", - "model": "meta-llama/llama-3.1-405b-instruct", - "apiKey": "" - } - ] -} -``` - ## Replicate Replicate 让使用 API 托管和运行开源 AI 变得简单。 diff --git a/extensions/intellij/.run/Run Extension.run.xml b/extensions/intellij/.run/Run Extension.run.xml index fd9562480..b63167cde 100644 --- a/extensions/intellij/.run/Run Extension.run.xml +++ b/extensions/intellij/.run/Run Extension.run.xml @@ -9,7 +9,7 @@