From c0923a0dd7ca3a6e9dcbd9b02bfc34250269d2ef Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 6 Aug 2024 11:31:10 -0700 Subject: [PATCH 1/9] fix: filepath replacements in prompt files (#1939) * fix: filepath replacements in prompt files * remove file extensions --- core/commands/index.ts | 12 +- core/config/promptFile.ts | 244 ++++++++++-------- core/llm/llms/index.ts | 128 +++------ core/promptFiles/createNewPromptFile.ts | 57 ++++ core/promptFiles/getContextProviderHelpers.ts | 37 +++ core/promptFiles/getPromptFiles.ts | 25 ++ core/promptFiles/handlebarUtils.ts | 114 ++++++++ core/promptFiles/index.ts | 8 + core/promptFiles/renderTemplatedString.ts | 30 +++ .../promptFiles/slashCommandFromPromptFile.ts | 93 +++++++ core/promptFiles/updateChatHistory.ts | 55 ++++ docs/docs/features/prompt-files.md | 4 +- extensions/vscode/src/commands.ts | 11 +- .../providers/QuickActionsCodeLensProvider.ts | 43 ++- extensions/vscode/src/util/ideUtils.ts | 42 ++- gui/src/components/mainInput/MentionList.tsx | 76 +++--- 16 files changed, 668 insertions(+), 311 deletions(-) create mode 100644 core/promptFiles/createNewPromptFile.ts create mode 100644 core/promptFiles/getContextProviderHelpers.ts create mode 100644 core/promptFiles/getPromptFiles.ts create mode 100644 core/promptFiles/handlebarUtils.ts create mode 100644 core/promptFiles/index.ts create mode 100644 core/promptFiles/renderTemplatedString.ts create mode 100644 core/promptFiles/slashCommandFromPromptFile.ts create mode 100644 core/promptFiles/updateChatHistory.ts diff --git a/core/commands/index.ts b/core/commands/index.ts index 2b1a67bbd..fd075c6ff 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -1,11 +1,7 @@ -import { - CustomCommand, - SlashCommand, - SlashCommandDescription, -} from "../index.js"; -import { stripImages } from "../llm/images.js"; -import { renderTemplatedString } from "../llm/llms/index.js"; -import SlashCommands from "./slash/index.js"; +import { CustomCommand, SlashCommand, SlashCommandDescription } from "../"; +import { stripImages } from "../llm/images"; +import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; +import SlashCommands from "./slash"; export function slashFromCustomCommand( customCommand: CustomCommand, diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index bc5be2da7..92d558aaf 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -4,8 +4,8 @@ import * as YAML from "yaml"; import type { IDE, SlashCommand } from ".."; import { walkDir } from "../indexing/walkDir"; import { stripImages } from "../llm/images"; -import { renderTemplatedString } from "../llm/llms/index"; import { getBasename } from "../util/index"; +import { renderTemplatedString } from "../promptFiles/renderTemplatedString"; export const DEFAULT_PROMPTS_FOLDER = ".prompts"; @@ -15,6 +15,7 @@ export async function getPromptFiles( ): Promise<{ path: string; content: string }[]> { try { const exists = await ide.fileExists(dir); + if (!exists) { return []; } @@ -89,6 +90,32 @@ export function slashCommandFromPromptFile( path: string, content: string, ): SlashCommand { + const { name, description, systemMessage, prompt } = parsePromptFile( + path, + content, + ); + + return { + name, + description, + run: async function* (context) { + const userInput = extractUserInput(context.input, name); + const renderedPrompt = await renderPrompt(prompt, context, userInput); + const messages = updateChatHistory( + context.history, + name, + renderedPrompt, + systemMessage, + ); + + for await (const chunk of context.llm.streamChat(messages)) { + yield stripImages(chunk.content); + } + }, + }; +} + +function parsePromptFile(path: string, content: string) { let [preambleRaw, prompt] = content.split("\n---\n"); if (prompt === undefined) { prompt = preambleRaw; @@ -105,115 +132,122 @@ export function slashCommandFromPromptFile( prompt = prompt.split("")[1].trim(); } - return { - name, - description, - run: async function* ({ - input, - llm, - history, - ide, - config, - fetch, - selectedCode, - addContextItem, - }) { - // Remove slash command prefix from input - let userInput = input; - if (userInput.startsWith(`/${name}`)) { - userInput = userInput - .slice(name.length + 1, userInput.length) - .trimStart(); - } + return { name, description, systemMessage, prompt }; +} - // Render prompt template - const helpers: [string, Handlebars.HelperDelegate][] | undefined = - config.contextProviders?.map((provider) => { - return [ - provider.description.title, - async (context: any) => { - const items = await provider.getContextItems(context, { - config, - embeddingsProvider: config.embeddingsProvider, - fetch, - fullInput: userInput, - ide, - llm, - reranker: config.reranker, - selectedCode, - }); - items.forEach((item) => - addContextItem({ - ...item, - id: { - itemId: item.description, - providerTitle: provider.description.title, - }, - }), - ); - return items.map((item) => item.content).join("\n\n"); - }, - ]; - }); +function extractUserInput(input: string, commandName: string): string { + if (input.startsWith(`/${commandName}`)) { + return input.slice(commandName.length + 1).trimStart(); + } + return input; +} - // A few context providers that don't need to be in config.json to work in .prompt files - const diff = await ide.getDiff(); - const currentFilePath = await ide.getCurrentFile(); - const promptUserInput = await renderTemplatedString( - prompt, - ide.readFile.bind(ide), - { - input: userInput, - diff, - currentFile: currentFilePath - ? await ide.readFile(currentFilePath) - : undefined, - }, - helpers, +async function renderPrompt(prompt: string, context: any, userInput: string) { + const helpers = getContextProviderHelpers(context); + + // A few context providers that don't need to be in config.json to work in .prompt files + const diff = await context.ide.getDiff(); + const currentFilePath = await context.ide.getCurrentFile(); + const currentFile = currentFilePath + ? await context.ide.readFile(currentFilePath) + : undefined; + + return renderTemplatedString( + prompt, + context.ide.readFile.bind(context.ide), + { diff, currentFile, input: userInput }, + helpers, + ); +} + +function getContextProviderHelpers( + context: any, +): Array<[string, Handlebars.HelperDelegate]> | undefined { + return context.config.contextProviders?.map((provider: any) => [ + provider.description.title, + async (helperContext: any) => { + const items = await provider.getContextItems(helperContext, { + config: context.config, + embeddingsProvider: context.config.embeddingsProvider, + fetch: context.fetch, + fullInput: context.input, + ide: context.ide, + llm: context.llm, + reranker: context.config.reranker, + selectedCode: context.selectedCode, + }); + + items.forEach((item: any) => + context.addContextItem(createContextItem(item, provider)), ); - const messages = [...history]; - // Find the last chat message with this slash command and replace it with the user input - for (let i = messages.length - 1; i >= 0; i--) { - const { role, content } = messages[i]; - if (role !== "user") { - continue; - } + return items.map((item: any) => item.content).join("\n\n"); + }, + ]); +} - if ( - Array.isArray(content) && - content.some((part) => part.text?.startsWith(`/${name}`)) - ) { - messages[i] = { - ...messages[i], - content: content.map((part) => { - return part.text?.startsWith(`/${name}`) - ? { ...part, text: promptUserInput } - : part; - }), - }; - break; - } else if ( - typeof content === "string" && - content.startsWith(`/${name}`) - ) { - messages[i] = { ...messages[i], content: promptUserInput }; - break; - } - } - - // System message - if (systemMessage) { - if (messages[0]?.role === "system") { - messages[0].content = systemMessage; - } else { - messages.unshift({ role: "system", content: systemMessage }); - } - } - - for await (const chunk of llm.streamChat(messages)) { - yield stripImages(chunk.content); - } +function createContextItem(item: any, provider: any) { + return { + ...item, + id: { + itemId: item.description, + providerTitle: provider.description.title, }, }; } + +function updateChatHistory( + history: any[], + commandName: string, + renderedPrompt: string, + systemMessage?: string, +) { + const messages = [...history]; + + for (let i = messages.length - 1; i >= 0; i--) { + const { role, content } = messages[i]; + if (role !== "user") { + continue; + } + + if (Array.isArray(content)) { + if (content.some((part) => part.text?.startsWith(`/${commandName}`))) { + messages[i] = updateArrayContent( + messages[i], + commandName, + renderedPrompt, + ); + break; + } + } else if ( + typeof content === "string" && + content.startsWith(`/${commandName}`) + ) { + messages[i] = { ...messages[i], content: renderedPrompt }; + break; + } + } + + if (systemMessage) { + messages[0]?.role === "system" + ? (messages[0].content = systemMessage) + : messages.unshift({ role: "system", content: systemMessage }); + } + + return messages; +} + +function updateArrayContent( + message: any, + commandName: string, + renderedPrompt: string, +) { + return { + ...message, + content: message.content.map((part: any) => + part.text?.startsWith(`/${commandName}`) + ? { ...part, text: renderedPrompt } + : part, + ), + }; +} diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 84455399d..bbd85ef15 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -1,105 +1,39 @@ -import Handlebars from "handlebars"; -import { v4 as uuidv4 } from "uuid"; import { BaseCompletionOptions, IdeSettings, ILLM, LLMOptions, ModelDescription, -} from "../../index.js"; -import { DEFAULT_MAX_TOKENS } from "../constants.js"; -import { BaseLLM } from "../index.js"; -import Anthropic from "./Anthropic.js"; -import Bedrock from "./Bedrock.js"; -import Cloudflare from "./Cloudflare.js"; -import Cohere from "./Cohere.js"; -import DeepInfra from "./DeepInfra.js"; -import Deepseek from "./Deepseek.js"; -import Fireworks from "./Fireworks.js"; -import Flowise from "./Flowise.js"; -import FreeTrial from "./FreeTrial.js"; -import Gemini from "./Gemini.js"; -import Groq from "./Groq.js"; -import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI.js"; -import HuggingFaceTGI from "./HuggingFaceTGI.js"; -import LMStudio from "./LMStudio.js"; -import LlamaCpp from "./LlamaCpp.js"; -import Llamafile from "./Llamafile.js"; -import Mistral from "./Mistral.js"; -import Msty from "./Msty.js"; -import Azure from "./Azure.js"; -import Ollama from "./Ollama.js"; -import OpenAI from "./OpenAI.js"; -import Replicate from "./Replicate.js"; -import TextGenWebUI from "./TextGenWebUI.js"; -import Together from "./Together.js"; -import ContinueProxy from "./stubs/ContinueProxy.js"; -import WatsonX from "./WatsonX.js"; - -function convertToLetter(num: number): string { - let result = ""; - while (num > 0) { - const remainder = (num - 1) % 26; - result = String.fromCharCode(97 + remainder) + result; - num = Math.floor((num - 1) / 26); - } - return result; -} - -const getHandlebarsVars = ( - value: string, -): [string, { [key: string]: string }] => { - const ast = Handlebars.parse(value); - - const keysToFilepath: { [key: string]: string } = {}; - let keyIndex = 1; - for (const i in ast.body) { - if (ast.body[i].type === "MustacheStatement") { - const letter = convertToLetter(keyIndex); - keysToFilepath[letter] = (ast.body[i] as any).path.original; - value = value.replace( - new RegExp(`{{\\s*${(ast.body[i] as any).path.original}\\s*}}`), - `{{${letter}}}`, - ); - keyIndex++; - } - } - return [value, keysToFilepath]; -}; - -export async function renderTemplatedString( - template: string, - readFile: (filepath: string) => Promise, - inputData: any, - helpers?: [string, Handlebars.HelperDelegate][], -): Promise { - const promises: { [key: string]: Promise } = {}; - if (helpers) { - for (const [name, helper] of helpers) { - Handlebars.registerHelper(name, (...args) => { - const id = uuidv4(); - promises[id] = helper(...args); - return `__${id}__`; - }); - } - } - - const [newTemplate, vars] = getHandlebarsVars(template); - const data: any = { ...inputData }; - for (const key in vars) { - const fileContents = await readFile(vars[key]); - data[key] = fileContents || (inputData[vars[key]] ?? vars[key]); - } - const templateFn = Handlebars.compile(newTemplate); - let final = templateFn(data); - - await Promise.all(Object.values(promises)); - for (const id in promises) { - final = final.replace(`__${id}__`, await promises[id]); - } - - return final; -} +} from "../.."; +import { DEFAULT_MAX_TOKENS } from "../constants"; +import { BaseLLM } from "../index"; +import Anthropic from "./Anthropic"; +import Bedrock from "./Bedrock"; +import Cloudflare from "./Cloudflare"; +import Cohere from "./Cohere"; +import DeepInfra from "./DeepInfra"; +import Deepseek from "./Deepseek"; +import Fireworks from "./Fireworks"; +import Flowise from "./Flowise"; +import FreeTrial from "./FreeTrial"; +import Gemini from "./Gemini"; +import Groq from "./Groq"; +import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI"; +import HuggingFaceTGI from "./HuggingFaceTGI"; +import LMStudio from "./LMStudio"; +import LlamaCpp from "./LlamaCpp"; +import Llamafile from "./Llamafile"; +import Mistral from "./Mistral"; +import Msty from "./Msty"; +import Azure from "./Azure"; +import Ollama from "./Ollama"; +import OpenAI from "./OpenAI"; +import Replicate from "./Replicate"; +import TextGenWebUI from "./TextGenWebUI"; +import Together from "./Together"; +import ContinueProxy from "./stubs/ContinueProxy"; +import WatsonX from "./WatsonX"; +import { renderTemplatedString } from "../../promptFiles/renderTemplatedString"; const LLMs = [ Anthropic, @@ -127,7 +61,7 @@ const LLMs = [ Deepseek, Msty, Azure, - WatsonX + WatsonX, ]; export async function llmFromDescription( diff --git a/core/promptFiles/createNewPromptFile.ts b/core/promptFiles/createNewPromptFile.ts new file mode 100644 index 000000000..d686e0d72 --- /dev/null +++ b/core/promptFiles/createNewPromptFile.ts @@ -0,0 +1,57 @@ +import path from "path"; +import { IDE } from ".."; +import { DEFAULT_PROMPTS_FOLDER } from "./"; + +const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file +# It is used to define and reuse prompts within Continue +# Continue will automatically create a slash command for each prompt in the .prompts folder +# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files +temperature: 0.0 +--- +{{{ diff }}} + +Give me feedback on the above changes. For each file, you should output a markdown section including the following: +- If you found any problems, an h3 like "❌ " +- If you didn't find any problems, an h3 like "✅ " +- If you found any problems, add below a bullet point description of what you found, including a minimal code snippet explaining how to fix it +- If you didn't find any problems, you don't need to add anything else + +Here is an example. The example is surrounded in backticks, but your response should not be: + +\`\`\` +### ✅ + +### ❌ + + +\`\`\` + +You should look primarily for the following types of issues, and only mention other problems if they are highly pressing. + +- console.logs that have been left after debugging +- repeated code +- algorithmic errors that could fail under edge cases +- something that could be refactored + +Make sure to review ALL files that were changed, do not skip any. +`; + +export async function createNewPromptFile( + ide: IDE, + promptPath: string | undefined, +): Promise { + const workspaceDirs = await ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + throw new Error( + "No workspace directories found. Make sure you've opened a folder in your IDE.", + ); + } + const promptFilePath = path.join( + workspaceDirs[0], + promptPath ?? DEFAULT_PROMPTS_FOLDER, + "new-prompt-file.prompt", + ); + + await ide.writeFile(promptFilePath, DEFAULT_PROMPT_FILE); + await ide.openFile(promptFilePath); +} diff --git a/core/promptFiles/getContextProviderHelpers.ts b/core/promptFiles/getContextProviderHelpers.ts new file mode 100644 index 000000000..263724efa --- /dev/null +++ b/core/promptFiles/getContextProviderHelpers.ts @@ -0,0 +1,37 @@ +import Handlebars from "handlebars"; + +export function getContextProviderHelpers( + context: any, +): Array<[string, Handlebars.HelperDelegate]> | undefined { + return context.config.contextProviders?.map((provider: any) => [ + provider.description.title, + async (helperContext: any) => { + const items = await provider.getContextItems(helperContext, { + config: context.config, + embeddingsProvider: context.config.embeddingsProvider, + fetch: context.fetch, + fullInput: context.input, + ide: context.ide, + llm: context.llm, + reranker: context.config.reranker, + selectedCode: context.selectedCode, + }); + + items.forEach((item: any) => + context.addContextItem(createContextItem(item, provider)), + ); + + return items.map((item: any) => item.content).join("\n\n"); + }, + ]); +} + +function createContextItem(item: any, provider: any) { + return { + ...item, + id: { + itemId: item.description, + providerTitle: provider.description.title, + }, + }; +} diff --git a/core/promptFiles/getPromptFiles.ts b/core/promptFiles/getPromptFiles.ts new file mode 100644 index 000000000..2ab9dc893 --- /dev/null +++ b/core/promptFiles/getPromptFiles.ts @@ -0,0 +1,25 @@ +import { IDE } from ".."; +import { walkDir } from "../indexing/walkDir"; + +export async function getPromptFiles( + ide: IDE, + dir: string, +): Promise<{ path: string; content: string }[]> { + try { + const exists = await ide.fileExists(dir); + + if (!exists) { + return []; + } + + const paths = await walkDir(dir, ide, { ignoreFiles: [] }); + const results = paths.map(async (path) => { + const content = await ide.readFile(path); // make a try catch + return { path, content }; + }); + return Promise.all(results); + } catch (e) { + console.error(e); + return []; + } +} diff --git a/core/promptFiles/handlebarUtils.ts b/core/promptFiles/handlebarUtils.ts new file mode 100644 index 000000000..ada9fa6b7 --- /dev/null +++ b/core/promptFiles/handlebarUtils.ts @@ -0,0 +1,114 @@ +import Handlebars from "handlebars"; +import { v4 as uuidv4 } from "uuid"; + +export function convertToLetter(num: number): string { + let result = ""; + while (num > 0) { + const remainder = (num - 1) % 26; + result = String.fromCharCode(97 + remainder) + result; + num = Math.floor((num - 1) / 26); + } + return result; +} + +/** + * We replace filepaths with alphabetic characters to handle + * escaping issues. + */ +export const replaceFilepaths = ( + value: string, + ctxProviderNames: string[], +): [string, { [key: string]: string }] => { + const ast = Handlebars.parse(value); + + const keysToFilepath: { [key: string]: string } = {}; + + let keyIndex = 1; + + for (const i in ast.body) { + const node = ast.body[i] as any; + + if (node.type === "MustacheStatement") { + const originalNodeVal = node.path.original; + const isFilepath = !ctxProviderNames.includes(originalNodeVal); + + if (isFilepath) { + const letter = convertToLetter(keyIndex); + + keysToFilepath[letter] = originalNodeVal; + + value = value.replace( + new RegExp(`{{\\s*${originalNodeVal}\\s*}}`), + `{{${letter}}}`, + ); + + keyIndex++; + } + } + } + + return [value, keysToFilepath]; +}; + +export function registerHelpers( + helpers: Array<[string, Handlebars.HelperDelegate]>, +): { + [key: string]: Promise; +} { + const promises: { [key: string]: Promise } = {}; + + for (const [name, helper] of helpers) { + Handlebars.registerHelper(name, (...args) => { + const id = uuidv4(); + promises[id] = helper(...args); + return `__${id}__`; + }); + } + + return promises; +} + +export async function prepareTemplateAndData( + template: string, + readFile: (filepath: string) => Promise, + inputData: any, + ctxProviderNames: string[], +): Promise<[string, any]> { + const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames); + + const data: any = { ...inputData }; + + for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) { + data[replacedName] = + inputData[originalCtxProviderName] ?? originalCtxProviderName; + + // If it's not a context provider, assume it's a filepath. + if (!ctxProviderNames.includes(originalCtxProviderName)) { + const fileContents = await readFile(vars[replacedName]); + + if (fileContents) { + data[replacedName] = fileContents; + } + } + } + + return [newTemplate, data]; +} + +export function compileAndRenderTemplate(template: string, data: any): string { + const templateFn = Handlebars.compile(template); + return templateFn(data); +} + +export async function resolveHelperPromises( + renderedString: string, + promises: { [key: string]: Promise }, +): Promise { + await Promise.all(Object.values(promises)); + + for (const id in promises) { + renderedString = renderedString.replace(`__${id}__`, await promises[id]); + } + + return renderedString; +} diff --git a/core/promptFiles/index.ts b/core/promptFiles/index.ts new file mode 100644 index 000000000..c3afdec76 --- /dev/null +++ b/core/promptFiles/index.ts @@ -0,0 +1,8 @@ +import { IDE } from ".."; +import { getPromptFiles } from "./getPromptFiles"; +import { createNewPromptFile } from "./createNewPromptFile"; +import { slashCommandFromPromptFile } from "./slashCommandFromPromptFile"; + +export const DEFAULT_PROMPTS_FOLDER = ".prompts"; + +export { getPromptFiles, createNewPromptFile, slashCommandFromPromptFile }; diff --git a/core/promptFiles/renderTemplatedString.ts b/core/promptFiles/renderTemplatedString.ts new file mode 100644 index 000000000..d31cce0b9 --- /dev/null +++ b/core/promptFiles/renderTemplatedString.ts @@ -0,0 +1,30 @@ +import { + compileAndRenderTemplate, + prepareTemplateAndData, + registerHelpers, + resolveHelperPromises, +} from "./handlebarUtils"; + +export async function renderTemplatedString( + template: string, + readFile: (filepath: string) => Promise, + inputData: any, + availableHelpers?: Array<[string, Handlebars.HelperDelegate]>, +): Promise { + const helperPromises = availableHelpers + ? registerHelpers(availableHelpers) + : {}; + + const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? []; + + const [newTemplate, data] = await prepareTemplateAndData( + template, + readFile, + inputData, + ctxProviderNames, + ); + + let renderedString = compileAndRenderTemplate(newTemplate, data); + + return resolveHelperPromises(renderedString, helperPromises); +} diff --git a/core/promptFiles/slashCommandFromPromptFile.ts b/core/promptFiles/slashCommandFromPromptFile.ts new file mode 100644 index 000000000..e81f13615 --- /dev/null +++ b/core/promptFiles/slashCommandFromPromptFile.ts @@ -0,0 +1,93 @@ +import { SlashCommand } from ".."; +import { stripImages } from "../llm/images"; +import { getContextProviderHelpers } from "./getContextProviderHelpers"; +import { renderTemplatedString } from "./renderTemplatedString"; +import { updateChatHistory } from "./updateChatHistory"; +import * as YAML from "yaml"; +import { getBasename } from "../util/index"; + +export function extractName(preamble: { name?: string }, path: string): string { + return preamble.name ?? getBasename(path).split(".prompt")[0]; +} + +export function parsePromptFile(path: string, content: string) { + let [preambleRaw, prompt] = content.split("\n---\n"); + if (prompt === undefined) { + prompt = preambleRaw; + preambleRaw = ""; + } + + const preamble = YAML.parse(preambleRaw) ?? {}; + const name = extractName(preamble, path); + const description = preamble.description ?? name; + + let systemMessage: string | undefined = undefined; + if (prompt.includes("")) { + systemMessage = prompt.split("")[1].split("")[0].trim(); + prompt = prompt.split("")[1].trim(); + } + + return { name, description, systemMessage, prompt }; +} + +export function extractUserInput(input: string, commandName: string): string { + if (input.startsWith(`/${commandName}`)) { + return input.slice(commandName.length + 1).trimStart(); + } + return input; +} + +export async function getDefaultVariables(context: any, userInput: string) { + const currentFilePath = await context.ide.getCurrentFile(); + const currentFile = currentFilePath + ? await context.ide.readFile(currentFilePath) + : undefined; + + return { currentFile, input: userInput }; +} + +export async function renderPrompt( + prompt: string, + context: any, + userInput: string, +) { + const helpers = getContextProviderHelpers(context); + + const inputData = await getDefaultVariables(context, userInput); + + return renderTemplatedString( + prompt, + context.ide.readFile.bind(context.ide), + inputData, + helpers, + ); +} + +export function slashCommandFromPromptFile( + path: string, + content: string, +): SlashCommand { + const { name, description, systemMessage, prompt } = parsePromptFile( + path, + content, + ); + + return { + name, + description, + run: async function* (context) { + const userInput = extractUserInput(context.input, name); + const renderedPrompt = await renderPrompt(prompt, context, userInput); + const messages = updateChatHistory( + context.history, + name, + renderedPrompt, + systemMessage, + ); + + for await (const chunk of context.llm.streamChat(messages)) { + yield stripImages(chunk.content); + } + }, + }; +} diff --git a/core/promptFiles/updateChatHistory.ts b/core/promptFiles/updateChatHistory.ts new file mode 100644 index 000000000..8ebc6f038 --- /dev/null +++ b/core/promptFiles/updateChatHistory.ts @@ -0,0 +1,55 @@ +export function updateChatHistory( + history: any[], + commandName: string, + renderedPrompt: string, + systemMessage?: string, +) { + const messages = [...history]; + + for (let i = messages.length - 1; i >= 0; i--) { + const { role, content } = messages[i]; + if (role !== "user") { + continue; + } + + if (Array.isArray(content)) { + if (content.some((part) => part.text?.startsWith(`/${commandName}`))) { + messages[i] = updateArrayContent( + messages[i], + commandName, + renderedPrompt, + ); + break; + } + } else if ( + typeof content === "string" && + content.startsWith(`/${commandName}`) + ) { + messages[i] = { ...messages[i], content: renderedPrompt }; + break; + } + } + + if (systemMessage) { + messages[0]?.role === "system" + ? (messages[0].content = systemMessage) + : messages.unshift({ role: "system", content: systemMessage }); + } + + return messages; +} + +function updateArrayContent( + message: any, + commandName: string, + renderedPrompt: string, +) { + return { + ...message, + content: message.content.map((part: any) => + part.text?.startsWith(`/${commandName}`) + ? { ...part, text: renderedPrompt } + : part, + ), + }; +} diff --git a/docs/docs/features/prompt-files.md b/docs/docs/features/prompt-files.md index aacd12dcb..34ddbd1c3 100644 --- a/docs/docs/features/prompt-files.md +++ b/docs/docs/features/prompt-files.md @@ -69,8 +69,8 @@ To add a system message, start the body with `` tags like in th The body also supports templating with [Handlebars syntax](https://handlebarsjs.com/guide/). The following variables are currently available: -- `input`: The full text from the input box in the sidebar that is sent along with the slash command -- `currentFile`: The currently open file in your IDE +- `{{{ input }}}`: The full text from the input box in the sidebar that is sent along with the slash command +- `{{{ currentFile }}}`: The currently open file in your IDE #### Context providers diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 695881931..b2ec0dea7 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -320,8 +320,6 @@ const commandsMap: ( // Handle closing the GUI only if we are focused on the input if (fullScreenTab) { fullScreenPanel?.dispose(); - } else { - vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); } } else { // Handle opening the GUI otherwise @@ -480,11 +478,6 @@ const commandsMap: ( //Full screen not open - open it captureCommandTelemetry("openFullScreen"); - // Close the sidebar.webviews - // vscode.commands.executeCommand("workbench.action.closeSidebar"); - vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); - // vscode.commands.executeCommand("workbench.action.toggleZenMode"); - //create the full screen panel let panel = vscode.window.createWebviewPanel( "continue.continueGUIView", @@ -601,8 +594,8 @@ const commandsMap: ( currentStatus === StatusBarStatus.Paused ? StatusBarStatus.Enabled : currentStatus === StatusBarStatus.Disabled - ? StatusBarStatus.Paused - : StatusBarStatus.Disabled; + ? StatusBarStatus.Paused + : StatusBarStatus.Disabled; } else { // Toggle between Disabled and Enabled targetStatus = diff --git a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts index 950f43b5e..66a914402 100644 --- a/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts +++ b/extensions/vscode/src/lang-server/codeLens/providers/QuickActionsCodeLensProvider.ts @@ -95,38 +95,29 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { return [quickEdit]; } - getSymbolsFrom(symbol: vscode.DocumentSymbol): vscode.DocumentSymbol[] { - if (symbol.children.length === 0) { - return [symbol]; - } - - const symbols: vscode.DocumentSymbol[] = []; - - symbols.push(symbol); - - for (const children of symbol.children) { - if (children.children.length === 0) { - symbols.push(children); - } else { - symbols.push(...this.getSymbolsFrom(children)); - } - } - return symbols; - } - - async getAllSymbols(uri: vscode.Uri) { - const docSymbols = await vscode.commands.executeCommand< + /** + * Get all top-level symbols and their immediate children. + * We do not recurse through all children to avoid noise. + */ + async getTopLevelAndChildrenSymbols(uri: vscode.Uri) { + const topLevelSymbols = await vscode.commands.executeCommand< Array | undefined >("vscode.executeDocumentSymbolProvider", uri); - if (!docSymbols) { + if (!topLevelSymbols) { return []; } - const symbols = docSymbols.flatMap((symbol) => this.getSymbolsFrom(symbol)); + const childrenSymbols = topLevelSymbols.flatMap( + (symbol) => symbol.children, + ); - const filteredSmybols = symbols?.filter((def) => - this.quickActionSymbolKinds.includes(def.kind), + const symbols = [...topLevelSymbols, ...childrenSymbols]; + + const filteredSmybols = symbols?.filter( + (symbol) => + this.quickActionSymbolKinds.includes(symbol.kind) && + !symbol.range.isSingleLine, ); return filteredSmybols; @@ -147,7 +138,7 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider { return []; } - const symbols = await this.getAllSymbols(document.uri); + const symbols = await this.getTopLevelAndChildrenSymbols(document.uri); return symbols.flatMap(({ range }) => { const commands: vscode.Command[] = !!this.customQuickActionsConfig diff --git a/extensions/vscode/src/util/ideUtils.ts b/extensions/vscode/src/util/ideUtils.ts index 51f614ff2..15f79ddfd 100644 --- a/extensions/vscode/src/util/ideUtils.ts +++ b/extensions/vscode/src/util/ideUtils.ts @@ -135,22 +135,6 @@ export class VsCodeIdeUtils { ); } - showMultiFileEdit(edits: FileEdit[]) { - vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); - const panel = vscode.window.createWebviewPanel( - "continue.continueGUIView", - "Continue", - vscode.ViewColumn.One, - ); - // panel.webview.html = this.sidebar.getSidebarContent( - // extensionContext, - // panel, - // this.ide, - // "/monaco", - // edits - // ); - } - openFile(filepath: string, range?: vscode.Range) { // vscode has a builtin open/get open files return openEditorAndRevealRange(filepath, range, vscode.ViewColumn.One); @@ -380,7 +364,9 @@ export class VsCodeIdeUtils { const lastLine = lines.pop()?.trim(); if (lastLine) { let i = lines.length - 1; - while (i >= 0 && !lines[i].trim().startsWith(lastLine)) i--; + while (i >= 0 && !lines[i].trim().startsWith(lastLine)) { + i--; + } terminalContents = lines.slice(Math.max(i, 0)).join("\n"); } @@ -400,7 +386,9 @@ export class VsCodeIdeUtils { async getAvailableThreads(): Promise { const session = vscode.debug.activeDebugSession; - if (!session) return []; + if (!session) { + return []; + } const threadsResponse = await this._getThreads(session); return threadsResponse.threads; @@ -449,7 +437,9 @@ export class VsCodeIdeUtils { stackDepth = 3, ): Promise { const session = vscode.debug.activeDebugSession; - if (!session) return []; + if (!session) { + return []; + } const sourcesPromises = await session .customRequest("stackTrace", { @@ -476,7 +466,9 @@ export class VsCodeIdeUtils { } private async retrieveSource(sourceContainer: any): Promise { - if (!sourceContainer.source) return ""; + if (!sourceContainer.source) { + return ""; + } const sourceRef = sourceContainer.source.sourceReference; if (sourceRef && sourceRef > 0) { @@ -498,7 +490,7 @@ export class VsCodeIdeUtils { sourceContainer.endColumn, ), ); - } else if (sourceContainer.line) + } else if (sourceContainer.line) { // fall back to 5 line of context return await this.readRangeInFile( sourceContainer.source.path, @@ -509,7 +501,9 @@ export class VsCodeIdeUtils { 0, ), ); - else return "unavailable"; + } else { + return "unavailable"; + } } private async _getRepo( @@ -557,7 +551,9 @@ export class VsCodeIdeUtils { let i = 0; while (!repo?.state?.HEAD?.name) { - if (this._repoWasNone) return undefined; + if (this._repoWasNone) { + return undefined; + } await new Promise((resolve) => setTimeout(resolve, 1000)); i++; diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index fc07b32e0..7ad231a39 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -2,12 +2,9 @@ import { ArrowRightIcon, ArrowUpOnSquareIcon, AtSymbolIcon, - BeakerIcon, BookOpenIcon, CodeBracketIcon, - Cog6ToothIcon, CommandLineIcon, - CubeIcon, ExclamationCircleIcon, ExclamationTriangleIcon, FolderIcon, @@ -15,10 +12,11 @@ import { GlobeAltIcon, HashtagIcon, MagnifyingGlassIcon, - PaintBrushIcon, + PencilIcon, PlusIcon, SparklesIcon, TrashIcon, + BoltIcon, } from "@heroicons/react/24/outline"; import { Editor } from "@tiptap/react"; import { @@ -62,16 +60,11 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = { docs: BookOpenIcon, issue: ExclamationCircleIcon, trash: TrashIcon, - "/edit": PaintBrushIcon, + "/edit": PencilIcon, "/clear": TrashIcon, - "/test": BeakerIcon, - "/config": Cog6ToothIcon, "/comment": HashtagIcon, "/share": ArrowUpOnSquareIcon, "/cmd": CommandLineIcon, - "/codebase": SparklesIcon, - "/so": GlobeAltIcon, - "/issue": ExclamationCircleIcon, }; function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { @@ -81,41 +74,41 @@ function DropdownIcon(props: { className?: string; item: ComboBoxItem }) { ); } - const provider = - props.item.type === "contextProvider" - ? props.item.id - : props.item.type === "slashCommand" - ? props.item.id - : props.item.type; + const provider = (() => { + switch (props.item.type) { + case "contextProvider": + case "slashCommand": + return props.item.id; + default: + return props.item.type; + } + })(); - const iconClass = `${props.className} flex-shrink-0`; + const IconComponent = + ICONS_FOR_DROPDOWN[provider] ?? + (props.item.type === "contextProvider" ? AtSymbolIcon : BoltIcon); - let fallbackIcon; - const Icon = ICONS_FOR_DROPDOWN[provider]; - if (!Icon) { - fallbackIcon = - props.item.type === "contextProvider" ? ( - - ) : ( - - ); - } else { - fallbackIcon = ; + const fallbackIcon = ( + + ); + + if (!props.item.icon) { + return fallbackIcon; } - if (props.item.icon) { - return ( - - ); - } - - return fallbackIcon; + return ( + + ); } const ItemsDiv = styled.div` @@ -212,6 +205,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { description: "Add a new documentation source", }); } + setAllItems(items); }, [subMenuTitle, props.items, props.editor]); From 28085a0f8918d4419784dbcab524284b3307e2ae Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 6 Aug 2024 12:22:01 -0700 Subject: [PATCH 2/9] Update prompt-files.md (#1940) * Update prompt-files.md * Update prompt-files.md --- docs/docs/features/prompt-files.md | 46 ++++++++++++++++-------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/docs/docs/features/prompt-files.md b/docs/docs/features/prompt-files.md index 34ddbd1c3..89063c8c9 100644 --- a/docs/docs/features/prompt-files.md +++ b/docs/docs/features/prompt-files.md @@ -1,8 +1,12 @@ # Prompt files (experimental) -Prompt (`.prompt`) files are an easy way to build and share LLM prompts with others. The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), and adds templating so that you can easily refer to files, your current git diff, and eventually much more. +Prompt files provide a convenient way to standardize common patterns and share a collection of LLM prompts with your team. They make it easy to build and use these prompts. -## How to create a prompt file +## Quick start + +:::tip[Prompt library] +To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-example). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts! +::: Below is a quick example of setting up a prompt file to write unit tests using Jest. @@ -29,22 +33,23 @@ Write unit tests for the above selected code, following each of these instructio - Don't explain how to set up `jest` ``` -Now to use this prompt, you can highlight code and use cmd/ctrl+L to select it in the Continue sidebar. Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. +Now to use this prompt, you can highlight code and use `cmd/ctrl+L` to select it in the Continue sidebar. -## Examples library +Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file. -To assist you in getting started, we've curated a small library of `.prompt` files. You can access this collection here: +## Format -We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts! +The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to use context providers and built-in variables using [Handlebars syntax](https://handlebarsjs.com/guide/). -## Syntax - -> The current state of this format is experimental and subject to change +:::info +The current state of this format is experimental and subject to change +::: ### Preamble The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters: +- `name` - `temperature` - `topP` - `topK` @@ -54,29 +59,28 @@ The "preamble" is everything above the `---` separator, and lets you specify mod - `mirostat` - `stop` - `maxTokens` -- `name` - `description` If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator. -### Body - -The "body" is everything below the `---` separator, and contains your prompt. - -At its most basic, the body can be just text. +### System message To add a system message, start the body with `` tags like in the example above and place your system message inside. -The body also supports templating with [Handlebars syntax](https://handlebarsjs.com/guide/). The following variables are currently available: +### Built-in variables -- `{{{ input }}}`: The full text from the input box in the sidebar that is sent along with the slash command -- `{{{ currentFile }}}`: The currently open file in your IDE +The following built-in variables are currently available: -#### Context providers +- `{{{ input }}}` - The full text from the input box in the sidebar that is sent along with the slash command +- `{{{ currentFile }}}` - The currently open file in your IDE +- `{{{ ./path/to/file.js }}}` - Any file can be directly referenced -The body of a .prompt file also supports any [context provider](../customization/context-providers.md) that you have added to your config by referencing the name of the context provider. +### Context providers -For example, if you wanted to include the contents of the terminal in your prompt, then you would use `{{{terminal}}}` in your prompt file. If you wanted to use the "url" context provider to include the contents of , you would use `{{{url "https://github.com/continuedev/continue"}}}`, where the second part is the argument to the context provider, separated by a space. +Any [context provider](../customization/context-providers.md) that you have added to your config can be referenced using the name of the context provider. Context providers that receive an input are also supported. + +- `{{{ terminal }}}` - The contents of the terminal +- `{{{ url "https://github.com/continuedev/continue" }}}` - The contents of a URL ## Feedback From fe05db541dafc45c9870d52d9f15e812e1ea90ad Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 6 Aug 2024 13:59:15 -0700 Subject: [PATCH 3/9] fix: handle closed webview on quick edit (#1942) --- .../src/quickEdit/QuickEditQuickPick.ts | 227 ++++++++++-------- extensions/vscode/src/webviewProtocol.ts | 40 +-- 2 files changed, 149 insertions(+), 118 deletions(-) diff --git a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts index 4be583ccd..58f6696c7 100644 --- a/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts +++ b/extensions/vscode/src/quickEdit/QuickEditQuickPick.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/naming-convention */ -import { IDE } from "core"; +import { ContinueConfig, IDE } from "core"; import { walkDir } from "core/indexing/walkDir"; import { Telemetry } from "core/util/posthog"; import * as vscode from "vscode"; @@ -94,6 +94,104 @@ export class QuickEdit { this.initializeFileSearchState(); } + /** + * Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt. + * Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string. + * Displays a quick pick for "Model" to set the current model title. + * Appends the entered prompt to the history and streams the edit with input and context. + */ + async show(args?: QuickEditShowParams) { + // Clean up state from previous quick picks, e.g. if a user pressed `esc` + this.clear(); + + const editor = vscode.window.activeTextEditor; + + // We only allow users to interact with a quick edit if there is an open editor + if (!editor) { + return; + } + + // Set state that is unique to each quick pick instance + this.setActiveEditorAndPrevInput(editor); + + if (!this.editorWhenOpened) { + return; + } + + const config = await this.configHandler.loadConfig(); + + if (!!args?.initialPrompt) { + this.initialPrompt = args.initialPrompt; + } + + if (!!args?.range) { + this.range = args.range; + } + + const selectedLabelOrInputVal = await this._getInitialQuickPickVal(); + + if (!selectedLabelOrInputVal) { + return; + } + + Telemetry.capture("quickEditSelection", { + selection: selectedLabelOrInputVal, + }); + + let prompt: string | undefined = undefined; + + switch (selectedLabelOrInputVal) { + case QuickEditInitialItemLabels.History: + const historyVal = await getHistoryQuickPickVal(this.context); + prompt = historyVal ?? ""; + break; + + case QuickEditInitialItemLabels.ContextProviders: + const contextProviderVal = await getContextProviderQuickPickVal( + config, + this.ide, + ); + this.contextProviderStr = contextProviderVal ?? ""; + + // Recurse back to let the user write their prompt + this.show(args); + + break; + + case QuickEditInitialItemLabels.Model: + const curModelTitle = await this.getCurModelTitle(); + + if (!curModelTitle) { + break; + } + + const selectedModelTitle = await getModelQuickPickVal( + curModelTitle, + config, + ); + + if (selectedModelTitle) { + this._curModelTitle = selectedModelTitle; + } + + // Recurse back to let the user write their prompt + this.show(args); + + break; + + default: + // If it wasn't a label we can assume it was user input + if (selectedLabelOrInputVal) { + prompt = selectedLabelOrInputVal; + appendToHistory(selectedLabelOrInputVal, this.context); + } + } + + if (prompt) { + await this._streamEditWithInputAndContext(prompt); + } + } + private async initializeFileSearchState() { const workspaceDirs = await this.ide.getWorkspaceDirs(); @@ -123,22 +221,31 @@ export class QuickEdit { /** * Gets the model title the user has chosen, or their default model */ - private async _getCurModelTitle() { + private async getCurModelTitle() { const config = await this.configHandler.loadConfig(); if (this._curModelTitle) { return this._curModelTitle; } - let defaultModelTitle = - config.experimental?.modelRoles?.inlineEdit ?? - (await this.webviewProtocol.request("getDefaultModelTitle", undefined)); + const inlineEditModel = config.experimental?.modelRoles?.inlineEdit; - if (!defaultModelTitle) { - defaultModelTitle = config.models[0]?.title!; + if (inlineEditModel) { + return inlineEditModel; } - return defaultModelTitle; + let defaultModelTitle: string | undefined = + await this.webviewProtocol.request( + "getDefaultModelTitle", + undefined, + false, + ); + + if (!defaultModelTitle) { + defaultModelTitle = config.models[0].title; + } + + return defaultModelTitle || inlineEditModel; } /** @@ -148,7 +255,7 @@ export class QuickEdit { * @example * // "Edit myFile.ts", "Edit myFile.ts:5-10", "Edit myFile.ts:15" */ - _getQuickPickTitle = () => { + private getQuickPickTitle = () => { const { uri } = this.editorWhenOpened.document; const fileName = vscode.workspace.asRelativePath(uri, true); @@ -167,7 +274,7 @@ export class QuickEdit { }; private async _streamEditWithInputAndContext(prompt: string) { - const modelTitle = await this._getCurModelTitle(); + const modelTitle = await this.getCurModelTitle(); // Extracts all file references from the prompt string, // which are denoted by an '@' symbol followed by @@ -202,7 +309,13 @@ export class QuickEdit { } async _getInitialQuickPickVal(): Promise { - const modelTitle = await this._getCurModelTitle(); + const modelTitle = await this.getCurModelTitle(); + + if (!modelTitle) { + this.ide.infoPopup("Please configure a model to use Quick Edit"); + return undefined; + } + const { uri } = this.editorWhenOpened.document; const initialItems: vscode.QuickPickItem[] = [ @@ -247,7 +360,7 @@ export class QuickEdit { quickPick.items = initialItems; quickPick.placeholder = "Enter a prompt to edit your code (@ to search files, ⏎ to submit)"; - quickPick.title = this._getQuickPickTitle(); + quickPick.title = this.getQuickPickTitle(); quickPick.ignoreFocusOut = true; quickPick.value = this.initialPrompt ?? ""; @@ -361,94 +474,4 @@ export class QuickEdit { this.initialPrompt = undefined; this.range = undefined; } - - /** - * Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt. - * Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string. - * Displays a quick pick for "Model" to set the current model title. - * Appends the entered prompt to the history and streams the edit with input and context. - */ - async show(args?: QuickEditShowParams) { - // Clean up state from previous quick picks, e.g. if a user pressed `esc` - this.clear(); - - const editor = vscode.window.activeTextEditor; - - // We only allow users to interact with a quick edit if there is an open editor - if (!editor) { - return; - } - - // Set state that is unique to each quick pick instance - this.setActiveEditorAndPrevInput(editor); - - if (!this.editorWhenOpened) { - return; - } - - const config = await this.configHandler.loadConfig(); - - if (!!args?.initialPrompt) { - this.initialPrompt = args.initialPrompt; - } - - if (!!args?.range) { - this.range = args.range; - } - - const selectedLabelOrInputVal = await this._getInitialQuickPickVal(); - - Telemetry.capture("quickEditSelection", { - selection: selectedLabelOrInputVal, - }); - - let prompt: string | undefined = undefined; - - switch (selectedLabelOrInputVal) { - case QuickEditInitialItemLabels.History: - const historyVal = await getHistoryQuickPickVal(this.context); - prompt = historyVal ?? ""; - break; - - case QuickEditInitialItemLabels.ContextProviders: - const contextProviderVal = await getContextProviderQuickPickVal( - config, - this.ide, - ); - this.contextProviderStr = contextProviderVal ?? ""; - - // Recurse back to let the user write their prompt - this.show(args); - - break; - - case QuickEditInitialItemLabels.Model: - const curModelTitle = await this._getCurModelTitle(); - - const selectedModelTitle = await getModelQuickPickVal( - curModelTitle, - config, - ); - - if (selectedModelTitle) { - this._curModelTitle = selectedModelTitle; - } - - // Recurse back to let the user write their prompt - this.show(args); - - break; - - default: - // If it wasn't a label we can assume it was user input - if (selectedLabelOrInputVal) { - prompt = selectedLabelOrInputVal; - appendToHistory(selectedLabelOrInputVal, this.context); - } - } - - if (prompt) { - await this._streamEditWithInputAndContext(prompt); - } - } } diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 3496691c5..6c20f7dcb 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -194,29 +194,37 @@ export class VsCodeWebviewProtocol public request( messageType: T, data: ToWebviewProtocol[T][0], + retry: boolean = true, ): Promise { const messageId = uuidv4(); return new Promise(async (resolve) => { - let i = 0; - while (!this.webview) { - if (i >= 10) { - resolve(undefined); - return; - } else { - await new Promise((res) => setTimeout(res, i >= 5 ? 1000 : 500)); - i++; + if (retry) { + let i = 0; + while (!this.webview) { + if (i >= 10) { + resolve(undefined); + return; + } else { + await new Promise((res) => setTimeout(res, i >= 5 ? 1000 : 500)); + i++; + } } } this.send(messageType, data, messageId); - const disposable = this.webview.onDidReceiveMessage( - (msg: Message) => { - if (msg.messageId === messageId) { - resolve(msg.data); - disposable?.dispose(); - } - }, - ); + + if (this.webview) { + const disposable = this.webview.onDidReceiveMessage( + (msg: Message) => { + if (msg.messageId === messageId) { + resolve(msg.data); + disposable?.dispose(); + } + }, + ); + } else if (!retry) { + resolve(undefined); + } }); } } From 477ecd63acc85be25ec992d4329f6460c42c6785 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 6 Aug 2024 14:42:44 -0700 Subject: [PATCH 4/9] fix: ts ignore declaration file issue w/ dbinfoz (#1945) --- core/context/providers/DatabaseContextProvider.ts | 7 +++---- extensions/vscode/package-lock.json | 8 ++++---- extensions/vscode/package.json | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/core/context/providers/DatabaseContextProvider.ts b/core/context/providers/DatabaseContextProvider.ts index d1a837c45..81a0a2710 100644 --- a/core/context/providers/DatabaseContextProvider.ts +++ b/core/context/providers/DatabaseContextProvider.ts @@ -6,6 +6,7 @@ import { LoadSubmenuItemsArgs, } from "../../index.js"; import { BaseContextProvider } from "../index.js"; +import getDatabaseAdapter from "dbinfoz"; class DatabaseContextProvider extends BaseContextProvider { static description: ContextProviderDescription = { @@ -30,10 +31,9 @@ class DatabaseContextProvider extends BaseContextProvider { const [connectionName, table] = query.split("."); - const { getDatabaseAdapter } = await import("dbinfoz"); - for (const connection of connections) { if (connection.name === connectionName) { + // @ts-ignore (incorrect typings on module's declaration file) const adapter = getDatabaseAdapter( connection.connection_type, connection.connection, @@ -87,9 +87,8 @@ class DatabaseContextProvider extends BaseContextProvider { return contextItems; } - const { getDatabaseAdapter } = await import("dbinfoz"); - for (const connection of connections) { + // @ts-ignore (incorrect typings on module's declaration file) const adapter = getDatabaseAdapter( connection.connection_type, connection.connection, diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index e8848611a..319219691 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -18,7 +18,7 @@ "axios": "^1.2.5", "core": "file:../../core", "cors": "^2.8.5", - "dbinfoz": "^0.1.4", + "dbinfoz": "^0.11.0", "downshift": "^7.6.0", "esbuild": "^0.17.19", "express": "^4.18.2", @@ -3918,9 +3918,9 @@ } }, "node_modules/dbinfoz": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.1.4.tgz", - "integrity": "sha512-MB56+xS571ip7qoXqxdnOUtXebbWaqoZN+S++W51SQYJRSjQFGEIPucNmxgeQlBGJ1vM4mQNV47wzV6fcrezZg==", + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.11.0.tgz", + "integrity": "sha512-l7REBd9pwTBI6PWSk/dx+zCpSE2tiJdSKfApeoOajnSgyMJgkwGfhpPO2mV76MLQeKPaSm0mMKxmoqd38SaHmw==", "dependencies": { "mysql2": "^3.9.1", "pg": "^8.11.3", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 28a4a4a61..eda6c3fd4 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -579,7 +579,7 @@ "axios": "^1.2.5", "core": "file:../../core", "cors": "^2.8.5", - "dbinfoz": "^0.1.4", + "dbinfoz": "^0.11.0", "downshift": "^7.6.0", "esbuild": "^0.17.19", "express": "^4.18.2", From a3cee9195e7e770b1005de7bf660b8b4710e5576 Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Tue, 6 Aug 2024 16:09:38 -0700 Subject: [PATCH 5/9] chore: bump target and lib versions for tsconfig (#1949) --- extensions/vscode/tsconfig.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/tsconfig.json b/extensions/vscode/tsconfig.json index b160ec053..639fc167c 100644 --- a/extensions/vscode/tsconfig.json +++ b/extensions/vscode/tsconfig.json @@ -1,9 +1,9 @@ { "compilerOptions": { "module": "commonjs", - "target": "ES2020", + "target": "ES2022", + "lib": ["ES2022", "dom", "es6", "es5", "dom.iterable", "scripthost"], "outDir": "out/tsc/src", - "lib": ["ES2021", "dom", "es6", "es5", "dom.iterable", "scripthost"], "sourceMap": true, "rootDir": "../../", "strict": true /* enable all strict type-checking options */, From dfbc6aabcb41c739a8f209c0d3618023fb10d6fe Mon Sep 17 00:00:00 2001 From: Rob Leidle Date: Tue, 6 Aug 2024 16:14:05 -0700 Subject: [PATCH 6/9] Convert ChunkCodebaseIndexer's sqlite inserts into a single bulk insert to improve performance (#1943) This change greatly improves the performance when inserting chunks. Co-authored-by: Rob Leidle --- core/indexing/chunk/ChunkCodebaseIndex.ts | 166 ++++++++++++---------- 1 file changed, 93 insertions(+), 73 deletions(-) diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index eba76ad8b..aff9d7c52 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -1,10 +1,13 @@ +import { RunResult } from "sqlite3"; import { IContinueServerClient } from "../../continueServer/interface.js"; import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js"; import { getBasename } from "../../util/index.js"; +import { getLanguageForFile } from "../../util/treeSitter.js"; import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js"; import { IndexResultType, MarkCompleteCallback, + PathAndCacheKey, RefreshIndexResults, type CodebaseIndex, } from "../types.js"; @@ -23,27 +26,6 @@ export class ChunkCodebaseIndex implements CodebaseIndex { this.readFile = readFile; } - private async _createTables(db: DatabaseConnection) { - await db.exec("PRAGMA journal_mode=WAL;"); - - await db.exec(`CREATE TABLE IF NOT EXISTS chunks ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - cacheKey TEXT NOT NULL, - path TEXT NOT NULL, - idx INTEGER NOT NULL, - startLine INTEGER NOT NULL, - endLine INTEGER NOT NULL, - content TEXT NOT NULL - )`); - - await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - tag TEXT NOT NULL, - chunkId INTEGER NOT NULL, - FOREIGN KEY (chunkId) REFERENCES chunks (id) - )`); - } - async *update( tag: IndexTag, results: RefreshIndexResults, @@ -51,28 +33,9 @@ export class ChunkCodebaseIndex implements CodebaseIndex { repoName: string | undefined, ): AsyncGenerator { const db = await SqliteDb.get(); - await this._createTables(db); + await this.createTables(db); const tagString = tagToString(tag); - async function handleChunk(chunk: Chunk) { - const { lastID } = await db.run( - "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)", - [ - chunk.digest, - chunk.filepath, - chunk.index, - chunk.startLine, - chunk.endLine, - chunk.content, - ], - ); - - await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [ - lastID, - tagString, - ]); - } - // Check the remote cache if (this.continueServerClient.connected) { try { @@ -84,9 +47,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex { ); for (const [cacheKey, chunks] of Object.entries(resp.files)) { - for (const chunk of chunks) { - await handleChunk(chunk); - } + await this.insertChunks(db, tagString, chunks); } results.compute = results.compute.filter( (item) => !resp.files[item.cacheKey], @@ -96,37 +57,15 @@ export class ChunkCodebaseIndex implements CodebaseIndex { } } - const progressReservedForTagging = 0.3; let accumulatedProgress = 0; - // Compute chunks for new files - const contents = await Promise.all( - results.compute.map(({ path }) => this.readFile(path)), - ); - for (let i = 0; i < results.compute.length; i++) { - const item = results.compute[i]; - - // Insert chunks - if (contents.length) { - for await (const chunk of chunkDocument({ - filepath: item.path, - contents: contents[i], - maxChunkSize: this.maxChunkSize, - digest: item.cacheKey, - })) { - await handleChunk(chunk); - } - } - - accumulatedProgress = - (i / results.compute.length) * (1 - progressReservedForTagging); - yield { - progress: accumulatedProgress, - desc: `Chunking ${getBasename(item.path)}`, - status: "indexing", - }; - markComplete([item], IndexResultType.Compute); - } + yield { + desc: `Chunking ${results.compute.length} ${this.formatListPlurality("file", results.compute.length)}`, + status: "indexing", + progress: accumulatedProgress, + }; + const chunks = await this.computeChunks(results.compute); + await this.insertChunks(db, tagString, chunks); // Add tag for (const item of results.addTag) { @@ -189,4 +128,85 @@ export class ChunkCodebaseIndex implements CodebaseIndex { }; } } + + + private async createTables(db: DatabaseConnection) { + await db.exec("PRAGMA journal_mode=WAL;"); + + await db.exec(`CREATE TABLE IF NOT EXISTS chunks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + cacheKey TEXT NOT NULL, + path TEXT NOT NULL, + idx INTEGER NOT NULL, + startLine INTEGER NOT NULL, + endLine INTEGER NOT NULL, + content TEXT NOT NULL + )`); + + await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tag TEXT NOT NULL, + chunkId INTEGER NOT NULL, + FOREIGN KEY (chunkId) REFERENCES chunks (id) + )`); + } + + private async packToChunks(pack: PathAndCacheKey): Promise { + const contents = await this.readFile(pack.path); + if (!contents.length) { + return []; + } + const chunks: Chunk[] = []; + const chunkParams = { + filepath: pack.path, + contents, + maxChunkSize: this.maxChunkSize, + digest: pack.cacheKey, + }; + for await (const c of chunkDocument(chunkParams)) { + chunks.push(c); + } + return chunks; + } + + private async computeChunks(paths: PathAndCacheKey[]): Promise { + const chunkLists = await Promise.all(paths.map(this.packToChunks.bind(this))); + return chunkLists.flat(); + } + + private async insertChunks(db: DatabaseConnection, tagString: string, chunks: Chunk[]) { + await new Promise((resolve, reject) => { + db.db.serialize(() => { + db.db.exec("BEGIN", (err: Error | null) => { + if (err) { + reject(new Error("error creating transaction", { cause: err })); + } + }); + const chunksSQL = "INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)"; + chunks.map(c => { + db.db.run(chunksSQL, [c.digest, c.filepath, c.index, c.startLine, c.endLine, c.content], (result: RunResult, err: Error) => { + if (err) { + reject(new Error("error inserting into chunks table", { cause: err })); + } + }); + const chunkTagsSQL = "INSERT INTO chunk_tags (chunkId, tag) VALUES (last_insert_rowid(), ?)"; + db.db.run(chunkTagsSQL, [ tagString ], (result: RunResult, err: Error) => { + if (err) { + reject(new Error("error inserting into chunk_tags table", { cause: err })); + } + }); + }); + db.db.exec("COMMIT", (err: Error | null) => { + if (err) { + reject(new Error("error while committing insert chunks transaction", { cause: err })); + } + }); + resolve(); + }); + }); + } + + private formatListPlurality(word: string, length: number): string { + return length <= 1 ? word : `${word}s`; + } } From 88c72c342673d74d55cacd2b7a38119e6ad089b1 Mon Sep 17 00:00:00 2001 From: Rob Leidle Date: Tue, 6 Aug 2024 16:14:17 -0700 Subject: [PATCH 7/9] Change the LanceDBIndex to compute its new cache rows in parallel and then do a bulk insert (#1944) This greatly improves the performance of indexing. Combined with the change for bulk inserts in ChunkCodebaseIndexer, indexing is over twice as fast. However, it can be much faster if the other indexers are converted to use bulk insert as well. In addition, this indexer is not using the computed chunks in the chunk table. It would be faster to reference the already computed chunks, however, for the purposes of this PR we are not changing that behavior. Co-authored-by: Rob Leidle --- core/indexing/LanceDbIndex.ts | 228 +++++++++++++++++----------------- 1 file changed, 112 insertions(+), 116 deletions(-) diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 9a5d94e07..84333b439 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -19,6 +19,7 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; +import { RunResult } from "sqlite3"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { @@ -84,96 +85,76 @@ export class LanceDbIndex implements CodebaseIndex { ); } - private async *computeChunks( - items: PathAndCacheKey[], - ): AsyncGenerator< - | [ - number, - LanceDbRow, - { startLine: number; endLine: number; contents: string }, - string, - ] - | PathAndCacheKey - > { - const contents = await Promise.all( - items.map(({ path }) => this.readFile(path)), - ); - - for (let i = 0; i < items.length; i++) { - // Break into chunks - const content = contents[i]; - const chunks: Chunk[] = []; - - let hasEmptyChunks = false; - - for await (const chunk of chunkDocument({ - filepath: items[i].path, - contents: content, - maxChunkSize: this.embeddingsProvider.maxChunkSize, - digest: items[i].cacheKey, - })) { - if (chunk.content.length == 0) { - hasEmptyChunks = true; - break; - } - chunks.push(chunk); - } - - if (hasEmptyChunks) { + private async packToRows(item: PathAndCacheKey): Promise { + const content = await this.readFile(item.path); + const chunks: Chunk[] = []; + const chunkParams = { + filepath: item.path, + contents: content, + maxChunkSize: this.embeddingsProvider.maxChunkSize, + digest: item.cacheKey, + }; + for await (const chunk of chunkDocument(chunkParams)) { + if (chunk.content.length === 0) { // File did not chunk properly, let's skip it. - continue; + throw new Error(`did not chunk properly`); } - + chunks.push(chunk); if (chunks.length > 20) { // Too many chunks to index, probably a larger file than we want to include - continue; + throw new Error(`too large to index`); } - - let embeddings: number[][]; - try { - // Calculate embeddings - embeddings = await this.embeddingsProvider.embed( - chunks.map((c) => c.content), - ); - } catch (e) { - // Rather than fail the entire indexing process, we'll just skip this file - // so that it may be picked up on the next indexing attempt - console.warn( - `Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${e}`, - ); - continue; - } - - if (embeddings.some((emb) => emb === undefined)) { - throw new Error( - `Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}`, - ); - } - - // Create row format - for (let j = 0; j < chunks.length; j++) { - const progress = (i + j / chunks.length) / items.length; - const row = { - vector: embeddings[j], - path: items[i].path, - cachekey: items[i].cacheKey, - uuid: uuidv4(), - }; - const chunk = chunks[j]; - yield [ - progress, - row, - { - contents: chunk.content, - startLine: chunk.startLine, - endLine: chunk.endLine, - }, - `Indexing ${getBasename(chunks[j].filepath)}`, - ]; - } - - yield items[i]; } + const embeddings = await this.chunkListToEmbedding(chunks); + if (chunks.length !== embeddings.length) { + throw new Error(`Unexpected lengths: chunks and embeddings do not match for ${item.path}`); + } + const results = []; + for (let i = 0; i < chunks.length; i++) { + results.push({ + path: item.path, + cachekey: item.cacheKey, + uuid: uuidv4(), + vector: embeddings[i], + startLine: chunks[i].startLine, + endLine: chunks[i].endLine, + contents: chunks[i].content, + }) + } + return results; + } + + private async chunkListToEmbedding(chunks: Chunk[]): Promise { + let embeddings: number[][]; + try { + embeddings = await this.embeddingsProvider.embed(chunks.map((c) => c.content)); + } catch (err) { + throw new Error( + `Failed to generate embedding for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}: ${err}`, + { cause: err } + ); + } + if (embeddings.some((emb) => emb === undefined)) { + throw new Error( + `Empty embedding returned for ${chunks[0]?.filepath} with provider: ${this.embeddingsProvider.id}` + ); + } + return embeddings; + } + + private async computeRows( + items: PathAndCacheKey[], + ): Promise { + const rowChunkPromises = items.map(this.packToRows.bind(this)); + const rowChunkLists = [] + for (let i = 0; i < items.length; i++) { + try { + rowChunkLists.push(await rowChunkPromises[i]); + } catch (err) { + console.log(`LanceDBIndex, skipping ${items[i].path}: ${err}`); + } + } + return rowChunkLists.flat(); } async *update( @@ -279,40 +260,15 @@ export class LanceDbIndex implements CodebaseIndex { } } - const progressReservedForTagging = 0.1; + yield { + progress: 0, + desc: `Computing embeddings for ${results.compute.length} ${this.formatListPlurality("file", results.compute.length)}`, + status: "indexing", + }; + const dbRows = await this.computeRows(results.compute); + this.insertRows(sqlite, dbRows); let accumulatedProgress = 0; - let computedRows: LanceDbRow[] = []; - for await (const update of this.computeChunks(results.compute)) { - if (Array.isArray(update)) { - const [progress, row, data, desc] = update; - computedRows.push(row); - - // Add the computed row to the cache - await sqlite.run( - "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - row.uuid, - row.cachekey, - row.path, - this.artifactId, - JSON.stringify(row.vector), - data.startLine, - data.endLine, - data.contents, - ); - - accumulatedProgress = progress * (1 - progressReservedForTagging); - yield { - progress: accumulatedProgress, - desc, - status: "indexing", - }; - } else { - await addComputedLanceDbRows(update, computedRows); - computedRows = []; - } - } - // Add tag - retrieve the computed info from lance sqlite cache for (const { path, cacheKey } of results.addTag) { const stmt = await sqlite.prepare( @@ -468,4 +424,44 @@ export class LanceDbIndex implements CodebaseIndex { }; }); } + + private async insertRows(db: DatabaseConnection, rows: LanceDbRow[]): Promise { + return new Promise((resolve, reject) => { + db.db.serialize(() => { + db.db.exec("BEGIN", (err: Error | null) => { + if (err) { + reject(new Error("error creating transaction", { cause: err })); + } + }); + + const sql = "INSERT INTO lance_db_cache (uuid, cacheKey, path, artifact_id, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + rows.map(r => { + db.db.run(sql, [ + r.uuid, + r.cachekey, + r.path, + this.artifactId, + JSON.stringify(r.vector), + r.startLine, + r.endLine, + r.contents, + ], (result: RunResult, err: Error) => { + if (err) { + reject(new Error("error inserting into lance_db_cache table", { cause: err })); + } + }); + }); + db.db.exec("COMMIT", (err: Error | null) => { + if (err) { + reject(new Error("error while committing insert into lance_db_rows transaction", { cause: err })); + } + }); + resolve(); + }); + }); + } + + private formatListPlurality(word: string, length: number): string { + return length <= 1 ? word : `${word}s`; + } } From 8a278ff8b41f45794600e2ec457e9ca307af0a2c Mon Sep 17 00:00:00 2001 From: Rob Leidle Date: Tue, 6 Aug 2024 16:18:49 -0700 Subject: [PATCH 8/9] Enable async encoding for the GPTEncoder (#1946) This will improve the performance of indexing when using a GPT model. Also, improved the Async interface to also have an async decode method. Note: I was only able to test this method with the test I added as I do not have access to a GPT model. Co-authored-by: Rob Leidle --- core/llm/asyncEncoder.ts | 32 +++++++++++++------ core/llm/llamaTokenizerWorkerPool.mjs | 5 +++ core/llm/tiktokenWorkerPool.mjs | 17 ++++++++++ core/test/llm/asyncEncoder.test.ts | 41 +++++++++++++++++++++++++ extensions/vscode/scripts/prepackage.js | 1 + 5 files changed, 87 insertions(+), 9 deletions(-) create mode 100644 core/llm/tiktokenWorkerPool.mjs create mode 100644 core/test/llm/asyncEncoder.test.ts diff --git a/core/llm/asyncEncoder.ts b/core/llm/asyncEncoder.ts index 722664ead..ed6425df2 100644 --- a/core/llm/asyncEncoder.ts +++ b/core/llm/asyncEncoder.ts @@ -5,22 +5,23 @@ import * as path from "path"; export interface AsyncEncoder { encode(text: string): Promise; - decode(tokens: number[]): string; + decode(tokens: number[]): Promise; + close(): Promise; } export class LlamaAsyncEncoder implements AsyncEncoder { private workerPool: workerpool.Pool; constructor() { - this.workerPool = workerpool.pool(path.join(__dirname, "/llamaTokenizerWorkerPool.mjs")); + this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs")); } async encode(text: string): Promise { return this.workerPool.exec("encode", [text]); } - decode(tokens: number[]): string { - return llamaTokenizer.decode(tokens); + async decode(tokens: number[]): Promise { + return this.workerPool.exec("decode", [tokens]); } // TODO: this should be called somewhere before exit or potentially with a shutdown hook @@ -31,17 +32,30 @@ export class LlamaAsyncEncoder implements AsyncEncoder { // this class does not yet do anything asynchronous export class GPTAsyncEncoder implements AsyncEncoder { - private tiktokenEncoding: Tiktoken; + private workerPool: workerpool.Pool; constructor() { - this.tiktokenEncoding = _encodingForModel("gpt-4"); + this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs")); } async encode(text: string): Promise { - return this.tiktokenEncoding.encode(text, "all", []); + return this.workerPool.exec("encode", [text]); } - decode(tokens: number[]): string { - return this.tiktokenEncoding.decode(tokens); + async decode(tokens: number[]): Promise { + return this.workerPool.exec("decode", [tokens]); } + + // TODO: this should be called somewhere before exit or potentially with a shutdown hook + public async close(): Promise { + await this.workerPool.terminate(); + } +} + +function workerCodeFilePath(workerFileName: string): string { + if (process.env.NODE_ENV === "test") { + // `cross-env` seems to make it so __dirname is the root of the project and not the directory containing this file + return path.join(__dirname, "llm", workerFileName); + } + return path.join(__dirname, workerFileName); } \ No newline at end of file diff --git a/core/llm/llamaTokenizerWorkerPool.mjs b/core/llm/llamaTokenizerWorkerPool.mjs index 2131f4a1a..1ef82c872 100644 --- a/core/llm/llamaTokenizerWorkerPool.mjs +++ b/core/llm/llamaTokenizerWorkerPool.mjs @@ -5,6 +5,11 @@ function encode(segment) { return llamaTokenizer.encode(segment); } +function decode(tokens) { + return llamaTokenizer.decode(tokens); +} + workerpool.worker({ + decode, encode, }); \ No newline at end of file diff --git a/core/llm/tiktokenWorkerPool.mjs b/core/llm/tiktokenWorkerPool.mjs new file mode 100644 index 000000000..9e0462f33 --- /dev/null +++ b/core/llm/tiktokenWorkerPool.mjs @@ -0,0 +1,17 @@ +import workerpool from "workerpool"; +import { encodingForModel as _encodingForModel } from "js-tiktoken"; + +const tiktokenEncoding = _encodingForModel("gpt-4"); + +function encode(text) { + return tiktokenEncoding.encode(text, "all", []); +} + +function decode(tokens) { + return tiktokenEncoding.decode(tokens); +} + +workerpool.worker({ + decode, + encode, +}); \ No newline at end of file diff --git a/core/test/llm/asyncEncoder.test.ts b/core/test/llm/asyncEncoder.test.ts new file mode 100644 index 000000000..f181a05ca --- /dev/null +++ b/core/test/llm/asyncEncoder.test.ts @@ -0,0 +1,41 @@ +import { GPTAsyncEncoder, LlamaAsyncEncoder } from "../../llm/asyncEncoder"; + +describe("llama encoder", () => { + var tokenizer: LlamaAsyncEncoder; + + beforeAll(() => { + tokenizer = new LlamaAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); + +describe("tiktoken encoder", () => { + var tokenizer: GPTAsyncEncoder; + + beforeAll(() => { + tokenizer = new GPTAsyncEncoder(); + }); + + afterAll(() => { + tokenizer.close(); + }); + + test("hello world", async () => { + const input = "the quick brown fox jumped over the lazy dog"; + const output = await tokenizer.encode(input); + expect(output).toEqual([1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679]); + const decoded = await tokenizer.decode(output); + expect(decoded).toBe(input); + }); +}); \ No newline at end of file diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 95aaf0010..f7ca0e5d7 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -245,6 +245,7 @@ const exe = os === "win32" ? ".exe" : ""; "../../../core/vendor/tree-sitter.wasm", "../../../core/llm/llamaTokenizerWorkerPool.mjs", "../../../core/llm/llamaTokenizer.mjs", + "../../../core/llm/tiktokenWorkerPool.mjs", ]; for (const f of filesToCopy) { fs.copyFileSync(path.join(__dirname, f), path.join(__dirname, "..", "out", path.basename(f))); From fed8ace39a3e431b34d8fff34c9e5d7a6030fc37 Mon Sep 17 00:00:00 2001 From: Priyash <38959321+priyashpatil@users.noreply.github.com> Date: Wed, 7 Aug 2024 04:49:14 +0530 Subject: [PATCH 9/9] docs: add privacy section with more details on telemetry and development data (#1910) --- docs/docs/development-data.md | 54 +++++++++++++++++++++++++++++++---- docs/docs/telemetry.md | 49 +++++++++++++++++++------------ docs/sidebars.js | 17 +++++++++-- 3 files changed, 95 insertions(+), 25 deletions(-) diff --git a/docs/docs/development-data.md b/docs/docs/development-data.md index 6432197b3..3f230d0ed 100644 --- a/docs/docs/development-data.md +++ b/docs/docs/development-data.md @@ -1,11 +1,55 @@ --- -title: 🧑‍💻 Development data +title: Development Data description: Collecting data on how you build software -keywords: [development data, dev data, LLM-aided development] +keywords: [development data, dev data, LLM-aided development, software development, coding feedback] --- -# 🧑‍💻 Development Data +# Development Data -When you use Continue, you automatically collect data on how you build software. By default, this development data is saved to `.continue/dev_data` on your local machine. When combined with the code that you ultimately commit, it can be used to improve the LLM that you or your team use (if you allow). +## Why You Need Development Data -You can read more about how development data is generated as a byproduct of LLM-aided development and why we believe that you should start collecting it now: [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software) +Development data is essential for any organization aiming to optimize its software development process. It provides crucial insights into how software is built by capturing the detailed workflow, context behind decisions, and natural language reasoning used during coding. Collecting and utilizing this data helps in: + +- **Improving LLMs**: Enhancing the performance and relevance of Large Language Models (LLMs) that assist in coding, making them more accurate and helpful. +- **Understanding Developer Challenges**: Identifying what frustrates developers and how they overcome challenges. +- **Demonstrating ROI**: Calculating the return on investment (ROI) of using LLMs within your organization. +- **Continual Improvement**: Establishing a continuous feedback loop to keep LLMs updated with the latest information, code, and preferred styles. + +## Understanding Development Data + +### Data Components + +- **Step-by-Step Process**: Detailed record of each step taken while completing a task. +- **Context Capture**: Information used to make decisions, such as code snippets, documentation, and logs. +- **Natural Language Reasoning**: Explanations and decisions made in natural language during coding. + +### Data Storage + +By default, the development data collected by Continue is stored locally on your machine in the directory `~/.continue/dev_data`. + +The data remains within your control on your local machine. If you choose to share your data with Continue for improving LLMs or other services, you must give explicit consent. If you are interested in working with us, please email us at [data@continue.dev](mailto:data@continue.dev). + +## Utilizing Development Data + +When combined with the code you commit, the development data can significantly improve the performance and relevance of LLMs. This results in more accurate suggestions and assistance during coding. Continue helps establish a continuous feedback loop to ensure LLMs always have fresh information, code, and preferred styles. + +Continue plays a critical role in leveraging development data for enhancing LLMs: + +- **Automatic Data Collection**: Continue automatically collects development data, including the step-by-step process, context, and natural language reasoning. + +- **Improvement of LLMs**: The collected data is used to create a continuous feedback loop, ensuring the LLMs are constantly updated with fresh and relevant information, thus improving their performance and accuracy. + +- **Development Data Engine**: Continue aids organizations in setting up development data engines. These engines offer visibility into how developers interact with LLMs, help calculate the ROI, identify frustrations, and enhance the models to overcome challenges. + +- **Open-Source Coding Autopilot**: Continue is building an open-source coding autopilot that enables the automatic collection and utilization of development data, providing flexibility, customization, and better privacy and security. + +- **Customized Improvement**: Continue allows teams to track and improve the metrics that matter most to their specific definitions of "great" software. + +- **Addressing Budget and Data Staleness**: Continue supports organizations in justifying their LLM budgets and managing data staleness by helping them extract, load, and transform their data effectively. + +## Privacy, Security, and Additional Resources + +Understanding the privacy and security implications of development data collection is crucial. Ensure that sensitive information is safeguarded and that data collection aligns with your organization's privacy policies. For more detailed insights and guidelines, refer to the following: + +- [Privacy Policy](https://continue.dev/privacy) +- [It’s time to collect data on how you build software](https://blog.continue.dev/its-time-to-collect-data-on-how-you-build-software) (Article) diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index 886f129c8..144e8cd59 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -1,40 +1,53 @@ --- -title: 🦔 Telemetry -description: Continue collects anonymous usage information +title: Telemetry +description: Learn how Continue collects anonymous usage information and how you can opt out. keywords: [telemetry, anonymous, usage info, opt out] --- -# 🦔 Telemetry +# Telemetry ## Overview -Continue collects and reports **anonymous** usage information. +Continue collects and reports **anonymous** usage information to help us improve our product. This data enables us to understand user interactions and optimize the user experience effectively. You can opt out of telemetry collection at any time if you prefer not to share your usage information. -This data is essential to understanding how we should improve the product. You can opt out of it at any time. +We utilize [Posthog](https://posthog.com/), an open-source platform for product analytics, to gather and store this data. For transparency, you can review the implementation code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx) or read our [official privacy policy](https://continue.dev/privacy). -We use [Posthog](https://posthog.com/), an open source platform for product analytics, to collect and store the data. You can review the code [here](https://github.com/continuedev/continue/blob/main/gui/src/hooks/CustomPostHogProvider.tsx), or review our official policy [here](https://continue.dev/privacy). +## Tracking Policy -## Tracking policy +All data collected by Continue is anonymized and stripped of personally identifiable information (PII) before being sent to PostHog. We are committed to maintaining the privacy and security of your data. -All data is anonymous and cleaned of PII before being sent to PostHog. +## What We Track -## What we track +The following usage information is collected and reported: -- Whether you accept or reject suggestions (never including the code or the prompt) -- The name of the model and command used -- The number of tokens generated -- The name of your OS and IDE -- Pageviews +- **Suggestion Interactions:** Whether you accept or reject suggestions (excluding the actual code or prompts involved). +- **Model and Command Information:** The name of the model and command used. +- **Token Metrics:** The number of tokens generated. +- **System Information:** The name of your operating system (OS) and integrated development environment (IDE). +- **Pageviews:** General pageview statistics. -## How to opt out +## How to Opt Out -The `~/.continue` directory contains a `config.json` file that looks like this: +You can disable anonymous telemetry by modifying the `config.json` file located in the `~/.continue` directory. This file typically includes the following entry: ```json title="~/.continue/config.json" { "allowAnonymousTelemetry": true, - ... } ``` -You can turn off anonymous telemetry by changing the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can uncheck the "Continue: Telemetry Enabled" box in VS Code settings. +To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box. + +### Steps to Disable Telemetry via Configuration File + +1. Open the `~/.continue/config.json` file in your text editor. +2. Locate the `"allowAnonymousTelemetry"` setting. +3. Change the value from `true` to `false`. +4. Save the file. + +### Steps to Disable Telemetry via VS Code Settings + +1. Open VS Code. +2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut `Ctrl+,` on Windows/Linux or `Cmd+,` on macOS). +3. In the search bar, type "Continue: Telemetry Enabled". +4. Uncheck the "Continue: Telemetry Enabled" checkbox. diff --git a/docs/sidebars.js b/docs/sidebars.js index f38b4aec6..84493e2bd 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -59,8 +59,21 @@ const sidebars = { collapsed: true, items: ["walkthroughs/set-up-codestral", "walkthroughs/llama3.1"], }, - "development-data", - "telemetry", + { + type: "category", + label: "🧑‍💻 Privacy", + collapsible: true, + collapsed: true, + items: [ + "development-data", + "telemetry", + { + type: 'link', + label: 'Privacy Policy', + href: 'https://www.continue.dev/privacy', + }, + ], + }, "troubleshooting", { type: "category",