diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index 568a30af8..38df9a775 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -21,6 +21,7 @@ export const sharedConfigSchema = z useCurrentFileAsContext: z.boolean(), optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), + onlyUseSystemMessageTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), enableStaticContextualization: z.boolean(), @@ -185,6 +186,11 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.optInNextEditFeature = sharedConfig.optInNextEditFeature; } + if (sharedConfig.onlyUseSystemMessageTools !== undefined) { + configCopy.experimental.onlyUseSystemMessageTools = + sharedConfig.onlyUseSystemMessageTools; + } + if (sharedConfig.codebaseToolCallingOnly !== undefined) { configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; diff --git a/core/config/types.ts b/core/config/types.ts index 9aa061a55..c90220ed4 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -1121,7 +1121,6 @@ declare global { * This is needed to crawl a large number of documentation sites that are dynamically rendered. */ useChromiumForDocsCrawling?: boolean; - useTools?: boolean; modelContextProtocolServers?: MCPOptions[]; } diff --git a/core/index.d.ts b/core/index.d.ts index 8a35f1166..f5b560a40 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1084,6 +1084,7 @@ export interface Tool { faviconUrl?: string; group: string; originalFunctionName?: string; + systemMessageDescription?: string; } interface ToolChoice { @@ -1514,6 +1515,7 @@ export interface ExperimentalConfig { defaultContext?: DefaultContextProvider[]; promptPath?: string; enableExperimentalTools?: boolean; + onlyUseSystemMessageTools?: boolean; /** * Quick actions are a way to add custom commands to the Code Lens of diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index a220b5dbd..92693456d 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,9 +1,4 @@ -import { - ChatMessage, - ModelCapability, - ModelDescription, - TemplateType, -} from "../index.js"; +import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; import { anthropicTemplateMessages, @@ -41,7 +36,6 @@ import { xWinCoderEditPrompt, zephyrEditPrompt, } from "./templates/edit.js"; -import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js"; const PROVIDER_HANDLES_TEMPLATING: string[] = [ "lmstudio", @@ -107,17 +101,6 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "granite-vision", ]; -function modelSupportsTools(modelDescription: ModelDescription) { - if (modelDescription.capabilities?.tools !== undefined) { - return modelDescription.capabilities.tools; - } - const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; - if (!providerSupport) { - return false; - } - return providerSupport(modelDescription.model) ?? false; -} - function modelSupportsImages( provider: string, model: string, @@ -400,5 +383,4 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, - modelSupportsTools, }; diff --git a/core/llm/index.ts b/core/llm/index.ts index 6a67cac6c..f280eedd4 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -531,7 +531,7 @@ export abstract class BaseLLM implements ILLM { let contentToShow = ""; if (msg.role === "tool") { contentToShow = msg.content; - } else if (msg.role === "assistant" && msg.toolCalls) { + } else if (msg.role === "assistant" && msg.toolCalls?.length) { contentToShow = msg.toolCalls ?.map( (toolCall) => @@ -539,10 +539,7 @@ export abstract class BaseLLM implements ILLM { ) .join("\n"); } else if ("content" in msg) { - if (Array.isArray(msg.content)) { - msg.content = renderChatMessage(msg); - } - contentToShow = msg.content; + contentToShow = renderChatMessage(msg); } return `<${msg.role}>\n${contentToShow}\n\n`; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index a3b643c34..a7edbbd36 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -1,4 +1,5 @@ import { parseProxyModelName } from "@continuedev/config-yaml"; +import { ModelDescription } from ".."; export const PROVIDER_TOOL_SUPPORT: Record boolean> = { @@ -288,3 +289,31 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, }; + +export function isRecommendedAgentModel(modelName: string): boolean { + // AND behavior + const recs: RegExp[][] = [ + [/o[134]/], + [/deepseek/, /r1|reasoner/], + [/gemini/, /2\.5/, /pro/], + [/gpt/, /4/], + [/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/], + [/claude/, /opus/, /-4/], + ]; + for (const combo of recs) { + if (combo.every((regex) => modelName.toLowerCase().match(regex))) { + return true; + } + } + return false; +} +export function modelSupportsNativeTools(modelDescription: ModelDescription) { + if (modelDescription.capabilities?.tools !== undefined) { + return modelDescription.capabilities.tools; + } + const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider]; + if (!providerSupport) { + return false; + } + return providerSupport(modelDescription.model) ?? false; +} diff --git a/core/tools/constants.ts b/core/tools/constants.ts new file mode 100644 index 000000000..0b5278209 --- /dev/null +++ b/core/tools/constants.ts @@ -0,0 +1,2 @@ +export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output"; +export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call."; diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts index fffe51e02..0714a230b 100644 --- a/core/tools/definitions/codebaseTool.ts +++ b/core/tools/definitions/codebaseTool.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const codebaseTool: Tool = { type: "function", @@ -26,4 +27,9 @@ export const codebaseTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.CodebaseTool, + `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`, + [["query", "How is user authentication handled in this codebase?"]], + ), }; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 41bea0b91..152af5693 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const createNewFileTool: Tool = { type: "function", @@ -30,4 +31,12 @@ export const createNewFileTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.CreateNewFile, + `To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`, + [ + ["filepath", "path/to/the_file.txt"], + ["contents", "Contents of the file"], + ], + ), }; diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 8f19c5955..e6bf6689e 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -1,5 +1,20 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; + +const NAME_ARG_DESC = + "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')"; +const RULE_ARG_DESC = + "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard."; +const DESC_ARG_DESC = + "Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types."; +const GLOB_ARG_DESC = + "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])"; +const REGEX_ARG_DESC = + "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)"; + +const ALWAYS_APPLY_DESC = + "Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules."; export const createRuleBlock: Tool = { type: "function", @@ -20,35 +35,54 @@ export const createRuleBlock: Tool = { properties: { name: { type: "string", - description: - "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')", + description: NAME_ARG_DESC, }, rule: { type: "string", - description: - "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", + description: RULE_ARG_DESC, }, description: { type: "string", - description: - "Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.", + description: DESC_ARG_DESC, }, globs: { type: "string", - description: - "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])", + description: GLOB_ARG_DESC, }, regex: { type: "string", - description: - "Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)", + description: REGEX_ARG_DESC, }, alwaysApply: { type: "boolean", - description: - "Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.", + description: ALWAYS_APPLY_DESC, }, }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.CreateRuleBlock, + `Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions. +This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules. +To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments: +- name: ${NAME_ARG_DESC} +- rule: ${RULE_ARG_DESC} +- description: ${DESC_ARG_DESC} +- globs: ${GLOB_ARG_DESC} +- alwaysApply: ${ALWAYS_APPLY_DESC} +For example:`, + [ + ["name", "Use PropTypes"], + [ + "rule", + "Always use PropTypes when declaring React component properties", + ], + [ + "description", + "Ensure that all prop types are explicitly declared for better type safety and code maintainability in React components.", + ], + ["globs", "**/*.js"], + ["alwaysApply", "false"], + ], + ), }; diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 7abd658fc..59e20c681 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile"; export interface EditToolArgs { @@ -8,6 +9,9 @@ export interface EditToolArgs { changes: string; } +const CHANGES_DESCRIPTION = + "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'"; + export const editFileTool: Tool = { type: "function", displayTitle: "Edit File", @@ -31,10 +35,24 @@ export const editFileTool: Tool = { }, changes: { type: "string", - description: - "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'", + description: CHANGES_DESCRIPTION, }, }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.EditExistingFile, + `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with +- filepath: the relative filepath to the file. +- changes: ${CHANGES_DESCRIPTION} +Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first. +For example:`, + [ + ["filepath", "path/to/the_file.ts"], + [ + "changes", + "// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...", + ], + ], + ), }; diff --git a/core/tools/definitions/fetchUrlContent.ts b/core/tools/definitions/fetchUrlContent.ts index e0122f55b..ae57fc532 100644 --- a/core/tools/definitions/fetchUrlContent.ts +++ b/core/tools/definitions/fetchUrlContent.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const fetchUrlContentTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const fetchUrlContentTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.FetchUrlContent, + `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`, + [["url", "https://example.com"]], + ), }; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index 42e8afd2d..e0f195a66 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const globSearchTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const globSearchTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.FileGlobSearch, + `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, + [["pattern", "*.py"]], + ), }; diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index 60a4e2710..e276d5a8f 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const grepSearchTool: Tool = { type: "function", @@ -26,4 +27,9 @@ export const grepSearchTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.GrepSearch, + `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, + [["query", ".*main_services.*"]], + ), }; diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts index 71f4e5cf9..97d23f4f6 100644 --- a/core/tools/definitions/ls.ts +++ b/core/tools/definitions/ls.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const lsTool: Tool = { type: "function", @@ -30,4 +31,12 @@ export const lsTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.LSTool, + `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`, + [ + ["dirPath", "path/to/dir"], + ["recursive", "false"], + ], + ), }; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 9c15105a6..3f07f816f 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readCurrentlyOpenFileTool: Tool = { type: "function", @@ -19,4 +20,10 @@ export const readCurrentlyOpenFileTool: Tool = { properties: {}, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ReadCurrentlyOpenFile, + `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. +If the user is asking about a file and you don't see any code, use this to check the current file`, + [], + ), }; diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index 42737fe63..fb13eba05 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readFileTool: Tool = { type: "function", @@ -26,4 +27,9 @@ export const readFileTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ReadFile, + `To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`, + [["filepath", "path/to/the_file.txt"]], + ), }; diff --git a/core/tools/definitions/requestRule.test.ts b/core/tools/definitions/requestRule.test.ts index e1d0feb81..0fd7b5de8 100644 --- a/core/tools/definitions/requestRule.test.ts +++ b/core/tools/definitions/requestRule.test.ts @@ -25,7 +25,8 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); expect(result).toBe( - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.", + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + + "No rules available.", ); }); @@ -69,7 +70,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Agent Rule 1: First agent-requested rule\n" + "Agent Rule 2: Second agent-requested rule"; @@ -90,7 +91,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Rule Without Description: undefined"; expect(result).toBe(expected); @@ -110,7 +111,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "undefined: Rule without name"; expect(result).toBe(expected); @@ -130,7 +131,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Rule Without File: Rule without file path"; expect(result).toBe(expected); @@ -159,7 +160,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Valid Agent Rule: This should be included"; expect(result).toBe(expected); @@ -198,7 +199,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Valid Agent Rule: This should be included"; expect(result).toBe(expected); @@ -210,7 +211,8 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); expect(result).toBe( - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.", + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + + "No rules available.", ); }); @@ -229,7 +231,7 @@ describe("getRequestRuleDescription", () => { const result = getRequestRuleDescription(rules); const expected = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" + + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" + "Single Rule: The only agent-requested rule"; expect(result).toBe(expected); diff --git a/core/tools/definitions/requestRule.ts b/core/tools/definitions/requestRule.ts index cb60cda73..4e2f1ef61 100644 --- a/core/tools/definitions/requestRule.ts +++ b/core/tools/definitions/requestRule.ts @@ -1,30 +1,41 @@ import { ConfigDependentToolParams, GetTool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface RequestRuleArgs { name: string; } -export function getRequestRuleDescription( - rules: ConfigDependentToolParams["rules"], -): string { +function getAvailableRules(rules: ConfigDependentToolParams["rules"]) { // Must be explicitly false and no globs const agentRequestedRules = rules.filter( (rule) => rule.alwaysApply === false && !rule.globs, ); - const prefix = - "Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n"; - - const body = agentRequestedRules - .map((rule) => `${rule.name}: ${rule.description}`) - .join("\n"); - - if (body.length === 0) { - return prefix + "No rules available."; + if (agentRequestedRules.length === 0) { + return "No rules available."; } - return prefix + body; + return agentRequestedRules + .map((rule) => `${rule.name}: ${rule.description}`) + .join("\n"); +} + +export function getRequestRuleDescription( + rules: ConfigDependentToolParams["rules"], +): string { + const prefix = + "Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n"; + return prefix + getAvailableRules(rules); +} + +function getRequestRuleSystemMessageDescription( + rules: ConfigDependentToolParams["rules"], +): string { + const prefix = `To retrieve "rules" that contain more context/instructions based on their descriptions, use the ${BuiltInToolNames.RequestRule} tool with the name of the rule. The available rules are:\n`; + const availableRules = getAvailableRules(rules); + const suffix = "\n\nFor example, you might respond with:"; + return prefix + availableRules + suffix; } export const requestRuleTool: GetTool = ({ rules }) => ({ @@ -49,4 +60,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({ }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.RequestRule, + getRequestRuleSystemMessageDescription(rules), + [["name", "rule_name"]], + ), }); diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index fe5e032de..d0119c796 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,13 +1,13 @@ +import os from "os"; import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; - -import os from "os"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; /** * Get the preferred shell for the current platform * @returns The preferred shell command or path */ -export function getPreferredShell(): string { +function getPreferredShell(): string { const platform = os.platform(); if (platform === "win32") { @@ -20,7 +20,13 @@ export function getPreferredShell(): string { } } -export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`; +const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`; + +const RUN_COMMAND_NOTES = `The shell is not stateful and will not remember any previous commands.\ + When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\ + When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\ + Do NOT perform actions requiring special/admin privileges.\ + ${PLATFORM_INFO}`; export const runTerminalCommandTool: Tool = { type: "function", @@ -32,12 +38,7 @@ export const runTerminalCommandTool: Tool = { group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.RunTerminalCommand, - description: `Run a terminal command in the current directory.\ - The shell is not stateful and will not remember any previous commands.\ - When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\ - When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\ - Do NOT perform actions requiring special/admin privileges.\ - ${PLATFORM_INFO}`, + description: `Run a terminal command in the current directory.\n${RUN_COMMAND_NOTES}`, parameters: { type: "object", required: ["command"], @@ -55,4 +56,12 @@ export const runTerminalCommandTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.RunTerminalCommand, + `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool +${RUN_COMMAND_NOTES} +You can also optionally include the waitForCompletion argument set to false to run the command in the background. +For example, to see the git log, you could respond with:`, + [["command", "git log"]], + ), }; diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index 97b79ca4d..96dac65da 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface SearchAndReplaceInFileArgs { filepath: string; @@ -10,46 +11,16 @@ export interface SearchAndReplaceInFileArgs { export const NO_PARALLEL_TOOL_CALLING_INSRUCTION = "Note this tool CANNOT be called in parallel."; -/** - * This tool is in an experimental state. - * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 - */ -export const searchAndReplaceInFileTool: Tool = { - type: "function", - displayTitle: "Edit File", - wouldLikeTo: "edit {{{ filepath }}}", - isCurrently: "editing {{{ filepath }}}", - hasAlready: "edited {{{ filepath }}}", - group: BUILT_IN_GROUP_NAME, - readonly: false, - isInstant: false, - function: { - name: BuiltInToolNames.SearchAndReplaceInFile, - description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, - parameters: { - type: "object", - required: ["filepath", "diffs"], - properties: { - filepath: { - type: "string", - description: - "The path of the file to modify, relative to the root of the workspace.", - }, - diffs: { - type: "array", - items: { - type: "string", - }, - description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: -\`\`\` -------- SEARCH +const SEARCH_AND_REPLACE_TOOL_DESCRIPTION = `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`; +const SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION = + "The path of the file to modify, relative to the root of the workspace."; +const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH [exact content to find] ======= [new content to replace with] -+++++++ REPLACE -\`\`\` ++++++++ REPLACE`; -Critical rules: +const SEARCH_AND_REPLACE_RULES = `Critical rules: 1. SEARCH content must match the associated file section to find EXACTLY: * Match character-for-character including whitespace, indentation, line endings * Include all comments, docstrings, etc. @@ -69,26 +40,84 @@ Critical rules: * DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call] 6. Special operations: * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) - * To delete code: Use empty REPLACE section + * To delete code: Use empty REPLACE section`; + +const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format: +\`\`\` +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} +\`\`\` + +${SEARCH_AND_REPLACE_RULES} Usage: \`\`\` -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} -------- SEARCH -[exact content to find] -======= -[new content to replace with] -+++++++ REPLACE - \`\`\` +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} +\`\`\` -Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`, +Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`; + +/** + * This tool is in an experimental state. + * Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121 + */ +export const searchAndReplaceInFileTool: Tool = { + type: "function", + displayTitle: "Edit File", + wouldLikeTo: "edit {{{ filepath }}}", + isCurrently: "editing {{{ filepath }}}", + hasAlready: "edited {{{ filepath }}}", + group: BUILT_IN_GROUP_NAME, + readonly: false, + isInstant: false, + function: { + name: BuiltInToolNames.SearchAndReplaceInFile, + description: SEARCH_AND_REPLACE_TOOL_DESCRIPTION, + parameters: { + type: "object", + required: ["filepath", "diffs"], + properties: { + filepath: { + type: "string", + description: SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION, + }, + diffs: { + type: "array", + items: { + type: "string", + }, + description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION, }, }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.SearchAndReplaceInFile, + `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. +Each block should follow this format: +${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} + +${SEARCH_AND_REPLACE_RULES} + + For example, you could respond with:`, + [ + ["filepath", "path/to/file.ts"], + [ + "diffs", + `[ +"------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE", +"------- SEARCH +[exact content to find] +======= +[new content to replace with] ++++++++ REPLACE" +]`, + ], + ], + ), }; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index d2ce78efc..bcaa743a3 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const searchWebTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const searchWebTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.SearchWeb, + `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`, + [["query", "What is the current weather in San Francisco?"]], + ), }; diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index d835986b0..bf488f171 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewDiffTool: Tool = { type: "function", @@ -19,4 +20,9 @@ export const viewDiffTool: Tool = { properties: {}, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ViewDiff, + `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`, + [], + ), }; diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index dc76e8309..a58584fc1 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -1,6 +1,7 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewRepoMapTool: Tool = { type: "function", @@ -19,4 +20,9 @@ export const viewRepoMapTool: Tool = { properties: {}, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ViewRepoMap, + `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`, + [], + ), }; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 41c1a904c..11c27a775 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,5 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; +import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewSubdirectoryTool: Tool = { type: "function", @@ -25,4 +26,9 @@ export const viewSubdirectoryTool: Tool = { }, }, }, + systemMessageDescription: createSystemMessageExampleCall( + BuiltInToolNames.ViewSubdirectory, + `To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`, + [["directory_path", "path/to/subdirectory"]], + ), }; diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index a026d0f47..ae8964445 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -10,7 +10,9 @@ export const readFileImpl: ToolImpl = async (args, extras) => { const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); if (!firstUriMatch) { - throw new Error(`Could not find file ${filepath}`); + throw new Error( + `File "${filepath}" does not exist. You might want to check the path and try again.`, + ); } const content = await extras.ide.readFile(firstUriMatch); diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.ts b/core/tools/systemMessageTools/buildToolsSystemMessage.ts new file mode 100644 index 000000000..8536c794f --- /dev/null +++ b/core/tools/systemMessageTools/buildToolsSystemMessage.ts @@ -0,0 +1,167 @@ +import { Tool } from "../.."; +import { closeTag } from "./systemToolUtils"; + +export const TOOL_INSTRUCTIONS_TAG = ""; +export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION"; +export const TOOL_DESCRIPTION_TAG = "DESCRIPTION"; + +const EXAMPLE_DYNAMIC_TOOL = ` +\`\`\`tool_definition +TOOL_NAME: example_tool +TOOL_ARG: arg_1 (string, required) +Description of the first argument +END_ARG +TOOL_ARG: arg_2 (number, optional) +END_ARG +\`\`\``.trim(); + +const EXAMPLE_DYNAMIC_TOOL_CALL = ` +\`\`\`tool +TOOL_NAME: example_tool +BEGIN_ARG: arg_1 +The value +of arg 1 +END_ARG +BEGIN_ARG: arg_2 +3 +END_ARG +\`\`\``.trim(); + +export function createSystemMessageExampleCall( + name: string, + instructions: string, + args: Array<[string, string]> = [], +) { + let callExample = `\`\`\`tool +TOOL_NAME: ${name}`; + + // Add each argument dynamically + for (const [argName, argValue] of args) { + callExample += ` +BEGIN_ARG: ${argName} +${argValue} +END_ARG`; + } + + callExample += ` +\`\`\``; + + return `${instructions.trim()} +${callExample}`; +} + +function toolToSystemToolDefinition(tool: Tool): string { + let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`; + + if (tool.function.description) { + toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`; + } + + if (tool.function.parameters && "properties" in tool.function.parameters) { + for (const [key, value] of Object.entries( + tool.function.parameters.properties as object, + )) { + const isRequired = tool.function.parameters.required?.includes(key); + const requiredText = isRequired ? "required" : "optional"; + + let argType = "string"; + if ("type" in value) { + argType = value.type; + } + let argDescription = ""; + if ("description" in value) { + argDescription = value.description; + } + + toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`; + if (argDescription) { + toolDefinition += argDescription + "\n"; + } + toolDefinition += `END_ARG\n`; + } + } + + toolDefinition += `\`\`\``; + return toolDefinition.trim(); +} + +export const generateToolsSystemMessage = (tools: Tool[]): string => { + if (tools.length === 0) { + return ""; + } + const withPredefinedMessage = tools.filter( + (tool) => !!tool.systemMessageDescription, + ); + + const withDynamicMessage = tools.filter( + (tool) => !tool.systemMessageDescription, + ); + + const instructions: string[] = []; + instructions.push(TOOL_INSTRUCTIONS_TAG); + instructions.push( + `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`, + ); + instructions.push( + `To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`, + ); + + if (withPredefinedMessage.length > 0) { + instructions.push(`\nThe following tools are available to you:`); + for (const tool of withPredefinedMessage) { + instructions.push(`\n${tool.systemMessageDescription}`); + } + } + + if (withDynamicMessage.length > 0) { + instructions.push( + `\nAlso, these additional tool definitions show other tools you can call with the same syntax:`, + ); + + for (const tool of tools) { + try { + const definition = toolToSystemToolDefinition(tool); + instructions.push(`\n${definition}`); + } catch (e) { + console.error( + "Failed to convert tool to system message tool:\n" + + JSON.stringify(tool), + ); + } + } + + instructions.push(`\nFor example, this tool definition:\n`); + instructions.push(EXAMPLE_DYNAMIC_TOOL); + instructions.push("\nCan be called like this:\n"); + instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL); + } + + instructions.push( + `\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`, + ); + instructions.push( + `Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`, + ); + instructions.push( + `Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`, + ); + instructions.push( + `You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`, + ); + + instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`); + return instructions.join("\n"); +}; + +export function addSystemMessageToolsToSystemMessage( + baseSystemMessage: string, + systemMessageTools: Tool[], +): string { + let systemMessage = baseSystemMessage; + if (systemMessageTools.length > 0) { + const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools); + systemMessage += `\n\n${toolsSystemMessage}`; + } + + return systemMessage; +} diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts b/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts new file mode 100644 index 000000000..70215c477 --- /dev/null +++ b/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts @@ -0,0 +1,252 @@ +import { describe, expect, it } from "vitest"; +import { Tool } from "../.."; +import { + TOOL_INSTRUCTIONS_TAG, + addSystemMessageToolsToSystemMessage, + createSystemMessageExampleCall, + generateToolsSystemMessage, +} from "./buildToolsSystemMessage"; +import { closeTag } from "./systemToolUtils"; + +const SHARED_TOOL_FIELDS = { + displayTitle: "DUD", + group: "DUD", + readonly: true, + type: "function" as const, +}; + +describe("createSystemMessageExampleCall", () => { + it("creates a system message example call with no args", () => { + const result = createSystemMessageExampleCall( + "test_tool", + "Use this tool to test things", + ); + expect(result).includes("Use this tool to test things"); + expect(result).includes("```tool"); + expect(result).includes("TOOL_NAME: test_tool"); + expect(result).includes("```"); + }); + + it("creates a system message example call with args", () => { + const result = createSystemMessageExampleCall( + "test_tool", + "Use this tool to test things", + [ + ["arg1", "value1"], + ["arg2", "value2"], + ], + ); + + expect(result).includes("Use this tool to test things"); + expect(result).includes("```tool"); + expect(result).includes("TOOL_NAME: test_tool"); + expect(result).includes("BEGIN_ARG: arg1"); + expect(result).includes("value1"); + expect(result).includes("END_ARG"); + expect(result).includes("BEGIN_ARG: arg2"); + expect(result).includes("value2"); + }); + + it("handles multiline arg values correctly", () => { + const multilineValue = "value\nwith\nmultiple\nlines"; + const result = createSystemMessageExampleCall( + "test_tool", + "Use this tool to test things", + [["arg1", multilineValue]], + ); + + expect(result).includes("BEGIN_ARG: arg1"); + expect(result).includes(multilineValue); + expect(result).includes("END_ARG"); + }); +}); + +describe("generateToolsSystemMessage", () => { + it("returns empty string for empty tools array", () => { + const result = generateToolsSystemMessage([]); + expect(result).toBe(""); + }); + + it("generates system message for tools with system message descriptions", () => { + const customDescription = + "This is test tool 1's system message description"; + const tools: Tool[] = [ + { + function: { + name: "test_tool1", + description: "Test tool 1 description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + systemMessageDescription: customDescription, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check structure rather than exact text + expect(result).includes(TOOL_INSTRUCTIONS_TAG); + expect(result).includes(customDescription); + expect(result).includes(closeTag(TOOL_INSTRUCTIONS_TAG)); + + // Check for general section about available tools without requiring exact wording + const hasToolsAvailableSection = /tools are available to you/i.test(result); + expect(hasToolsAvailableSection).toBe(true); + }); + + it("generates system message for tools without system message descriptions", () => { + const toolName = "test_tool2"; + const toolDesc = "Test tool 2 description"; + const paramDesc = "Parameter 1 description"; + + const tools: Tool[] = [ + { + function: { + name: toolName, + description: toolDesc, + parameters: { + type: "object", + properties: { + param1: { + type: "string", + description: paramDesc, + }, + }, + required: ["param1"], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check for key elements without requiring exact wording + expect(result).includes(`TOOL_NAME: ${toolName}`); + expect(result).includes("TOOL_DESCRIPTION:"); + expect(result).includes(toolDesc); + expect(result).includes("TOOL_ARG: param1 (string, required)"); + expect(result).includes(paramDesc); + + // Check for dynamic tool section without exact text matching + const hasDynamicToolsSection = /additional tool definitions/i.test(result); + expect(hasDynamicToolsSection).toBe(true); + }); + + it("handles tools with and without system message descriptions", () => { + const customMsg = "Custom system message"; + const tools: Tool[] = [ + { + function: { + name: "tool_with_description", + description: "Tool description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + systemMessageDescription: customMsg, + ...SHARED_TOOL_FIELDS, + }, + { + function: { + name: "tool_without_description", + description: "Another tool description", + parameters: { + type: "object", + properties: { + param1: { + type: "string", + description: "Parameter description", + }, + }, + required: ["param1"], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check for both types of tools + expect(result).includes(customMsg); + expect(result).includes("TOOL_NAME: tool_without_description"); + + // Verify structure without exact text matching + const hasAvailableToolsSection = /tools are available to you/i.test(result); + expect(hasAvailableToolsSection).toBe(true); + + const hasDynamicToolsSection = /additional tool definitions/i.test(result); + expect(hasDynamicToolsSection).toBe(true); + }); + + it("includes example tool definition and call", () => { + const tools: Tool[] = [ + { + function: { + name: "test_tool", + description: "Test description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = generateToolsSystemMessage(tools); + + // Check for example sections without exact text + expect(result).includes("```tool_definition"); + expect(result).includes("TOOL_NAME: example_tool"); + expect(result).includes("```tool"); + + // Check for example format structure + const hasExampleDefinition = /example.*tool definition/i.test(result); + const hasExampleCall = /called like this/i.test(result); + + expect(hasExampleDefinition).toBe(true); + expect(hasExampleCall).toBe(true); + }); +}); + +describe("addSystemMessageToolsToSystemMessage", () => { + it("returns original system message when no tools are provided", () => { + const baseMessage = "This is the base system message"; + const result = addSystemMessageToolsToSystemMessage(baseMessage, []); + expect(result).toBe(baseMessage); + }); + + it("appends tools system message to base message", () => { + const baseMessage = "This is the base system message"; + const toolName = "test_tool"; + const tools: Tool[] = [ + { + function: { + name: toolName, + description: "Test description", + parameters: { + type: "object", + properties: {}, + required: [], + }, + }, + ...SHARED_TOOL_FIELDS, + }, + ]; + + const result = addSystemMessageToolsToSystemMessage(baseMessage, tools); + + expect(result.startsWith(baseMessage)).toBe(true); + expect(result).includes(TOOL_INSTRUCTIONS_TAG); + expect(result).includes(`TOOL_NAME: ${toolName}`); + }); +}); diff --git a/core/tools/systemMessageTools/convertSystemTools.ts b/core/tools/systemMessageTools/convertSystemTools.ts new file mode 100644 index 000000000..4517915d0 --- /dev/null +++ b/core/tools/systemMessageTools/convertSystemTools.ts @@ -0,0 +1,95 @@ +import { + AssistantChatMessage, + MessagePart, + ToolCallState, + UserChatMessage, +} from "../.."; +import { + normalizeToMessageParts, + renderContextItems, +} from "../../util/messageContent"; +import { + CANCELLED_TOOL_CALL_MESSAGE, + NO_TOOL_CALL_OUTPUT_MESSAGE, +} from "../constants"; +function toolCallStateToSystemToolCall(state: ToolCallState): string { + let parts = ["```tool"]; + parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); + try { + for (const arg in state.parsedArgs) { + parts.push(`BEGIN_ARG: ${arg}`); + parts.push(JSON.stringify(state.parsedArgs[arg])); + parts.push(`END_ARG`); + } + } catch (e) { + console.log("Failed to stringify json args", state.parsedArgs); + } + // TODO - include tool call id for parallel. Confuses dumb models + parts.push("```"); + return parts.join("\n"); +} + +function toolCallStateToSystemToolOutput(state: ToolCallState): string { + let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; + // TODO - include tool call id for parallel. Confuses dumb models + // let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`; + if (state.status === "canceled") { + output += CANCELLED_TOOL_CALL_MESSAGE; + } else if (state.output?.length) { + output += renderContextItems(state.output); + } else { + output += NO_TOOL_CALL_OUTPUT_MESSAGE; + } + return output; +} + +export function convertToolCallStatesToSystemCallsAndOutput( + originalAssistantMessage: AssistantChatMessage, + toolCallStates: ToolCallState[], +): { + assistantMessage: AssistantChatMessage; + userMessage: UserChatMessage; +} { + const parts = normalizeToMessageParts(originalAssistantMessage); + if (originalAssistantMessage.toolCalls) { + parts.push( + ...toolCallStates.map((state) => ({ + type: "text" as const, + text: toolCallStateToSystemToolCall(state), + })), + ); + } + + // new message with tool calls moved to content + const assistantMessage: AssistantChatMessage = { + ...originalAssistantMessage, + content: parts, + toolCalls: undefined, // remove tool calls from the assistant message + }; + + const userParts: MessagePart[] = []; + if (toolCallStates) { + for (const state of toolCallStates) { + userParts.push({ + type: "text", + text: toolCallStateToSystemToolOutput(state), + }); + } + } + if (userParts.length === 0) { + userParts.push({ + type: "text", + text: "Error: no tool output for tool calls", + }); + } + + const userMessage: UserChatMessage = { + role: "user", + content: userParts, + }; + + return { + assistantMessage, + userMessage, + }; +} diff --git a/core/tools/systemMessageTools/detectToolCallStart.ts b/core/tools/systemMessageTools/detectToolCallStart.ts new file mode 100644 index 000000000..f99ce03d5 --- /dev/null +++ b/core/tools/systemMessageTools/detectToolCallStart.ts @@ -0,0 +1,33 @@ +let boundaryTypeIndex = 0; + +// Poor models are really bad at following instructions +// Give some leeway in how the initiate +const acceptedToolStarts: [string, string][] = [ + ["```tool\n", "```tool\n"], + ["tool_name:", "```tool\nTOOL_NAME:"], +]; + +export function detectToolCallStart(buffer: string) { + let modifiedBuffer = buffer; + let isInToolCall = false; + let isInPartialStart = false; + const lowerCaseBuffer = buffer.toLowerCase(); + for (let i = 0; i < acceptedToolStarts.length; i++) { + const [start, replacement] = acceptedToolStarts[i]; + if (lowerCaseBuffer.startsWith(start)) { + // for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive + if (i !== 0) { + modifiedBuffer = buffer.replace(new RegExp(start, "i"), replacement); + } + isInToolCall = true; + break; + } else if (start.startsWith(lowerCaseBuffer)) { + isInPartialStart = true; + } + } + return { + isInToolCall, + isInPartialStart, + modifiedBuffer, + }; +} diff --git a/core/tools/systemMessageTools/detectToolCallStart.vitest.ts b/core/tools/systemMessageTools/detectToolCallStart.vitest.ts new file mode 100644 index 000000000..715113475 --- /dev/null +++ b/core/tools/systemMessageTools/detectToolCallStart.vitest.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { detectToolCallStart } from "./detectToolCallStart"; + +describe("detectToolCallStart", () => { + it("detects standard tool call start", () => { + const buffer = "```tool\nTOOL_NAME: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("detects tool_name start without codeblock", () => { + const buffer = "tool_name: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool"); + }); + + it("detects case-insensitive tool call start", () => { + const buffer = "```ToOl\nTOOL_NAME: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("detects case-insensitive tool_name start", () => { + const buffer = "ToOl_NaMe: example_tool"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(true); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool"); + }); + + it("identifies partial tool call start", () => { + const buffer = "```to"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(true); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("identifies partial tool_name start", () => { + const buffer = "tool_na"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(true); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("does not detect tool call in unrelated text", () => { + const buffer = "This is some regular text."; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); + + it("does not detect tool call in similar but different markdown block", () => { + const buffer = "```javascript\nconst x = 10;"; + const result = detectToolCallStart(buffer); + + expect(result.isInToolCall).toBe(false); + expect(result.isInPartialStart).toBe(false); + expect(result.modifiedBuffer).toBe(buffer); + }); +}); diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.ts b/core/tools/systemMessageTools/interceptSystemToolCalls.ts new file mode 100644 index 000000000..31fb562bf --- /dev/null +++ b/core/tools/systemMessageTools/interceptSystemToolCalls.ts @@ -0,0 +1,114 @@ +import { ChatMessage, PromptLog, TextMessagePart } from "../.."; +import { normalizeToMessageParts } from "../../util/messageContent"; +import { detectToolCallStart } from "./detectToolCallStart"; +import { + getInitialTooLCallParseState, + handleToolCallBuffer, + ToolCallParseState, +} from "./parseSystemToolCall"; +import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils"; + +/* + Function to intercept tool calls in markdown code blocks format from a chat message stream + 1. Skips non-assistant messages + 2. Intercepts text that looks like a tool call in a markdown code block format: + ```tool + TOOL_NAME: example_tool + BEGIN_ARG: arg1 + value + END_ARG + ``` + 3. Parses tool calls line by line and generates proper tool call deltas + 4. Once the tool call is complete, resets state for potential future tool calls +*/ +export async function* interceptSystemToolCalls( + messageGenerator: AsyncGenerator, + abortController: AbortController, +): AsyncGenerator { + let buffer = ""; + let parseState: ToolCallParseState | undefined; + + while (true) { + const result = await messageGenerator.next(); + if (result.done) { + // Case: non-standard tool termination causes hanging args + if (parseState && !parseState.done && parseState.processedArgNames.size) { + yield [ + { + role: "assistant", + content: "", + toolCalls: [createDelta("", "}", parseState.toolCallId)], + }, + ]; + } + + return result.value; + } else { + for await (const message of result.value) { + if (abortController.signal.aborted || parseState?.done) { + break; + } + // Skip non-assistant messages or messages with native tool calls + if (message.role !== "assistant" || message.toolCalls) { + yield [message]; + continue; + } + + const parts = normalizeToMessageParts(message); + + // Image output cannot be combined with tools + if (parts.find((part) => part.type === "imageUrl")) { + yield [message]; + continue; + } + + const chunks = (parts as TextMessagePart[]) + .map((part) => splitAtCodeblocksAndNewLines(part.text)) + .flat(); + + for (const chunk of chunks) { + buffer += chunk; + if (!parseState) { + const { isInPartialStart, isInToolCall, modifiedBuffer } = + detectToolCallStart(buffer); + + if (isInPartialStart) { + continue; + } + if (isInToolCall) { + parseState = getInitialTooLCallParseState(); + buffer = modifiedBuffer; + } + } + + if (parseState && !parseState.done) { + const delta = handleToolCallBuffer(buffer, parseState); + if (delta) { + yield [ + { + ...message, + content: "", + toolCalls: [delta], + }, + ]; + } + } else { + // Prevent content after tool calls for now + if (parseState) { + continue; + } + + // Yield normal assistant message + yield [ + { + ...message, + content: [{ type: "text", text: buffer }], + }, + ]; + } + buffer = ""; + } + } + } + } +} diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts b/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts new file mode 100644 index 000000000..756125bd4 --- /dev/null +++ b/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts @@ -0,0 +1,325 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { AssistantChatMessage, ChatMessage, PromptLog } from "../.."; +import { interceptSystemToolCalls } from "./interceptSystemToolCalls"; + +describe("interceptSystemToolCalls", () => { + let abortController: AbortController; + + beforeEach(() => { + abortController = new AbortController(); + }); + + const createAsyncGenerator = async function* ( + messages: ChatMessage[][], + ): AsyncGenerator { + for (const messageGroup of messages) { + yield messageGroup; + } + return undefined; + }; + + it("passes through non-assistant messages unchanged", async () => { + const messages: ChatMessage[][] = [ + [{ role: "user", content: "Hello" }], + [{ role: "system", content: "System message" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + let result = await generator.next(); + expect(result.value).toEqual([{ role: "user", content: "Hello" }]); + + result = await generator.next(); + expect(result.value).toEqual([ + { role: "system", content: "System message" }, + ]); + + result = await generator.next(); + expect(result.done).toBe(true); + }); + + it("passes through assistant messages with existing tool calls", async () => { + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: "", + toolCalls: [ + { + type: "function", + function: { + name: "existing_tool", + arguments: '{"arg1":"value1"}', + }, + id: "existing_call_id", + }, + ], + }, + ], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + const result = await generator.next(); + expect(result.value).toEqual(messages[0]); + }); + + it("passes through assistant messages with image URLs unchanged", async () => { + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: [ + { type: "text", text: "Here's an image:" }, + { + type: "imageUrl", + imageUrl: { + url: "https://example.com/image.png", + }, + }, + ], + }, + ], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + const result = await generator.next(); + expect(result.value).toEqual(messages[0]); + }); + + it("processes standard tool call format", async () => { + const messages: ChatMessage[][] = [ + [ + { + role: "assistant", + content: "I'll help you with that. Let me use a tool:\n", + }, + ], + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: arg1\n" }], + [{ role: "assistant", content: "value1\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "```" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // First chunk should be normal text + let result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "I'll help you with that. Let me use a tool:", + }, + ], + }, + ]); + + result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "\n", + }, + ], + }, + ]); + + // Tool name detection + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name, + ).toBe("test_tool"); + + // Begin argument + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toContain('{"arg1":'); + + // Argument value + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe('"value1"'); + + // End of tool call + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("}"); + }); + + it("processes tool_name without codeblock format", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "I'll help you with that.\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: arg1\n" }], + [{ role: "assistant", content: "value1\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // First chunk should be normal text + let result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [{ type: "text", text: "I'll help you with that." }], + }, + ]); + + result = await generator.next(); + expect(result.value).toEqual([ + { + role: "assistant", + content: [ + { + type: "text", + text: "\n", + }, + ], + }, + ]); + + // The system should detect the tool_name format and convert it + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name, + ).toBe("test_tool"); + + // Rest of processing should work as normal + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe('{"arg1":'); + + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe('"value1"'); + + result = await generator.next(); + expect( + (result.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("}"); + }); + + it("ignores content after a tool call", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: arg1\n" }], + [{ role: "assistant", content: "value1\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "```\n" }], + [{ role: "assistant", content: "This content should be ignored" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + let result; + // Process through all the tool call parts + for (let i = 0; i < 6; i++) { + result = await generator.next(); + } + + // The content after the tool call should be ignored + result = await generator.next(); + expect(result.value).toBeUndefined(); + }); + + it("stops processing when aborted", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // Process the first part + let result = await generator.next(); + + // Abort before processing the second part + abortController.abort(); + + // The next value should be undefined + result = await generator.next(); + expect(result.value).toBeUndefined(); + }); + + it("handles JSON parsing for argument values", async () => { + const messages: ChatMessage[][] = [ + [{ role: "assistant", content: "```tool\n" }], + [{ role: "assistant", content: "TOOL_NAME: test_tool\n" }], + [{ role: "assistant", content: "BEGIN_ARG: number_arg\n" }], + [{ role: "assistant", content: "123\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "BEGIN_ARG: boolean_arg\n" }], + [{ role: "assistant", content: "true\n" }], + [{ role: "assistant", content: "END_ARG\n" }], + [{ role: "assistant", content: "```" }], + ]; + + const generator = interceptSystemToolCalls( + createAsyncGenerator(messages), + abortController, + ); + + // Skip to number arg end + await generator.next(); + await generator.next(); + let result; + result = await generator.next(); + + expect( + (result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("123"); + + // Skip to boolean arg end + await generator.next(); + result = await generator.next(); + + expect( + (result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function + ?.arguments, + ).toBe("true"); + }); +}); diff --git a/core/tools/systemMessageTools/parseSystemToolCall.ts b/core/tools/systemMessageTools/parseSystemToolCall.ts new file mode 100644 index 000000000..0300654d9 --- /dev/null +++ b/core/tools/systemMessageTools/parseSystemToolCall.ts @@ -0,0 +1,143 @@ +import { ToolCallDelta } from "../.."; +import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils"; + +export type ToolCallParseState = { + toolCallId: string; + isOnArgBeginLine: boolean; + currentArgName: string | undefined; + currentArgLines: string[]; + processedArgNames: Set; + currentLineIndex: number; + lineChunks: string[][]; + done: boolean; +}; + +export const getInitialTooLCallParseState = (): ToolCallParseState => ({ + toolCallId: generateOpenAIToolCallId(), + isOnArgBeginLine: false, + currentArgName: undefined, + currentArgLines: [], + currentLineIndex: 0, + processedArgNames: new Set(), + lineChunks: [], + done: false, +}); + +/* + Efficiently applies chunks to a tool call state as they come in + Expects chunks to be broken so that new lines and codeblocks are alone + For now, this parser collects entire arg before + This is because support for JSON booleans is tricky otherwise + +*/ +export function handleToolCallBuffer( + chunk: string, + state: ToolCallParseState, +): ToolCallDelta | undefined { + // Add chunks + const lineIndex = state.currentLineIndex; + if (!state.lineChunks[lineIndex]) { + state.lineChunks[lineIndex] = []; + } + state.lineChunks[lineIndex].push(chunk); + + const isNewLine = chunk === "\n"; + if (isNewLine) { + state.currentLineIndex++; + } + + const line = state.lineChunks[lineIndex].join(""); + + switch (lineIndex) { + // The first line will be skipped (e.g. ```tool\n) + case 0: + // non-standard start sequences will sometimes include stuff in the tool_name line + const splitBuffer = line.split("\n"); + if (splitBuffer[0]) { + state.lineChunks[0] = [splitBuffer[0], "\n"]; + } + if (splitBuffer[1]) { + state.lineChunks[1] = [splitBuffer[1]]; + } + + state.currentLineIndex = 1; + // Tool name line - process once line 2 is reached + case 1: + if (isNewLine) { + const name = (line.split(/tool_?name:/i)[1] ?? "").trim(); + if (!name) { + throw new Error("Invalid tool name"); + } + return createDelta(name, "", state.toolCallId); + } + return; + default: + if (state.isOnArgBeginLine) { + if (isNewLine) { + const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim(); + if (!argName) { + throw new Error("Invalid begin arg line"); + } + state.currentArgName = argName; + state.isOnArgBeginLine = false; + const argPrefix = state.processedArgNames.size === 0 ? "{" : ","; + return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId); + } + } else if (state.currentArgName) { + if (isNewLine) { + const isEndArgTag = line.match(/end_?arg/i); + if (isEndArgTag) { + let trimmedValue = state.currentArgLines.join("").trim(); + state.currentArgLines.length = 0; + state.processedArgNames.add(state.currentArgName); + state.currentArgName = undefined; + + try { + if ( + trimmedValue.startsWith("[") || + trimmedValue.startsWith("{") + ) { + trimmedValue = trimmedValue.replace( + /"((?:\\[\s\S]|[^"\\])*?)"/g, + (match) => { + const content = match.slice(1, -1); + // Replace unescaped newlines + return ( + '"' + + content + .replace(/([^\\])\n/g, "$1\\n") + .replace(/^\n/g, "\\n") + + '"' + ); + }, + ); + } + const parsed = JSON.parse(trimmedValue); + const stringifiedArg = JSON.stringify(parsed); + return createDelta("", stringifiedArg, state.toolCallId); + } catch (e) { + const stringifiedArg = JSON.stringify(trimmedValue); + return createDelta("", stringifiedArg, state.toolCallId); + } + } else { + state.currentArgLines.push(line); + } + } + } else { + // Check for entry into arg + const isBeginArgLine = line.match(/begin_?arg:/i); + if (isBeginArgLine) { + state.isOnArgBeginLine = true; + } + + // Check for exit + if (line === "```" || isNewLine) { + state.done = true; + // finish args JSON if applicable + if (state.processedArgNames.size > 0) { + return createDelta("", "}", state.toolCallId); + } + } + } + } +} diff --git a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts b/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts new file mode 100644 index 000000000..2aeac2ce8 --- /dev/null +++ b/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts @@ -0,0 +1,301 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + ToolCallParseState, + getInitialTooLCallParseState, + handleToolCallBuffer, +} from "./parseSystemToolCall"; + +describe("getInitialTooLCallParseState", () => { + it("returns a properly initialized parse state", () => { + const state = getInitialTooLCallParseState(); + + expect(state).toEqual({ + isOnArgBeginLine: false, + currentArgName: undefined, + currentArgLines: [], + currentLineIndex: 0, + processedArgNames: new Set(), + lineChunks: [], + done: false, + toolCallId: expect.any(String), + }); + }); +}); + +describe("handleToolCallBuffer", () => { + let state: ToolCallParseState; + + beforeEach(() => { + state = getInitialTooLCallParseState(); + }); + + it("handles the ```tool\ntool_name the name", () => { + handleToolCallBuffer("```tool\ntool_name: my_name", state); + expect(state.currentLineIndex).toBe(1); + + const result = handleToolCallBuffer("\n", state); + expect(result).toEqual({ + type: "function", + function: { + name: "my_name", + arguments: "", + }, + id: expect.any(String), + }); + expect(state.currentLineIndex).toBe(2); + }); + + it("handles the tool name line", () => { + // Line 0 (```tool) is skipped internally + state.currentLineIndex = 1; + + const result = handleToolCallBuffer("TOOL_NAME: test_tool", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "test_tool", + arguments: "", + }, + id: expect.any(String), + }); + expect(state.currentLineIndex).toBe(2); + }); + + it("handles case-insensitive tool name line", () => { + state.currentLineIndex = 1; + + const result = handleToolCallBuffer("tool_name: test_tool", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "test_tool", + arguments: "", + }, + id: expect.any(String), + }); + }); + + it("begins an argument correctly", () => { + state.currentLineIndex = 2; + + const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state); + expect(result).toBeUndefined(); + expect(state.isOnArgBeginLine).toBe(true); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '{"test_arg":', + }, + id: expect.any(String), + }); + expect(state.currentArgName).toBe("test_arg"); + expect(state.isOnArgBeginLine).toBe(false); + }); + + it("handles case-insensitive begin arg", () => { + state.currentLineIndex = 2; + + const result = handleToolCallBuffer("begin_arg: test_arg", state); + expect(result).toBeUndefined(); + expect(state.isOnArgBeginLine).toBe(true); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '{"test_arg":', + }, + id: expect.any(String), + }); + }); + + it("collects arg value lines", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + + handleToolCallBuffer("line 1", state); + const newLineResult1 = handleToolCallBuffer("\n", state); + expect(newLineResult1).toBeUndefined(); + + handleToolCallBuffer("line 2", state); + const newLineResult2 = handleToolCallBuffer("\n", state); + expect(newLineResult2).toBeUndefined(); + + expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]); + }); + + it("ends an argument correctly with string value", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = ["string value"]; + + const result = handleToolCallBuffer("END_ARG", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '"string value"', + }, + id: expect.any(String), + }); + expect(state.currentArgName).toBeUndefined(); + expect(state.processedArgNames.has("test_arg")).toBe(true); + }); + + it("handles case-insensitive end arg", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = ["string value"]; + + const result = handleToolCallBuffer("end_arg", state); + expect(result).toBeUndefined(); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '"string value"', + }, + id: expect.any(String), + }); + }); + + it("attempts to parse JSON values", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = ["123"]; + + handleToolCallBuffer("END_ARG", state); + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: "123", + }, + id: expect.any(String), + }); + }); + + it("handles multiple arguments", () => { + // Setup first arg + state.currentLineIndex = 2; + state.isOnArgBeginLine = true; + state.lineChunks[2] = ["BEGIN_ARG: first_arg"]; + + handleToolCallBuffer("\n", state); + handleToolCallBuffer("value1", state); + handleToolCallBuffer("\n", state); + handleToolCallBuffer("END_ARG", state); + handleToolCallBuffer("\n", state); + + expect(state.processedArgNames.has("first_arg")).toBe(true); + + // Setup second arg + state.isOnArgBeginLine = true; + handleToolCallBuffer("BEGIN_ARG: second_arg", state); + handleToolCallBuffer("\n", state); + handleToolCallBuffer("value2", state); + handleToolCallBuffer("\n", state); + handleToolCallBuffer("END_ARG", state); + + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: '"value2"', + }, + id: expect.any(String), + }); + expect(state.processedArgNames.has("second_arg")).toBe(true); + }); + + it("finalizes JSON object at end of tool call", () => { + state.currentLineIndex = 5; + state.processedArgNames.add("test_arg"); + + const result = handleToolCallBuffer("```", state); + + expect(result).toEqual({ + type: "function", + function: { + name: "", + arguments: "}", + }, + id: expect.any(String), + }); + expect(state.done).toBe(true); + }); + + it("finalizes on newline after all args processed", () => { + state.currentLineIndex = 5; + state.processedArgNames.add("test_arg"); + + const result = handleToolCallBuffer("\n", state); + + expect(result).toEqual({ + type: "function", + function: { + name: "", + arguments: "}", + }, + id: expect.any(String), + }); + expect(state.done).toBe(true); + }); + + it("handles JSON array args", () => { + state.currentLineIndex = 3; + state.currentArgName = "test_arg"; + state.currentArgLines = [ + "[\n", + '"------- SEARCH\n', + " subtract(number) {\n", + " return this;\n", + " }\n", + "=======\n", + " subtract(number) {\n", + " this -= number\n", + " return this;\n", + " }\n", + '+++++++ REPLACE"\n', + "]\n", + ]; + + handleToolCallBuffer("END_ARG", state); + const newLineResult = handleToolCallBuffer("\n", state); + + expect(newLineResult).toEqual({ + type: "function", + function: { + name: "", + arguments: + '["------- SEARCH\\n subtract(number) {\\n return this;\\n }\\n=======\\n subtract(number) {\\n this -= number\\n return this;\\n }\\n+++++++ REPLACE"]', + }, + id: expect.any(String), + }); + }); +}); diff --git a/core/tools/systemMessageTools/systemToolUtils.ts b/core/tools/systemMessageTools/systemToolUtils.ts new file mode 100644 index 000000000..2271f269b --- /dev/null +++ b/core/tools/systemMessageTools/systemToolUtils.ts @@ -0,0 +1,38 @@ +import { ToolCallDelta } from "../.."; + +export function closeTag(openingTag: string): string { + return ` { + const testCases = [ + { + input: "
", + expectedOutput: "
", + }, + { + input: "

", + expectedOutput: "

", + }, + // Add more test cases as needed + ]; + + testCases.forEach((testCase) => { + test(`closes tag "${testCase.input}" to " { + const result = closeTag(testCase.input); + expect(result).toEqual(testCase.expectedOutput); + }); + }); +}); + +describe("splitAtCodeblocks", () => { + test("doesn't split plain text without codeblocks", () => { + expect(splitAtCodeblocksAndNewLines("hello world")).toEqual([ + "hello world", + ]); + }); + + test("splits at codeblocks", () => { + expect(splitAtCodeblocksAndNewLines("```middle```")).toEqual([ + "```", + "middle", + "```", + "", + ]); + }); + + test("splits at new lines", () => { + expect(splitAtCodeblocksAndNewLines("hello\nhoware\n you\n")).toEqual([ + "hello", + "\n", + "howare", + "\n", + " you", + "\n", + ]); + }); + + test("splits at both codeblocks and new lines", () => { + expect(splitAtCodeblocksAndNewLines("hello```\nho```ware\n you\n")).toEqual( + ["hello", "```", "\n", "ho", "```", "ware", "\n", " you", "\n"], + ); + }); +}); diff --git a/core/tools/systemMessageTools/textifySystemTools.ts b/core/tools/systemMessageTools/textifySystemTools.ts new file mode 100644 index 000000000..f654037df --- /dev/null +++ b/core/tools/systemMessageTools/textifySystemTools.ts @@ -0,0 +1,102 @@ +import { + AssistantChatMessage, + MessagePart, + ToolCallState, + UserChatMessage, +} from "../.."; +import { + normalizeToMessageParts, + renderContextItems, +} from "../../util/messageContent"; +import { + CANCELLED_TOOL_CALL_MESSAGE, + NO_TOOL_CALL_OUTPUT_MESSAGE, +} from "../constants"; +function toolCallStateToSystemToolCall(state: ToolCallState): string { + let parts = ["```tool"]; + parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); + try { + for (const arg in state.parsedArgs) { + parts.push(`BEGIN_ARG: ${arg}`); + parts.push(JSON.stringify(state.parsedArgs[arg])); + parts.push(`END_ARG`); + } + } catch (e) { + console.log("Failed to stringify json args", state.parsedArgs); + } + // TODO - include tool call id for parallel. Confuses dumb models + parts.push("```"); + return parts.join("\n"); +} + +function toolCallStateToSystemToolOutput(state: ToolCallState): string { + let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; + // TODO - include tool call id for parallel. Confuses dumb models + // let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`; + if (state.status === "canceled") { + output += CANCELLED_TOOL_CALL_MESSAGE; + } else if (state.output?.length) { + output += renderContextItems(state.output); + } else { + output += NO_TOOL_CALL_OUTPUT_MESSAGE; + } + return output; +} + +export function convertToolCallStatesToSystemCallsAndOutput( + originalAssistantMessage: AssistantChatMessage, + toolCallStates: ToolCallState[], +): { + assistantMessage: AssistantChatMessage; + userMessage: UserChatMessage; +} { + const assistantParts = normalizeToMessageParts(originalAssistantMessage); + if (originalAssistantMessage.toolCalls) { + assistantParts.push( + ...toolCallStates.map((state) => ({ + type: "text" as const, + text: toolCallStateToSystemToolCall(state), + })), + ); + } + + const userParts: MessagePart[] = []; + if (toolCallStates) { + for (const state of toolCallStates) { + userParts.push({ + type: "text", + text: toolCallStateToSystemToolOutput(state), + }); + } + } + if (userParts.length === 0) { + userParts.push({ + type: "text", + text: "No tool output for tool calls", + }); + } + + const nonEmptyAssistantParts = assistantParts.filter( + (p) => p.type !== "text" || !!p.text, + ); + const nonEmptyUserParts = userParts.filter( + (p) => p.type !== "text" || !!p.text, + ); + + // new message with tool calls moved to content + const assistantMessage: AssistantChatMessage = { + ...originalAssistantMessage, + content: nonEmptyAssistantParts, + toolCalls: undefined, // remove tool calls from the assistant message + }; + + const userMessage: UserChatMessage = { + role: "user", + content: nonEmptyUserParts, + }; + + return { + assistantMessage, + userMessage, + }; +} diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index e53f2129a..66481cb14 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -7,7 +7,7 @@ import { WebDriver, WebElement, WebView, - until, + until } from "vscode-extension-tester"; import { GlobalActions } from "../actions/Global.actions"; @@ -299,8 +299,6 @@ describe("GUI Test", () => { expect(await statusMessage.getText()).contain( "Continue viewed the git diff", ); - // wait for 30 seconds, promise - await new Promise((resolve) => setTimeout(resolve, 30000)); }).timeout(DEFAULT_TIMEOUT.MD * 100); it("should call tool after approval", async () => { @@ -367,8 +365,9 @@ describe("GUI Test", () => { }).timeout(DEFAULT_TIMEOUT.MD); }); - describe("Repeat back the system message", () => { + describe("should repeat back the system message", () => { it("should repeat back the system message", async () => { + await GUIActions.selectModeFromDropdown(view, "Chat"); await GUIActions.selectModelFromDropdown(view, "SYSTEM MESSAGE MOCK LLM"); const [messageInput] = await GUISelectors.getMessageInputFields(view); await messageInput.sendKeys("Hello"); @@ -376,8 +375,8 @@ describe("GUI Test", () => { await TestUtils.waitForSuccess(() => GUISelectors.getThreadMessageByText(view, "TEST_SYS_MSG"), ); - }); - }); + }).timeout(DEFAULT_TIMEOUT.XL * 1000); + }) describe("Chat Paths", () => { it("Send many messages → chat auto scrolls → go to history → open previous chat → it is scrolled to the bottom", async () => { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3768befe3..0f419444a 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -129,6 +129,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -142,7 +143,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/gui/package-lock.json b/gui/package-lock.json index d611543e2..c9ad23ed0 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -140,6 +140,7 @@ "handlebars": "^4.7.8", "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", + "iconv-lite": "^0.6.3", "ignore": "^5.3.1", "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", @@ -153,7 +154,7 @@ "node-html-markdown": "^1.3.0", "ollama": "^0.4.6", "onnxruntime-node": "1.14.0", - "openai": "^4.76.0", + "openai": "^4.104.0", "p-limit": "^6.1.0", "partial-json": "^0.1.7", "pg": "^8.11.3", diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index b7bc81c2e..002e5dce2 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -1,10 +1,15 @@ import { CheckIcon, ChevronDownIcon, + ExclamationTriangleIcon, InformationCircleIcon, } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { + isRecommendedAgentModel, + modelSupportsNativeTools, +} from "core/llm/toolSupport"; +import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; @@ -19,9 +24,23 @@ export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); - const agentModeSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + const useSystemTools = useAppSelector( + (state) => state.config.config.experimental?.onlyUseSystemMessageTools, + ); + const isAgentSupported = useMemo(() => { + if (!selectedModel) { + return undefined; + } + return !!useSystemTools || modelSupportsNativeTools(selectedModel); + }, [selectedModel, useSystemTools]); + + const isGoodAtAgentMode = useMemo(() => { + if (!selectedModel) { + return undefined; + } + return isRecommendedAgentModel(selectedModel.model); }, [selectedModel]); + const { mainEditor } = useMainEditor(); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); @@ -32,10 +51,10 @@ export function ModeSelect() { if (!selectedModel) { return; } - if (mode !== "chat" && !agentModeSupported) { + if (mode !== "chat" && !isAgentSupported) { dispatch(setMode("chat")); } - }, [mode, agentModeSupported, dispatch, selectedModel]); + }, [mode, isAgentSupported, selectedModel]); const cycleMode = useCallback(() => { if (mode === "chat") { @@ -76,6 +95,25 @@ export function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [cycleMode]); + const notSupported = (Not supported); + const notGreatAtAgent = ( + <> + + + {`${capitalize(mode)} might not work well with this model.`} + + + ); + return (
@@ -117,11 +155,7 @@ export function ModeSelect() {
{mode === "chat" && } - +
Plan @@ -138,19 +172,19 @@ export function ModeSelect() { Read-only/MCP tools available
- {agentModeSupported ? ( - + {isAgentSupported ? ( + <> + {!isGoodAtAgentMode && notGreatAtAgent} + + ) : ( - (Not supported) + notSupported )}
- + +
Agent @@ -167,12 +201,15 @@ export function ModeSelect() { All tools available
- {agentModeSupported ? ( - + {isAgentSupported ? ( + <> + {!isGoodAtAgentMode && notGreatAtAgent} + + ) : ( - (Not supported) + notSupported )}
diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 068432792..0dc09a438 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -5,7 +5,7 @@ import { TrashIcon, } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; -import { modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { renderChatMessage } from "core/util/messageContent"; import { useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -41,7 +41,7 @@ export default function ResponseActions({ ); const isPruned = useAppSelector((state) => state.session.isPruned); const ruleGenerationSupported = useMemo(() => { - return selectedModel && modelSupportsTools(selectedModel); + return selectedModel && modelSupportsNativeTools(selectedModel); }, [selectedModel]); const percent = Math.round((contextPercentage ?? 0) * 100); diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 85ea9a238..5911f537a 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -5,7 +5,7 @@ import { } from "@heroicons/react/24/outline"; import { LightBulbIcon as LightBulbIconSolid } from "@heroicons/react/24/solid"; import { InputModifiers } from "core"; -import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect"; +import { modelSupportsImages } from "core/llm/autodetect"; import { useContext, useRef } from "react"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -57,8 +57,6 @@ function InputToolbar(props: InputToolbarProps) { const isEnterDisabled = props.disabled || (isInEdit && codeToEdit.length === 0); - const toolsSupported = defaultModel && modelSupportsTools(defaultModel); - const supportsImages = defaultModel && modelSupportsImages( @@ -178,7 +176,7 @@ function InputToolbar(props: InputToolbarProps) { {!isInEdit && } {!props.toolbarOptions?.hideUseCodebase && !isInEdit && (