WIP: only add tool messages in construct messages

This commit is contained in:
Dallin Romney 2025-06-27 21:34:21 -07:00
parent c28f70a9f0
commit 9700a10e50
7 changed files with 82 additions and 24 deletions

View file

@ -4,11 +4,15 @@ import {
ContextItemWithId,
RuleWithSource,
TextMessagePart,
Tool,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import {
normalizeToMessageParts,
renderContextItems,
} from "../util/messageContent";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
import { RulePolicies } from "./rules/types";
@ -109,30 +113,38 @@ export function constructMessages(
history: ChatHistoryItem[],
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
tools: Tool[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
const validTools = new Set(tools.map((tool) => tool.function.name));
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
if (messageMode === "chat") {
const toolMessage: ToolResultChatMessage =
historyItem.message as ToolResultChatMessage;
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
// remove all tool calls from the history
continue;
}
for (const item of filteredHistory) {
if (item.message.role === "tool") {
continue; // Tool messages will be re-inserted
}
if (historyItem.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
// This was implemented for APIs that require all tool calls to have
// A corresponsing tool sent, which means if a user excluded a tool
// Then sessions with that tool call in the history would fail
// if (messageMode === "chat") {
// const toolMessage: ToolResultChatMessage =
// historyItem.message as ToolResultChatMessage;
// if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
// // remove all tool calls from the history
// continue;
// }
// }
const ctxItems = historyItem.contextItems
if (item.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(item.message);
const ctxItems = item.contextItems
.map((ctxItem) => {
return {
type: "text",
@ -143,11 +155,47 @@ export function constructMessages(
content = [...ctxItems, ...content];
msgs.push({
...historyItem.message,
...item.message,
content,
});
} else {
msgs.push(historyItem.message);
msgs.push(item.message);
}
if (item.message.role === "assistant") {
// First, push a version of the message with any valid tools calls
const validToolCalls = item.message.toolCalls?.filter(
(toolCall) =>
toolCall.function?.name &&
toolCall.id &&
validTools.has(toolCall.function.name),
);
// Case where no valid tool calls or content are present
msgs.push({
...item.message,
toolCalls: validToolCalls,
});
// Then push a tool message for each valid tool call
if (validToolCalls?.length) {
// If the assistant message has tool calls, we need to insert tool messages
for (const toolCall of validToolCalls) {
let content: string = "No tool output";
// TODO toolCallState only supports one tool call per message for now
if (
item.toolCallState?.toolCallId === toolCall.id &&
item.toolCallState?.output
) {
content = renderContextItems(item.toolCallState.output);
}
msgs.push({
role: "tool",
content,
toolCallId: toolCall.id!,
});
}
}
}
}

View file

@ -143,7 +143,6 @@ export function ContextItemsPeekItem({
{contextItem.uri?.type === "file"
? getUriPathBasename(contextItem.description)
: contextItem.description}
adsfasdfasdjk; asdfl;kjasdl;fkjasdlk;fja asdfklj;asdl;fkjasdf
</span>
{isUrl && (
<ArrowTopRightOnSquareIcon className="h-3 w-3 flex-shrink-0 text-gray-400 opacity-80 group-hover:opacity-100" />

View file

@ -2,7 +2,6 @@ import { ChevronRightIcon } from "@heroicons/react/24/outline";
import { Tool, ToolCallState } from "core";
import { ComponentType, useMemo, useState } from "react";
import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs";
import { toolCallStateToContextItems } from "./toolCallStateToContextItem";
import { ToolCallStatusMessage } from "./ToolCallStatusMessage";
@ -21,8 +20,6 @@ export function SimpleToolCallUI({
tool,
historyIndex,
}: SimpleToolCallUIProps) {
const history = useAppSelector((state) => state.session.history);
const dispatch = useAppDispatch();
const shownContextItems = useMemo(() => {
const contextItems = toolCallStateToContextItems(toolCallState);
return contextItems.filter((item) => !item.hidden);

View file

@ -19,7 +19,7 @@ export function ToolTruncateHistoryIcon({
}, [history]);
const dispatch = useAppDispatch();
const { mainEditor } = useMainEditor();
if (isStreaming || lastMessageIndex) {
if (isStreaming || historyIndex === lastMessageIndex) {
return null;
}
return (
@ -34,8 +34,7 @@ export function ToolTruncateHistoryIcon({
mainEditor?.commands.focus();
}}
>
{historyIndex}/{history.length - 1}
<BarsArrowUpIcon className="h-2.5 w-2.5 flex-shrink-0 opacity-60" />
<BarsArrowUpIcon className="h-2.5 w-2.5 flex-shrink-0" />
</ToolbarButtonWithTooltip>
);
}

View file

@ -157,6 +157,7 @@ export const sessionSlice = createSlice({
const { index } = payload;
if (state.history.length && index < state.history.length) {
state.codeBlockApplyStates.curIndex = 0;
state.history = state.history.slice(0, index + 1).concat({
message: {
id: uuidv4(),

View file

@ -1,11 +1,13 @@
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 posthog from "posthog-js";
import { v4 as uuidv4 } from "uuid";
import { getBaseSystemMessage } from "../../util";
import { selectActiveTools } from "../selectors/selectActiveTools";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
setAppliedRulesAtIndex,
@ -119,11 +121,16 @@ export const streamResponseThunk = createAsyncThunk<
messageMode,
);
const activeTools = selectActiveTools(state);
const toolsSupported = modelSupportsTools(selectedChatModel);
const availableTools = toolsSupported ? activeTools : [];
const messages = constructMessages(
messageMode,
[...updatedHistory],
baseChatOrAgentSystemMessage,
applicableRules,
availableTools,
rulePolicies,
);

View file

@ -1,8 +1,10 @@
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 { ThunkApiType } from "../store";
@ -67,11 +69,16 @@ export const streamResponseAfterToolCall = createAsyncThunk<
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 })));