fix: countTokens bug

This commit is contained in:
Patrick Erichsen 2025-07-09 10:55:41 -07:00
parent a9e3a56a61
commit cd30d42181
4 changed files with 42 additions and 12 deletions

2
core/index.d.ts vendored
View file

@ -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[];

View file

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

View file

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

View file

@ -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() {
<div className="thread-message">
<TimelineItem
item={item}
iconElement={<ChatBubbleOvalLeftIcon width="16px" height="16px" />}
iconElement={
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
}
open={
typeof stepsOpen[index] === "undefined" ? true : stepsOpen[index]!
typeof stepsOpen[index] === "undefined"
? true
: stepsOpen[index]!
}
onToggle={() => {}}
>
@ -331,7 +334,7 @@ export function Chat() {
/>
</TimelineItem>
</div>
{/* Additionally render tool calls if they exist */}
{toolCallStates && (
<ToolCallsGroup