From cd30d421810c4bc0e65ca5a9a0927ede23f721bd Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 9 Jul 2025 10:55:41 -0700 Subject: [PATCH] fix: countTokens bug --- core/index.d.ts | 2 +- core/llm/countTokens.ts | 36 +++++++++++++++++++++++++++++++----- core/llm/messages.ts | 3 ++- gui/src/pages/gui/Chat.tsx | 13 ++++++++----- 4 files changed, 42 insertions(+), 12 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 093841349..d45739146 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -461,7 +461,7 @@ export interface ChatHistoryItem { editorState?: any; modifiers?: InputModifiers; promptLogs?: PromptLog[]; - toolCallStates?: ToolCallState[]; // Support for multiple parallel tool calls + toolCallStates?: ToolCallState[]; isGatheringContext?: boolean; reasoning?: Reasoning; appliedRules?: RuleWithSource[]; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2297813b4..9fc52d015 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -382,12 +382,27 @@ function compileChatMessages({ } let lastToolCallsMsg: ChatMessage | undefined = undefined; + let toolMessages: ChatMessage[] = []; + if (lastUserOrToolMsg.role === "tool") { + // Collect all consecutive tool messages from the end + toolMessages.push(lastUserOrToolMsg); + + // Check if there are more tool messages before the last one + while (msgsCopy.length > 0 && msgsCopy[msgsCopy.length - 1].role === "tool") { + toolMessages.unshift(msgsCopy.pop()!); + } + + // Now find the assistant message that should contain all the tool calls lastToolCallsMsg = msgsCopy.pop(); - if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) { - throw new Error( - `Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`, - ); + + // Validate that the assistant message has all the required tool call IDs + for (const toolMsg of toolMessages) { + if (toolMsg.role === "tool" && !messageHasToolCallId(lastToolCallsMsg, toolMsg.toolCallId)) { + throw new Error( + `Error parsing chat history: no tool call found to match tool output for id "${toolMsg.toolCallId}"`, + ); + } } } @@ -395,6 +410,11 @@ function compileChatMessages({ if (lastToolCallsMsg) { lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg); } + + // Count tokens for all tool messages (in case of parallel tool calls) + for (const toolMsg of toolMessages.slice(0, -1)) { // Skip the last one since it's already counted as lastUserOrToolMsg + lastMessagesTokens += countChatMessageTokens(modelName, toolMsg); + } // System message let systemMsgTokens = 0; @@ -468,7 +488,13 @@ function compileChatMessages({ if (lastToolCallsMsg) { reassembled.push(lastToolCallsMsg); } - reassembled.push(lastUserOrToolMsg); + + // Push all tool messages, not just the last one + if (toolMessages.length > 0) { + reassembled.push(...toolMessages); + } else { + reassembled.push(lastUserOrToolMsg); + } // Flatten the messages (combines adjacent similar messages) const flattenedHistory = flattenMessages(reassembled); diff --git a/core/llm/messages.ts b/core/llm/messages.ts index 8a0312766..d4973c90b 100644 --- a/core/llm/messages.ts +++ b/core/llm/messages.ts @@ -14,7 +14,8 @@ export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { flattened.length > 0 && flattened[flattened.length - 1].role === msg.role && !messageHasToolCalls(msg) && - !messageHasToolCalls(flattened[flattened.length - 1]) + !messageHasToolCalls(flattened[flattened.length - 1]) && + msg.role !== "tool" // Don't merge tool messages - each has a unique toolCallId ) { flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`; } else { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 53b5d824a..15c3a3e66 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -25,7 +25,6 @@ import ContinueInputBox from "../../components/mainInput/ContinueInputBox"; import { useOnboardingCard } from "../../components/OnboardingCard"; import StepContainer from "../../components/StepContainer"; import { TabBar } from "../../components/TabBar/TabBar"; -import { ToolCallsGroup } from "./ToolCallsGroup"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; @@ -48,12 +47,12 @@ import { streamEditThunk } from "../../redux/thunks/edit"; import { loadLastSession } from "../../redux/thunks/session"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; +import { ToolCallsGroup } from "./ToolCallsGroup"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { getLocalStorage, setLocalStorage } from "../../util/localStorage"; import { EmptyChatBody } from "./EmptyChatBody"; import { ExploreDialogWatcher } from "./ExploreDialogWatcher"; -import { ToolCallDiv } from "./ToolCallDiv"; import { useAutoScroll } from "./useAutoScroll"; const StepsDiv = styled.div` @@ -318,9 +317,13 @@ export function Chat() {
} + iconElement={ + + } open={ - typeof stepsOpen[index] === "undefined" ? true : stepsOpen[index]! + typeof stepsOpen[index] === "undefined" + ? true + : stepsOpen[index]! } onToggle={() => {}} > @@ -331,7 +334,7 @@ export function Chat() { />
- + {/* Additionally render tool calls if they exist */} {toolCallStates && (