feat: system message tools

This commit is contained in:
Dallin Romney 2025-07-20 10:52:22 +02:00
parent bdf9b37287
commit b708c355a6
13 changed files with 678 additions and 10 deletions

1
core/index.d.ts vendored
View file

@ -1080,6 +1080,7 @@ export interface Tool {
faviconUrl?: string;
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
}
interface ToolChoice {

View file

@ -524,7 +524,7 @@ export abstract class BaseLLM implements ILLM {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls) {
} else if (msg.role === "assistant" && msg.toolCalls?.length) {
contentToShow = msg.toolCalls
?.map(
(toolCall) =>
@ -532,10 +532,7 @@ export abstract class BaseLLM implements ILLM {
)
.join("\n");
} else if ("content" in msg) {
if (Array.isArray(msg.content)) {
msg.content = renderChatMessage(msg);
}
contentToShow = msg.content;
contentToShow = renderChatMessage(msg);
}
return `<${msg.role}>\n${contentToShow}\n\n`;

2
core/tools/constants.ts Normal file
View file

@ -0,0 +1,2 @@
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";

View file

@ -0,0 +1,157 @@
import { Tool } from "../..";
import { closeTag } from "./systemToolUtils";
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.argDescription;
}
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[]) => {
if (tools.length === 0) {
return undefined;
}
const withPredefinedMessage = tools.filter(
(tool) => !!tool.systemMessageDescription,
);
const withDynamicMessage = tools.filter(
(tool) => !tool.systemMessageDescription,
);
let prompt = `${TOOL_INSTRUCTIONS_TAG}\n`;
prompt += `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`;
prompt += `\nTo use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`;
if (withPredefinedMessage.length > 0) {
prompt += `\n\nThe following tools are available to you:`;
for (const tool of withPredefinedMessage) {
prompt += "\n\n";
prompt += tool.systemMessageDescription;
}
}
if (withDynamicMessage.length > 0) {
prompt += `\n\nAlso, these additional tool definitions show other tools you can call with the same syntax:`;
for (const tool of tools) {
try {
const definition = toolToSystemToolDefinition(tool);
prompt += "\n\n";
prompt += definition;
} catch (e) {
console.error(
"Failed to convert tool to system message tool:\n" +
JSON.stringify(tool),
);
}
}
prompt += `\n\nFor example, this tool definition:\n\n`;
prompt += EXAMPLE_DYNAMIC_TOOL;
prompt += "\n\nCan be called like this:\n";
prompt += EXAMPLE_DYNAMIC_TOOL_CALL;
}
prompt += `\n\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`;
prompt += `\nThen send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`;
prompt += `\nDo not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`;
prompt += `\nYou 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.`;
prompt += `\n${closeTag(TOOL_INSTRUCTIONS_TAG)}`;
return prompt;
};
export function addSystemMessageToolsToSystemMessage(
baseSystemMessage: string,
systemMessageTools: Tool[],
): string {
let systemMessage = baseSystemMessage;
if (systemMessageTools.length > 0) {
const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools);
systemMessage += `\n\n${toolsSystemMessage}`;
}
return systemMessage;
}

View file

@ -0,0 +1,37 @@
let boundaryTypeIndex = 0;
// Poor models are really bad at following instructions
// Give some leeway in how the initiate
const acceptedToolStarts: [string, string][] = [
["```tool\n", "```tool\n"],
["tool_name:", "```tool\ntool_name:"],
];
export function detectToolCallStart(buffer: string) {
let modifiedBuffer = buffer;
let isInToolCall = false;
let isInPartialStart = false;
const lowerCaseBuffer = buffer.toLowerCase();
for (let i = 0; i < acceptedToolStarts.length; i++) {
const [start, _] = acceptedToolStarts[i];
if (lowerCaseBuffer.startsWith(start)) {
boundaryTypeIndex = i;
// for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive
if (boundaryTypeIndex !== 0) {
modifiedBuffer = buffer.replace(
new RegExp(start, "i"),
acceptedToolStarts[boundaryTypeIndex][1],
);
}
isInToolCall = true;
break;
} else if (start.startsWith(lowerCaseBuffer)) {
isInPartialStart = true;
}
}
return {
isInToolCall,
isInPartialStart,
modifiedBuffer,
};
}

View file

@ -0,0 +1,126 @@
import { ChatMessage, PromptLog, TextMessagePart } from "../..";
import { normalizeToMessageParts } from "../../util/messageContent";
import { detectToolCallStart } from "./detectToolCallStart";
import { generateOpenAIToolCallId } from "./openAiToolCallId";
import {
getInitialTooLCallParseState,
handleToolCallBuffer,
ToolCallParseState,
} from "./parseSystemToolCall";
import { splitAtCodeblocksAndNewLines } from "./systemToolUtils";
/*
Function to intercept tool calls in markdown code blocks format from a chat message stream
1. Skips non-assistant messages
2. Intercepts text that looks like a tool call in a markdown code block format:
```tool
TOOL_NAME: example_tool
BEGIN_ARG: arg1
value
END_ARG
```
3. Parses tool calls line by line and generates proper tool call deltas
4. Once the tool call is complete, resets state for potential future tool calls
*/
export async function* interceptSystemToolCalls(
messageGenerator: AsyncGenerator<ChatMessage[], PromptLog | undefined>,
abortController: AbortController,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
let hasSeenToolCall = false;
let inToolCall = false;
let currentToolCallId: string | undefined = undefined;
let buffer = "";
let parseState: ToolCallParseState | undefined;
while (true) {
const result = await messageGenerator.next();
if (result.done) {
return result.value;
} else {
for await (const message of result.value) {
if (abortController.signal.aborted || parseState?.done) {
break;
}
// Skip non-assistant messages or messages with native tool calls
if (message.role !== "assistant" || message.toolCalls) {
yield [message];
continue;
}
const parts = normalizeToMessageParts(message);
// Image output cannot be combined with tools
if (parts.find((part) => part.type === "imageUrl")) {
yield [message];
continue;
}
const chunks = (parts as TextMessagePart[])
.map((part) => splitAtCodeblocksAndNewLines(part.text))
.flat();
for (const chunk of chunks) {
buffer += chunk;
if (!inToolCall) {
const { isInPartialStart, isInToolCall, modifiedBuffer } =
detectToolCallStart(buffer);
if (isInPartialStart) {
continue;
}
if (isInToolCall) {
inToolCall = true;
buffer = modifiedBuffer;
}
}
if (inToolCall) {
if (!currentToolCallId) {
currentToolCallId = generateOpenAIToolCallId();
}
if (!parseState) {
parseState = getInitialTooLCallParseState();
}
const delta = handleToolCallBuffer(
buffer,
currentToolCallId,
parseState,
);
if (delta) {
hasSeenToolCall = true;
yield [
{
...message,
content: "",
toolCalls: [delta],
},
];
}
if (parseState.done) {
inToolCall = false;
currentToolCallId = undefined;
parseState = undefined;
}
} else {
// Prevent content after tool calls for now
if (hasSeenToolCall) {
continue;
}
// Yield normal assistant message
yield [
{
...message,
content: [{ type: "text", text: buffer }],
},
];
}
buffer = "";
}
}
}
}
}

View file

@ -0,0 +1,13 @@
function randomLettersAndNumbers(length: number): string {
const characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
export function generateOpenAIToolCallId(): string {
return `call_${randomLettersAndNumbers(24)}`;
}

View file

@ -0,0 +1,128 @@
import { ToolCallDelta } from "../..";
export type ToolCallParseState = {
isOnArgBeginLine: boolean;
currentArgName: string | undefined;
currentArgLines: string[];
processedArgNames: Set<string>;
currentLineIndex: number;
lineChunks: string[][];
done: boolean;
};
export const getInitialTooLCallParseState = (): ToolCallParseState => ({
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
});
function createDelta(name: string, args: string, id: string): ToolCallDelta {
return {
type: "function",
function: {
name,
arguments: args,
},
id,
};
}
/*
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,
toolCallId: string,
state: ToolCallParseState,
): ToolCallDelta | undefined {
// Add chunks
const lineIndex = state.currentLineIndex;
if (!state.lineChunks[lineIndex]) {
state.lineChunks[lineIndex] = [];
}
state.lineChunks[lineIndex].push(chunk);
const isNewLine = chunk === "\n";
if (isNewLine) {
state.currentLineIndex++;
}
const line = state.lineChunks[lineIndex].join("");
switch (lineIndex) {
// The first line will be skipped (e.g. ```tool\n)
case 0:
state.currentLineIndex = 1;
if (!line.toLowerCase().includes("name")) {
return;
}
// tool_name alternate start case
// Tool name line - process once line 2 is reached
case 1:
if (isNewLine) {
const name = (line.split(/tool_?name:/i)[1] ?? "").trim();
if (!name) {
throw new Error("Invalid tool name");
}
return createDelta(name, "", toolCallId);
}
return;
default:
if (state.isOnArgBeginLine) {
if (isNewLine) {
const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim();
if (!argName) {
throw new Error("Invalid begin arg line");
}
state.currentArgName = argName;
state.isOnArgBeginLine = false;
const argPrefix = state.processedArgNames.size === 0 ? "{" : ",";
return createDelta("", `${argPrefix}"${argName}":`, toolCallId);
}
} else if (state.currentArgName) {
if (isNewLine) {
const isEndArgTag = line.match(/end_?arg/i);
if (isEndArgTag) {
const trimmedValue = state.currentArgLines.join("").trim();
state.currentArgLines.length = 0;
state.processedArgNames.add(state.currentArgName);
state.currentArgName = undefined;
try {
const parsed = JSON.parse(trimmedValue);
const stringifiedArg = JSON.stringify(parsed);
return createDelta("", stringifiedArg, toolCallId);
} catch (e) {
const stringifiedArg = JSON.stringify(trimmedValue);
return createDelta("", stringifiedArg, toolCallId);
}
} else {
state.currentArgLines.push(line);
}
}
} else {
// Check for entry into arg
const isBeginArgLine = line.match(/begin_?arg:/i);
if (isBeginArgLine) {
state.isOnArgBeginLine = true;
}
// Check for exit
if (line === "```" || isNewLine) {
state.done = true;
// finish args JSON if applicable
if (state.processedArgNames.size > 0) {
return createDelta("", "}", toolCallId);
}
}
}
}
}

View file

@ -0,0 +1,17 @@
export function closeTag(openingTag: string): string {
return `</${openingTag.slice(1)}`;
}
export function getStringDelta(original: string, updated: string): string {
if (!updated.startsWith(original)) {
console.warn(
`Original string "${original}" is not a prefix of updated string "${updated}"`,
);
return updated;
}
return updated.slice(original.length);
}
export function splitAtCodeblocksAndNewLines(content: string) {
return content.split(/(```|\n)/g).filter(Boolean);
}

View file

@ -0,0 +1,57 @@
import { describe, expect, test } from "vitest";
import { closeTag, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
describe("closeTag", () => {
const testCases = [
{
input: "<div>",
expectedOutput: "</div>",
},
{
input: "<p>",
expectedOutput: "</p>",
},
// Add more test cases as needed
];
testCases.forEach((testCase) => {
test(`closes tag "${testCase.input}" to "</${testCase.input.slice(1)}"`, () => {
const result = closeTag(testCase.input);
expect(result).toEqual(testCase.expectedOutput);
});
});
});
describe("splitAtCodeblocks", () => {
test("doesn't split plain text without codeblocks", () => {
expect(splitAtCodeblocksAndNewLines("hello world")).toEqual([
"hello world",
]);
});
test("splits at codeblocks", () => {
expect(splitAtCodeblocksAndNewLines("```<one>middle```<two>")).toEqual([
"```",
"<one>middle",
"```",
"<two>",
]);
});
test("splits at new lines", () => {
expect(splitAtCodeblocksAndNewLines("hello\nhoware\n you\n")).toEqual([
"hello",
"\n",
"howare",
"\n",
" you",
"\n",
]);
});
test("splits at both codeblocks and new lines", () => {
expect(splitAtCodeblocksAndNewLines("hello```\nho```ware\n you\n")).toEqual(
["hello", "```", "\n", "ho", "```", "ware", "\n", " you", "\n"],
);
});
});

View file

@ -0,0 +1,95 @@
import {
AssistantChatMessage,
MessagePart,
ToolCallState,
UserChatMessage,
} from "../..";
import {
normalizeToMessageParts,
renderContextItems,
} from "../../util/messageContent";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
// TODO - include tool call id for parallel. Confuses dumb models
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
if (state.status === "canceled") {
output += CANCELLED_TOOL_CALL_MESSAGE;
} else if (state.output?.length) {
output += renderContextItems(state.output);
} else {
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
}
return output;
}
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
} {
const parts = normalizeToMessageParts(originalAssistantMessage);
if (originalAssistantMessage.toolCalls) {
parts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
})),
);
}
// new message with tool calls moved to content
const assistantMessage: AssistantChatMessage = {
...originalAssistantMessage,
content: parts,
toolCalls: undefined, // remove tool calls from the assistant message
};
const userParts: MessagePart[] = [];
if (toolCallStates) {
for (const state of toolCallStates) {
userParts.push({
type: "text",
text: toolCallStateToSystemToolOutput(state),
});
}
}
if (userParts.length === 0) {
userParts.push({
type: "text",
text: "Error: no tool output for tool calls",
});
}
const userMessage: UserChatMessage = {
role: "user",
content: userParts,
};
return {
assistantMessage,
userMessage,
};
}

View file

@ -21,10 +21,11 @@ import { AppThunkDispatch, RootState, ThunkApiType } from "../store";
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 { selectCurrentToolCalls } from "../selectors/selectToolCalls";
import { getBaseSystemMessage } from "../util/getBaseSystemMessage";
import { callToolById } from "./callToolById";
/**
* Handles the execution of tool calls that may be automatically accepted.
* Sets all tools as generated first, then executes auto-approved tool calls.
@ -139,11 +140,13 @@ export const streamNormalInput = createAsyncThunk<
// Get tools and filter them based on the selected model
const allActiveTools = selectActiveTools(state);
const activeTools = filterToolsForModel(allActiveTools, selectedChatModel);
const toolsSupported = modelSupportsNativeTools(selectedChatModel);
const useNativeTools =
!state.config.config.experimental?.onlyUseSystemMessageTools &&
modelSupportsNativeTools(selectedChatModel);
// Construct completion options
let completionOptions: LLMFullCompletionOptions = {};
if (toolsSupported && activeTools.length > 0) {
if (useNativeTools && activeTools.length > 0) {
completionOptions = {
tools: activeTools,
};
@ -163,15 +166,20 @@ export const streamNormalInput = createAsyncThunk<
selectedChatModel,
);
const systemMessage = useNativeTools
? baseSystemMessage
: addSystemMessageToolsToSystemMessage(baseSystemMessage, activeTools);
const withoutMessageIds = state.session.history.map((item) => {
const { id, ...messageWithoutId } = item.message;
return { ...item, message: messageWithoutId };
});
const { messages, appliedRules, appliedRuleIndex } = constructMessages(
withoutMessageIds,
baseSystemMessage,
systemMessage,
state.config.config.rules,
state.ui.ruleSettings,
!useNativeTools,
);
// TODO parallel tool calls will cause issues with this
@ -209,7 +217,7 @@ export const streamNormalInput = createAsyncThunk<
// Send request and stream response
const streamAborter = state.session.streamAborter;
const gen = extra.ideMessenger.llmStreamChat(
let gen = extra.ideMessenger.llmStreamChat(
{
completionOptions,
title: selectedChatModel.title,
@ -219,6 +227,9 @@ export const streamNormalInput = createAsyncThunk<
},
streamAborter.signal,
);
if (!useNativeTools && activeTools.length > 0) {
gen = interceptSystemToolCalls(gen, streamAborter);
}
let next = await gen.next();
while (!next.done) {

View file

@ -1,9 +1,11 @@
import {
AssistantChatMessage,
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
RuleWithSource,
TextMessagePart,
ToolCallState,
ToolResultChatMessage,
UserChatMessage,
} from "core";
@ -29,6 +31,7 @@ export function constructMessages(
baseSystemMessage: string | undefined,
availableRules: RuleWithSource[],
rulePolicies: RulePolicies,
useSystemMessageTools: Boolean,
): {
messages: ChatMessage[];
appliedRules: RuleWithSource[];
@ -92,6 +95,24 @@ export function constructMessages(
message: item.message,
});
} else if (item.message.role === "assistant") {
// When using system message tools, convert tool calls/states to text content
if (item.toolCallStates?.length && useSystemMessageTools) {
const { userMessage, assistantMessage } =
convertToolCallStatesToSystemCallsAndOutput(
item.message,
item.toolCallStates ?? [],
);
msgs.push({
message: assistantMessage,
ctxItems: [],
});
msgs.push({
message: userMessage,
ctxItems: [],
});
continue;
}
msgs.push({
ctxItems: item.contextItems,
message: item.message,
@ -193,3 +214,9 @@ export function constructMessages(
appliedRuleIndex,
};
}
function convertToolCallStatesToSystemCallsAndOutput(
message: AssistantChatMessage,
arg1: ToolCallState[],
): { userMessage: any; assistantMessage: any } {
throw new Error("Function not implemented.");
}