Merge pull request #6874 from continuedev/dallin/system-tools-plug-and-play

feat: Plug and play system message tool frameworks
This commit is contained in:
Dallin Romney 2025-08-06 18:04:39 -07:00 • committed by GitHub
commit f216ec8cdc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 379 additions and 445 deletions

5
core/index.d.ts vendored
View file

@ -1093,7 +1093,10 @@ export interface Tool {
faviconUrl?: string;
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
systemMessageDescription?: {
prefix: string;
exampleArgs?: Array<[string, string | number]>;
};
defaultToolPolicy?: ToolPolicy;
}

View file

@ -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",
@ -28,9 +27,10 @@ export const codebaseTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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?"],
],
},
};

View file

@ -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",
@ -32,12 +31,11 @@ export const createNewFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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"],
],
),
},
};

View file

@ -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')";
@ -61,9 +60,8 @@ export const createRuleBlock: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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}
@ -72,7 +70,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",
@ -85,5 +83,5 @@ For example:`,
["globs", "**/*.js"],
["alwaysApply", "false"],
],
),
},
};

View file

@ -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 {
@ -41,19 +40,18 @@ export const editFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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 ...",
],
],
),
},
};

View file

@ -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",
@ -27,9 +26,8 @@ export const fetchUrlContentTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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"]],
},
};

View file

@ -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",
@ -27,9 +26,8 @@ export const globSearchTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
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"]],
},
};

View file

@ -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",
@ -28,9 +27,8 @@ export const grepSearchTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
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.*"]],
},
};

View file

@ -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",
@ -32,12 +31,11 @@ export const lsTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
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"],
],
),
},
};

View file

@ -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",
@ -21,10 +20,8 @@ export const readCurrentlyOpenFileTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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`,
[],
),
},
};

View file

@ -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,10 +26,9 @@ export const readFileTool: Tool = {
},
},
},
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"]],
},
defaultToolPolicy: "allowedWithoutPermission",
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"]],
),
};

View file

@ -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,10 +59,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
},
},
},
systemMessageDescription: {
prefix: getRequestRuleSystemMessageDescription(rules),
exampleArgs: [["name", "rule_name"]],
},
defaultToolPolicy: "disabled",
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RequestRule,
getRequestRuleSystemMessageDescription(rules),
[["name", "rule_name"]],
),
});

View file

@ -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
@ -57,12 +56,11 @@ export const runTerminalCommandTool: Tool = {
},
},
defaultToolPolicy: "allowedWithPermission",
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"]],
},
};

View file

@ -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;
@ -90,16 +89,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 filepath (relative to the root of the workspace) and 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 filepath (relative to the root of the workspace) and 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",
@ -109,6 +107,6 @@ ${SEARCH_AND_REPLACE_RULES}
]`,
],
],
),
},
defaultToolPolicy: "allowedWithPermission",
};

View file

@ -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",
@ -27,9 +26,8 @@ export const searchWebTool: Tool = {
},
},
defaultToolPolicy: "allowedWithoutPermission",
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?"]],
},
};

View file

@ -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,10 +19,8 @@ export const viewDiffTool: Tool = {
properties: {},
},
},
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.`,
},
defaultToolPolicy: "allowedWithoutPermission",
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.`,
[],
),
};

View file

@ -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,10 +19,8 @@ export const viewRepoMapTool: Tool = {
properties: {},
},
},
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.`,
},
defaultToolPolicy: "allowedWithPermission",
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.`,
[],
),
};

View file

@ -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,10 +25,9 @@ export const viewSubdirectoryTool: Tool = {
},
},
},
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"]],
},
defaultToolPolicy: "allowedWithPermission",
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"]],
),
};

View file

@ -1,91 +1,13 @@
import { Tool } from "../..";
import { closeTag } from "./systemToolUtils";
import { SystemMessageToolsFramework } from "./types";
export const TOOL_INSTRUCTIONS_TAG = "<tool_use_instructions>";
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}`;
}

View file

@ -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),
})),
);
}

View file

@ -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) {

View file

@ -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<ChatMessage[], PromptLog | undefined>,
abortController: AbortController,
systemToolFramework: SystemMessageToolsFramework,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
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 [
{

View file

@ -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,
};
}

View file

@ -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);

View file

@ -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);

View file

@ -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}`;
}
}

View file

@ -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

View file

@ -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<string>;
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

View file

@ -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",

View file

@ -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<string>;
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,
});

View file

@ -25,6 +25,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";
@ -147,6 +148,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 = {};
@ -171,8 +175,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) => {
@ -185,7 +193,7 @@ export const streamNormalInput = createAsyncThunk<
systemMessage,
state.config.config.rules,
state.ui.ruleSettings,
!useNativeTools,
systemToolsFramework,
);
// TODO parallel tool calls will cause issues with this
@ -233,8 +241,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();

View file

@ -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,