@librechat/agents 2.3.2 → 2.3.4
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/core.cjs +3 -3
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +36 -16
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/stream.cjs +6 -5
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/messages/core.mjs +3 -3
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +36 -16
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/stream.mjs +6 -5
- package/dist/esm/stream.mjs.map +1 -1
- package/package.json +1 -1
- package/src/messages/core.ts +5 -5
- package/src/messages/prune.ts +38 -16
- package/src/specs/token-distribution-edge-case.test.ts +296 -0
- package/src/stream.ts +9 -5
|
@@ -56,11 +56,11 @@ function reduceBlocks(blocks) {
|
|
|
56
56
|
// Merge consecutive 'reasoning_content'
|
|
57
57
|
if (block.type === 'reasoning_content' && lastBlock.type === 'reasoning_content') {
|
|
58
58
|
// append text if exists
|
|
59
|
-
if (block.reasoningText.text) {
|
|
60
|
-
lastBlock.reasoningText.text = (lastBlock.reasoningText
|
|
59
|
+
if (block.reasoningText?.text != null && block.reasoningText.text) {
|
|
60
|
+
lastBlock.reasoningText.text = (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;
|
|
61
61
|
}
|
|
62
62
|
// preserve the signature if exists
|
|
63
|
-
if (block.reasoningText.signature) {
|
|
63
|
+
if (block.reasoningText?.signature != null && block.reasoningText.signature) {
|
|
64
64
|
lastBlock.reasoningText.signature = block.reasoningText.signature;
|
|
65
65
|
}
|
|
66
66
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.cjs","sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { Providers } from '@/common';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [..._allowedTypes, 'thinking'],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content\n}: {\n provider: Providers, messageType: string, content: t.ExtendedMessageContent[]\n}): t.ExtendedMessageContent[] => {\n const allowedTypes = allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock = t.BedrockReasoningContentText | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1];\n\n // Merge consecutive 'reasoning_content'\n if (block.type === 'reasoning_content' && lastBlock.type === 'reasoning_content') {\n // append text if exists\n if (block.reasoningText.text) {\n lastBlock.reasoningText.text = (lastBlock.reasoningText.text || '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (block.reasoningText.signature) {\n lastBlock.reasoningText.signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nexport function modifyDeltaProperties(provider: Providers, obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = reduceBlocks(obj.content as ContentBlock[]);\n }\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent({ provider, messageType, content: obj.content });\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent({ provider, messageType, content: obj.lc_kwargs.content });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":["HumanMessage","Providers","AIMessage","messages","ToolMessage","AIMessageChunk"],"mappings":";;;;;AAAA;AAMM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,EAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CA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C,IAAI,CAAC,GAAG,GAAG,CAAC,OAAO,CAAC;AACtC,QAAA,GAAG,CAAC,OAAO,GAAG,kEAAkE;QAChF,iBAAiB,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC;AACjD,KAAC,CAAC;;AAGF,IAAA,IAAI,iBAAiB,CAAC,MAAM,GAAG,CAAC,EAAE;AAChC,QAAAD,UAAQ,CAAC,IAAI,CAAC,IAAIH,qBAAY,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;;AAEnE;AAEgB,SAAA,aAAa,CAAI,KAAU,EAAE,SAAgC,EAAA;AAC3E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"core.cjs","sources":["../../../src/messages/core.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { Providers } from '@/common';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst _allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\nconst allowedTypesByProvider: Record<string, string[]> = {\n default: _allowedTypes,\n [Providers.ANTHROPIC]: [..._allowedTypes, 'thinking'],\n [Providers.BEDROCK]: [..._allowedTypes, 'reasoning_content'],\n [Providers.OPENAI]: _allowedTypes,\n};\n\nconst modifyContent = ({\n provider,\n messageType,\n content\n}: {\n provider: Providers, messageType: string, content: t.ExtendedMessageContent[]\n}): t.ExtendedMessageContent[] => {\n const allowedTypes = allowedTypesByProvider[provider] ?? allowedTypesByProvider.default;\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\ntype ContentBlock = Partial<t.BedrockReasoningContentText> | t.MessageDeltaUpdate;\n\nfunction reduceBlocks(blocks: ContentBlock[]): ContentBlock[] {\n const reduced: ContentBlock[] = [];\n\n for (const block of blocks) {\n const lastBlock = reduced[reduced.length - 1];\n\n // Merge consecutive 'reasoning_content'\n if (block.type === 'reasoning_content' && lastBlock.type === 'reasoning_content') {\n // append text if exists\n if (block.reasoningText?.text != null && block.reasoningText.text) {\n (lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']).text = (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;\n }\n // preserve the signature if exists\n if (block.reasoningText?.signature != null && block.reasoningText.signature) {\n (lastBlock.reasoningText as t.BedrockReasoningContentText['reasoningText']).signature = block.reasoningText.signature;\n }\n }\n // Merge consecutive 'text'\n else if (block.type === 'text' && lastBlock.type === 'text') {\n lastBlock.text += block.text;\n }\n // add a new block as it's a different type or first element\n else {\n // deep copy to avoid mutation of original\n reduced.push(JSON.parse(JSON.stringify(block)));\n }\n }\n\n return reduced;\n}\n\nexport function modifyDeltaProperties(provider: Providers, obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (provider === Providers.BEDROCK && Array.isArray(obj.content)) {\n obj.content = reduceBlocks(obj.content as ContentBlock[]);\n }\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent({ provider, messageType, content: obj.content });\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent({ provider, messageType, content: obj.lc_kwargs.content });\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":["HumanMessage","Providers","AIMessage","messages","ToolMessage","AIMessageChunk"],"mappings":";;;;;AAAA;AAMM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,EAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CAAC,CAAC;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO;CACvB;AAEC,IAAA,OAAO,IAAIA,qBAAY,CAAC,OAAO,CAAC;AAClC;AAEA,MAAM,aAAa,GAAG,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,aAAa,CAAC;AACtE,MAAM,sBAAsB,GAA6B;AACvD,IAAA,OAAO,EAAE,aAAa;IACtB,CAACC,eAAS,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IAAIH,qBAAY,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;;AAEnE;AAEgB,SAAA,aAAa,CAAI,KAAU,EAAE,SAAgC,EAAA;AAC3E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC;;;IAGZ,OAAO,EAAE;AACX;;;;;;;;;;"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var stream = require('@langchain/core/utils/stream');
|
|
4
3
|
var messages = require('@langchain/core/messages');
|
|
5
4
|
var _enum = require('../common/enum.cjs');
|
|
6
5
|
|
|
@@ -8,6 +7,16 @@ function isIndexInContext(arrayA, arrayB, targetIndex) {
|
|
|
8
7
|
const startingIndexInA = arrayA.length - arrayB.length;
|
|
9
8
|
return targetIndex >= startingIndexInA;
|
|
10
9
|
}
|
|
10
|
+
function addThinkingBlock(message, thinkingBlock) {
|
|
11
|
+
const content = Array.isArray(message.content)
|
|
12
|
+
? message.content
|
|
13
|
+
: [{
|
|
14
|
+
type: _enum.ContentTypes.TEXT,
|
|
15
|
+
text: message.content,
|
|
16
|
+
}];
|
|
17
|
+
content.unshift(thinkingBlock);
|
|
18
|
+
return content;
|
|
19
|
+
}
|
|
11
20
|
/**
|
|
12
21
|
* Calculates the total tokens from a single usage object
|
|
13
22
|
*
|
|
@@ -145,13 +154,7 @@ tokenCounter, }) {
|
|
|
145
154
|
thinkingStartIndex = originalLength - 1 - assistantIndex;
|
|
146
155
|
const thinkingTokenCount = tokenCounter(new messages.AIMessage({ content: [thinkingBlock] }));
|
|
147
156
|
const newRemainingCount = remainingContextTokens - thinkingTokenCount;
|
|
148
|
-
const content =
|
|
149
|
-
? context[assistantIndex].content
|
|
150
|
-
: [{
|
|
151
|
-
type: _enum.ContentTypes.TEXT,
|
|
152
|
-
text: context[assistantIndex].content,
|
|
153
|
-
}];
|
|
154
|
-
content.unshift(thinkingBlock);
|
|
157
|
+
const content = addThinkingBlock(context[assistantIndex], thinkingBlock);
|
|
155
158
|
context[assistantIndex].content = content;
|
|
156
159
|
if (newRemainingCount > 0) {
|
|
157
160
|
result.context = context.reverse();
|
|
@@ -192,10 +195,8 @@ tokenCounter, }) {
|
|
|
192
195
|
}
|
|
193
196
|
}
|
|
194
197
|
if (firstMessageType === 'ai') {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
tool_calls: stream.concat(firstMessage.tool_calls, thinkingMessage.tool_calls),
|
|
198
|
-
});
|
|
198
|
+
const content = addThinkingBlock(firstMessage, thinkingBlock);
|
|
199
|
+
newContext[newContext.length - 1].content = content;
|
|
199
200
|
}
|
|
200
201
|
else {
|
|
201
202
|
newContext.push(thinkingMessage);
|
|
@@ -213,6 +214,7 @@ function checkValidNumber(value) {
|
|
|
213
214
|
function createPruneMessages(factoryParams) {
|
|
214
215
|
const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };
|
|
215
216
|
let lastTurnStartIndex = factoryParams.startIndex;
|
|
217
|
+
let lastCutOffIndex = 0;
|
|
216
218
|
let totalTokens = (Object.values(indexTokenCountMap)).reduce((a, b) => a + b, 0);
|
|
217
219
|
return function pruneMessages(params) {
|
|
218
220
|
let currentUsage;
|
|
@@ -235,15 +237,32 @@ function createPruneMessages(factoryParams) {
|
|
|
235
237
|
totalTokens += indexTokenCountMap[i];
|
|
236
238
|
}
|
|
237
239
|
}
|
|
238
|
-
// If `currentUsage` is defined, we need to distribute the current total
|
|
239
|
-
// for all message index keys before `lastTurnStartIndex`, as it has the most accurate count for those messages.
|
|
240
|
+
// If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,
|
|
240
241
|
// We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,
|
|
241
242
|
// relative the manually counted tokens in `indexTokenCountMap`.
|
|
243
|
+
// EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.
|
|
242
244
|
if (currentUsage) {
|
|
243
|
-
|
|
245
|
+
// Calculate the sum of tokens only for indices at or after lastCutOffIndex
|
|
246
|
+
const totalIndexTokens = Object.entries(indexTokenCountMap).reduce((sum, [key, value]) => {
|
|
247
|
+
// Convert string key to number and check if it's >= lastCutOffIndex
|
|
248
|
+
const numericKey = Number(key);
|
|
249
|
+
if (numericKey === 0 && params.messages[0].getType() === 'system') {
|
|
250
|
+
return sum + value;
|
|
251
|
+
}
|
|
252
|
+
return numericKey >= lastCutOffIndex ? sum + value : sum;
|
|
253
|
+
}, 0);
|
|
254
|
+
// Calculate ratio based only on messages that remain in the context
|
|
244
255
|
const ratio = currentUsage.total_tokens / totalIndexTokens;
|
|
256
|
+
// Apply the ratio adjustment only to messages at or after lastCutOffIndex
|
|
245
257
|
for (const key in indexTokenCountMap) {
|
|
246
|
-
|
|
258
|
+
const numericKey = Number(key);
|
|
259
|
+
if (numericKey === 0 && params.messages[0].getType() === 'system') {
|
|
260
|
+
indexTokenCountMap[key] = Math.round(indexTokenCountMap[key] * ratio);
|
|
261
|
+
}
|
|
262
|
+
else if (numericKey >= lastCutOffIndex) {
|
|
263
|
+
// Only adjust token counts for messages still in the context
|
|
264
|
+
indexTokenCountMap[key] = Math.round(indexTokenCountMap[key] * ratio);
|
|
265
|
+
}
|
|
247
266
|
}
|
|
248
267
|
}
|
|
249
268
|
lastTurnStartIndex = params.messages.length;
|
|
@@ -258,6 +277,7 @@ function createPruneMessages(factoryParams) {
|
|
|
258
277
|
thinkingEnabled: factoryParams.thinkingEnabled,
|
|
259
278
|
tokenCounter: factoryParams.tokenCounter,
|
|
260
279
|
});
|
|
280
|
+
lastCutOffIndex = Math.max(params.messages.length - context.length, 0);
|
|
261
281
|
return { context, indexTokenCountMap };
|
|
262
282
|
};
|
|
263
283
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prune.cjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import { concat } from '@langchain/core/utils/stream';\nimport { AIMessage, BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport type { ThinkingContentText, MessageContentComplex } from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes } from '@/common';\nexport type PruneMessagesFactoryParams = {\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n}\n\nfunction isIndexInContext(arrayA: BaseMessage[], arrayB: BaseMessage[], targetIndex: number): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\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(usage: Partial<UsageMetadata>): 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\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 /** We may need to use this when recalculating */\n tokenCounter,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n tokenCounter: TokenCounter;\n startType?: string;\n thinkingEnabled?: boolean;\n}): {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n} {\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 = _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount = 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: BaseMessage[] = [];\n\n let thinkingStartIndex = -1;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (messages.length > 0 && currentTokenCount < remainingContextTokens && currentIndex > endIndex) {\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 (thinkingEnabled === true && thinkingEndIndex === -1 && (currentIndex === (originalLength - 1)) && (messageType === 'ai' || messageType === 'tool')) {\n thinkingEndIndex = currentIndex;\n }\n if (thinkingEndIndex > -1 && !thinkingBlock && thinkingStartIndex < 0 && messageType === 'ai' && Array.isArray(poppedMessage.content)) {\n thinkingBlock = (poppedMessage.content.find((content) => content.type === ContentTypes.THINKING)) 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' && messageType !== 'tool')\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (prunedMemory.length === 0 && ((currentTokenCount + tokenCount) <= remainingContextTokens)) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1) {\n continue;\n }\n break;\n }\n }\n\n if (thinkingEndIndex > -1 && context[context.length - 1].getType() === 'tool') {\n startType = 'ai';\n }\n\n if (startType != null && startType && context.length > 0) {\n const requiredTypeIndex = context.findIndex(msg => msg.getType() === startType);\n\n if (requiredTypeIndex > 0) {\n context = context.slice(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 = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (prunedMemory.length === 0 || thinkingEndIndex < 0 || (thinkingStartIndex > -1 && isIndexInContext(_messages, context, thinkingStartIndex))) {\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();\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error('The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.');\n }\n\n if (!thinkingBlock) {\n throw new Error('The payload is malformed. There is a thinking sequence but no thinking block found.');\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('The payload is malformed. There is a thinking sequence but no \"AI\" messages to append thinking blocks to.');\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(new AIMessage({ content: [thinkingBlock] }));\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n\n const content: MessageContentComplex[] = Array.isArray(context[assistantIndex].content)\n ? context[assistantIndex].content as MessageContentComplex[]\n : [{\n type: ContentTypes.TEXT,\n text: context[assistantIndex].content,\n }];\n content.unshift(thinkingBlock);\n context[assistantIndex].content = content;\n if (newRemainingCount > 0) {\n result.context = context.reverse();\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex];\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount = (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 (secondRoundMessages.length > 0 && currentTokenCount < remainingContextTokens && currentIndex > thinkingStartIndex) {\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';\n }\n\n if (startType != null && startType && newContext.length > 0) {\n const requiredTypeIndex = newContext.findIndex(msg => msg.getType() === startType);\n if (requiredTypeIndex > 0) {\n newContext = newContext.slice(requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n newContext[newContext.length - 1] = new AIMessage({\n content: concat(thinkingMessage.content as MessageContentComplex[], newContext[newContext.length - 1].content as MessageContentComplex[]),\n tool_calls: concat(firstMessage.tool_calls, thinkingMessage.tool_calls),\n });\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\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let totalTokens = (Object.values(indexTokenCountMap)).reduce((a, b) => a + b, 0);\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number>;\n } {\n let currentUsage: UsageMetadata | undefined;\n if (params.usageMetadata && (\n checkValidNumber(params.usageMetadata.input_tokens)\n || (\n checkValidNumber(params.usageMetadata.input_token_details)\n && (\n checkValidNumber(params.usageMetadata.input_token_details.cache_creation)\n || checkValidNumber(params.usageMetadata.input_token_details.cache_read)\n )\n )\n ) && checkValidNumber(params.usageMetadata.output_tokens)) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (i === lastTurnStartIndex && indexTokenCountMap[i] === undefined && currentUsage) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n totalTokens += indexTokenCountMap[i];\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokensto our `indexTokenCountMap`,\n // for all message index keys before `lastTurnStartIndex`, as it has the most accurate count for those messages.\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 if (currentUsage) {\n const totalIndexTokens = Object.values(indexTokenCountMap).reduce((a, b) => a + b, 0);\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n for (const key in indexTokenCountMap) {\n indexTokenCountMap[key] = Math.round(indexTokenCountMap[key] * ratio);\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n });\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":["messages","ContentTypes","AIMessage","concat"],"mappings":";;;;;;AAkBA,SAAS,gBAAgB,CAAC,MAAqB,EAAE,MAAqB,EAAE,WAAmB,EAAA;IACzF,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;IACtD,OAAO,WAAW,IAAI,gBAAgB;AACxC;AAEA;;;;;AAKG;AACG,SAAU,oBAAoB,CAAC,KAA6B,EAAA;IAChE,MAAM,eAAe,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC;AACvD,IAAA,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC,mBAAmB,EAAE,cAAc,CAAC,IAAI,CAAC;AAC5E,IAAA,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,mBAAmB,EAAE,UAAU,CAAC,IAAI,CAAC;AAEpE,IAAA,MAAM,gBAAgB,GAAG,eAAe,GAAG,aAAa,GAAG,SAAS;IACpE,MAAM,iBAAiB,GAAG,MAAM,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC;IAE1D,OAAO;AACL,QAAA,YAAY,EAAE,gBAAgB;AAC9B,QAAA,aAAa,EAAE,iBAAiB;QAChC,YAAY,EAAE,gBAAgB,GAAG;KAClC;AACH;AAEA;;;;;;AA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BAAkB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;AACrF,YAAA,MAAM,KAAK,GAAG,YAAY,CAAC,YAAY,GAAG,gBAAgB;AAC1D,YAAA,KAAK,MAAM,GAAG,IAAI,kBAAkB,EAAE;AACpC,gBAAA,kBAAkB,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,kBAAkB,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;;;AAIzE,QAAA,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM;AAC3C,QAAA,IAAI,WAAW,IAAI,aAAa,CAAC,SAAS,EAAE;YAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,EAAE,kBAAkB,EAAE;;AAGzD,QAAA,MAAM,EAAE,OAAO,EAAE,GAAG,2BAA2B,CAAC;YAC9C,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;AACzC,SAAA,CAAC;AAEF,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"prune.cjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import { AIMessage, BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport type { ThinkingContentText, MessageContentComplex } from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes } from '@/common';\nexport type PruneMessagesFactoryParams = {\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n}\n\nfunction isIndexInContext(arrayA: BaseMessage[], arrayB: BaseMessage[], targetIndex: number): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(message: AIMessage, thinkingBlock: ThinkingContentText): MessageContentComplex[] {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? message.content as MessageContentComplex[]\n : [{\n type: ContentTypes.TEXT,\n text: message.content,\n }];\n content.unshift(thinkingBlock);\n return content;\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(usage: Partial<UsageMetadata>): 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\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 /** We may need to use this when recalculating */\n tokenCounter,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n tokenCounter: TokenCounter;\n startType?: string;\n thinkingEnabled?: boolean;\n}): {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n} {\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 = _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount = 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: BaseMessage[] = [];\n\n let thinkingStartIndex = -1;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (messages.length > 0 && currentTokenCount < remainingContextTokens && currentIndex > endIndex) {\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 (thinkingEnabled === true && thinkingEndIndex === -1 && (currentIndex === (originalLength - 1)) && (messageType === 'ai' || messageType === 'tool')) {\n thinkingEndIndex = currentIndex;\n }\n if (thinkingEndIndex > -1 && !thinkingBlock && thinkingStartIndex < 0 && messageType === 'ai' && Array.isArray(poppedMessage.content)) {\n thinkingBlock = (poppedMessage.content.find((content) => content.type === ContentTypes.THINKING)) 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' && messageType !== 'tool')\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (prunedMemory.length === 0 && ((currentTokenCount + tokenCount) <= remainingContextTokens)) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1) {\n continue;\n }\n break;\n }\n }\n\n if (thinkingEndIndex > -1 && context[context.length - 1].getType() === 'tool') {\n startType = 'ai';\n }\n\n if (startType != null && startType && context.length > 0) {\n const requiredTypeIndex = context.findIndex(msg => msg.getType() === startType);\n\n if (requiredTypeIndex > 0) {\n context = context.slice(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 = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (prunedMemory.length === 0 || thinkingEndIndex < 0 || (thinkingStartIndex > -1 && isIndexInContext(_messages, context, thinkingStartIndex))) {\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();\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error('The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.');\n }\n\n if (!thinkingBlock) {\n throw new Error('The payload is malformed. There is a thinking sequence but no thinking block found.');\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('The payload is malformed. There is a thinking sequence but no \"AI\" messages to append thinking blocks to.');\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(new AIMessage({ content: [thinkingBlock] }));\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n\n const content: MessageContentComplex[] = addThinkingBlock(context[assistantIndex] as AIMessage, thinkingBlock);\n context[assistantIndex].content = content;\n if (newRemainingCount > 0) {\n result.context = context.reverse();\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex];\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount = (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 (secondRoundMessages.length > 0 && currentTokenCount < remainingContextTokens && currentIndex > thinkingStartIndex) {\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';\n }\n\n if (startType != null && startType && newContext.length > 0) {\n const requiredTypeIndex = newContext.findIndex(msg => msg.getType() === startType);\n if (requiredTypeIndex > 0) {\n newContext = newContext.slice(requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const content = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1].content = content;\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\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((a, b) => a + b, 0);\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number>;\n } {\n let currentUsage: UsageMetadata | undefined;\n if (params.usageMetadata && (\n checkValidNumber(params.usageMetadata.input_tokens)\n || (\n checkValidNumber(params.usageMetadata.input_token_details)\n && (\n checkValidNumber(params.usageMetadata.input_token_details.cache_creation)\n || checkValidNumber(params.usageMetadata.input_token_details.cache_read)\n )\n )\n ) && checkValidNumber(params.usageMetadata.output_tokens)) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (i === lastTurnStartIndex && indexTokenCountMap[i] === undefined && currentUsage) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n totalTokens += indexTokenCountMap[i];\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 // Calculate the sum of tokens only for indices at or after lastCutOffIndex\n const totalIndexTokens = Object.entries(indexTokenCountMap).reduce((sum, [key, value]) => {\n // Convert string key to number and check if it's >= lastCutOffIndex\n const numericKey = Number(key);\n if (numericKey === 0 && params.messages[0].getType() === 'system') {\n return sum + value;\n }\n return numericKey >= lastCutOffIndex ? sum + value : sum;\n }, 0);\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex\n for (const key in indexTokenCountMap) {\n const numericKey = Number(key);\n if (numericKey === 0 && params.messages[0].getType() === 'system') {\n indexTokenCountMap[key] = Math.round(indexTokenCountMap[key] * ratio);\n } else if (numericKey >= lastCutOffIndex) {\n // Only adjust token counts for messages still in the context\n indexTokenCountMap[key] = Math.round(indexTokenCountMap[key] * ratio);\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n });\n lastCutOffIndex = Math.max(params.messages.length - context.length, 0);\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":["ContentTypes","messages","AIMessage"],"mappings":";;;;;AAiBA,SAAS,gBAAgB,CAAC,MAAqB,EAAE,MAAqB,EAAE,WAAmB,EAAA;IACzF,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;IACtD,OAAO,WAAW,IAAI,gBAAgB;AACxC;AAEA,SAAS,gBAAgB,CAAC,OAAkB,EAAE,aAAkC,EAAA;IAC9E,MAAM,OAAO,GAA4B,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO;UAClE,OAAO,CAAC;AACV,UAAE,CAAC;gBACD,IAAI,EAAEA,kBAAY,CAAC,IAAI;gBACvB,IAAI,EAAE,OAAO,CAAC,OAAO;AACtB,aAAA,CAAC;AACJ,IAAA,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC;AAC9B,IAAA,OAAO,OAAO;AAChB;AAEA;;;;;AAKG;AACG,SAAU,oBAAoB,CAAC,KAA6B,EAAA;IAChE,MAAM,eAAe,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC;AACvD,IAAA,MAAM,aAAa,GAAG,MAAM,CAAC,KAAK,CA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AG,2BAA2B,CAAC;YAC9C,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;AACzC,SAAA,CAAC;AACF,QAAA,eAAe,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;AAEtE,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -102,7 +102,7 @@ class ChatModelStreamHandler {
|
|
|
102
102
|
const content = chunk.additional_kwargs?.[graph.reasoningKey] ?? chunk.content;
|
|
103
103
|
this.handleReasoning(chunk, graph);
|
|
104
104
|
let hasToolCalls = false;
|
|
105
|
-
if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {
|
|
105
|
+
if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')) {
|
|
106
106
|
hasToolCalls = true;
|
|
107
107
|
handleToolCalls(chunk.tool_calls, metadata, graph);
|
|
108
108
|
}
|
|
@@ -188,16 +188,17 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
188
188
|
});
|
|
189
189
|
}
|
|
190
190
|
}
|
|
191
|
-
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.TEXT))) {
|
|
191
|
+
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.TEXT) ?? false)) {
|
|
192
192
|
graph.dispatchMessageDelta(stepId, {
|
|
193
193
|
content,
|
|
194
194
|
});
|
|
195
195
|
}
|
|
196
|
-
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.THINKING)
|
|
196
|
+
else if (content.every((c) => (c.type?.startsWith(_enum.ContentTypes.THINKING) ?? false) ||
|
|
197
|
+
(c.type?.startsWith(_enum.ContentTypes.REASONING_CONTENT) ?? false))) {
|
|
197
198
|
graph.dispatchReasoningDelta(stepId, {
|
|
198
199
|
content: content.map((c) => ({
|
|
199
200
|
type: _enum.ContentTypes.THINK,
|
|
200
|
-
think: c.thinking ?? c.reasoningText
|
|
201
|
+
think: c.thinking ?? c.reasoningText?.text ?? '',
|
|
201
202
|
}))
|
|
202
203
|
});
|
|
203
204
|
}
|
|
@@ -334,7 +335,7 @@ function createContentAggregator() {
|
|
|
334
335
|
}
|
|
335
336
|
else if (partType.startsWith(_enum.ContentTypes.AGENT_UPDATE) &&
|
|
336
337
|
_enum.ContentTypes.AGENT_UPDATE in contentPart &&
|
|
337
|
-
contentPart.agent_update) {
|
|
338
|
+
contentPart.agent_update != null) {
|
|
338
339
|
const update = {
|
|
339
340
|
type: _enum.ContentTypes.AGENT_UPDATE,
|
|
340
341
|
agent_update: contentPart.agent_update,
|
package/dist/cjs/stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ?? chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n this.handleToolCallChunks({ graph, stepKey, toolCallChunks: chunk.tool_call_chunks });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n }\n } else if (content.every((c) => c.type?.startsWith(ContentTypes.TEXT))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (content.every((c) => c.type?.startsWith(ContentTypes.THINKING) || c.type?.startsWith(ContentTypes.REASONING_CONTENT))) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think: (c as t.ThinkingContentText).thinking ?? (c as t.BedrockReasoningContentText).reasoningText.text ?? '',\n }))});\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[],\n }): void => {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n }],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n };\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined;\n if (Array.isArray(chunk.content) && (chunk.content[0]?.type === 'thinking' || chunk.content[0]?.type === 'reasoning_content')) {\n reasoning_content = 'valid';\n }\n if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '' || reasoning_content === 'valid')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (graph.tokenTypeSwitch === 'reasoning' && graph.currentTokenType !== ContentTypes.TEXT && chunk.content != null && chunk.content !== '') {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (chunk.content != null && typeof chunk.content === 'string' && chunk.content.includes('<think>')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (graph.lastToken != null && graph.lastToken.includes('</think>')) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false,\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.AgentUpdate | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_AGENT_UPDATE && (data as t.AgentUpdate | undefined)?.agent_update) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn('No run step or runId found for completed tool call event');\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["nanoid","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK;;;AAGhB,IAAA,OAAO,SAAS;AAClB;AAEO,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC;AACxD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAAgB,GAAG,SAAS,GAAG,SAAS;;IAGjD,MAAM,eAAe,GAAG,KAAK,CAAC,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAC;AACpE,IAAA,IAAI,eAAe,IAAI,IAAI,IAAI,eAAe,EAAE;AAC9C,QAAA,KAAK,CAAC,yBAAyB,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/C,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,EAAE,eAAe,CAAC;AACvD,QAAA,OAAO,eAAe;;AAGxB,IAAA,MAAM,UAAU,GAAG,CAAA,IAAA,EAAOA,aAAM,EAAE,EAAE;IACpC,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,EAAE,UAAU,CAAC;AAClD,IAAA,OAAO,UAAU;AACnB;AAEa,MAAA,eAAe,GAAG,CAAC,SAAsB,EAAE,QAAkC,EAAE,KAAa,KAAU;AACjH,IAAA,IA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gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAGnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ?? chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n this.handleToolCallChunks({ graph, stepKey, toolCallChunks: chunk.tool_call_chunks });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n }\n } else if (content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think: (c as t.ThinkingContentText).thinking ?? (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ?? '',\n }))});\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[],\n }): void => {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n }],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n };\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined;\n if (Array.isArray(chunk.content) && (chunk.content[0]?.type === 'thinking' || chunk.content[0]?.type === 'reasoning_content')) {\n reasoning_content = 'valid';\n }\n if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '' || reasoning_content === 'valid')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (graph.tokenTypeSwitch === 'reasoning' && graph.currentTokenType !== ContentTypes.TEXT && chunk.content != null && chunk.content !== '') {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (chunk.content != null && typeof chunk.content === 'string' && chunk.content.includes('<think>')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (graph.lastToken != null && graph.lastToken.includes('</think>')) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false,\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.AgentUpdate | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_AGENT_UPDATE && (data as t.AgentUpdate | undefined)?.agent_update) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn('No run step or runId found for completed tool call event');\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["nanoid","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK;;;AAGhB,IAAA,OAAO,SAAS;AAClB;A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'reasoning_content') {
|
|
56
56
|
// append text if exists
|
|
57
|
-
if (block.reasoningText.text) {
|
|
58
|
-
lastBlock.reasoningText.text = (lastBlock.reasoningText
|
|
57
|
+
if (block.reasoningText?.text != null && block.reasoningText.text) {
|
|
58
|
+
lastBlock.reasoningText.text = (lastBlock.reasoningText?.text ?? '') + block.reasoningText.text;
|
|
59
59
|
}
|
|
60
60
|
// preserve the signature if exists
|
|
61
|
-
if (block.reasoningText.signature) {
|
|
61
|
+
if (block.reasoningText?.signature != null && block.reasoningText.signature) {
|
|
62
62
|
lastBlock.reasoningText.signature = block.reasoningText.signature;
|
|
63
63
|
}
|
|
64
64
|
}
|