From af1b6b1bc4c0ce0e387e63ab674fd8ba79c862e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 29 Jul 2025 15:22:55 -0700 Subject: [PATCH 1/2] feat: plug and play system message tool frameworks --- core/index.d.ts | 5 +- core/tools/definitions/codebaseTool.ts | 12 +- core/tools/definitions/createNewFile.ts | 10 +- core/tools/definitions/createRuleBlock.ts | 10 +- core/tools/definitions/editFile.ts | 10 +- core/tools/definitions/fetchUrlContent.ts | 10 +- core/tools/definitions/globSearch.ts | 10 +- core/tools/definitions/grepSearch.ts | 10 +- core/tools/definitions/ls.ts | 10 +- .../definitions/readCurrentlyOpenFile.ts | 9 +- core/tools/definitions/readFile.ts | 10 +- core/tools/definitions/requestRule.ts | 10 +- core/tools/definitions/runTerminalCommand.ts | 10 +- .../definitions/searchAndReplaceInFile.ts | 10 +- core/tools/definitions/searchWeb.ts | 10 +- core/tools/definitions/viewDiff.ts | 9 +- core/tools/definitions/viewRepoMap.ts | 9 +- core/tools/definitions/viewSubdirectory.ts | 10 +- .../buildToolsSystemMessage.ts | 127 +++--------------- .../systemMessageTools/convertSystemTools.ts | 20 +-- .../systemMessageTools/detectToolCallStart.ts | 19 ++- .../interceptSystemToolCalls.ts | 20 +-- .../systemMessageTools/textifySystemTools.ts | 102 -------------- .../buildSystemMessage.vitest.ts} | 47 ++++--- .../detectToolCallStart.vitest.ts | 20 +-- .../toolCodeblocks/index.ts | 120 +++++++++++++++++ .../interceptSystemToolCalls.vitest.ts | 14 +- .../interceptionTests.vitest.ts | 0 .../parseSystemToolCall.ts | 40 ++---- .../parseSystemToolCall.vitest.ts | 46 ++----- core/tools/systemMessageTools/types.ts | 51 +++++++ gui/src/redux/thunks/streamNormalInput.ts | 18 ++- gui/src/redux/util/constructMessages.ts | 6 +- 33 files changed, 379 insertions(+), 445 deletions(-) delete mode 100644 core/tools/systemMessageTools/textifySystemTools.ts rename core/tools/systemMessageTools/{buildToolsSystemMessage.vitest.ts => toolCodeblocks/buildSystemMessage.vitest.ts} (85%) rename core/tools/systemMessageTools/{ => toolCodeblocks}/detectToolCallStart.vitest.ts (76%) create mode 100644 core/tools/systemMessageTools/toolCodeblocks/index.ts rename core/tools/systemMessageTools/{ => toolCodeblocks}/interceptSystemToolCalls.vitest.ts (96%) create mode 100644 core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts rename core/tools/systemMessageTools/{ => toolCodeblocks}/parseSystemToolCall.ts (79%) rename core/tools/systemMessageTools/{ => toolCodeblocks}/parseSystemToolCall.vitest.ts (87%) create mode 100644 core/tools/systemMessageTools/types.ts diff --git a/core/index.d.ts b/core/index.d.ts index f96cc7716..69fa259e3 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1084,7 +1084,10 @@ export interface Tool { faviconUrl?: string; group: string; originalFunctionName?: string; - systemMessageDescription?: string; + systemMessageDescription?: { + prefix: string; + exampleArgs?: Array<[string, string | number]>; + }; } interface ToolChoice { diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts index 0714a230b..71af43508 100644 --- a/core/tools/definitions/codebaseTool.ts +++ b/core/tools/definitions/codebaseTool.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const codebaseTool: Tool = { type: "function", @@ -27,9 +26,10 @@ 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?"]], - ), + systemMessageDescription: { + prefix: `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`, + exampleArgs: [ + ["query", "How is user authentication handled in this codebase?"], + ], + }, }; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 152af5693..e078bd261 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const createNewFileTool: Tool = { type: "function", @@ -31,12 +30,11 @@ 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:`, - [ + systemMessageDescription: { + prefix: `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:`, + exampleArgs: [ ["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 e6bf6689e..ccfd0ec59 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -1,6 +1,5 @@ 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')"; @@ -60,9 +59,8 @@ export const createRuleBlock: Tool = { }, }, }, - 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. + systemMessageDescription: { + prefix: `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} @@ -71,7 +69,7 @@ To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call a - globs: ${GLOB_ARG_DESC} - alwaysApply: ${ALWAYS_APPLY_DESC} For example:`, - [ + exampleArgs: [ ["name", "Use PropTypes"], [ "rule", @@ -84,5 +82,5 @@ For example:`, ["globs", "**/*.js"], ["alwaysApply", "false"], ], - ), + }, }; diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 59e20c681..b195d9ab0 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,7 +1,6 @@ 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 { @@ -40,19 +39,18 @@ export const editFileTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.EditExistingFile, - `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with + systemMessageDescription: { + prefix: `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:`, - [ + exampleArgs: [ ["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 ae57fc532..543aaa81a 100644 --- a/core/tools/definitions/fetchUrlContent.ts +++ b/core/tools/definitions/fetchUrlContent.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const fetchUrlContentTool: Tool = { type: "function", @@ -26,9 +25,8 @@ 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"]], - ), + systemMessageDescription: { + prefix: `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:`, + exampleArgs: [["url", "https://example.com"]], + }, }; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index e0f195a66..7fd77e0b2 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const globSearchTool: Tool = { type: "function", @@ -26,9 +25,8 @@ 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"]], - ), + systemMessageDescription: { + prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, + exampleArgs: [["pattern", "*.py"]], + }, }; diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index e276d5a8f..b322b5259 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const grepSearchTool: Tool = { type: "function", @@ -27,9 +26,8 @@ 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.*"]], - ), + systemMessageDescription: { + prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, + exampleArgs: [["query", ".*main_services.*"]], + }, }; diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts index 97d23f4f6..b96f44cde 100644 --- a/core/tools/definitions/ls.ts +++ b/core/tools/definitions/ls.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const lsTool: Tool = { type: "function", @@ -31,12 +30,11 @@ 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:`, - [ + systemMessageDescription: { + prefix: `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`, + exampleArgs: [ ["dirPath", "path/to/dir"], ["recursive", "false"], ], - ), + }, }; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 3f07f816f..df771b870 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readCurrentlyOpenFileTool: Tool = { type: "function", @@ -20,10 +19,8 @@ export const readCurrentlyOpenFileTool: Tool = { properties: {}, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.ReadCurrentlyOpenFile, - `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. + systemMessageDescription: { + prefix: `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 fb13eba05..bf693bb65 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readFileTool: Tool = { type: "function", @@ -27,9 +26,8 @@ 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"]], - ), + systemMessageDescription: { + prefix: `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:`, + exampleArgs: [["filepath", "path/to/the_file.txt"]], + }, }; diff --git a/core/tools/definitions/requestRule.ts b/core/tools/definitions/requestRule.ts index 4e2f1ef61..00bf8bd2c 100644 --- a/core/tools/definitions/requestRule.ts +++ b/core/tools/definitions/requestRule.ts @@ -1,6 +1,5 @@ import { ConfigDependentToolParams, GetTool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface RequestRuleArgs { name: string; @@ -60,9 +59,8 @@ export const requestRuleTool: GetTool = ({ rules }) => ({ }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.RequestRule, - getRequestRuleSystemMessageDescription(rules), - [["name", "rule_name"]], - ), + systemMessageDescription: { + prefix: getRequestRuleSystemMessageDescription(rules), + exampleArgs: [["name", "rule_name"]], + }, }); diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 8ab379e1b..09275061c 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,7 +1,6 @@ import os from "os"; import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; /** * Get the preferred shell for the current platform @@ -56,12 +55,11 @@ export const runTerminalCommandTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.RunTerminalCommand, - `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool + systemMessageDescription: { + prefix: `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"]], - ), + exampleArgs: [["command", "git log"]], + }, }; diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index 96dac65da..c43d96153 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface SearchAndReplaceInFileArgs { filepath: string; @@ -92,16 +91,15 @@ export const searchAndReplaceInFileTool: Tool = { }, }, }, - 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. + systemMessageDescription: { + prefix: `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:`, - [ + exampleArgs: [ ["filepath", "path/to/file.ts"], [ "diffs", @@ -119,5 +117,5 @@ ${SEARCH_AND_REPLACE_RULES} ]`, ], ], - ), + }, }; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index bcaa743a3..0770b121c 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const searchWebTool: Tool = { type: "function", @@ -26,9 +25,8 @@ 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?"]], - ), + systemMessageDescription: { + prefix: `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:`, + exampleArgs: [["query", "What is the current weather in San Francisco?"]], + }, }; diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index bf488f171..e8aaa8dd8 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewDiffTool: Tool = { type: "function", @@ -20,9 +19,7 @@ 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.`, - [], - ), + systemMessageDescription: { + prefix: `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 a58584fc1..17f9dac4c 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewRepoMapTool: Tool = { type: "function", @@ -20,9 +19,7 @@ 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.`, - [], - ), + systemMessageDescription: { + prefix: `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 11c27a775..08a1c83f7 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewSubdirectoryTool: Tool = { type: "function", @@ -26,9 +25,8 @@ 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"]], - ), + systemMessageDescription: { + prefix: `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.`, + exampleArgs: [["directory_path", "path/to/subdirectory"]], + }, }; diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.ts b/core/tools/systemMessageTools/buildToolsSystemMessage.ts index 8536c794f..750e6bb43 100644 --- a/core/tools/systemMessageTools/buildToolsSystemMessage.ts +++ b/core/tools/systemMessageTools/buildToolsSystemMessage.ts @@ -1,91 +1,13 @@ import { Tool } from "../.."; import { closeTag } from "./systemToolUtils"; +import { SystemMessageToolsFramework } from "./types"; 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 => { +export const generateToolsSystemMessage = ( + tools: Tool[], + framework: SystemMessageToolsFramework, +): string => { if (tools.length === 0) { return ""; } @@ -99,17 +21,17 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => { 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:`, - ); + instructions.push(framework.systemMessagePrefix); if (withPredefinedMessage.length > 0) { instructions.push(`\nThe following tools are available to you:`); for (const tool of withPredefinedMessage) { - instructions.push(`\n${tool.systemMessageDescription}`); + const definition = framework.createSystemMessageExampleCall( + tool.function.name, + tool.systemMessageDescription!.prefix, + tool.systemMessageDescription!.exampleArgs, + ); + instructions.push(`\n${definition}`); } } @@ -120,7 +42,7 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => { for (const tool of tools) { try { - const definition = toolToSystemToolDefinition(tool); + const definition = framework.toolToSystemToolDefinition(tool); instructions.push(`\n${definition}`); } catch (e) { console.error( @@ -131,35 +53,28 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => { } instructions.push(`\nFor example, this tool definition:\n`); - instructions.push(EXAMPLE_DYNAMIC_TOOL); + instructions.push(framework.exampleDynamicToolDefinition); instructions.push("\nCan be called like this:\n"); - instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL); + instructions.push(framework.exampleDynamicToolCall); } - 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("\n" + framework.systemMessageSuffix); instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`); return instructions.join("\n"); }; export function addSystemMessageToolsToSystemMessage( + framework: SystemMessageToolsFramework, baseSystemMessage: string, systemMessageTools: Tool[], ): string { let systemMessage = baseSystemMessage; if (systemMessageTools.length > 0) { - const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools); + const toolsSystemMessage = generateToolsSystemMessage( + systemMessageTools, + framework, + ); systemMessage += `\n\n${toolsSystemMessage}`; } diff --git a/core/tools/systemMessageTools/convertSystemTools.ts b/core/tools/systemMessageTools/convertSystemTools.ts index 4517915d0..5002bfcdd 100644 --- a/core/tools/systemMessageTools/convertSystemTools.ts +++ b/core/tools/systemMessageTools/convertSystemTools.ts @@ -12,22 +12,7 @@ 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"); -} +import { SystemMessageToolsFramework } from "./types"; function toolCallStateToSystemToolOutput(state: ToolCallState): string { let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; @@ -46,6 +31,7 @@ function toolCallStateToSystemToolOutput(state: ToolCallState): string { export function convertToolCallStatesToSystemCallsAndOutput( originalAssistantMessage: AssistantChatMessage, toolCallStates: ToolCallState[], + framework: SystemMessageToolsFramework, ): { assistantMessage: AssistantChatMessage; userMessage: UserChatMessage; @@ -55,7 +41,7 @@ export function convertToolCallStatesToSystemCallsAndOutput( parts.push( ...toolCallStates.map((state) => ({ type: "text" as const, - text: toolCallStateToSystemToolCall(state), + text: framework.toolCallStateToSystemToolCall(state), })), ); } diff --git a/core/tools/systemMessageTools/detectToolCallStart.ts b/core/tools/systemMessageTools/detectToolCallStart.ts index f99ce03d5..e143411dd 100644 --- a/core/tools/systemMessageTools/detectToolCallStart.ts +++ b/core/tools/systemMessageTools/detectToolCallStart.ts @@ -1,19 +1,16 @@ -let boundaryTypeIndex = 0; +import { SystemMessageToolsFramework } from "./types"; -// 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) { +export function detectToolCallStart( + buffer: string, + toolCallFramework: SystemMessageToolsFramework, +) { + const starts = toolCallFramework.acceptedToolCallStarts; 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]; + for (let i = 0; i < starts.length; i++) { + const [start, replacement] = starts[i]; if (lowerCaseBuffer.startsWith(start)) { // for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive if (i !== 0) { diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.ts b/core/tools/systemMessageTools/interceptSystemToolCalls.ts index 31fb562bf..a89fbdcfb 100644 --- a/core/tools/systemMessageTools/interceptSystemToolCalls.ts +++ b/core/tools/systemMessageTools/interceptSystemToolCalls.ts @@ -1,12 +1,12 @@ 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"; +import { + getInitialToolCallParseState, + SystemMessageToolsFramework, + ToolCallParseState, +} from "./types"; /* Function to intercept tool calls in markdown code blocks format from a chat message stream @@ -24,6 +24,7 @@ import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils"; export async function* interceptSystemToolCalls( messageGenerator: AsyncGenerator, abortController: AbortController, + systemToolFramework: SystemMessageToolsFramework, ): AsyncGenerator { let buffer = ""; let parseState: ToolCallParseState | undefined; @@ -70,19 +71,22 @@ export async function* interceptSystemToolCalls( buffer += chunk; if (!parseState) { const { isInPartialStart, isInToolCall, modifiedBuffer } = - detectToolCallStart(buffer); + detectToolCallStart(buffer, systemToolFramework); if (isInPartialStart) { continue; } if (isInToolCall) { - parseState = getInitialTooLCallParseState(); + parseState = getInitialToolCallParseState(); buffer = modifiedBuffer; } } if (parseState && !parseState.done) { - const delta = handleToolCallBuffer(buffer, parseState); + const delta = systemToolFramework.handleToolCallBuffer( + buffer, + parseState, + ); if (delta) { yield [ { diff --git a/core/tools/systemMessageTools/textifySystemTools.ts b/core/tools/systemMessageTools/textifySystemTools.ts deleted file mode 100644 index f654037df..000000000 --- a/core/tools/systemMessageTools/textifySystemTools.ts +++ /dev/null @@ -1,102 +0,0 @@ -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/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/buildSystemMessage.vitest.ts similarity index 85% rename from core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/buildSystemMessage.vitest.ts index 70215c477..669d1c103 100644 --- a/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/buildSystemMessage.vitest.ts @@ -1,12 +1,13 @@ import { describe, expect, it } from "vitest"; -import { Tool } from "../.."; +import { Tool } from "../../.."; import { TOOL_INSTRUCTIONS_TAG, addSystemMessageToolsToSystemMessage, - createSystemMessageExampleCall, generateToolsSystemMessage, -} from "./buildToolsSystemMessage"; -import { closeTag } from "./systemToolUtils"; +} from "../buildToolsSystemMessage"; + +import { SystemMessageToolCodeblocksFramework } from "."; +import { closeTag } from "../systemToolUtils"; const SHARED_TOOL_FIELDS = { displayTitle: "DUD", @@ -15,9 +16,11 @@ const SHARED_TOOL_FIELDS = { type: "function" as const, }; +const framework = new SystemMessageToolCodeblocksFramework(); + describe("createSystemMessageExampleCall", () => { it("creates a system message example call with no args", () => { - const result = createSystemMessageExampleCall( + const result = framework.createSystemMessageExampleCall( "test_tool", "Use this tool to test things", ); @@ -28,7 +31,7 @@ describe("createSystemMessageExampleCall", () => { }); it("creates a system message example call with args", () => { - const result = createSystemMessageExampleCall( + const result = framework.createSystemMessageExampleCall( "test_tool", "Use this tool to test things", [ @@ -49,7 +52,7 @@ describe("createSystemMessageExampleCall", () => { it("handles multiline arg values correctly", () => { const multilineValue = "value\nwith\nmultiple\nlines"; - const result = createSystemMessageExampleCall( + const result = framework.createSystemMessageExampleCall( "test_tool", "Use this tool to test things", [["arg1", multilineValue]], @@ -63,7 +66,7 @@ describe("createSystemMessageExampleCall", () => { describe("generateToolsSystemMessage", () => { it("returns empty string for empty tools array", () => { - const result = generateToolsSystemMessage([]); + const result = generateToolsSystemMessage([], framework); expect(result).toBe(""); }); @@ -81,12 +84,14 @@ describe("generateToolsSystemMessage", () => { required: [], }, }, - systemMessageDescription: customDescription, + systemMessageDescription: { + prefix: customDescription, + }, ...SHARED_TOOL_FIELDS, }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check structure rather than exact text expect(result).includes(TOOL_INSTRUCTIONS_TAG); @@ -123,7 +128,7 @@ describe("generateToolsSystemMessage", () => { }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check for key elements without requiring exact wording expect(result).includes(`TOOL_NAME: ${toolName}`); @@ -150,7 +155,9 @@ describe("generateToolsSystemMessage", () => { required: [], }, }, - systemMessageDescription: customMsg, + systemMessageDescription: { + prefix: customMsg, + }, ...SHARED_TOOL_FIELDS, }, { @@ -172,7 +179,7 @@ describe("generateToolsSystemMessage", () => { }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check for both types of tools expect(result).includes(customMsg); @@ -202,7 +209,7 @@ describe("generateToolsSystemMessage", () => { }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check for example sections without exact text expect(result).includes("```tool_definition"); @@ -221,7 +228,11 @@ describe("generateToolsSystemMessage", () => { describe("addSystemMessageToolsToSystemMessage", () => { it("returns original system message when no tools are provided", () => { const baseMessage = "This is the base system message"; - const result = addSystemMessageToolsToSystemMessage(baseMessage, []); + const result = addSystemMessageToolsToSystemMessage( + framework, + baseMessage, + [], + ); expect(result).toBe(baseMessage); }); @@ -243,7 +254,11 @@ describe("addSystemMessageToolsToSystemMessage", () => { }, ]; - const result = addSystemMessageToolsToSystemMessage(baseMessage, tools); + const result = addSystemMessageToolsToSystemMessage( + framework, + baseMessage, + tools, + ); expect(result.startsWith(baseMessage)).toBe(true); expect(result).includes(TOOL_INSTRUCTIONS_TAG); diff --git a/core/tools/systemMessageTools/detectToolCallStart.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/detectToolCallStart.vitest.ts similarity index 76% rename from core/tools/systemMessageTools/detectToolCallStart.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/detectToolCallStart.vitest.ts index 715113475..297c58ec4 100644 --- a/core/tools/systemMessageTools/detectToolCallStart.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/detectToolCallStart.vitest.ts @@ -1,10 +1,12 @@ import { describe, expect, it } from "vitest"; -import { detectToolCallStart } from "./detectToolCallStart"; +import { SystemMessageToolCodeblocksFramework } from "."; +import { detectToolCallStart } from "../detectToolCallStart"; describe("detectToolCallStart", () => { + let framework = new SystemMessageToolCodeblocksFramework(); it("detects standard tool call start", () => { const buffer = "```tool\nTOOL_NAME: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -13,7 +15,7 @@ describe("detectToolCallStart", () => { it("detects tool_name start without codeblock", () => { const buffer = "tool_name: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -22,7 +24,7 @@ describe("detectToolCallStart", () => { it("detects case-insensitive tool call start", () => { const buffer = "```ToOl\nTOOL_NAME: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -31,7 +33,7 @@ describe("detectToolCallStart", () => { it("detects case-insensitive tool_name start", () => { const buffer = "ToOl_NaMe: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -40,7 +42,7 @@ describe("detectToolCallStart", () => { it("identifies partial tool call start", () => { const buffer = "```to"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(true); @@ -49,7 +51,7 @@ describe("detectToolCallStart", () => { it("identifies partial tool_name start", () => { const buffer = "tool_na"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(true); @@ -58,7 +60,7 @@ describe("detectToolCallStart", () => { it("does not detect tool call in unrelated text", () => { const buffer = "This is some regular text."; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(false); @@ -67,7 +69,7 @@ describe("detectToolCallStart", () => { it("does not detect tool call in similar but different markdown block", () => { const buffer = "```javascript\nconst x = 10;"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(false); diff --git a/core/tools/systemMessageTools/toolCodeblocks/index.ts b/core/tools/systemMessageTools/toolCodeblocks/index.ts new file mode 100644 index 000000000..97baa19fa --- /dev/null +++ b/core/tools/systemMessageTools/toolCodeblocks/index.ts @@ -0,0 +1,120 @@ +import { Tool, ToolCallState } from "../../.."; +import { SystemMessageToolsFramework } from "../types"; +import { handleToolCallBuffer } from "./parseSystemToolCall"; + +export class SystemMessageToolCodeblocksFramework + implements SystemMessageToolsFramework +{ + // Poor models are really bad at following instructions, alternate starts allowed: + acceptedToolCallStarts: [string, string][] = [ + ["```tool\n", "```tool\n"], + ["tool_name:", "```tool\nTOOL_NAME:"], + ]; + + 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"); + } + + handleToolCallBuffer = handleToolCallBuffer; + + 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(); + } + + systemMessagePrefix = `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User. +To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`; + + systemMessageSuffix = `If 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 +Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line. +Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant. +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.`; + + exampleDynamicToolDefinition = ` +\`\`\`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(); + + exampleDynamicToolCall = ` +\`\`\`tool +TOOL_NAME: example_tool +BEGIN_ARG: arg_1 +The value +of arg 1 +END_ARG +BEGIN_ARG: arg_2 +3 +END_ARG +\`\`\``.trim(); + + createSystemMessageExampleCall( + toolName: string, + prefix: string, + exampleArgs: Array<[string, string | number]> = [], + ) { + let callExample = `\`\`\`tool +TOOL_NAME: ${toolName}`; + + // Add each argument dynamically + for (const [argName, argValue] of exampleArgs) { + callExample += ` +BEGIN_ARG: ${argName} +${argValue} +END_ARG`; + } + + callExample += ` +\`\`\``; + + return `${prefix.trim()} +${callExample}`; + } +} diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/interceptSystemToolCalls.vitest.ts similarity index 96% rename from core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/interceptSystemToolCalls.vitest.ts index 756125bd4..a636cc6a9 100644 --- a/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/interceptSystemToolCalls.vitest.ts @@ -1,9 +1,11 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { AssistantChatMessage, ChatMessage, PromptLog } from "../.."; -import { interceptSystemToolCalls } from "./interceptSystemToolCalls"; +import { SystemMessageToolCodeblocksFramework } from "."; +import { AssistantChatMessage, ChatMessage, PromptLog } from "../../.."; +import { interceptSystemToolCalls } from "../interceptSystemToolCalls"; describe("interceptSystemToolCalls", () => { let abortController: AbortController; + let framework = new SystemMessageToolCodeblocksFramework(); beforeEach(() => { abortController = new AbortController(); @@ -27,6 +29,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); let result = await generator.next(); @@ -64,6 +67,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); const result = await generator.next(); @@ -91,6 +95,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); const result = await generator.next(); @@ -116,6 +121,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // First chunk should be normal text @@ -185,6 +191,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // First chunk should be normal text @@ -249,6 +256,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); let result; @@ -271,6 +279,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // Process the first part @@ -300,6 +309,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // Skip to number arg end diff --git a/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts new file mode 100644 index 000000000..e69de29bb diff --git a/core/tools/systemMessageTools/parseSystemToolCall.ts b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.ts similarity index 79% rename from core/tools/systemMessageTools/parseSystemToolCall.ts rename to core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.ts index 0300654d9..acba31727 100644 --- a/core/tools/systemMessageTools/parseSystemToolCall.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.ts @@ -1,34 +1,12 @@ -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, -}); +import { ToolCallDelta } from "../../.."; +import { createDelta } from "../systemToolUtils"; +import { ToolCallParseState } from "../types"; /* 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, @@ -72,14 +50,14 @@ export function handleToolCallBuffer( } return; default: - if (state.isOnArgBeginLine) { + if (state.isWithinArgStart) { 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; + state.isWithinArgStart = false; const argPrefix = state.processedArgNames.size === 0 ? "{" : ","; return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId); } @@ -87,8 +65,8 @@ export function handleToolCallBuffer( if (isNewLine) { const isEndArgTag = line.match(/end_?arg/i); if (isEndArgTag) { - let trimmedValue = state.currentArgLines.join("").trim(); - state.currentArgLines.length = 0; + let trimmedValue = state.currentArgChunks.join("").trim(); + state.currentArgChunks.length = 0; state.processedArgNames.add(state.currentArgName); state.currentArgName = undefined; @@ -120,14 +98,14 @@ export function handleToolCallBuffer( return createDelta("", stringifiedArg, state.toolCallId); } } else { - state.currentArgLines.push(line); + state.currentArgChunks.push(line); } } } else { // Check for entry into arg const isBeginArgLine = line.match(/begin_?arg:/i); if (isBeginArgLine) { - state.isOnArgBeginLine = true; + state.isWithinArgStart = true; } // Check for exit diff --git a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.vitest.ts similarity index 87% rename from core/tools/systemMessageTools/parseSystemToolCall.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.vitest.ts index 2aeac2ce8..95fae25b6 100644 --- a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.vitest.ts @@ -1,32 +1,12 @@ 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), - }); - }); -}); +import { getInitialToolCallParseState, ToolCallParseState } from "../types"; +import { handleToolCallBuffer } from "./parseSystemToolCall"; describe("handleToolCallBuffer", () => { let state: ToolCallParseState; beforeEach(() => { - state = getInitialTooLCallParseState(); + state = getInitialToolCallParseState(); }); it("handles the ```tool\ntool_name the name", () => { @@ -88,7 +68,7 @@ describe("handleToolCallBuffer", () => { const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state); expect(result).toBeUndefined(); - expect(state.isOnArgBeginLine).toBe(true); + expect(state.isWithinArgStart).toBe(true); const newLineResult = handleToolCallBuffer("\n", state); @@ -101,7 +81,7 @@ describe("handleToolCallBuffer", () => { id: expect.any(String), }); expect(state.currentArgName).toBe("test_arg"); - expect(state.isOnArgBeginLine).toBe(false); + expect(state.isWithinArgStart).toBe(false); }); it("handles case-insensitive begin arg", () => { @@ -109,7 +89,7 @@ describe("handleToolCallBuffer", () => { const result = handleToolCallBuffer("begin_arg: test_arg", state); expect(result).toBeUndefined(); - expect(state.isOnArgBeginLine).toBe(true); + expect(state.isWithinArgStart).toBe(true); const newLineResult = handleToolCallBuffer("\n", state); @@ -135,13 +115,13 @@ describe("handleToolCallBuffer", () => { const newLineResult2 = handleToolCallBuffer("\n", state); expect(newLineResult2).toBeUndefined(); - expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]); + expect(state.currentArgChunks).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"]; + state.currentArgChunks = ["string value"]; const result = handleToolCallBuffer("END_ARG", state); expect(result).toBeUndefined(); @@ -163,7 +143,7 @@ describe("handleToolCallBuffer", () => { it("handles case-insensitive end arg", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = ["string value"]; + state.currentArgChunks = ["string value"]; const result = handleToolCallBuffer("end_arg", state); expect(result).toBeUndefined(); @@ -183,7 +163,7 @@ describe("handleToolCallBuffer", () => { it("attempts to parse JSON values", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = ["123"]; + state.currentArgChunks = ["123"]; handleToolCallBuffer("END_ARG", state); const newLineResult = handleToolCallBuffer("\n", state); @@ -201,7 +181,7 @@ describe("handleToolCallBuffer", () => { it("handles multiple arguments", () => { // Setup first arg state.currentLineIndex = 2; - state.isOnArgBeginLine = true; + state.isWithinArgStart = true; state.lineChunks[2] = ["BEGIN_ARG: first_arg"]; handleToolCallBuffer("\n", state); @@ -213,7 +193,7 @@ describe("handleToolCallBuffer", () => { expect(state.processedArgNames.has("first_arg")).toBe(true); // Setup second arg - state.isOnArgBeginLine = true; + state.isWithinArgStart = true; handleToolCallBuffer("BEGIN_ARG: second_arg", state); handleToolCallBuffer("\n", state); handleToolCallBuffer("value2", state); @@ -270,7 +250,7 @@ describe("handleToolCallBuffer", () => { it("handles JSON array args", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = [ + state.currentArgChunks = [ "[\n", '"------- SEARCH\n', " subtract(number) {\n", diff --git a/core/tools/systemMessageTools/types.ts b/core/tools/systemMessageTools/types.ts new file mode 100644 index 000000000..22496a7d9 --- /dev/null +++ b/core/tools/systemMessageTools/types.ts @@ -0,0 +1,51 @@ +import { Tool, ToolCallDelta, ToolCallState } from "../.."; +import { generateOpenAIToolCallId } from "./systemToolUtils"; + +export interface SystemMessageToolsFramework { + acceptedToolCallStarts: [string, string][]; + + toolCallStateToSystemToolCall(state: ToolCallState): string; + + handleToolCallBuffer( + chunk: string, + state: ToolCallParseState, + ): ToolCallDelta | undefined; + + toolToSystemToolDefinition: (tool: Tool) => string; + + systemMessagePrefix: string; + + systemMessageSuffix: string; + + exampleDynamicToolDefinition: string; + + exampleDynamicToolCall: string; + + createSystemMessageExampleCall( + toolName: string, + prefix: string, + exampleArgs?: Array<[string, string | number]>, + ): string; +} + +export type ToolCallParseState = { + toolCallId: string; + isWithinArgStart: boolean; + currentArgName: string | undefined; + currentArgChunks: string[]; + processedArgNames: Set; + currentLineIndex: number; + lineChunks: string[][]; + done: boolean; +}; + +export const getInitialToolCallParseState = (): ToolCallParseState => ({ + toolCallId: generateOpenAIToolCallId(), + isWithinArgStart: false, + currentArgName: undefined, + currentArgChunks: [], + currentLineIndex: 0, + processedArgNames: new Set(), + lineChunks: [], + done: false, +}); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index fbff48d23..1bab0f04f 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -24,6 +24,7 @@ import { constructMessages } from "../util/constructMessages"; import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage"; import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls"; +import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks"; import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; import { callToolById } from "./callToolById"; @@ -146,6 +147,9 @@ export const streamNormalInput = createAsyncThunk< // Use the centralized selector to determine if system message tools should be used const useSystemTools = selectUseSystemMessageTools(state); const useNativeTools = !useSystemTools && supportsNativeTools; + const systemToolsFramework = useSystemTools + ? new SystemMessageToolCodeblocksFramework() + : undefined; // Construct completion options let completionOptions: LLMFullCompletionOptions = {}; @@ -170,8 +174,12 @@ export const streamNormalInput = createAsyncThunk< selectedChatModel, ); - const systemMessage = useSystemTools - ? addSystemMessageToolsToSystemMessage(baseSystemMessage, activeTools) + const systemMessage = systemToolsFramework + ? addSystemMessageToolsToSystemMessage( + systemToolsFramework, + baseSystemMessage, + activeTools, + ) : baseSystemMessage; const withoutMessageIds = state.session.history.map((item) => { @@ -184,7 +192,7 @@ export const streamNormalInput = createAsyncThunk< systemMessage, state.config.config.rules, state.ui.ruleSettings, - !useNativeTools, + systemToolsFramework, ); // TODO parallel tool calls will cause issues with this @@ -232,8 +240,8 @@ export const streamNormalInput = createAsyncThunk< }, streamAborter.signal, ); - if (!useNativeTools && activeTools.length > 0) { - gen = interceptSystemToolCalls(gen, streamAborter); + if (systemToolsFramework && activeTools.length > 0) { + gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework); } let next = await gen.next(); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index ac70bdafa..f75eb8b49 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -15,6 +15,7 @@ import { NO_TOOL_CALL_OUTPUT_MESSAGE, } from "core/tools/constants"; import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools"; +import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types"; import { findLast, findLastIndex } from "core/util/findLast"; import { normalizeToMessageParts, @@ -30,7 +31,7 @@ export function constructMessages( baseSystemMessage: string | undefined, availableRules: RuleWithSource[], rulePolicies: RulePolicies, - useSystemMessageTools?: boolean, + useSystemToolsFramework?: SystemMessageToolsFramework, ): { messages: ChatMessage[]; appliedRules: RuleWithSource[]; @@ -95,11 +96,12 @@ export function constructMessages( }); } else if (item.message.role === "assistant") { // When using system message tools, convert tool calls/states to text content - if (item.toolCallStates?.length && useSystemMessageTools) { + if (item.toolCallStates?.length && useSystemToolsFramework) { const { userMessage, assistantMessage } = convertToolCallStatesToSystemCallsAndOutput( item.message, item.toolCallStates ?? [], + useSystemToolsFramework, ); msgs.push({ message: assistantMessage, From 031179ecf7107e4cbd0ae319415cad80c46ad83a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 29 Jul 2025 15:31:57 -0700 Subject: [PATCH 2/2] fix: remove blank test file --- .../systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts diff --git a/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts deleted file mode 100644 index e69de29bb..000000000