@librechat/agents 3.1.30 → 3.1.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/messages/prune.cjs +1 -1
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +5 -7
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/messages/prune.mjs +1 -1
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +5 -7
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/package.json +1 -1
- package/src/messages/prune.ts +1 -1
- package/src/specs/thinking-prune.test.ts +172 -51
- package/src/tools/ToolNode.ts +4 -5
|
@@ -192,7 +192,7 @@ function getMessagesWithinTokenLimit({ messages: _messages, maxContextTokens, in
|
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
if (assistantIndex === -1) {
|
|
195
|
-
throw new Error('
|
|
195
|
+
throw new Error('Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.');
|
|
196
196
|
}
|
|
197
197
|
thinkingStartIndex = originalLength - 1 - assistantIndex;
|
|
198
198
|
const thinkingTokenCount = tokenCounter(new messages.AIMessage({ content: [thinkingBlock] }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prune.cjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import {\n AIMessage,\n BaseMessage,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ThinkingContentText,\n MessageContentComplex,\n ReasoningContentText,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes, Providers } from '@/common';\n\nexport type PruneMessagesFactoryParams = {\n provider?: Providers;\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number | undefined>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n};\n\nfunction isIndexInContext(\n arrayA: unknown[],\n arrayB: unknown[],\n targetIndex: number\n): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(\n message: AIMessage,\n thinkingBlock: ThinkingContentText | ReasoningContentText\n): AIMessage {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? (message.content as MessageContentComplex[])\n : [\n {\n type: ContentTypes.TEXT,\n text: message.content,\n },\n ];\n /** Edge case, the message already has the thinking block */\n if (content[0].type === thinkingBlock.type) {\n return message;\n }\n content.unshift(thinkingBlock);\n return new AIMessage({\n ...message,\n content,\n });\n}\n\n/**\n * Calculates the total tokens from a single usage object\n *\n * @param usage The usage metadata object containing token information\n * @returns An object containing the total input and output tokens\n */\nexport function calculateTotalTokens(\n usage: Partial<UsageMetadata>\n): UsageMetadata {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation = Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const totalInputTokens = baseInputTokens + cacheCreation + cacheRead;\n const totalOutputTokens = Number(usage.output_tokens) || 0;\n\n return {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n total_tokens: totalInputTokens + totalOutputTokens,\n };\n}\n\nexport type PruningResult = {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n thinkingStartIndex?: number;\n};\n\n/**\n * Processes an array of messages and returns a context of messages that fit within a specified token limit.\n * It iterates over the messages from newest to oldest, adding them to the context until the token limit is reached.\n *\n * @param options Configuration options for processing messages\n * @returns Object containing the message context, remaining tokens, messages not included, and summary index\n */\nexport function getMessagesWithinTokenLimit({\n messages: _messages,\n maxContextTokens,\n indexTokenCountMap,\n startType: _startType,\n thinkingEnabled,\n tokenCounter,\n thinkingStartIndex: _thinkingStartIndex = -1,\n reasoningType = ContentTypes.THINKING,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n startType?: string | string[];\n thinkingEnabled?: boolean;\n tokenCounter: TokenCounter;\n thinkingStartIndex?: number;\n reasoningType?: ContentTypes.THINKING | ContentTypes.REASONING_CONTENT;\n}): PruningResult {\n // Every reply is primed with <|start|>assistant<|message|>, so we\n // start with 3 tokens for the label after all messages have been counted.\n let currentTokenCount = 3;\n const instructions =\n _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount =\n instructions != null ? (indexTokenCountMap[0] ?? 0) : 0;\n const initialContextTokens = maxContextTokens - instructionsTokenCount;\n let remainingContextTokens = initialContextTokens;\n let startType = _startType;\n const originalLength = _messages.length;\n const messages = [..._messages];\n /**\n * IMPORTANT: this context array gets reversed at the end, since the latest messages get pushed first.\n *\n * This may be confusing to read, but it is done to ensure the context is in the correct order for the model.\n * */\n let context: Array<BaseMessage | undefined> = [];\n\n let thinkingStartIndex = _thinkingStartIndex;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | ReasoningContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (_thinkingStartIndex > -1) {\n const thinkingMessageContent = messages[_thinkingStartIndex]?.content;\n if (Array.isArray(thinkingMessageContent)) {\n thinkingBlock = thinkingMessageContent.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n }\n }\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (\n messages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > endIndex\n ) {\n currentIndex--;\n if (messages.length === 1 && instructions) {\n break;\n }\n const poppedMessage = messages.pop();\n if (!poppedMessage) continue;\n const messageType = poppedMessage.getType();\n if (\n thinkingEnabled === true &&\n thinkingEndIndex === -1 &&\n currentIndex === originalLength - 1 &&\n (messageType === 'ai' || messageType === 'tool')\n ) {\n thinkingEndIndex = currentIndex;\n }\n if (\n thinkingEndIndex > -1 &&\n !thinkingBlock &&\n thinkingStartIndex < 0 &&\n messageType === 'ai' &&\n Array.isArray(poppedMessage.content)\n ) {\n thinkingBlock = poppedMessage.content.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n thinkingStartIndex = thinkingBlock != null ? currentIndex : -1;\n }\n /** False start, the latest message was not part of a multi-assistant/tool sequence of messages */\n if (\n thinkingEndIndex > -1 &&\n currentIndex === thinkingEndIndex - 1 &&\n messageType !== 'ai' &&\n messageType !== 'tool'\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (\n prunedMemory.length === 0 &&\n currentTokenCount + tokenCount <= remainingContextTokens\n ) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n continue;\n }\n break;\n }\n }\n\n if (context[context.length - 1]?.getType() === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && context.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = context.length - 1; i >= 0; i--) {\n const currentType = context[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n context = context.slice(0, requiredTypeIndex);\n }\n }\n }\n\n if (instructions && originalLength > 0) {\n context.push(_messages[0] as BaseMessage);\n messages.shift();\n }\n\n remainingContextTokens -= currentTokenCount;\n const result: PruningResult = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (thinkingStartIndex > -1) {\n result.thinkingStartIndex = thinkingStartIndex;\n }\n\n if (\n prunedMemory.length === 0 ||\n thinkingEndIndex < 0 ||\n (thinkingStartIndex > -1 &&\n isIndexInContext(_messages, context, thinkingStartIndex))\n ) {\n // we reverse at this step to ensure the context is in the correct order for the model, and we need to work backwards\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.'\n );\n }\n\n if (!thinkingBlock) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no thinking block found.'\n );\n }\n\n // Since we have a thinking sequence, we need to find the last assistant message\n // in the latest AI/tool sequence to add the thinking block that falls outside of the current context\n // Latest messages are ordered first.\n let assistantIndex = -1;\n for (let i = 0; i < context.length; i++) {\n const currentMessage = context[i];\n const type = currentMessage?.getType();\n if (type === 'ai') {\n assistantIndex = i;\n }\n if (assistantIndex > -1 && (type === 'human' || type === 'system')) {\n break;\n }\n }\n\n if (assistantIndex === -1) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages to append thinking blocks to.'\n );\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(\n new AIMessage({ content: [thinkingBlock] })\n );\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n const newMessage = addThinkingBlock(\n context[assistantIndex] as AIMessage,\n thinkingBlock\n );\n context[assistantIndex] = newMessage;\n if (newRemainingCount > 0) {\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex] as AIMessage;\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount =\n (indexTokenCountMap[thinkingStartIndex] ?? 0) + thinkingTokenCount;\n remainingContextTokens = initialContextTokens - newThinkingMessageTokenCount;\n currentTokenCount = 3;\n let newContext: BaseMessage[] = [];\n const secondRoundMessages = [..._messages];\n let currentIndex = secondRoundMessages.length;\n while (\n secondRoundMessages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > thinkingStartIndex\n ) {\n currentIndex--;\n const poppedMessage = secondRoundMessages.pop();\n if (!poppedMessage) continue;\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n if (currentTokenCount + tokenCount <= remainingContextTokens) {\n newContext.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n messages.push(poppedMessage);\n break;\n }\n }\n\n const firstMessage: AIMessage = newContext[newContext.length - 1];\n const firstMessageType = newContext[newContext.length - 1].getType();\n if (firstMessageType === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && newContext.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = newContext.length - 1; i >= 0; i--) {\n const currentType = newContext[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n newContext = newContext.slice(0, requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const newMessage = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1] = newMessage;\n } else {\n newContext.push(thinkingMessage);\n }\n\n if (instructions && originalLength > 0) {\n newContext.push(_messages[0] as BaseMessage);\n secondRoundMessages.shift();\n }\n\n result.context = newContext.reverse();\n return result;\n}\n\nexport function checkValidNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value) && value > 0;\n}\n\ntype ThinkingBlocks = {\n thinking_blocks?: Array<{\n type: 'thinking';\n thinking: string;\n signature: string;\n }>;\n};\n\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let lastCutOffIndex = 0;\n let totalTokens = Object.values(indexTokenCountMap).reduce(\n (a = 0, b = 0) => a + b,\n 0\n ) as number;\n let runThinkingStartIndex = -1;\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number | undefined>;\n } {\n if (\n factoryParams.provider === Providers.OPENAI &&\n factoryParams.thinkingEnabled === true\n ) {\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const m = params.messages[i];\n if (\n m.getType() === 'ai' &&\n typeof m.additional_kwargs.reasoning_content === 'string' &&\n Array.isArray(\n (\n m.additional_kwargs.provider_specific_fields as\n | ThinkingBlocks\n | undefined\n )?.thinking_blocks\n ) &&\n (m as AIMessage).tool_calls &&\n ((m as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const message = m as AIMessage;\n const thinkingBlocks = (\n message.additional_kwargs.provider_specific_fields as ThinkingBlocks\n ).thinking_blocks;\n const signature =\n thinkingBlocks?.[thinkingBlocks.length - 1].signature;\n const thinkingBlock: ThinkingContentText = {\n signature,\n type: ContentTypes.THINKING,\n thinking: message.additional_kwargs.reasoning_content as string,\n };\n\n params.messages[i] = new AIMessage({\n ...message,\n content: [thinkingBlock],\n additional_kwargs: {\n ...message.additional_kwargs,\n reasoning_content: undefined,\n },\n });\n }\n }\n }\n\n let currentUsage: UsageMetadata | undefined;\n if (\n params.usageMetadata &&\n (checkValidNumber(params.usageMetadata.input_tokens) ||\n (checkValidNumber(params.usageMetadata.input_token_details) &&\n (checkValidNumber(\n params.usageMetadata.input_token_details.cache_creation\n ) ||\n checkValidNumber(\n params.usageMetadata.input_token_details.cache_read\n )))) &&\n checkValidNumber(params.usageMetadata.output_tokens)\n ) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n const newOutputs = new Set<number>();\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n if (\n i === lastTurnStartIndex &&\n indexTokenCountMap[i] === undefined &&\n currentUsage\n ) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n if (currentUsage) {\n newOutputs.add(i);\n }\n totalTokens += indexTokenCountMap[i] ?? 0;\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,\n // We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,\n // relative the manually counted tokens in `indexTokenCountMap`.\n // EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.\n if (currentUsage) {\n let totalIndexTokens = 0;\n if (params.messages[0].getType() === 'system') {\n totalIndexTokens += indexTokenCountMap[0] ?? 0;\n }\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (i === 0 && params.messages[0].getType() === 'system') {\n continue;\n }\n if (newOutputs.has(i)) {\n continue;\n }\n totalIndexTokens += indexTokenCountMap[i] ?? 0;\n }\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n const isRatioSafe = ratio >= 1 / 3 && ratio <= 2.5;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex, and only if the ratio is safe\n if (isRatioSafe) {\n if (\n params.messages[0].getType() === 'system' &&\n lastCutOffIndex !== 0\n ) {\n indexTokenCountMap[0] = Math.round(\n (indexTokenCountMap[0] ?? 0) * ratio\n );\n }\n\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (newOutputs.has(i)) {\n continue;\n }\n indexTokenCountMap[i] = Math.round(\n (indexTokenCountMap[i] ?? 0) * ratio\n );\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (lastCutOffIndex === 0 && totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context, thinkingStartIndex } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n reasoningType:\n factoryParams.provider === Providers.BEDROCK\n ? ContentTypes.REASONING_CONTENT\n : ContentTypes.THINKING,\n thinkingStartIndex:\n factoryParams.thinkingEnabled === true\n ? runThinkingStartIndex\n : undefined,\n });\n runThinkingStartIndex = thinkingStartIndex ?? -1;\n /** The index is the first value of `context`, index relative to `params.messages` */\n lastCutOffIndex = Math.max(\n params.messages.length -\n (context.length - (context[0]?.getType() === 'system' ? 1 : 0)),\n 0\n );\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":["ContentTypes","AIMessage","messages","Providers"],"mappings":";;;;;AA2BA,SAAS,gBAAgB,CACvB,MAAiB,EACjB,MAAiB,EACjB,WAAmB,EAAA;IAEnB,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;IACtD,OAAO,WAAW,IAAI,gBAAgB;AACxC;AAEA,SAAS,gBAAgB,CACvB,OAAkB,EAClB,aAAyD,EAAA;IAEzD,MAAM,OAAO,GAA4B,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO;UACjE,OAAO,CAAC;AACX,UAAE;AACA,YAAA;gBACE,IAAI,EAAEA,kBAAY,CAAC,IAAI;gBACvB,IAAI,EAAE,OAAO,CAAC,OAAO;AACtB,aAAA;SACF;;IAEH,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,EAAE;AAC1C,QAAA,OAAO,OAAO;;AAEhB,IAAA,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC;IAC9B,OAAO,IAAIC,kBAAS,CAAC;AACnB,QAAA,GAAG,OAAO;QACV,OAAO;AACR,KAAA,CAAC;AACJ;AAEA;;;;;AAKG;AACG,SAAU,oBAAoB,CAClC,KAA6B,EAAA;IAE7B,MAAM,eAAe,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC;AACvD,IAAA,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAA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AAA,CAAC;AACF,QAAA,qBAAqB,GAAG,kBAAkB,IAAI,EAAE;;QAEhD,eAAe,GAAG,IAAI,CAAC,GAAG,CACxB,MAAM,CAAC,QAAQ,CAAC,MAAM;aACnB,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EACjE,CAAC,CACF;AAED,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"prune.cjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import {\n AIMessage,\n BaseMessage,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ThinkingContentText,\n MessageContentComplex,\n ReasoningContentText,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes, Providers } from '@/common';\n\nexport type PruneMessagesFactoryParams = {\n provider?: Providers;\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number | undefined>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n};\n\nfunction isIndexInContext(\n arrayA: unknown[],\n arrayB: unknown[],\n targetIndex: number\n): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(\n message: AIMessage,\n thinkingBlock: ThinkingContentText | ReasoningContentText\n): AIMessage {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? (message.content as MessageContentComplex[])\n : [\n {\n type: ContentTypes.TEXT,\n text: message.content,\n },\n ];\n /** Edge case, the message already has the thinking block */\n if (content[0].type === thinkingBlock.type) {\n return message;\n }\n content.unshift(thinkingBlock);\n return new AIMessage({\n ...message,\n content,\n });\n}\n\n/**\n * Calculates the total tokens from a single usage object\n *\n * @param usage The usage metadata object containing token information\n * @returns An object containing the total input and output tokens\n */\nexport function calculateTotalTokens(\n usage: Partial<UsageMetadata>\n): UsageMetadata {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation = Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const totalInputTokens = baseInputTokens + cacheCreation + cacheRead;\n const totalOutputTokens = Number(usage.output_tokens) || 0;\n\n return {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n total_tokens: totalInputTokens + totalOutputTokens,\n };\n}\n\nexport type PruningResult = {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n thinkingStartIndex?: number;\n};\n\n/**\n * Processes an array of messages and returns a context of messages that fit within a specified token limit.\n * It iterates over the messages from newest to oldest, adding them to the context until the token limit is reached.\n *\n * @param options Configuration options for processing messages\n * @returns Object containing the message context, remaining tokens, messages not included, and summary index\n */\nexport function getMessagesWithinTokenLimit({\n messages: _messages,\n maxContextTokens,\n indexTokenCountMap,\n startType: _startType,\n thinkingEnabled,\n tokenCounter,\n thinkingStartIndex: _thinkingStartIndex = -1,\n reasoningType = ContentTypes.THINKING,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n startType?: string | string[];\n thinkingEnabled?: boolean;\n tokenCounter: TokenCounter;\n thinkingStartIndex?: number;\n reasoningType?: ContentTypes.THINKING | ContentTypes.REASONING_CONTENT;\n}): PruningResult {\n // Every reply is primed with <|start|>assistant<|message|>, so we\n // start with 3 tokens for the label after all messages have been counted.\n let currentTokenCount = 3;\n const instructions =\n _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount =\n instructions != null ? (indexTokenCountMap[0] ?? 0) : 0;\n const initialContextTokens = maxContextTokens - instructionsTokenCount;\n let remainingContextTokens = initialContextTokens;\n let startType = _startType;\n const originalLength = _messages.length;\n const messages = [..._messages];\n /**\n * IMPORTANT: this context array gets reversed at the end, since the latest messages get pushed first.\n *\n * This may be confusing to read, but it is done to ensure the context is in the correct order for the model.\n * */\n let context: Array<BaseMessage | undefined> = [];\n\n let thinkingStartIndex = _thinkingStartIndex;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | ReasoningContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (_thinkingStartIndex > -1) {\n const thinkingMessageContent = messages[_thinkingStartIndex]?.content;\n if (Array.isArray(thinkingMessageContent)) {\n thinkingBlock = thinkingMessageContent.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n }\n }\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (\n messages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > endIndex\n ) {\n currentIndex--;\n if (messages.length === 1 && instructions) {\n break;\n }\n const poppedMessage = messages.pop();\n if (!poppedMessage) continue;\n const messageType = poppedMessage.getType();\n if (\n thinkingEnabled === true &&\n thinkingEndIndex === -1 &&\n currentIndex === originalLength - 1 &&\n (messageType === 'ai' || messageType === 'tool')\n ) {\n thinkingEndIndex = currentIndex;\n }\n if (\n thinkingEndIndex > -1 &&\n !thinkingBlock &&\n thinkingStartIndex < 0 &&\n messageType === 'ai' &&\n Array.isArray(poppedMessage.content)\n ) {\n thinkingBlock = poppedMessage.content.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n thinkingStartIndex = thinkingBlock != null ? currentIndex : -1;\n }\n /** False start, the latest message was not part of a multi-assistant/tool sequence of messages */\n if (\n thinkingEndIndex > -1 &&\n currentIndex === thinkingEndIndex - 1 &&\n messageType !== 'ai' &&\n messageType !== 'tool'\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (\n prunedMemory.length === 0 &&\n currentTokenCount + tokenCount <= remainingContextTokens\n ) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n continue;\n }\n break;\n }\n }\n\n if (context[context.length - 1]?.getType() === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && context.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = context.length - 1; i >= 0; i--) {\n const currentType = context[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n context = context.slice(0, requiredTypeIndex);\n }\n }\n }\n\n if (instructions && originalLength > 0) {\n context.push(_messages[0] as BaseMessage);\n messages.shift();\n }\n\n remainingContextTokens -= currentTokenCount;\n const result: PruningResult = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (thinkingStartIndex > -1) {\n result.thinkingStartIndex = thinkingStartIndex;\n }\n\n if (\n prunedMemory.length === 0 ||\n thinkingEndIndex < 0 ||\n (thinkingStartIndex > -1 &&\n isIndexInContext(_messages, context, thinkingStartIndex))\n ) {\n // we reverse at this step to ensure the context is in the correct order for the model, and we need to work backwards\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.'\n );\n }\n\n if (!thinkingBlock) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no thinking block found.'\n );\n }\n\n // Since we have a thinking sequence, we need to find the last assistant message\n // in the latest AI/tool sequence to add the thinking block that falls outside of the current context\n // Latest messages are ordered first.\n let assistantIndex = -1;\n for (let i = 0; i < context.length; i++) {\n const currentMessage = context[i];\n const type = currentMessage?.getType();\n if (type === 'ai') {\n assistantIndex = i;\n }\n if (assistantIndex > -1 && (type === 'human' || type === 'system')) {\n break;\n }\n }\n\n if (assistantIndex === -1) {\n throw new Error(\n 'Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.'\n );\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(\n new AIMessage({ content: [thinkingBlock] })\n );\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n const newMessage = addThinkingBlock(\n context[assistantIndex] as AIMessage,\n thinkingBlock\n );\n context[assistantIndex] = newMessage;\n if (newRemainingCount > 0) {\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex] as AIMessage;\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount =\n (indexTokenCountMap[thinkingStartIndex] ?? 0) + thinkingTokenCount;\n remainingContextTokens = initialContextTokens - newThinkingMessageTokenCount;\n currentTokenCount = 3;\n let newContext: BaseMessage[] = [];\n const secondRoundMessages = [..._messages];\n let currentIndex = secondRoundMessages.length;\n while (\n secondRoundMessages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > thinkingStartIndex\n ) {\n currentIndex--;\n const poppedMessage = secondRoundMessages.pop();\n if (!poppedMessage) continue;\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n if (currentTokenCount + tokenCount <= remainingContextTokens) {\n newContext.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n messages.push(poppedMessage);\n break;\n }\n }\n\n const firstMessage: AIMessage = newContext[newContext.length - 1];\n const firstMessageType = newContext[newContext.length - 1].getType();\n if (firstMessageType === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && newContext.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = newContext.length - 1; i >= 0; i--) {\n const currentType = newContext[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n newContext = newContext.slice(0, requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const newMessage = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1] = newMessage;\n } else {\n newContext.push(thinkingMessage);\n }\n\n if (instructions && originalLength > 0) {\n newContext.push(_messages[0] as BaseMessage);\n secondRoundMessages.shift();\n }\n\n result.context = newContext.reverse();\n return result;\n}\n\nexport function checkValidNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value) && value > 0;\n}\n\ntype ThinkingBlocks = {\n thinking_blocks?: Array<{\n type: 'thinking';\n thinking: string;\n signature: string;\n }>;\n};\n\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let lastCutOffIndex = 0;\n let totalTokens = Object.values(indexTokenCountMap).reduce(\n (a = 0, b = 0) => a + b,\n 0\n ) as number;\n let runThinkingStartIndex = -1;\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number | undefined>;\n } {\n if (\n factoryParams.provider === Providers.OPENAI &&\n factoryParams.thinkingEnabled === true\n ) {\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const m = params.messages[i];\n if (\n m.getType() === 'ai' &&\n typeof m.additional_kwargs.reasoning_content === 'string' &&\n Array.isArray(\n (\n m.additional_kwargs.provider_specific_fields as\n | ThinkingBlocks\n | undefined\n )?.thinking_blocks\n ) &&\n (m as AIMessage).tool_calls &&\n ((m as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const message = m as AIMessage;\n const thinkingBlocks = (\n message.additional_kwargs.provider_specific_fields as ThinkingBlocks\n ).thinking_blocks;\n const signature =\n thinkingBlocks?.[thinkingBlocks.length - 1].signature;\n const thinkingBlock: ThinkingContentText = {\n signature,\n type: ContentTypes.THINKING,\n thinking: message.additional_kwargs.reasoning_content as string,\n };\n\n params.messages[i] = new AIMessage({\n ...message,\n content: [thinkingBlock],\n additional_kwargs: {\n ...message.additional_kwargs,\n reasoning_content: undefined,\n },\n });\n }\n }\n }\n\n let currentUsage: UsageMetadata | undefined;\n if (\n params.usageMetadata &&\n (checkValidNumber(params.usageMetadata.input_tokens) ||\n (checkValidNumber(params.usageMetadata.input_token_details) &&\n (checkValidNumber(\n params.usageMetadata.input_token_details.cache_creation\n ) ||\n checkValidNumber(\n params.usageMetadata.input_token_details.cache_read\n )))) &&\n checkValidNumber(params.usageMetadata.output_tokens)\n ) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n const newOutputs = new Set<number>();\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n if (\n i === lastTurnStartIndex &&\n indexTokenCountMap[i] === undefined &&\n currentUsage\n ) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n if (currentUsage) {\n newOutputs.add(i);\n }\n totalTokens += indexTokenCountMap[i] ?? 0;\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,\n // We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,\n // relative the manually counted tokens in `indexTokenCountMap`.\n // EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.\n if (currentUsage) {\n let totalIndexTokens = 0;\n if (params.messages[0].getType() === 'system') {\n totalIndexTokens += indexTokenCountMap[0] ?? 0;\n }\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (i === 0 && params.messages[0].getType() === 'system') {\n continue;\n }\n if (newOutputs.has(i)) {\n continue;\n }\n totalIndexTokens += indexTokenCountMap[i] ?? 0;\n }\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n const isRatioSafe = ratio >= 1 / 3 && ratio <= 2.5;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex, and only if the ratio is safe\n if (isRatioSafe) {\n if (\n params.messages[0].getType() === 'system' &&\n lastCutOffIndex !== 0\n ) {\n indexTokenCountMap[0] = Math.round(\n (indexTokenCountMap[0] ?? 0) * ratio\n );\n }\n\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (newOutputs.has(i)) {\n continue;\n }\n indexTokenCountMap[i] = Math.round(\n (indexTokenCountMap[i] ?? 0) * ratio\n );\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (lastCutOffIndex === 0 && totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context, thinkingStartIndex } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n reasoningType:\n factoryParams.provider === Providers.BEDROCK\n ? ContentTypes.REASONING_CONTENT\n : ContentTypes.THINKING,\n thinkingStartIndex:\n factoryParams.thinkingEnabled === true\n ? runThinkingStartIndex\n : undefined,\n });\n runThinkingStartIndex = thinkingStartIndex ?? -1;\n /** The index is the first value of `context`, index relative to `params.messages` */\n lastCutOffIndex = Math.max(\n params.messages.length -\n (context.length - (context[0]?.getType() === 'system' ? 1 : 0)),\n 0\n );\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":["ContentTypes","AIMessage","messages","Providers"],"mappings":";;;;;AA2BA,SAAS,gBAAgB,CACvB,MAAiB,EACjB,MAAiB,EACjB,WAAmB,EAAA;IAEnB,MAAM,gBAAgB,GAAG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,CAAC,KAAK,CAChC,CAAC,kBAAkB,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CACrC;;;;AAKP,QAAA,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM;QAC3C,IAAI,eAAe,KAAK,CAAC,IAAI,WAAW,IAAI,aAAa,CAAC,SAAS,EAAE;YACnE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,kBAAkB,EAAE;;AAGzD,QAAA,MAAM,EAAE,OAAO,EAAE,kBAAkB,EAAE,GAAG,2BAA2B,CAAC;YAClE,gBAAgB,EAAE,aAAa,CAAC,SAAS;YACzC,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB;YAClB,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,eAAe,EAAE,aAAa,CAAC,eAAe;YAC9C,YAAY,EAAE,aAAa,CAAC,YAAY;AACxC,YAAA,aAAa,EACX,aAAa,CAAC,QAAQ,KAAKE,eAAS,CAAC;kBACjCH,kBAAY,CAAC;kBACbA,kBAAY,CAAC,QAAQ;AAC3B,YAAA,kBAAkB,EAChB,aAAa,CAAC,eAAe,KAAK;AAChC,kBAAE;AACF,kBAAE,SAAS;AAChB,SAAA,CAAC;AACF,QAAA,qBAAqB,GAAG,kBAAkB,IAAI,EAAE;;QAEhD,eAAe,GAAG,IAAI,CAAC,GAAG,CACxB,MAAM,CAAC,QAAQ,CAAC,MAAM;aACnB,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EACjE,CAAC,CACF;AAED,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;;;;"}
|
|
@@ -460,17 +460,15 @@ function areToolCallsInvoked(message, invokedToolIds) {
|
|
|
460
460
|
return (message.tool_calls?.every((toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)) ?? false);
|
|
461
461
|
}
|
|
462
462
|
function toolsCondition(state, toolNode, invokedToolIds) {
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
463
|
+
const messages = Array.isArray(state) ? state : state.messages;
|
|
464
|
+
const message = messages[messages.length - 1];
|
|
465
|
+
if (message &&
|
|
466
|
+
'tool_calls' in message &&
|
|
467
467
|
(message.tool_calls?.length ?? 0) > 0 &&
|
|
468
468
|
!areToolCallsInvoked(message, invokedToolIds)) {
|
|
469
469
|
return toolNode;
|
|
470
470
|
}
|
|
471
|
-
|
|
472
|
-
return langgraph.END;
|
|
473
|
-
}
|
|
471
|
+
return langgraph.END;
|
|
474
472
|
}
|
|
475
473
|
|
|
476
474
|
exports.ToolNode = ToolNode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n toolDefinitions,\n agentId,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n _injected_files: fileRefs,\n };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n const outputs: ToolMessage[] = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":["Send","RunnableCallable","Constants","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","safeDispatchCustomEvent","GraphEvents","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;AAyBA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA,cAAI;A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CACrE,IAAI,KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,OAAO,GAAc,KAAK,CAAC,OAAO,CAAC,KAAK;UAC1C,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;AACxB,UAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;SACV;AACL,QAAA,OAAOS,aAAG;;AAEd;;;;;"}
|
|
1
|
+
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n toolDefinitions,\n agentId,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n _injected_files: fileRefs,\n };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n const outputs: ToolMessage[] = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":["Send","RunnableCallable","Constants","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","safeDispatchCustomEvent","GraphEvents","messages","isAIMessage","Command","END"],"mappings":";;;;;;;;;;;;AAyBA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAYA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E,CAAC,CACrE,IAAI,KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,KAAK,GAAG,KAAK,CAAC,QAAQ;IAC9D,MAAM,OAAO,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAA0B;AAEtE,IAAA,IACE,OAAO;AACP,QAAA,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;AAEjB,IAAA,OAAOS,aAAG;AACZ;;;;;"}
|
|
@@ -190,7 +190,7 @@ function getMessagesWithinTokenLimit({ messages: _messages, maxContextTokens, in
|
|
|
190
190
|
}
|
|
191
191
|
}
|
|
192
192
|
if (assistantIndex === -1) {
|
|
193
|
-
throw new Error('
|
|
193
|
+
throw new Error('Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.');
|
|
194
194
|
}
|
|
195
195
|
thinkingStartIndex = originalLength - 1 - assistantIndex;
|
|
196
196
|
const thinkingTokenCount = tokenCounter(new AIMessage({ content: [thinkingBlock] }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prune.mjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import {\n AIMessage,\n BaseMessage,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ThinkingContentText,\n MessageContentComplex,\n ReasoningContentText,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes, Providers } from '@/common';\n\nexport type PruneMessagesFactoryParams = {\n provider?: Providers;\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number | undefined>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n};\n\nfunction isIndexInContext(\n arrayA: unknown[],\n arrayB: unknown[],\n targetIndex: number\n): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(\n message: AIMessage,\n thinkingBlock: ThinkingContentText | ReasoningContentText\n): AIMessage {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? (message.content as MessageContentComplex[])\n : [\n {\n type: ContentTypes.TEXT,\n text: message.content,\n },\n ];\n /** Edge case, the message already has the thinking block */\n if (content[0].type === thinkingBlock.type) {\n return message;\n }\n content.unshift(thinkingBlock);\n return new AIMessage({\n ...message,\n content,\n });\n}\n\n/**\n * Calculates the total tokens from a single usage object\n *\n * @param usage The usage metadata object containing token information\n * @returns An object containing the total input and output tokens\n */\nexport function calculateTotalTokens(\n usage: Partial<UsageMetadata>\n): UsageMetadata {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation = Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const totalInputTokens = baseInputTokens + cacheCreation + cacheRead;\n const totalOutputTokens = Number(usage.output_tokens) || 0;\n\n return {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n total_tokens: totalInputTokens + totalOutputTokens,\n };\n}\n\nexport type PruningResult = {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n thinkingStartIndex?: number;\n};\n\n/**\n * Processes an array of messages and returns a context of messages that fit within a specified token limit.\n * It iterates over the messages from newest to oldest, adding them to the context until the token limit is reached.\n *\n * @param options Configuration options for processing messages\n * @returns Object containing the message context, remaining tokens, messages not included, and summary index\n */\nexport function getMessagesWithinTokenLimit({\n messages: _messages,\n maxContextTokens,\n indexTokenCountMap,\n startType: _startType,\n thinkingEnabled,\n tokenCounter,\n thinkingStartIndex: _thinkingStartIndex = -1,\n reasoningType = ContentTypes.THINKING,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n startType?: string | string[];\n thinkingEnabled?: boolean;\n tokenCounter: TokenCounter;\n thinkingStartIndex?: number;\n reasoningType?: ContentTypes.THINKING | ContentTypes.REASONING_CONTENT;\n}): PruningResult {\n // Every reply is primed with <|start|>assistant<|message|>, so we\n // start with 3 tokens for the label after all messages have been counted.\n let currentTokenCount = 3;\n const instructions =\n _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount =\n instructions != null ? (indexTokenCountMap[0] ?? 0) : 0;\n const initialContextTokens = maxContextTokens - instructionsTokenCount;\n let remainingContextTokens = initialContextTokens;\n let startType = _startType;\n const originalLength = _messages.length;\n const messages = [..._messages];\n /**\n * IMPORTANT: this context array gets reversed at the end, since the latest messages get pushed first.\n *\n * This may be confusing to read, but it is done to ensure the context is in the correct order for the model.\n * */\n let context: Array<BaseMessage | undefined> = [];\n\n let thinkingStartIndex = _thinkingStartIndex;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | ReasoningContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (_thinkingStartIndex > -1) {\n const thinkingMessageContent = messages[_thinkingStartIndex]?.content;\n if (Array.isArray(thinkingMessageContent)) {\n thinkingBlock = thinkingMessageContent.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n }\n }\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (\n messages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > endIndex\n ) {\n currentIndex--;\n if (messages.length === 1 && instructions) {\n break;\n }\n const poppedMessage = messages.pop();\n if (!poppedMessage) continue;\n const messageType = poppedMessage.getType();\n if (\n thinkingEnabled === true &&\n thinkingEndIndex === -1 &&\n currentIndex === originalLength - 1 &&\n (messageType === 'ai' || messageType === 'tool')\n ) {\n thinkingEndIndex = currentIndex;\n }\n if (\n thinkingEndIndex > -1 &&\n !thinkingBlock &&\n thinkingStartIndex < 0 &&\n messageType === 'ai' &&\n Array.isArray(poppedMessage.content)\n ) {\n thinkingBlock = poppedMessage.content.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n thinkingStartIndex = thinkingBlock != null ? currentIndex : -1;\n }\n /** False start, the latest message was not part of a multi-assistant/tool sequence of messages */\n if (\n thinkingEndIndex > -1 &&\n currentIndex === thinkingEndIndex - 1 &&\n messageType !== 'ai' &&\n messageType !== 'tool'\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (\n prunedMemory.length === 0 &&\n currentTokenCount + tokenCount <= remainingContextTokens\n ) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n continue;\n }\n break;\n }\n }\n\n if (context[context.length - 1]?.getType() === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && context.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = context.length - 1; i >= 0; i--) {\n const currentType = context[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n context = context.slice(0, requiredTypeIndex);\n }\n }\n }\n\n if (instructions && originalLength > 0) {\n context.push(_messages[0] as BaseMessage);\n messages.shift();\n }\n\n remainingContextTokens -= currentTokenCount;\n const result: PruningResult = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (thinkingStartIndex > -1) {\n result.thinkingStartIndex = thinkingStartIndex;\n }\n\n if (\n prunedMemory.length === 0 ||\n thinkingEndIndex < 0 ||\n (thinkingStartIndex > -1 &&\n isIndexInContext(_messages, context, thinkingStartIndex))\n ) {\n // we reverse at this step to ensure the context is in the correct order for the model, and we need to work backwards\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.'\n );\n }\n\n if (!thinkingBlock) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no thinking block found.'\n );\n }\n\n // Since we have a thinking sequence, we need to find the last assistant message\n // in the latest AI/tool sequence to add the thinking block that falls outside of the current context\n // Latest messages are ordered first.\n let assistantIndex = -1;\n for (let i = 0; i < context.length; i++) {\n const currentMessage = context[i];\n const type = currentMessage?.getType();\n if (type === 'ai') {\n assistantIndex = i;\n }\n if (assistantIndex > -1 && (type === 'human' || type === 'system')) {\n break;\n }\n }\n\n if (assistantIndex === -1) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages to append thinking blocks to.'\n );\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(\n new AIMessage({ content: [thinkingBlock] })\n );\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n const newMessage = addThinkingBlock(\n context[assistantIndex] as AIMessage,\n thinkingBlock\n );\n context[assistantIndex] = newMessage;\n if (newRemainingCount > 0) {\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex] as AIMessage;\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount =\n (indexTokenCountMap[thinkingStartIndex] ?? 0) + thinkingTokenCount;\n remainingContextTokens = initialContextTokens - newThinkingMessageTokenCount;\n currentTokenCount = 3;\n let newContext: BaseMessage[] = [];\n const secondRoundMessages = [..._messages];\n let currentIndex = secondRoundMessages.length;\n while (\n secondRoundMessages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > thinkingStartIndex\n ) {\n currentIndex--;\n const poppedMessage = secondRoundMessages.pop();\n if (!poppedMessage) continue;\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n if (currentTokenCount + tokenCount <= remainingContextTokens) {\n newContext.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n messages.push(poppedMessage);\n break;\n }\n }\n\n const firstMessage: AIMessage = newContext[newContext.length - 1];\n const firstMessageType = newContext[newContext.length - 1].getType();\n if (firstMessageType === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && newContext.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = newContext.length - 1; i >= 0; i--) {\n const currentType = newContext[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n newContext = newContext.slice(0, requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const newMessage = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1] = newMessage;\n } else {\n newContext.push(thinkingMessage);\n }\n\n if (instructions && originalLength > 0) {\n newContext.push(_messages[0] as BaseMessage);\n secondRoundMessages.shift();\n }\n\n result.context = newContext.reverse();\n return result;\n}\n\nexport function checkValidNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value) && value > 0;\n}\n\ntype ThinkingBlocks = {\n thinking_blocks?: Array<{\n type: 'thinking';\n thinking: string;\n signature: string;\n }>;\n};\n\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let lastCutOffIndex = 0;\n let totalTokens = Object.values(indexTokenCountMap).reduce(\n (a = 0, b = 0) => a + b,\n 0\n ) as number;\n let runThinkingStartIndex = -1;\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number | undefined>;\n } {\n if (\n factoryParams.provider === Providers.OPENAI &&\n factoryParams.thinkingEnabled === true\n ) {\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const m = params.messages[i];\n if (\n m.getType() === 'ai' &&\n typeof m.additional_kwargs.reasoning_content === 'string' &&\n Array.isArray(\n (\n m.additional_kwargs.provider_specific_fields as\n | ThinkingBlocks\n | undefined\n )?.thinking_blocks\n ) &&\n (m as AIMessage).tool_calls &&\n ((m as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const message = m as AIMessage;\n const thinkingBlocks = (\n message.additional_kwargs.provider_specific_fields as ThinkingBlocks\n ).thinking_blocks;\n const signature =\n thinkingBlocks?.[thinkingBlocks.length - 1].signature;\n const thinkingBlock: ThinkingContentText = {\n signature,\n type: ContentTypes.THINKING,\n thinking: message.additional_kwargs.reasoning_content as string,\n };\n\n params.messages[i] = new AIMessage({\n ...message,\n content: [thinkingBlock],\n additional_kwargs: {\n ...message.additional_kwargs,\n reasoning_content: undefined,\n },\n });\n }\n }\n }\n\n let currentUsage: UsageMetadata | undefined;\n if (\n params.usageMetadata &&\n (checkValidNumber(params.usageMetadata.input_tokens) ||\n (checkValidNumber(params.usageMetadata.input_token_details) &&\n (checkValidNumber(\n params.usageMetadata.input_token_details.cache_creation\n ) ||\n checkValidNumber(\n params.usageMetadata.input_token_details.cache_read\n )))) &&\n checkValidNumber(params.usageMetadata.output_tokens)\n ) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n const newOutputs = new Set<number>();\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n if (\n i === lastTurnStartIndex &&\n indexTokenCountMap[i] === undefined &&\n currentUsage\n ) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n if (currentUsage) {\n newOutputs.add(i);\n }\n totalTokens += indexTokenCountMap[i] ?? 0;\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,\n // We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,\n // relative the manually counted tokens in `indexTokenCountMap`.\n // EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.\n if (currentUsage) {\n let totalIndexTokens = 0;\n if (params.messages[0].getType() === 'system') {\n totalIndexTokens += indexTokenCountMap[0] ?? 0;\n }\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (i === 0 && params.messages[0].getType() === 'system') {\n continue;\n }\n if (newOutputs.has(i)) {\n continue;\n }\n totalIndexTokens += indexTokenCountMap[i] ?? 0;\n }\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n const isRatioSafe = ratio >= 1 / 3 && ratio <= 2.5;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex, and only if the ratio is safe\n if (isRatioSafe) {\n if (\n params.messages[0].getType() === 'system' &&\n lastCutOffIndex !== 0\n ) {\n indexTokenCountMap[0] = Math.round(\n (indexTokenCountMap[0] ?? 0) * ratio\n );\n }\n\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (newOutputs.has(i)) {\n continue;\n }\n indexTokenCountMap[i] = Math.round(\n (indexTokenCountMap[i] ?? 0) * ratio\n );\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (lastCutOffIndex === 0 && totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context, thinkingStartIndex } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n reasoningType:\n factoryParams.provider === Providers.BEDROCK\n ? ContentTypes.REASONING_CONTENT\n : ContentTypes.THINKING,\n thinkingStartIndex:\n factoryParams.thinkingEnabled === true\n ? runThinkingStartIndex\n : undefined,\n });\n runThinkingStartIndex = thinkingStartIndex ?? -1;\n /** The index is the first value of `context`, index relative to `params.messages` */\n lastCutOffIndex = Math.max(\n params.messages.length -\n (context.length - (context[0]?.getType() === 'system' ? 1 : 0)),\n 0\n );\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":[],"mappings":";;;AA2BA,SAAS,gBAAgB,CACvB,MAAiB,EACjB,MAAiB,EACjB,WAAmB,EAAA;IAEnB,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;IACtD,OAAO,WAAW,IAAI,gBAAgB;AACxC;AAEA,SAAS,gBAAgB,CACvB,OAAkB,EAClB,aAAyD,EAAA;IAEzD,MAAM,OAAO,GAA4B,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO;UACjE,OAAO,CAAC;AACX,UAAE;AACA,YAAA;gBACE,IAAI,EAAE,YAAY,CAAC,IAAI;gBACvB,IAAI,EAAE,OAAO,CAAC,OAAO;AACtB,aAAA;SACF;;IAEH,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,EAAE;AAC1C,QAAA,OAAO,OAAO;;AAEhB,IAAA,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC;IAC9B,OAAO,IAAI,SAAS,CAAC;AACnB,QAAA,GAAG,OAAO;QACV,OAAO;AACR,KAAA,CAAC;AACJ;AAEA;;;;;AAKG;AACG,SAAU,oBAAoB,CAClC,KAA6B,EAAA;IAE7B,MAAM,eAAe,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC;AACvD,IAAA,MAAM,aAAa,G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,SAAA,CAAC;AACF,QAAA,qBAAqB,GAAG,kBAAkB,IAAI,EAAE;;QAEhD,eAAe,GAAG,IAAI,CAAC,GAAG,CACxB,MAAM,CAAC,QAAQ,CAAC,MAAM;aACnB,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EACjE,CAAC,CACF;AAED,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"prune.mjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import {\n AIMessage,\n BaseMessage,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ThinkingContentText,\n MessageContentComplex,\n ReasoningContentText,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes, Providers } from '@/common';\n\nexport type PruneMessagesFactoryParams = {\n provider?: Providers;\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number | undefined>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n};\n\nfunction isIndexInContext(\n arrayA: unknown[],\n arrayB: unknown[],\n targetIndex: number\n): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(\n message: AIMessage,\n thinkingBlock: ThinkingContentText | ReasoningContentText\n): AIMessage {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? (message.content as MessageContentComplex[])\n : [\n {\n type: ContentTypes.TEXT,\n text: message.content,\n },\n ];\n /** Edge case, the message already has the thinking block */\n if (content[0].type === thinkingBlock.type) {\n return message;\n }\n content.unshift(thinkingBlock);\n return new AIMessage({\n ...message,\n content,\n });\n}\n\n/**\n * Calculates the total tokens from a single usage object\n *\n * @param usage The usage metadata object containing token information\n * @returns An object containing the total input and output tokens\n */\nexport function calculateTotalTokens(\n usage: Partial<UsageMetadata>\n): UsageMetadata {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation = Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const totalInputTokens = baseInputTokens + cacheCreation + cacheRead;\n const totalOutputTokens = Number(usage.output_tokens) || 0;\n\n return {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n total_tokens: totalInputTokens + totalOutputTokens,\n };\n}\n\nexport type PruningResult = {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n thinkingStartIndex?: number;\n};\n\n/**\n * Processes an array of messages and returns a context of messages that fit within a specified token limit.\n * It iterates over the messages from newest to oldest, adding them to the context until the token limit is reached.\n *\n * @param options Configuration options for processing messages\n * @returns Object containing the message context, remaining tokens, messages not included, and summary index\n */\nexport function getMessagesWithinTokenLimit({\n messages: _messages,\n maxContextTokens,\n indexTokenCountMap,\n startType: _startType,\n thinkingEnabled,\n tokenCounter,\n thinkingStartIndex: _thinkingStartIndex = -1,\n reasoningType = ContentTypes.THINKING,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n startType?: string | string[];\n thinkingEnabled?: boolean;\n tokenCounter: TokenCounter;\n thinkingStartIndex?: number;\n reasoningType?: ContentTypes.THINKING | ContentTypes.REASONING_CONTENT;\n}): PruningResult {\n // Every reply is primed with <|start|>assistant<|message|>, so we\n // start with 3 tokens for the label after all messages have been counted.\n let currentTokenCount = 3;\n const instructions =\n _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount =\n instructions != null ? (indexTokenCountMap[0] ?? 0) : 0;\n const initialContextTokens = maxContextTokens - instructionsTokenCount;\n let remainingContextTokens = initialContextTokens;\n let startType = _startType;\n const originalLength = _messages.length;\n const messages = [..._messages];\n /**\n * IMPORTANT: this context array gets reversed at the end, since the latest messages get pushed first.\n *\n * This may be confusing to read, but it is done to ensure the context is in the correct order for the model.\n * */\n let context: Array<BaseMessage | undefined> = [];\n\n let thinkingStartIndex = _thinkingStartIndex;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | ReasoningContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (_thinkingStartIndex > -1) {\n const thinkingMessageContent = messages[_thinkingStartIndex]?.content;\n if (Array.isArray(thinkingMessageContent)) {\n thinkingBlock = thinkingMessageContent.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n }\n }\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (\n messages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > endIndex\n ) {\n currentIndex--;\n if (messages.length === 1 && instructions) {\n break;\n }\n const poppedMessage = messages.pop();\n if (!poppedMessage) continue;\n const messageType = poppedMessage.getType();\n if (\n thinkingEnabled === true &&\n thinkingEndIndex === -1 &&\n currentIndex === originalLength - 1 &&\n (messageType === 'ai' || messageType === 'tool')\n ) {\n thinkingEndIndex = currentIndex;\n }\n if (\n thinkingEndIndex > -1 &&\n !thinkingBlock &&\n thinkingStartIndex < 0 &&\n messageType === 'ai' &&\n Array.isArray(poppedMessage.content)\n ) {\n thinkingBlock = poppedMessage.content.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n thinkingStartIndex = thinkingBlock != null ? currentIndex : -1;\n }\n /** False start, the latest message was not part of a multi-assistant/tool sequence of messages */\n if (\n thinkingEndIndex > -1 &&\n currentIndex === thinkingEndIndex - 1 &&\n messageType !== 'ai' &&\n messageType !== 'tool'\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (\n prunedMemory.length === 0 &&\n currentTokenCount + tokenCount <= remainingContextTokens\n ) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n continue;\n }\n break;\n }\n }\n\n if (context[context.length - 1]?.getType() === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && context.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = context.length - 1; i >= 0; i--) {\n const currentType = context[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n context = context.slice(0, requiredTypeIndex);\n }\n }\n }\n\n if (instructions && originalLength > 0) {\n context.push(_messages[0] as BaseMessage);\n messages.shift();\n }\n\n remainingContextTokens -= currentTokenCount;\n const result: PruningResult = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (thinkingStartIndex > -1) {\n result.thinkingStartIndex = thinkingStartIndex;\n }\n\n if (\n prunedMemory.length === 0 ||\n thinkingEndIndex < 0 ||\n (thinkingStartIndex > -1 &&\n isIndexInContext(_messages, context, thinkingStartIndex))\n ) {\n // we reverse at this step to ensure the context is in the correct order for the model, and we need to work backwards\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.'\n );\n }\n\n if (!thinkingBlock) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no thinking block found.'\n );\n }\n\n // Since we have a thinking sequence, we need to find the last assistant message\n // in the latest AI/tool sequence to add the thinking block that falls outside of the current context\n // Latest messages are ordered first.\n let assistantIndex = -1;\n for (let i = 0; i < context.length; i++) {\n const currentMessage = context[i];\n const type = currentMessage?.getType();\n if (type === 'ai') {\n assistantIndex = i;\n }\n if (assistantIndex > -1 && (type === 'human' || type === 'system')) {\n break;\n }\n }\n\n if (assistantIndex === -1) {\n throw new Error(\n 'Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.'\n );\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(\n new AIMessage({ content: [thinkingBlock] })\n );\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n const newMessage = addThinkingBlock(\n context[assistantIndex] as AIMessage,\n thinkingBlock\n );\n context[assistantIndex] = newMessage;\n if (newRemainingCount > 0) {\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex] as AIMessage;\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount =\n (indexTokenCountMap[thinkingStartIndex] ?? 0) + thinkingTokenCount;\n remainingContextTokens = initialContextTokens - newThinkingMessageTokenCount;\n currentTokenCount = 3;\n let newContext: BaseMessage[] = [];\n const secondRoundMessages = [..._messages];\n let currentIndex = secondRoundMessages.length;\n while (\n secondRoundMessages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > thinkingStartIndex\n ) {\n currentIndex--;\n const poppedMessage = secondRoundMessages.pop();\n if (!poppedMessage) continue;\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n if (currentTokenCount + tokenCount <= remainingContextTokens) {\n newContext.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n messages.push(poppedMessage);\n break;\n }\n }\n\n const firstMessage: AIMessage = newContext[newContext.length - 1];\n const firstMessageType = newContext[newContext.length - 1].getType();\n if (firstMessageType === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && newContext.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = newContext.length - 1; i >= 0; i--) {\n const currentType = newContext[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n newContext = newContext.slice(0, requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const newMessage = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1] = newMessage;\n } else {\n newContext.push(thinkingMessage);\n }\n\n if (instructions && originalLength > 0) {\n newContext.push(_messages[0] as BaseMessage);\n secondRoundMessages.shift();\n }\n\n result.context = newContext.reverse();\n return result;\n}\n\nexport function checkValidNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value) && value > 0;\n}\n\ntype ThinkingBlocks = {\n thinking_blocks?: Array<{\n type: 'thinking';\n thinking: string;\n signature: string;\n }>;\n};\n\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let lastCutOffIndex = 0;\n let totalTokens = Object.values(indexTokenCountMap).reduce(\n (a = 0, b = 0) => a + b,\n 0\n ) as number;\n let runThinkingStartIndex = -1;\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number | undefined>;\n } {\n if (\n factoryParams.provider === Providers.OPENAI &&\n factoryParams.thinkingEnabled === true\n ) {\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const m = params.messages[i];\n if (\n m.getType() === 'ai' &&\n typeof m.additional_kwargs.reasoning_content === 'string' &&\n Array.isArray(\n (\n m.additional_kwargs.provider_specific_fields as\n | ThinkingBlocks\n | undefined\n )?.thinking_blocks\n ) &&\n (m as AIMessage).tool_calls &&\n ((m as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const message = m as AIMessage;\n const thinkingBlocks = (\n message.additional_kwargs.provider_specific_fields as ThinkingBlocks\n ).thinking_blocks;\n const signature =\n thinkingBlocks?.[thinkingBlocks.length - 1].signature;\n const thinkingBlock: ThinkingContentText = {\n signature,\n type: ContentTypes.THINKING,\n thinking: message.additional_kwargs.reasoning_content as string,\n };\n\n params.messages[i] = new AIMessage({\n ...message,\n content: [thinkingBlock],\n additional_kwargs: {\n ...message.additional_kwargs,\n reasoning_content: undefined,\n },\n });\n }\n }\n }\n\n let currentUsage: UsageMetadata | undefined;\n if (\n params.usageMetadata &&\n (checkValidNumber(params.usageMetadata.input_tokens) ||\n (checkValidNumber(params.usageMetadata.input_token_details) &&\n (checkValidNumber(\n params.usageMetadata.input_token_details.cache_creation\n ) ||\n checkValidNumber(\n params.usageMetadata.input_token_details.cache_read\n )))) &&\n checkValidNumber(params.usageMetadata.output_tokens)\n ) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n const newOutputs = new Set<number>();\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n if (\n i === lastTurnStartIndex &&\n indexTokenCountMap[i] === undefined &&\n currentUsage\n ) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n if (currentUsage) {\n newOutputs.add(i);\n }\n totalTokens += indexTokenCountMap[i] ?? 0;\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,\n // We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,\n // relative the manually counted tokens in `indexTokenCountMap`.\n // EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.\n if (currentUsage) {\n let totalIndexTokens = 0;\n if (params.messages[0].getType() === 'system') {\n totalIndexTokens += indexTokenCountMap[0] ?? 0;\n }\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (i === 0 && params.messages[0].getType() === 'system') {\n continue;\n }\n if (newOutputs.has(i)) {\n continue;\n }\n totalIndexTokens += indexTokenCountMap[i] ?? 0;\n }\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n const isRatioSafe = ratio >= 1 / 3 && ratio <= 2.5;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex, and only if the ratio is safe\n if (isRatioSafe) {\n if (\n params.messages[0].getType() === 'system' &&\n lastCutOffIndex !== 0\n ) {\n indexTokenCountMap[0] = Math.round(\n (indexTokenCountMap[0] ?? 0) * ratio\n );\n }\n\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (newOutputs.has(i)) {\n continue;\n }\n indexTokenCountMap[i] = Math.round(\n (indexTokenCountMap[i] ?? 0) * ratio\n );\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (lastCutOffIndex === 0 && totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context, thinkingStartIndex } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n reasoningType:\n factoryParams.provider === Providers.BEDROCK\n ? ContentTypes.REASONING_CONTENT\n : ContentTypes.THINKING,\n thinkingStartIndex:\n factoryParams.thinkingEnabled === true\n ? runThinkingStartIndex\n : undefined,\n });\n runThinkingStartIndex = thinkingStartIndex ?? -1;\n /** The index is the first value of `context`, index relative to `params.messages` */\n lastCutOffIndex = Math.max(\n params.messages.length -\n (context.length - (context[0]?.getType() === 'system' ? 1 : 0)),\n 0\n );\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":[],"mappings":";;;AA2BA,SAAS,gBAAgB,CACvB,MAAiB,EACjB,MAAiB,EACjB,WAAmB,EAAA;IAEnB,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MA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,IAAI,CAAC,IAAI,KAAK,CACrC;;;;AAKP,QAAA,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM;QAC3C,IAAI,eAAe,KAAK,CAAC,IAAI,WAAW,IAAI,aAAa,CAAC,SAAS,EAAE;YACnE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,kBAAkB,EAAE;;AAGzD,QAAA,MAAM,EAAE,OAAO,EAAE,kBAAkB,EAAE,GAAG,2BAA2B,CAAC;YAClE,gBAAgB,EAAE,aAAa,CAAC,SAAS;YACzC,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB;YAClB,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,eAAe,EAAE,aAAa,CAAC,eAAe;YAC9C,YAAY,EAAE,aAAa,CAAC,YAAY;AACxC,YAAA,aAAa,EACX,aAAa,CAAC,QAAQ,KAAK,SAAS,CAAC;kBACjC,YAAY,CAAC;kBACb,YAAY,CAAC,QAAQ;AAC3B,YAAA,kBAAkB,EAChB,aAAa,CAAC,eAAe,KAAK;AAChC,kBAAE;AACF,kBAAE,SAAS;AAChB,SAAA,CAAC;AACF,QAAA,qBAAqB,GAAG,kBAAkB,IAAI,EAAE;;QAEhD,eAAe,GAAG,IAAI,CAAC,GAAG,CACxB,MAAM,CAAC,QAAQ,CAAC,MAAM;aACnB,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EACjE,CAAC,CACF;AAED,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;"}
|
|
@@ -458,17 +458,15 @@ function areToolCallsInvoked(message, invokedToolIds) {
|
|
|
458
458
|
return (message.tool_calls?.every((toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)) ?? false);
|
|
459
459
|
}
|
|
460
460
|
function toolsCondition(state, toolNode, invokedToolIds) {
|
|
461
|
-
const
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
461
|
+
const messages = Array.isArray(state) ? state : state.messages;
|
|
462
|
+
const message = messages[messages.length - 1];
|
|
463
|
+
if (message &&
|
|
464
|
+
'tool_calls' in message &&
|
|
465
465
|
(message.tool_calls?.length ?? 0) > 0 &&
|
|
466
466
|
!areToolCallsInvoked(message, invokedToolIds)) {
|
|
467
467
|
return toolNode;
|
|
468
468
|
}
|
|
469
|
-
|
|
470
|
-
return END;
|
|
471
|
-
}
|
|
469
|
+
return END;
|
|
472
470
|
}
|
|
473
471
|
|
|
474
472
|
export { ToolNode, toolsCondition };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n toolDefinitions,\n agentId,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n _injected_files: fileRefs,\n };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n const outputs: ToolMessage[] = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;AAyBA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAY,IAAI;AAC9B;AAEA;AACM,MAAO,QAAkB,SAAQ,gBAAsB,CAAA;AACnD,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;IACvB,KAAK,GAAG,KAAK;AACb,IAAA,eAAe;AACf,IAAA,YAAY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KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;SACV;AACL,QAAA,OAAO,GAAG;;AAEd;;;;"}
|
|
1
|
+
{"version":3,"file":"ToolNode.mjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { ToolCall } from '@langchain/core/messages/tool';\nimport {\n ToolMessage,\n isAIMessage,\n isBaseMessage,\n} from '@langchain/core/messages';\nimport {\n END,\n Send,\n Command,\n isCommand,\n isGraphInterrupt,\n MessagesAnnotation,\n} from '@langchain/langgraph';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { Constants, GraphEvents } from '@/common';\n\n/**\n * Helper to check if a value is a Send object\n */\nfunction isSend(value: unknown): value is Send {\n return value instanceof Send;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n trace = false;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n /** Tool registry for filtering (lazy computation of programmatic maps) */\n private toolRegistry?: t.LCToolRegistry;\n /** Cached programmatic tools (computed once on first PTC call) */\n private programmaticCache?: t.ProgrammaticCache;\n /** Reference to Graph's sessions map for automatic session injection */\n private sessions?: t.ToolSessionMap;\n /** When true, dispatches ON_TOOL_EXECUTE events instead of invoking tools directly */\n private eventDrivenMode: boolean = false;\n /** Tool definitions for event-driven mode */\n private toolDefinitions?: Map<string, t.LCTool>;\n /** Agent ID for event-driven mode */\n private agentId?: string;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n toolRegistry,\n sessions,\n eventDrivenMode,\n toolDefinitions,\n agentId,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n this.toolRegistry = toolRegistry;\n this.sessions = sessions;\n this.eventDrivenMode = eventDrivenMode ?? false;\n this.toolDefinitions = toolDefinitions;\n this.agentId = agentId;\n }\n\n /**\n * Returns cached programmatic tools, computing once on first access.\n * Single iteration builds both toolMap and toolDefs simultaneously.\n */\n private getProgrammaticTools(): { toolMap: t.ToolMap; toolDefs: t.LCTool[] } {\n if (this.programmaticCache) return this.programmaticCache;\n\n const toolMap: t.ToolMap = new Map();\n const toolDefs: t.LCTool[] = [];\n\n if (this.toolRegistry) {\n for (const [name, toolDef] of this.toolRegistry) {\n if (\n (toolDef.allowed_callers ?? ['direct']).includes('code_execution')\n ) {\n toolDefs.push(toolDef);\n const tool = this.toolMap.get(name);\n if (tool) toolMap.set(name, tool);\n }\n }\n }\n\n this.programmaticCache = { toolMap, toolDefs };\n return this.programmaticCache;\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n /**\n * Runs a single tool call with error handling\n */\n protected async runTool(\n call: ToolCall,\n config: RunnableConfig\n ): Promise<BaseMessage | Command> {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n\n // Build invoke params - LangChain extracts non-schema fields to config.toolCall\n let invokeParams: Record<string, unknown> = {\n ...call,\n args,\n type: 'tool_call',\n stepId,\n turn,\n };\n\n // Inject runtime data for special tools (becomes available at config.toolCall)\n if (call.name === Constants.PROGRAMMATIC_TOOL_CALLING) {\n const { toolMap, toolDefs } = this.getProgrammaticTools();\n invokeParams = {\n ...invokeParams,\n toolMap,\n toolDefs,\n };\n } else if (call.name === Constants.TOOL_SEARCH) {\n invokeParams = {\n ...invokeParams,\n toolRegistry: this.toolRegistry,\n };\n }\n\n /**\n * Inject session context for code execution tools when available.\n * Each file uses its own session_id (supporting multi-session file tracking).\n * Both session_id and _injected_files are injected directly to invokeParams\n * (not inside args) so they bypass Zod schema validation and reach config.toolCall.\n */\n if (\n call.name === Constants.EXECUTE_CODE ||\n call.name === Constants.PROGRAMMATIC_TOOL_CALLING\n ) {\n const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as\n | t.CodeSessionContext\n | undefined;\n if (codeSession?.files != null && codeSession.files.length > 0) {\n /**\n * Convert tracked files to CodeEnvFile format for the API.\n * Each file uses its own session_id (set when file was created).\n * This supports files from multiple parallel/sequential executions.\n */\n const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({\n session_id: file.session_id ?? codeSession.session_id,\n id: file.id,\n name: file.name,\n }));\n /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */\n invokeParams = {\n ...invokeParams,\n session_id: codeSession.session_id,\n _injected_files: fileRefs,\n };\n }\n }\n\n const output = await tool.invoke(invokeParams, config);\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n status: 'success',\n name: tool.name,\n content: typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n if (this.errorHandler) {\n try {\n await this.errorHandler(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n } catch (handlerError) {\n // eslint-disable-next-line no-console\n console.error('Error in errorHandler:', {\n toolName: call.name,\n toolCallId: call.id,\n toolArgs: call.args,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn: this.toolUsageCount.get(call.name),\n originalError: {\n message: e.message,\n stack: e.stack ?? undefined,\n },\n handlerError:\n handlerError instanceof Error\n ? {\n message: handlerError.message,\n stack: handlerError.stack ?? undefined,\n }\n : {\n message: String(handlerError),\n stack: undefined,\n },\n });\n }\n }\n return new ToolMessage({\n status: 'error',\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }\n\n /**\n * Execute all tool calls via ON_TOOL_EXECUTE event dispatch.\n * Used in event-driven mode where the host handles actual tool execution.\n */\n private async executeViaEvent(\n toolCalls: ToolCall[],\n config: RunnableConfig,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n input: any\n ): Promise<T> {\n const requests: t.ToolCallRequest[] = toolCalls.map((call) => {\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n return {\n id: call.id!,\n name: call.name,\n args: call.args as Record<string, unknown>,\n stepId: this.toolCallStepIds?.get(call.id!),\n turn,\n };\n });\n\n const results = await new Promise<t.ToolExecuteResult[]>(\n (resolve, reject) => {\n const request: t.ToolExecuteBatchRequest = {\n toolCalls: requests,\n userId: config.configurable?.user_id as string | undefined,\n agentId: this.agentId,\n configurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n metadata: config.metadata as Record<string, unknown> | undefined,\n resolve,\n reject,\n };\n\n safeDispatchCustomEvent(GraphEvents.ON_TOOL_EXECUTE, request, config);\n }\n );\n\n const outputs: ToolMessage[] = results.map((result) => {\n const request = requests.find((r) => r.id === result.toolCallId);\n const toolName = request?.name ?? 'unknown';\n const stepId = this.toolCallStepIds?.get(result.toolCallId) ?? '';\n\n let toolMessage: ToolMessage;\n let contentString: string;\n\n if (result.status === 'error') {\n contentString = `Error: ${result.errorMessage ?? 'Unknown error'}\\n Please fix your mistakes.`;\n toolMessage = new ToolMessage({\n status: 'error',\n content: contentString,\n name: toolName,\n tool_call_id: result.toolCallId,\n });\n } else {\n contentString =\n typeof result.content === 'string'\n ? result.content\n : JSON.stringify(result.content);\n toolMessage = new ToolMessage({\n status: 'success',\n name: toolName,\n content: contentString,\n artifact: result.artifact,\n tool_call_id: result.toolCallId,\n });\n }\n\n const tool_call: t.ProcessedToolCall = {\n args:\n typeof request?.args === 'string'\n ? request.args\n : JSON.stringify(request?.args ?? {}),\n name: toolName,\n id: result.toolCallId,\n output: contentString,\n progress: 1,\n };\n\n const runStepCompletedData = {\n result: {\n id: stepId,\n index: request?.turn ?? 0,\n type: 'tool_call' as const,\n tool_call,\n },\n };\n\n safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n runStepCompletedData,\n config\n );\n\n return toolMessage;\n });\n\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n let outputs: (BaseMessage | Command)[];\n\n if (this.isSendInput(input)) {\n if (this.eventDrivenMode) {\n return this.executeViaEvent([input.lg_tool_call], config, input);\n }\n outputs = [await this.runTool(input.lg_tool_call, config)];\n } else {\n let messages: BaseMessage[];\n if (Array.isArray(input)) {\n messages = input;\n } else if (this.isMessagesState(input)) {\n messages = input.messages;\n } else {\n throw new Error(\n 'ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.'\n );\n }\n\n const toolMessageIds: Set<string> = new Set(\n messages\n .filter((msg) => msg._getType() === 'tool')\n .map((msg) => (msg as ToolMessage).tool_call_id)\n );\n\n let aiMessage: AIMessage | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (isAIMessage(message)) {\n aiMessage = message;\n break;\n }\n }\n\n if (aiMessage == null || !isAIMessage(aiMessage)) {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n aiMessage.tool_calls ?? []\n );\n this.toolMap =\n toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.programmaticCache = undefined; // Invalidate cache on toolMap change\n }\n\n const filteredCalls =\n aiMessage.tool_calls?.filter((call) => {\n /**\n * Filter out:\n * 1. Already processed tool calls (present in toolMessageIds)\n * 2. Server tool calls (e.g., web_search with IDs starting with 'srvtoolu_')\n * which are executed by the provider's API and don't require invocation\n */\n return (\n (call.id == null || !toolMessageIds.has(call.id)) &&\n !(call.id?.startsWith('srvtoolu_') ?? false)\n );\n }) ?? [];\n\n if (this.eventDrivenMode && filteredCalls.length > 0) {\n return this.executeViaEvent(filteredCalls, config, input);\n }\n\n outputs = await Promise.all(\n filteredCalls.map((call) => this.runTool(call, config))\n );\n }\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs: (\n | { messages: BaseMessage[] }\n | BaseMessage[]\n | Command\n )[] = [];\n let parentCommand: Command | null = null;\n\n /**\n * Collect handoff commands (Commands with string goto and Command.PARENT)\n * for potential parallel handoff aggregation\n */\n const handoffCommands: Command[] = [];\n const nonCommandOutputs: BaseMessage[] = [];\n\n for (const output of outputs) {\n if (isCommand(output)) {\n if (\n output.graph === Command.PARENT &&\n Array.isArray(output.goto) &&\n output.goto.every((send): send is Send => isSend(send))\n ) {\n /** Aggregate Send-based commands */\n if (parentCommand) {\n (parentCommand.goto as Send[]).push(...(output.goto as Send[]));\n } else {\n parentCommand = new Command({\n graph: Command.PARENT,\n goto: output.goto,\n });\n }\n } else if (output.graph === Command.PARENT) {\n /**\n * Handoff Command with destination.\n * Handle both string ('agent') and array (['agent']) formats.\n * Collect for potential parallel aggregation.\n */\n const goto = output.goto;\n const isSingleStringDest = typeof goto === 'string';\n const isSingleArrayDest =\n Array.isArray(goto) &&\n goto.length === 1 &&\n typeof goto[0] === 'string';\n\n if (isSingleStringDest || isSingleArrayDest) {\n handoffCommands.push(output);\n } else {\n /** Multi-destination or other command - pass through */\n combinedOutputs.push(output);\n }\n } else {\n /** Other commands - pass through */\n combinedOutputs.push(output);\n }\n } else {\n nonCommandOutputs.push(output);\n combinedOutputs.push(\n Array.isArray(input) ? [output] : { messages: [output] }\n );\n }\n }\n\n /**\n * Handle handoff commands - convert to Send objects for parallel execution\n * when multiple handoffs are requested\n */\n if (handoffCommands.length > 1) {\n /**\n * Multiple parallel handoffs - convert to Send objects.\n * Each Send carries its own state with the appropriate messages.\n * This enables LLM-initiated parallel execution when calling multiple\n * transfer tools simultaneously.\n */\n\n /** Collect all destinations for sibling tracking */\n const allDestinations = handoffCommands.map((cmd) => {\n const goto = cmd.goto;\n return typeof goto === 'string' ? goto : (goto as string[])[0];\n });\n\n const sends = handoffCommands.map((cmd, idx) => {\n const destination = allDestinations[idx];\n /** Get siblings (other destinations, not this one) */\n const siblings = allDestinations.filter((d) => d !== destination);\n\n /** Add siblings to ToolMessage additional_kwargs */\n const update = cmd.update as { messages?: BaseMessage[] } | undefined;\n if (update && update.messages) {\n for (const msg of update.messages) {\n if (msg.getType() === 'tool') {\n (msg as ToolMessage).additional_kwargs.handoff_parallel_siblings =\n siblings;\n }\n }\n }\n\n return new Send(destination, cmd.update);\n });\n\n const parallelCommand = new Command({\n graph: Command.PARENT,\n goto: sends,\n });\n combinedOutputs.push(parallelCommand);\n } else if (handoffCommands.length === 1) {\n /** Single handoff - pass through as-is */\n combinedOutputs.push(handoffCommands[0]);\n }\n\n if (parentCommand) {\n combinedOutputs.push(parentCommand);\n }\n\n return combinedOutputs as T;\n }\n\n private isSendInput(input: unknown): input is { lg_tool_call: ToolCall } {\n return (\n typeof input === 'object' && input != null && 'lg_tool_call' in input\n );\n }\n\n private isMessagesState(\n input: unknown\n ): input is { messages: BaseMessage[] } {\n return (\n typeof input === 'object' &&\n input != null &&\n 'messages' in input &&\n Array.isArray((input as { messages: unknown }).messages) &&\n (input as { messages: unknown[] }).messages.every(isBaseMessage)\n );\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const messages = Array.isArray(state) ? state : state.messages;\n const message = messages[messages.length - 1] as AIMessage | undefined;\n\n if (\n message &&\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n }\n return END;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAyBA;;AAEG;AACH,SAAS,MAAM,CAAC,KAAc,EAAA;IAC5B,OAAO,KAAK,YAAY,IAAI;AAC9B;AAEA;AACM,MAAO,QAAkB,SAAQ,gBAAsB,CAAA;AACnD,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;IACvB,KAAK,GAAG,KAAK;AACb,IAAA,eAAe;AACf,IAAA,YAAY;AACJ,IAAA,cAAc;;AAEd,IAAA,YAAY;;AAEZ,IAAA,iBAAiB;;AAEjB,IAAA,QAAQ;;IAER,eAAe,GAAY,KAAK;;AAEhC,IAAA,eAAe;;AAEf,IAAA,OAAO;IAEf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C;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;AAEjB,IAAA,OAAO,GAAG;AACZ;;;;"}
|
package/package.json
CHANGED
package/src/messages/prune.ts
CHANGED
|
@@ -293,7 +293,7 @@ export function getMessagesWithinTokenLimit({
|
|
|
293
293
|
|
|
294
294
|
if (assistantIndex === -1) {
|
|
295
295
|
throw new Error(
|
|
296
|
-
'
|
|
296
|
+
'Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.'
|
|
297
297
|
);
|
|
298
298
|
}
|
|
299
299
|
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
// src/specs/thinking-prune.test.ts
|
|
2
|
-
import {
|
|
2
|
+
import {
|
|
3
|
+
HumanMessage,
|
|
4
|
+
AIMessage,
|
|
5
|
+
SystemMessage,
|
|
6
|
+
BaseMessage,
|
|
7
|
+
ToolMessage,
|
|
8
|
+
} from '@langchain/core/messages';
|
|
3
9
|
import type * as t from '@/types';
|
|
4
10
|
import { createPruneMessages } from '@/messages/prune';
|
|
5
11
|
|
|
@@ -7,7 +13,10 @@ import { createPruneMessages } from '@/messages/prune';
|
|
|
7
13
|
const createTestTokenCounter = (): t.TokenCounter => {
|
|
8
14
|
return (message: BaseMessage): number => {
|
|
9
15
|
// Use type assertion to help TypeScript understand the type
|
|
10
|
-
const content = message.content as
|
|
16
|
+
const content = message.content as
|
|
17
|
+
| string
|
|
18
|
+
| Array<t.MessageContentComplex | string>
|
|
19
|
+
| undefined;
|
|
11
20
|
|
|
12
21
|
// Handle string content
|
|
13
22
|
if (typeof content === 'string') {
|
|
@@ -61,7 +70,8 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
61
70
|
content: [
|
|
62
71
|
{
|
|
63
72
|
type: 'thinking',
|
|
64
|
-
thinking:
|
|
73
|
+
thinking:
|
|
74
|
+
'The user is asking me to read a file located at `/home/danny/LibreChat/gistfile1.txt` in chunks of 200 lines at a time, mentioning that the file has 5000 lines total. They want me to continue reading through the entire file without stopping.\n\nI\'ll need to use the text editor tool to view the file in chunks of 200 lines each. Since the file has 5000 lines, I\'ll need to view it in 25 chunks (5000 ÷ 200 = 25).\n\nI\'ll need to make multiple calls to the text editor with the `view` command, specifying different line ranges for each call.\n\nLet me plan out the approach:\n1. Start with lines 1-200\n2. Then 201-400\n3. Then 401-600\n4. And so on until I reach 4801-5000\n\nFor each call, I\'ll use the `view` command with the specific line range in the `view_range` parameter. I\'ll continue until I\'ve shown all 5000 lines as requested.',
|
|
65
75
|
},
|
|
66
76
|
{
|
|
67
77
|
type: 'text',
|
|
@@ -71,7 +81,8 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
71
81
|
type: 'tool_use',
|
|
72
82
|
id: 'toolu_01YApWuFsEQCuBFDgYXmcmeZ',
|
|
73
83
|
name: 'text_editor_mcp_textEditor',
|
|
74
|
-
input:
|
|
84
|
+
input:
|
|
85
|
+
'{"command": "view", "path": "/home/danny/LibreChat/gistfile1.txt", "description": "Viewing lines 1-200 of the file", "view_range": [1,200]}',
|
|
75
86
|
},
|
|
76
87
|
],
|
|
77
88
|
});
|
|
@@ -97,7 +108,8 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
97
108
|
type: 'tool_use',
|
|
98
109
|
id: 'toolu_01VnyMQ4CvEd6zLDxxtTd6d4',
|
|
99
110
|
name: 'text_editor_mcp_textEditor',
|
|
100
|
-
input:
|
|
111
|
+
input:
|
|
112
|
+
'{"command": "view", "path": "/home/danny/LibreChat/gistfile1.txt", "description": "Viewing lines 201-400 of the file", "view_range": [201,400]}',
|
|
101
113
|
},
|
|
102
114
|
],
|
|
103
115
|
});
|
|
@@ -123,7 +135,8 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
123
135
|
type: 'tool_use',
|
|
124
136
|
id: 'toolu_01TZKs4nnBc58BYXKz1Mw4fp',
|
|
125
137
|
name: 'text_editor_mcp_textEditor',
|
|
126
|
-
input:
|
|
138
|
+
input:
|
|
139
|
+
'{"command": "view", "path": "/home/danny/LibreChat/gistfile1.txt", "description": "Viewing lines 401-600 of the file", "view_range": [401,600]}',
|
|
127
140
|
},
|
|
128
141
|
],
|
|
129
142
|
});
|
|
@@ -149,7 +162,8 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
149
162
|
type: 'tool_use',
|
|
150
163
|
id: 'toolu_01TZgBacNxjx1QNUpJg9hca5',
|
|
151
164
|
name: 'text_editor_mcp_textEditor',
|
|
152
|
-
input:
|
|
165
|
+
input:
|
|
166
|
+
'{"command": "view", "path": "/home/danny/LibreChat/gistfile1.txt", "description": "Viewing lines 601-800 of the file", "view_range": [601,800]}',
|
|
153
167
|
},
|
|
154
168
|
],
|
|
155
169
|
});
|
|
@@ -180,7 +194,7 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
180
194
|
// Create indexTokenCountMap based on the example provided
|
|
181
195
|
const indexTokenCountMap = {
|
|
182
196
|
'0': 617, // userMessage
|
|
183
|
-
'1': 52,
|
|
197
|
+
'1': 52, // assistantMessageWithThinking
|
|
184
198
|
'2': 4995, // toolResponseMessage1
|
|
185
199
|
'3': 307, // assistantMessage2
|
|
186
200
|
'4': 9359, // toolResponseMessage2
|
|
@@ -218,22 +232,34 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
218
232
|
expect(result.context.length).toBeGreaterThan(0);
|
|
219
233
|
|
|
220
234
|
// Find the first assistant message in the pruned context
|
|
221
|
-
const firstAssistantIndex = result.context.findIndex(
|
|
235
|
+
const firstAssistantIndex = result.context.findIndex(
|
|
236
|
+
(msg) => msg.getType() === 'ai'
|
|
237
|
+
);
|
|
222
238
|
expect(firstAssistantIndex).toBe(0);
|
|
223
239
|
|
|
224
240
|
const firstAssistantMsg = result.context[firstAssistantIndex];
|
|
225
241
|
expect(Array.isArray(firstAssistantMsg.content)).toBe(true);
|
|
226
242
|
|
|
227
243
|
// Verify that the first assistant message has a thinking block
|
|
228
|
-
const hasThinkingBlock = (
|
|
229
|
-
|
|
244
|
+
const hasThinkingBlock = (
|
|
245
|
+
firstAssistantMsg.content as t.MessageContentComplex[]
|
|
246
|
+
).some(
|
|
247
|
+
(item: t.MessageContentComplex) =>
|
|
248
|
+
typeof item === 'object' && item.type === 'thinking'
|
|
249
|
+
);
|
|
230
250
|
expect(hasThinkingBlock).toBe(true);
|
|
231
251
|
|
|
232
252
|
// Verify that the thinking block is from the original assistant message
|
|
233
|
-
const thinkingBlock = (
|
|
234
|
-
|
|
253
|
+
const thinkingBlock = (
|
|
254
|
+
firstAssistantMsg.content as t.MessageContentComplex[]
|
|
255
|
+
).find(
|
|
256
|
+
(item: t.MessageContentComplex) =>
|
|
257
|
+
typeof item === 'object' && item.type === 'thinking'
|
|
258
|
+
);
|
|
235
259
|
expect(thinkingBlock).toBeDefined();
|
|
236
|
-
expect((thinkingBlock as t.ThinkingContentText).thinking).toContain(
|
|
260
|
+
expect((thinkingBlock as t.ThinkingContentText).thinking).toContain(
|
|
261
|
+
'The user is asking me to read a file'
|
|
262
|
+
);
|
|
237
263
|
});
|
|
238
264
|
|
|
239
265
|
it('should handle token recalculation when inserting thinking blocks', () => {
|
|
@@ -451,35 +477,49 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
451
477
|
const result = pruneMessages({ messages });
|
|
452
478
|
|
|
453
479
|
// Find assistant message with tool call and its corresponding tool message in the pruned context
|
|
454
|
-
const assistantIndex = result.context.findIndex(
|
|
455
|
-
msg
|
|
456
|
-
|
|
457
|
-
|
|
480
|
+
const assistantIndex = result.context.findIndex(
|
|
481
|
+
(msg) =>
|
|
482
|
+
msg.getType() === 'ai' &&
|
|
483
|
+
Array.isArray(msg.content) &&
|
|
484
|
+
msg.content.some(
|
|
485
|
+
(item) =>
|
|
486
|
+
typeof item === 'object' &&
|
|
487
|
+
item.type === 'tool_use' &&
|
|
488
|
+
item.id === 'tool123'
|
|
489
|
+
)
|
|
458
490
|
);
|
|
459
491
|
|
|
460
492
|
// If the assistant message with tool call is in the context, its corresponding tool message should also be there
|
|
461
493
|
if (assistantIndex !== -1) {
|
|
462
|
-
const toolIndex = result.context.findIndex(
|
|
463
|
-
msg
|
|
464
|
-
|
|
465
|
-
|
|
494
|
+
const toolIndex = result.context.findIndex(
|
|
495
|
+
(msg) =>
|
|
496
|
+
msg.getType() === 'tool' &&
|
|
497
|
+
'tool_call_id' in msg &&
|
|
498
|
+
msg.tool_call_id === 'tool123'
|
|
466
499
|
);
|
|
467
500
|
|
|
468
501
|
expect(toolIndex).not.toBe(-1);
|
|
469
502
|
}
|
|
470
503
|
|
|
471
504
|
// If the tool message is in the context, its corresponding assistant message should also be there
|
|
472
|
-
const toolIndex = result.context.findIndex(
|
|
473
|
-
msg
|
|
474
|
-
|
|
475
|
-
|
|
505
|
+
const toolIndex = result.context.findIndex(
|
|
506
|
+
(msg) =>
|
|
507
|
+
msg.getType() === 'tool' &&
|
|
508
|
+
'tool_call_id' in msg &&
|
|
509
|
+
msg.tool_call_id === 'tool123'
|
|
476
510
|
);
|
|
477
511
|
|
|
478
512
|
if (toolIndex !== -1) {
|
|
479
|
-
const assistantWithToolIndex = result.context.findIndex(
|
|
480
|
-
msg
|
|
481
|
-
|
|
482
|
-
|
|
513
|
+
const assistantWithToolIndex = result.context.findIndex(
|
|
514
|
+
(msg) =>
|
|
515
|
+
msg.getType() === 'ai' &&
|
|
516
|
+
Array.isArray(msg.content) &&
|
|
517
|
+
msg.content.some(
|
|
518
|
+
(item) =>
|
|
519
|
+
typeof item === 'object' &&
|
|
520
|
+
item.type === 'tool_use' &&
|
|
521
|
+
item.id === 'tool123'
|
|
522
|
+
)
|
|
483
523
|
);
|
|
484
524
|
|
|
485
525
|
expect(assistantWithToolIndex).not.toBe(-1);
|
|
@@ -544,7 +584,9 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
544
584
|
// Calculate token counts for each message
|
|
545
585
|
const indexTokenCountMapWithoutSystem: Record<string, number> = {};
|
|
546
586
|
for (let i = 0; i < messagesWithoutSystem.length; i++) {
|
|
547
|
-
indexTokenCountMapWithoutSystem[i] = tokenCounter(
|
|
587
|
+
indexTokenCountMapWithoutSystem[i] = tokenCounter(
|
|
588
|
+
messagesWithoutSystem[i]
|
|
589
|
+
);
|
|
548
590
|
}
|
|
549
591
|
|
|
550
592
|
// Create pruneMessages function with thinking mode enabled
|
|
@@ -557,24 +599,33 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
557
599
|
});
|
|
558
600
|
|
|
559
601
|
// Prune messages
|
|
560
|
-
const resultWithoutSystem = pruneMessagesWithoutSystem({
|
|
602
|
+
const resultWithoutSystem = pruneMessagesWithoutSystem({
|
|
603
|
+
messages: messagesWithoutSystem,
|
|
604
|
+
});
|
|
561
605
|
|
|
562
606
|
// Verify that the pruned context contains at least one message
|
|
563
607
|
expect(resultWithoutSystem.context.length).toBeGreaterThan(0);
|
|
564
608
|
|
|
565
609
|
// Find all assistant messages in the latest sequence (after the last human message)
|
|
566
|
-
const lastHumanIndex = resultWithoutSystem.context
|
|
567
|
-
|
|
568
|
-
.
|
|
610
|
+
const lastHumanIndex = resultWithoutSystem.context
|
|
611
|
+
.map((msg) => msg.getType())
|
|
612
|
+
.lastIndexOf('human');
|
|
613
|
+
const assistantMessagesAfterLastHuman = resultWithoutSystem.context
|
|
614
|
+
.slice(lastHumanIndex + 1)
|
|
615
|
+
.filter((msg) => msg.getType() === 'ai');
|
|
569
616
|
|
|
570
617
|
// Verify that at least one assistant message exists in the latest sequence
|
|
571
618
|
expect(assistantMessagesAfterLastHuman.length).toBeGreaterThan(0);
|
|
572
619
|
|
|
573
620
|
// Verify that at least one of these assistant messages has a thinking block
|
|
574
|
-
const hasThinkingBlock = assistantMessagesAfterLastHuman.some(msg => {
|
|
621
|
+
const hasThinkingBlock = assistantMessagesAfterLastHuman.some((msg) => {
|
|
575
622
|
const content = msg.content as t.MessageContentComplex[];
|
|
576
|
-
return
|
|
577
|
-
|
|
623
|
+
return (
|
|
624
|
+
Array.isArray(content) &&
|
|
625
|
+
content.some(
|
|
626
|
+
(item) => typeof item === 'object' && item.type === 'thinking'
|
|
627
|
+
)
|
|
628
|
+
);
|
|
578
629
|
});
|
|
579
630
|
expect(hasThinkingBlock).toBe(true);
|
|
580
631
|
|
|
@@ -604,26 +655,36 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
604
655
|
});
|
|
605
656
|
|
|
606
657
|
// Prune messages
|
|
607
|
-
const resultWithSystem = pruneMessagesWithSystem({
|
|
658
|
+
const resultWithSystem = pruneMessagesWithSystem({
|
|
659
|
+
messages: messagesWithSystem,
|
|
660
|
+
});
|
|
608
661
|
|
|
609
662
|
// Verify that the system message remains first
|
|
610
663
|
expect(resultWithSystem.context.length).toBeGreaterThan(1);
|
|
611
664
|
expect(resultWithSystem.context[0].getType()).toBe('system');
|
|
612
665
|
|
|
613
666
|
// Find all assistant messages in the latest sequence (after the last human message)
|
|
614
|
-
const lastHumanIndexWithSystem = resultWithSystem.context
|
|
615
|
-
|
|
616
|
-
.
|
|
667
|
+
const lastHumanIndexWithSystem = resultWithSystem.context
|
|
668
|
+
.map((msg) => msg.getType())
|
|
669
|
+
.lastIndexOf('human');
|
|
670
|
+
const assistantMessagesAfterLastHumanWithSystem = resultWithSystem.context
|
|
671
|
+
.slice(lastHumanIndexWithSystem + 1)
|
|
672
|
+
.filter((msg) => msg.getType() === 'ai');
|
|
617
673
|
|
|
618
674
|
// Verify that at least one assistant message exists in the latest sequence
|
|
619
675
|
expect(assistantMessagesAfterLastHumanWithSystem.length).toBeGreaterThan(0);
|
|
620
676
|
|
|
621
677
|
// Verify that at least one of these assistant messages has a thinking block
|
|
622
|
-
const hasThinkingBlockWithSystem =
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
678
|
+
const hasThinkingBlockWithSystem =
|
|
679
|
+
assistantMessagesAfterLastHumanWithSystem.some((msg) => {
|
|
680
|
+
const content = msg.content as t.MessageContentComplex[];
|
|
681
|
+
return (
|
|
682
|
+
Array.isArray(content) &&
|
|
683
|
+
content.some(
|
|
684
|
+
(item) => typeof item === 'object' && item.type === 'thinking'
|
|
685
|
+
)
|
|
686
|
+
);
|
|
687
|
+
});
|
|
627
688
|
expect(hasThinkingBlockWithSystem).toBe(true);
|
|
628
689
|
});
|
|
629
690
|
|
|
@@ -686,18 +747,78 @@ describe('Prune Messages with Thinking Mode Tests', () => {
|
|
|
686
747
|
const result = pruneMessages({ messages });
|
|
687
748
|
|
|
688
749
|
// Find the first assistant message in the pruned context
|
|
689
|
-
const firstAssistantIndex = result.context.findIndex(
|
|
750
|
+
const firstAssistantIndex = result.context.findIndex(
|
|
751
|
+
(msg) => msg.getType() === 'ai'
|
|
752
|
+
);
|
|
690
753
|
expect(firstAssistantIndex).not.toBe(-1);
|
|
691
754
|
|
|
692
755
|
const firstAssistantMsg = result.context[firstAssistantIndex];
|
|
693
756
|
expect(Array.isArray(firstAssistantMsg.content)).toBe(true);
|
|
694
757
|
|
|
695
758
|
// Verify that the first assistant message has a thinking block
|
|
696
|
-
const thinkingBlock = (
|
|
697
|
-
|
|
759
|
+
const thinkingBlock = (
|
|
760
|
+
firstAssistantMsg.content as t.MessageContentComplex[]
|
|
761
|
+
).find((item) => typeof item === 'object' && item.type === 'thinking');
|
|
698
762
|
expect(thinkingBlock).toBeDefined();
|
|
699
763
|
|
|
700
764
|
// Verify that it's the newer thinking block
|
|
701
|
-
expect((thinkingBlock as t.ThinkingContentText).thinking).toContain(
|
|
765
|
+
expect((thinkingBlock as t.ThinkingContentText).thinking).toContain(
|
|
766
|
+
'newer thinking block'
|
|
767
|
+
);
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
it('should throw descriptive error when aggressive pruning removes all AI messages', () => {
|
|
771
|
+
const tokenCounter = createTestTokenCounter();
|
|
772
|
+
|
|
773
|
+
const assistantMessageWithThinking = new AIMessage({
|
|
774
|
+
content: [
|
|
775
|
+
{
|
|
776
|
+
type: 'thinking',
|
|
777
|
+
thinking: 'This is a thinking block that will be pruned',
|
|
778
|
+
},
|
|
779
|
+
{
|
|
780
|
+
type: 'text',
|
|
781
|
+
text: 'Response with thinking',
|
|
782
|
+
},
|
|
783
|
+
{
|
|
784
|
+
type: 'tool_use',
|
|
785
|
+
id: 'tool123',
|
|
786
|
+
name: 'large_tool',
|
|
787
|
+
input: '{"query": "test"}',
|
|
788
|
+
},
|
|
789
|
+
],
|
|
790
|
+
});
|
|
791
|
+
|
|
792
|
+
const largeToolResponse = new ToolMessage({
|
|
793
|
+
content: 'A'.repeat(10000),
|
|
794
|
+
tool_call_id: 'tool123',
|
|
795
|
+
name: 'large_tool',
|
|
796
|
+
});
|
|
797
|
+
|
|
798
|
+
const messages = [
|
|
799
|
+
new SystemMessage('System instruction'),
|
|
800
|
+
new HumanMessage('Hello'),
|
|
801
|
+
assistantMessageWithThinking,
|
|
802
|
+
largeToolResponse,
|
|
803
|
+
];
|
|
804
|
+
|
|
805
|
+
const indexTokenCountMap: Record<string, number> = {
|
|
806
|
+
'0': 17,
|
|
807
|
+
'1': 5,
|
|
808
|
+
'2': 100,
|
|
809
|
+
'3': 10000,
|
|
810
|
+
};
|
|
811
|
+
|
|
812
|
+
const pruneMessages = createPruneMessages({
|
|
813
|
+
maxTokens: 50,
|
|
814
|
+
startIndex: 0,
|
|
815
|
+
tokenCounter,
|
|
816
|
+
indexTokenCountMap: { ...indexTokenCountMap },
|
|
817
|
+
thinkingEnabled: true,
|
|
818
|
+
});
|
|
819
|
+
|
|
820
|
+
expect(() => pruneMessages({ messages })).toThrow(
|
|
821
|
+
/Context window exceeded/
|
|
822
|
+
);
|
|
702
823
|
});
|
|
703
824
|
});
|
package/src/tools/ToolNode.ts
CHANGED
|
@@ -585,17 +585,16 @@ export function toolsCondition<T extends string>(
|
|
|
585
585
|
toolNode: T,
|
|
586
586
|
invokedToolIds?: Set<string>
|
|
587
587
|
): T | typeof END {
|
|
588
|
-
const
|
|
589
|
-
|
|
590
|
-
: state.messages[state.messages.length - 1];
|
|
588
|
+
const messages = Array.isArray(state) ? state : state.messages;
|
|
589
|
+
const message = messages[messages.length - 1] as AIMessage | undefined;
|
|
591
590
|
|
|
592
591
|
if (
|
|
592
|
+
message &&
|
|
593
593
|
'tool_calls' in message &&
|
|
594
594
|
(message.tool_calls?.length ?? 0) > 0 &&
|
|
595
595
|
!areToolCallsInvoked(message, invokedToolIds)
|
|
596
596
|
) {
|
|
597
597
|
return toolNode;
|
|
598
|
-
} else {
|
|
599
|
-
return END;
|
|
600
598
|
}
|
|
599
|
+
return END;
|
|
601
600
|
}
|