construct message: tool messages

This commit is contained in:
Dallin Romney 2025-06-30 11:15:48 -07:00
parent 2d238d9c1e
commit bebc8bc71e
9 changed files with 138 additions and 224 deletions

View file

@ -112,7 +112,7 @@ export async function* streamDiffLines({
// If any rules are present this will result in using chat instead of legacy completion
const systemMessage = rulesToInclude
? getSystemMessageWithRules({
rules: rulesToInclude,
availableRules: rulesToInclude,
userMessage:
typeof prompt === "string"
? ({
@ -125,7 +125,7 @@ export async function* streamDiffLines({
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
contextItems: [],
})
}).systemMessage
: undefined;
if (systemMessage) {

View file

@ -2,19 +2,19 @@ import {
AssistantChatMessage,
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
ModelDescription,
RuleWithSource,
TextMessagePart,
Tool,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { findLastIndex } from "../util/findLast";
import {
normalizeToMessageParts,
renderContextItems,
} from "../util/messageContent";
import { chatMessageIsEmpty, isUserOrToolMsg } from "./messages";
import { chatMessageIsEmpty } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
import { RulePolicies } from "./rules/types";
@ -84,50 +84,30 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
${EDIT_MESSAGE}
</important_rules>`;
/**
* Helper function to get the context items for a user message
*/
function getUserContextItems(
userMsg: UserChatMessage | ToolResultChatMessage | undefined,
history: ChatHistoryItem[],
): ContextItemWithId[] {
if (!userMsg) return [];
// Find the history item that contains the userMsg
const historyItem = history.find((item) => {
// Check if the message ID matches
if ("id" in userMsg && "id" in item.message) {
return (item.message as any).id === (userMsg as any).id;
}
// Fallback to content comparison
return (
item.message.content === userMsg.content &&
item.message.role === userMsg.role
);
});
return historyItem?.contextItems || [];
}
export function constructMessages(
messageMode: string,
history: ChatHistoryItem[],
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
model: ModelDescription,
availableRules: RuleWithSource[],
rulePolicies: RulePolicies,
tools: Tool[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
): {
messages: ChatMessage[];
appliedRulesIndex: number;
appliedRules: RuleWithSource[];
} {
const historyCopy = [...history];
const validTools = new Set(tools.map((tool) => tool.function.name));
const msgs: ChatMessage[] = [];
for (const item of history) {
for (const item of historyCopy) {
if (
item.message.role === "system" ||
item.message.role === "tool" ||
chatMessageIsEmpty(item.message)
) {
continue;
// Tool messages will be re-inserted
continue;
}
if (item.message.role === "user") {
@ -169,7 +149,7 @@ export function constructMessages(
if (chatMessageIsEmpty(msgWithValidToolCalls)) {
msgs.push({
role: "assistant",
content: "Message redacted", // TODO this might be confusing, edge case situation where tools are excluded
content: "Tool call message redacted in chat mode", // TODO this might be confusing, edge case situation where tools are excluded
});
}
@ -202,21 +182,41 @@ export function constructMessages(
}
}
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
| UserChatMessage
| ToolResultChatMessage
| undefined;
// Get context items for the last user message
const lastUserContextItems = getUserContextItems(
lastUserMsg,
filteredHistory,
const lastUserMsgIndex = findLastIndex(
historyCopy,
(item) => item.message.role === "user",
);
const systemMessage = getSystemMessageWithRules({
const lastUserOrToolMsgIndex = findLastIndex(
historyCopy,
(item) => item.message.role === "user" || item.message.role === "tool",
);
const lastUserOrToolMsg = historyCopy[lastUserOrToolMsgIndex]?.message as
| UserChatMessage
| ToolResultChatMessage;
const itemsBackToLastUserMessage = history
.slice(lastUserMsgIndex, historyCopy.length)
.filter(
(item) => item.message.role === "tool" || item.message.role === "user",
);
const rulesContextItems = itemsBackToLastUserMessage
.map((item) => item.contextItems)
.flat();
// Get system message
let baseChatOrAgentSystemMessage: string | undefined;
if (messageMode === "agent") {
baseChatOrAgentSystemMessage =
model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
} else {
baseChatOrAgentSystemMessage =
model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
}
const { systemMessage } = getSystemMessageWithRules({
baseSystemMessage: baseChatOrAgentSystemMessage,
rules,
userMessage: lastUserMsg,
contextItems: lastUserContextItems,
availableRules,
userMessage: lastUserOrToolMsg,
contextItems: rulesContextItems,
rulePolicies,
});
@ -227,9 +227,13 @@ export function constructMessages(
});
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const messages = msgs.map((msg) => {
const { id, ...rest } = msg as any;
return rest;
});
return {
messages,
appliedRulesIndex: lastUserOrToolMsgIndex,
appliedRules: availableRules,
};
}

View file

@ -327,27 +327,33 @@ export const getApplicableRules = (
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
availableRules,
contextItems,
rulePolicies = {},
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
availableRules: RuleWithSource[];
contextItems: ContextItemWithId[];
rulePolicies?: RulePolicies;
}) => {
const applicableRules = getApplicableRules(
}): {
systemMessage: string;
appliedRules: RuleWithSource[];
} => {
const appliedRules = getApplicableRules(
userMessage,
rules,
availableRules,
contextItems,
rulePolicies,
);
let systemMessage = baseSystemMessage ?? "";
for (const rule of applicableRules) {
for (const rule of appliedRules) {
systemMessage += `\n\n${rule.rule}`;
}
return systemMessage;
return {
systemMessage,
appliedRules,
};
};

View file

@ -20,13 +20,16 @@ import {
SessionMetadata,
} from "core";
import { NEW_SESSION_TITLE } from "core/util/constants";
import { renderChatMessage } from "core/util/messageContent";
import {
renderChatMessage,
renderContextItems,
} from "core/util/messageContent";
import { findUriInDirs, getUriPathBasename } from "core/util/uri";
import { v4 as uuidv4 } from "uuid";
import { addToolCallDeltaToState } from "../../util/toolCallState";
import { RootState } from "../store";
import { streamResponseThunk } from "../thunks/streamResponse";
import { findCurrentToolCall, findToolCall } from "../util";
import { findCurrentToolCall, findToolCall, findToolOutput } from "../util";
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
@ -547,6 +550,7 @@ export const sessionSlice = createSlice({
contextItems: ContextItem[];
}>,
) => {
// Update tool call state and corresponding tool output message
const toolCallState = findToolCall(
state.history,
action.payload.toolCallId,
@ -554,6 +558,22 @@ export const sessionSlice = createSlice({
if (toolCallState) {
toolCallState.output = action.payload.contextItems;
}
const toolItem = findToolOutput(state.history, action.payload.toolCallId);
if (toolItem) {
toolItem.message.content = renderContextItems(
action.payload.contextItems,
);
}
// addContextItemsAtIndex({
// index: initialHistory.length,
// contextItems: toolOutput.map((contextItem) => ({
// ...contextItem,
// id: {
// providerTitle: "toolCall",
// itemId: toolCallId,
// },
// })),
// }),
},
cancelToolCall: (
state,

View file

@ -1,6 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage, LLMFullCompletionOptions } from "core";
import { LLMFullCompletionOptions } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { constructMessages } from "core/llm/constructMessages";
import { ToCoreProtocol } from "core/protocol";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
@ -9,6 +10,7 @@ import {
abortStream,
addPromptCompletionPair,
setActive,
setAppliedRulesAtIndex,
setInactive,
setToolGenerated,
streamUpdate,
@ -19,28 +21,30 @@ import { callCurrentTool } from "./callCurrentTool";
export const streamNormalInput = createAsyncThunk<
void,
{
messages: ChatMessage[];
legacySlashCommandData?: ToCoreProtocol["llm/streamChat"][0]["legacySlashCommandData"];
},
ThunkApiType
>(
"chat/streamNormalInput",
async (
{ messages, legacySlashCommandData },
{ dispatch, extra, getState },
) => {
// Gather state
async ({ legacySlashCommandData }, { dispatch, extra, getState }) => {
const state = getState();
const selectedChatModel = selectSelectedChatModel(state);
const streamAborter = state.session.streamAborter;
if (!selectedChatModel) {
throw new Error("Default model not defined");
throw new Error("No chat model selected");
}
let completionOptions: LLMFullCompletionOptions = {};
const chatHistory = state.session.history;
const messageMode = state.session.mode;
const rulePolicies = state.ui.ruleSettings;
const streamAborter = state.session.streamAborter;
// Get tools
const activeTools = selectActiveTools(state);
const toolsSupported = modelSupportsTools(selectedChatModel);
// Construct completion options
let completionOptions: LLMFullCompletionOptions = {};
if (toolsSupported && activeTools.length > 0) {
completionOptions = {
tools: activeTools,
@ -55,6 +59,23 @@ export const streamNormalInput = createAsyncThunk<
};
}
// Construct messages
const { messages, appliedRules, appliedRulesIndex } = constructMessages(
messageMode,
chatHistory,
selectedChatModel,
state.config.config.rules,
rulePolicies,
toolsSupported ? activeTools : [],
);
dispatch(
setAppliedRulesAtIndex({
index: appliedRulesIndex,
appliedRules: appliedRules,
}),
);
dispatch(setActive());
// Send request

View file

@ -1,17 +1,11 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { constructMessages } from "core/llm/constructMessages";
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
import { InputModifiers } from "core";
import posthog from "posthog-js";
import { v4 as uuidv4 } from "uuid";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
import { getBaseSystemMessage } from "../../util";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
setAppliedRulesAtIndex,
submitEditorAndInitAtIndex,
updateHistoryItemAtIndex,
} from "../slices/sessionSlice";
@ -79,7 +73,7 @@ export const streamResponseThunk = createAsyncThunk<
.map((item) => item.uri!.value),
...selectedCode.map((rif) => rif.filepath),
];
dispatch(updateFileSymbolsFromFiles(filesForSymbols));
void dispatch(updateFileSymbolsFromFiles(filesForSymbols));
dispatch(
updateHistoryItemAtIndex({
@ -95,52 +89,6 @@ export const streamResponseThunk = createAsyncThunk<
}),
);
// Get updated history after the update
const updatedHistory = getState().session.history;
// Determine which rules apply to this message
const userMsg = updatedHistory[inputIndex].message;
const rules = getState().config.config.rules;
const rulePolicies = getState().ui.ruleSettings;
// Calculate applicable rules once
// We need to check the message type to match what getApplicableRules expects
const applicableRules = getApplicableRules(
userMsg.role === "user" || userMsg.role === "tool"
? (userMsg as UserChatMessage | ToolResultChatMessage)
: undefined,
rules,
selectedContextItems,
rulePolicies,
);
// Store in history for UI display
dispatch(
setAppliedRulesAtIndex({
index: inputIndex,
appliedRules: applicableRules,
}),
);
const messageMode = getState().session.mode;
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
selectedChatModel,
messageMode,
);
const activeTools = selectActiveTools(state);
const toolsSupported = modelSupportsTools(selectedChatModel);
const availableTools = toolsSupported ? activeTools : [];
const messages = constructMessages(
messageMode,
[...updatedHistory],
baseChatOrAgentSystemMessage,
applicableRules,
availableTools,
rulePolicies,
);
posthog.capture("step run", {
step_name: "User Input",
params: {},
@ -157,7 +105,6 @@ export const streamResponseThunk = createAsyncThunk<
unwrapResult(
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: legacyCommandWithInput
? {
command: legacyCommandWithInput.command,

View file

@ -1,12 +1,7 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ChatMessage } from "core";
import { modelSupportsTools } from "core/llm/autodetect";
import { constructMessages } from "core/llm/constructMessages";
import { renderContextItems } from "core/util/messageContent";
import { getBaseSystemMessage } from "../../util";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectSelectedChatModel } from "../slices/configSlice";
import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
import { streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCall } from "../util";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
@ -23,15 +18,8 @@ export const streamResponseAfterToolCall = createAsyncThunk<
await dispatch(
streamThunkWrapper(async () => {
const state = getState();
const initialHistory = state.session.history;
const selectedChatModel = selectSelectedChatModel(state);
if (!selectedChatModel) {
throw new Error("No model selected");
}
const toolCallState = findToolCall(state.session.history, toolCallId);
if (!toolCallState) {
return; // in cases where edit tool is cancelled mid apply, this will be triggered
}
@ -42,46 +30,15 @@ export const streamResponseAfterToolCall = createAsyncThunk<
await new Promise((resolve) => setTimeout(resolve, 0));
// TODO paralell tool calls - dispatch one tool message per tool call
const newMessage: ChatMessage = {
role: "tool",
content: renderContextItems(toolOutput),
toolCallId,
};
dispatch(streamUpdate([newMessage]));
dispatch(
addContextItemsAtIndex({
index: initialHistory.length,
contextItems: toolOutput.map((contextItem) => ({
...contextItem,
id: {
providerTitle: "toolCall",
itemId: toolCallId,
},
})),
}),
);
const updatedHistory = getState().session.history;
const messageMode = getState().session.mode;
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
selectedChatModel,
messageMode,
);
const activeTools = selectActiveTools(state);
const toolsSupported = modelSupportsTools(selectedChatModel);
const availableTools = toolsSupported ? activeTools : [];
const messages = constructMessages(
messageMode,
[...updatedHistory],
baseChatOrAgentSystemMessage,
state.config.config.rules,
availableTools,
);
unwrapResult(await dispatch(streamNormalInput({ messages })));
unwrapResult(await dispatch(streamNormalInput({})));
}),
);
},

View file

@ -1,4 +1,5 @@
import { ToolCallState } from "core";
import { ChatHistoryItemWithMessageId } from "../slices/sessionSlice";
import { RootState } from "../store";
export function findCurrentToolCall(
@ -15,3 +16,13 @@ export function findToolCall(
(item) => item.toolCallState?.toolCallId === toolCallId,
)?.toolCallState;
}
export function findToolOutput(
chatHistory: RootState["session"]["history"],
toolCallId: string,
): ChatHistoryItemWithMessageId | undefined {
return chatHistory.find(
(item) =>
item.message.role === "tool" && item.message.toolCallId === toolCallId,
);
}

View file

@ -1,10 +1,4 @@
import { MessageModes, ModelDescription } from "core";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import {
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
} from "core/llm/constructMessages";
import _ from "lodash";
import { KeyboardEvent as ReactKeyboardEvent } from "react";
import { getLocalStorage } from "./localStorage";
@ -88,52 +82,6 @@ export function isPrerelease() {
return false;
}
/**
* Updates the values of an object's properties based on the specified paths.
*
* This function creates a deep clone of the provided object and updates its properties
* based on the given path-to-value mappings. If a value in the mapping is a function,
* it will be used to determine the new value for the property. Otherwise, the value itself
* will be set for the property.
*
* @param {Object} old - The original object to be cloned and updated.
* @param {Object} pathToValue - An object where the keys represent the paths to the properties
* to be updated and the values represent the new values or functions
* to determine the new values.
* @returns {Object} A new object with the updated values.
*/
export function updatedObj(old: any, pathToValue: { [key: string]: any }) {
const newObject = _.cloneDeep(old);
for (const key in pathToValue) {
if (typeof pathToValue[key] === "function") {
_.updateWith(newObject, key, pathToValue[key]);
} else {
_.updateWith(newObject, key, (__) => pathToValue[key]);
}
}
return newObject;
}
export function isLocalProfile(profile: ProfileDescription): boolean {
return profile.profileType === "local";
}
/**
* Get the base system message for the agent or chat mode from the model description.
*/
export function getBaseSystemMessage(
modelDetails: ModelDescription | null,
mode: MessageModes,
) {
let baseChatOrAgentSystemMessage: string | undefined;
if (mode === "agent") {
baseChatOrAgentSystemMessage =
modelDetails?.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE;
} else {
baseChatOrAgentSystemMessage =
modelDetails?.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE;
}
return baseChatOrAgentSystemMessage;
}