@librechat/agents 3.1.30 → 3.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/messages/prune.cjs +1 -1
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +36 -53
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +5 -7
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +49 -27
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
- package/dist/esm/messages/prune.mjs +1 -1
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +36 -53
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +5 -7
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +49 -27
- package/dist/esm/tools/ToolSearch.mjs.map +1 -1
- package/dist/types/tools/ToolSearch.d.ts +6 -4
- package/dist/types/types/tools.d.ts +4 -0
- package/package.json +1 -1
- package/src/messages/prune.ts +1 -1
- package/src/specs/thinking-prune.test.ts +172 -51
- package/src/tools/ProgrammaticToolCalling.ts +40 -52
- package/src/tools/ToolNode.ts +4 -5
- package/src/tools/ToolSearch.ts +64 -30
- package/src/tools/__tests__/ToolSearch.test.ts +16 -3
- package/src/types/tools.ts +5 -0
|
@@ -192,7 +192,7 @@ function getMessagesWithinTokenLimit({ messages: _messages, maxContextTokens, in
|
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
if (assistantIndex === -1) {
|
|
195
|
-
throw new Error('
|
|
195
|
+
throw new Error('Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.');
|
|
196
196
|
}
|
|
197
197
|
thinkingStartIndex = originalLength - 1 - assistantIndex;
|
|
198
198
|
const thinkingTokenCount = tokenCounter(new messages.AIMessage({ content: [thinkingBlock] }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prune.cjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import {\n AIMessage,\n BaseMessage,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ThinkingContentText,\n MessageContentComplex,\n ReasoningContentText,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes, Providers } from '@/common';\n\nexport type PruneMessagesFactoryParams = {\n provider?: Providers;\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number | undefined>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n};\n\nfunction isIndexInContext(\n arrayA: unknown[],\n arrayB: unknown[],\n targetIndex: number\n): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(\n message: AIMessage,\n thinkingBlock: ThinkingContentText | ReasoningContentText\n): AIMessage {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? (message.content as MessageContentComplex[])\n : [\n {\n type: ContentTypes.TEXT,\n text: message.content,\n },\n ];\n /** Edge case, the message already has the thinking block */\n if (content[0].type === thinkingBlock.type) {\n return message;\n }\n content.unshift(thinkingBlock);\n return new AIMessage({\n ...message,\n content,\n });\n}\n\n/**\n * Calculates the total tokens from a single usage object\n *\n * @param usage The usage metadata object containing token information\n * @returns An object containing the total input and output tokens\n */\nexport function calculateTotalTokens(\n usage: Partial<UsageMetadata>\n): UsageMetadata {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation = Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const totalInputTokens = baseInputTokens + cacheCreation + cacheRead;\n const totalOutputTokens = Number(usage.output_tokens) || 0;\n\n return {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n total_tokens: totalInputTokens + totalOutputTokens,\n };\n}\n\nexport type PruningResult = {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n thinkingStartIndex?: number;\n};\n\n/**\n * Processes an array of messages and returns a context of messages that fit within a specified token limit.\n * It iterates over the messages from newest to oldest, adding them to the context until the token limit is reached.\n *\n * @param options Configuration options for processing messages\n * @returns Object containing the message context, remaining tokens, messages not included, and summary index\n */\nexport function getMessagesWithinTokenLimit({\n messages: _messages,\n maxContextTokens,\n indexTokenCountMap,\n startType: _startType,\n thinkingEnabled,\n tokenCounter,\n thinkingStartIndex: _thinkingStartIndex = -1,\n reasoningType = ContentTypes.THINKING,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n startType?: string | string[];\n thinkingEnabled?: boolean;\n tokenCounter: TokenCounter;\n thinkingStartIndex?: number;\n reasoningType?: ContentTypes.THINKING | ContentTypes.REASONING_CONTENT;\n}): PruningResult {\n // Every reply is primed with <|start|>assistant<|message|>, so we\n // start with 3 tokens for the label after all messages have been counted.\n let currentTokenCount = 3;\n const instructions =\n _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount =\n instructions != null ? (indexTokenCountMap[0] ?? 0) : 0;\n const initialContextTokens = maxContextTokens - instructionsTokenCount;\n let remainingContextTokens = initialContextTokens;\n let startType = _startType;\n const originalLength = _messages.length;\n const messages = [..._messages];\n /**\n * IMPORTANT: this context array gets reversed at the end, since the latest messages get pushed first.\n *\n * This may be confusing to read, but it is done to ensure the context is in the correct order for the model.\n * */\n let context: Array<BaseMessage | undefined> = [];\n\n let thinkingStartIndex = _thinkingStartIndex;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | ReasoningContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (_thinkingStartIndex > -1) {\n const thinkingMessageContent = messages[_thinkingStartIndex]?.content;\n if (Array.isArray(thinkingMessageContent)) {\n thinkingBlock = thinkingMessageContent.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n }\n }\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (\n messages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > endIndex\n ) {\n currentIndex--;\n if (messages.length === 1 && instructions) {\n break;\n }\n const poppedMessage = messages.pop();\n if (!poppedMessage) continue;\n const messageType = poppedMessage.getType();\n if (\n thinkingEnabled === true &&\n thinkingEndIndex === -1 &&\n currentIndex === originalLength - 1 &&\n (messageType === 'ai' || messageType === 'tool')\n ) {\n thinkingEndIndex = currentIndex;\n }\n if (\n thinkingEndIndex > -1 &&\n !thinkingBlock &&\n thinkingStartIndex < 0 &&\n messageType === 'ai' &&\n Array.isArray(poppedMessage.content)\n ) {\n thinkingBlock = poppedMessage.content.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n thinkingStartIndex = thinkingBlock != null ? currentIndex : -1;\n }\n /** False start, the latest message was not part of a multi-assistant/tool sequence of messages */\n if (\n thinkingEndIndex > -1 &&\n currentIndex === thinkingEndIndex - 1 &&\n messageType !== 'ai' &&\n messageType !== 'tool'\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (\n prunedMemory.length === 0 &&\n currentTokenCount + tokenCount <= remainingContextTokens\n ) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n continue;\n }\n break;\n }\n }\n\n if (context[context.length - 1]?.getType() === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && context.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = context.length - 1; i >= 0; i--) {\n const currentType = context[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n context = context.slice(0, requiredTypeIndex);\n }\n }\n }\n\n if (instructions && originalLength > 0) {\n context.push(_messages[0] as BaseMessage);\n messages.shift();\n }\n\n remainingContextTokens -= currentTokenCount;\n const result: PruningResult = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (thinkingStartIndex > -1) {\n result.thinkingStartIndex = thinkingStartIndex;\n }\n\n if (\n prunedMemory.length === 0 ||\n thinkingEndIndex < 0 ||\n (thinkingStartIndex > -1 &&\n isIndexInContext(_messages, context, thinkingStartIndex))\n ) {\n // we reverse at this step to ensure the context is in the correct order for the model, and we need to work backwards\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.'\n );\n }\n\n if (!thinkingBlock) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no thinking block found.'\n );\n }\n\n // Since we have a thinking sequence, we need to find the last assistant message\n // in the latest AI/tool sequence to add the thinking block that falls outside of the current context\n // Latest messages are ordered first.\n let assistantIndex = -1;\n for (let i = 0; i < context.length; i++) {\n const currentMessage = context[i];\n const type = currentMessage?.getType();\n if (type === 'ai') {\n assistantIndex = i;\n }\n if (assistantIndex > -1 && (type === 'human' || type === 'system')) {\n break;\n }\n }\n\n if (assistantIndex === -1) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages to append thinking blocks to.'\n );\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(\n new AIMessage({ content: [thinkingBlock] })\n );\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n const newMessage = addThinkingBlock(\n context[assistantIndex] as AIMessage,\n thinkingBlock\n );\n context[assistantIndex] = newMessage;\n if (newRemainingCount > 0) {\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex] as AIMessage;\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount =\n (indexTokenCountMap[thinkingStartIndex] ?? 0) + thinkingTokenCount;\n remainingContextTokens = initialContextTokens - newThinkingMessageTokenCount;\n currentTokenCount = 3;\n let newContext: BaseMessage[] = [];\n const secondRoundMessages = [..._messages];\n let currentIndex = secondRoundMessages.length;\n while (\n secondRoundMessages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > thinkingStartIndex\n ) {\n currentIndex--;\n const poppedMessage = secondRoundMessages.pop();\n if (!poppedMessage) continue;\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n if (currentTokenCount + tokenCount <= remainingContextTokens) {\n newContext.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n messages.push(poppedMessage);\n break;\n }\n }\n\n const firstMessage: AIMessage = newContext[newContext.length - 1];\n const firstMessageType = newContext[newContext.length - 1].getType();\n if (firstMessageType === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && newContext.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = newContext.length - 1; i >= 0; i--) {\n const currentType = newContext[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n newContext = newContext.slice(0, requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const newMessage = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1] = newMessage;\n } else {\n newContext.push(thinkingMessage);\n }\n\n if (instructions && originalLength > 0) {\n newContext.push(_messages[0] as BaseMessage);\n secondRoundMessages.shift();\n }\n\n result.context = newContext.reverse();\n return result;\n}\n\nexport function checkValidNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value) && value > 0;\n}\n\ntype ThinkingBlocks = {\n thinking_blocks?: Array<{\n type: 'thinking';\n thinking: string;\n signature: string;\n }>;\n};\n\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let lastCutOffIndex = 0;\n let totalTokens = Object.values(indexTokenCountMap).reduce(\n (a = 0, b = 0) => a + b,\n 0\n ) as number;\n let runThinkingStartIndex = -1;\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number | undefined>;\n } {\n if (\n factoryParams.provider === Providers.OPENAI &&\n factoryParams.thinkingEnabled === true\n ) {\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const m = params.messages[i];\n if (\n m.getType() === 'ai' &&\n typeof m.additional_kwargs.reasoning_content === 'string' &&\n Array.isArray(\n (\n m.additional_kwargs.provider_specific_fields as\n | ThinkingBlocks\n | undefined\n )?.thinking_blocks\n ) &&\n (m as AIMessage).tool_calls &&\n ((m as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const message = m as AIMessage;\n const thinkingBlocks = (\n message.additional_kwargs.provider_specific_fields as ThinkingBlocks\n ).thinking_blocks;\n const signature =\n thinkingBlocks?.[thinkingBlocks.length - 1].signature;\n const thinkingBlock: ThinkingContentText = {\n signature,\n type: ContentTypes.THINKING,\n thinking: message.additional_kwargs.reasoning_content as string,\n };\n\n params.messages[i] = new AIMessage({\n ...message,\n content: [thinkingBlock],\n additional_kwargs: {\n ...message.additional_kwargs,\n reasoning_content: undefined,\n },\n });\n }\n }\n }\n\n let currentUsage: UsageMetadata | undefined;\n if (\n params.usageMetadata &&\n (checkValidNumber(params.usageMetadata.input_tokens) ||\n (checkValidNumber(params.usageMetadata.input_token_details) &&\n (checkValidNumber(\n params.usageMetadata.input_token_details.cache_creation\n ) ||\n checkValidNumber(\n params.usageMetadata.input_token_details.cache_read\n )))) &&\n checkValidNumber(params.usageMetadata.output_tokens)\n ) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n const newOutputs = new Set<number>();\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n if (\n i === lastTurnStartIndex &&\n indexTokenCountMap[i] === undefined &&\n currentUsage\n ) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n if (currentUsage) {\n newOutputs.add(i);\n }\n totalTokens += indexTokenCountMap[i] ?? 0;\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,\n // We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,\n // relative the manually counted tokens in `indexTokenCountMap`.\n // EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.\n if (currentUsage) {\n let totalIndexTokens = 0;\n if (params.messages[0].getType() === 'system') {\n totalIndexTokens += indexTokenCountMap[0] ?? 0;\n }\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (i === 0 && params.messages[0].getType() === 'system') {\n continue;\n }\n if (newOutputs.has(i)) {\n continue;\n }\n totalIndexTokens += indexTokenCountMap[i] ?? 0;\n }\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n const isRatioSafe = ratio >= 1 / 3 && ratio <= 2.5;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex, and only if the ratio is safe\n if (isRatioSafe) {\n if (\n params.messages[0].getType() === 'system' &&\n lastCutOffIndex !== 0\n ) {\n indexTokenCountMap[0] = Math.round(\n (indexTokenCountMap[0] ?? 0) * ratio\n );\n }\n\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (newOutputs.has(i)) {\n continue;\n }\n indexTokenCountMap[i] = Math.round(\n (indexTokenCountMap[i] ?? 0) * ratio\n );\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (lastCutOffIndex === 0 && totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context, thinkingStartIndex } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n reasoningType:\n factoryParams.provider === Providers.BEDROCK\n ? ContentTypes.REASONING_CONTENT\n : ContentTypes.THINKING,\n thinkingStartIndex:\n factoryParams.thinkingEnabled === true\n ? runThinkingStartIndex\n : undefined,\n });\n runThinkingStartIndex = thinkingStartIndex ?? -1;\n /** The index is the first value of `context`, index relative to `params.messages` */\n lastCutOffIndex = Math.max(\n params.messages.length -\n (context.length - (context[0]?.getType() === 'system' ? 1 : 0)),\n 0\n );\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":["ContentTypes","AIMessage","messages","Providers"],"mappings":";;;;;AA2BA,SAAS,gBAAgB,CACvB,MAAiB,EACjB,MAAiB,EACjB,WAAmB,EAAA;IAEnB,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;IACtD,OAAO,WAAW,IAAI,gBAAgB;AACxC;AAEA,SAAS,gBAAgB,CACvB,OAAkB,EAClB,aAAyD,EAAA;IAEzD,MAAM,OAAO,GAA4B,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO;UACjE,OAAO,CAAC;AACX,UAAE;AACA,YAAA;gBACE,IAAI,EAAEA,kBAAY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AE,kBAAkB,EAAE;;AAGzD,QAAA,MAAM,EAAE,OAAO,EAAE,kBAAkB,EAAE,GAAG,2BAA2B,CAAC;YAClE,gBAAgB,EAAE,aAAa,CAAC,SAAS;YACzC,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,kBAAkB;YAClB,SAAS,EAAE,MAAM,CAAC,SAAS;YAC3B,eAAe,EAAE,aAAa,CAAC,eAAe;YAC9C,YAAY,EAAE,aAAa,CAAC,YAAY;AACxC,YAAA,aAAa,EACX,aAAa,CAAC,QAAQ,KAAKE,eAAS,CAAC;kBACjCH,kBAAY,CAAC;kBACbA,kBAAY,CAAC,QAAQ;AAC3B,YAAA,kBAAkB,EAChB,aAAa,CAAC,eAAe,KAAK;AAChC,kBAAE;AACF,kBAAE,SAAS;AAChB,SAAA,CAAC;AACF,QAAA,qBAAqB,GAAG,kBAAkB,IAAI,EAAE;;QAEhD,eAAe,GAAG,IAAI,CAAC,GAAG,CACxB,MAAM,CAAC,QAAQ,CAAC,MAAM;aACnB,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EACjE,CAAC,CACF;AAED,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"prune.cjs","sources":["../../../src/messages/prune.ts"],"sourcesContent":["import {\n AIMessage,\n BaseMessage,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ThinkingContentText,\n MessageContentComplex,\n ReasoningContentText,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport { ContentTypes, Providers } from '@/common';\n\nexport type PruneMessagesFactoryParams = {\n provider?: Providers;\n maxTokens: number;\n startIndex: number;\n tokenCounter: TokenCounter;\n indexTokenCountMap: Record<string, number | undefined>;\n thinkingEnabled?: boolean;\n};\nexport type PruneMessagesParams = {\n messages: BaseMessage[];\n usageMetadata?: Partial<UsageMetadata>;\n startType?: ReturnType<BaseMessage['getType']>;\n};\n\nfunction isIndexInContext(\n arrayA: unknown[],\n arrayB: unknown[],\n targetIndex: number\n): boolean {\n const startingIndexInA = arrayA.length - arrayB.length;\n return targetIndex >= startingIndexInA;\n}\n\nfunction addThinkingBlock(\n message: AIMessage,\n thinkingBlock: ThinkingContentText | ReasoningContentText\n): AIMessage {\n const content: MessageContentComplex[] = Array.isArray(message.content)\n ? (message.content as MessageContentComplex[])\n : [\n {\n type: ContentTypes.TEXT,\n text: message.content,\n },\n ];\n /** Edge case, the message already has the thinking block */\n if (content[0].type === thinkingBlock.type) {\n return message;\n }\n content.unshift(thinkingBlock);\n return new AIMessage({\n ...message,\n content,\n });\n}\n\n/**\n * Calculates the total tokens from a single usage object\n *\n * @param usage The usage metadata object containing token information\n * @returns An object containing the total input and output tokens\n */\nexport function calculateTotalTokens(\n usage: Partial<UsageMetadata>\n): UsageMetadata {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation = Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const totalInputTokens = baseInputTokens + cacheCreation + cacheRead;\n const totalOutputTokens = Number(usage.output_tokens) || 0;\n\n return {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n total_tokens: totalInputTokens + totalOutputTokens,\n };\n}\n\nexport type PruningResult = {\n context: BaseMessage[];\n remainingContextTokens: number;\n messagesToRefine: BaseMessage[];\n thinkingStartIndex?: number;\n};\n\n/**\n * Processes an array of messages and returns a context of messages that fit within a specified token limit.\n * It iterates over the messages from newest to oldest, adding them to the context until the token limit is reached.\n *\n * @param options Configuration options for processing messages\n * @returns Object containing the message context, remaining tokens, messages not included, and summary index\n */\nexport function getMessagesWithinTokenLimit({\n messages: _messages,\n maxContextTokens,\n indexTokenCountMap,\n startType: _startType,\n thinkingEnabled,\n tokenCounter,\n thinkingStartIndex: _thinkingStartIndex = -1,\n reasoningType = ContentTypes.THINKING,\n}: {\n messages: BaseMessage[];\n maxContextTokens: number;\n indexTokenCountMap: Record<string, number | undefined>;\n startType?: string | string[];\n thinkingEnabled?: boolean;\n tokenCounter: TokenCounter;\n thinkingStartIndex?: number;\n reasoningType?: ContentTypes.THINKING | ContentTypes.REASONING_CONTENT;\n}): PruningResult {\n // Every reply is primed with <|start|>assistant<|message|>, so we\n // start with 3 tokens for the label after all messages have been counted.\n let currentTokenCount = 3;\n const instructions =\n _messages[0]?.getType() === 'system' ? _messages[0] : undefined;\n const instructionsTokenCount =\n instructions != null ? (indexTokenCountMap[0] ?? 0) : 0;\n const initialContextTokens = maxContextTokens - instructionsTokenCount;\n let remainingContextTokens = initialContextTokens;\n let startType = _startType;\n const originalLength = _messages.length;\n const messages = [..._messages];\n /**\n * IMPORTANT: this context array gets reversed at the end, since the latest messages get pushed first.\n *\n * This may be confusing to read, but it is done to ensure the context is in the correct order for the model.\n * */\n let context: Array<BaseMessage | undefined> = [];\n\n let thinkingStartIndex = _thinkingStartIndex;\n let thinkingEndIndex = -1;\n let thinkingBlock: ThinkingContentText | ReasoningContentText | undefined;\n const endIndex = instructions != null ? 1 : 0;\n const prunedMemory: BaseMessage[] = [];\n\n if (_thinkingStartIndex > -1) {\n const thinkingMessageContent = messages[_thinkingStartIndex]?.content;\n if (Array.isArray(thinkingMessageContent)) {\n thinkingBlock = thinkingMessageContent.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n }\n }\n\n if (currentTokenCount < remainingContextTokens) {\n let currentIndex = messages.length;\n while (\n messages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > endIndex\n ) {\n currentIndex--;\n if (messages.length === 1 && instructions) {\n break;\n }\n const poppedMessage = messages.pop();\n if (!poppedMessage) continue;\n const messageType = poppedMessage.getType();\n if (\n thinkingEnabled === true &&\n thinkingEndIndex === -1 &&\n currentIndex === originalLength - 1 &&\n (messageType === 'ai' || messageType === 'tool')\n ) {\n thinkingEndIndex = currentIndex;\n }\n if (\n thinkingEndIndex > -1 &&\n !thinkingBlock &&\n thinkingStartIndex < 0 &&\n messageType === 'ai' &&\n Array.isArray(poppedMessage.content)\n ) {\n thinkingBlock = poppedMessage.content.find(\n (content) => content.type === reasoningType\n ) as ThinkingContentText | undefined;\n thinkingStartIndex = thinkingBlock != null ? currentIndex : -1;\n }\n /** False start, the latest message was not part of a multi-assistant/tool sequence of messages */\n if (\n thinkingEndIndex > -1 &&\n currentIndex === thinkingEndIndex - 1 &&\n messageType !== 'ai' &&\n messageType !== 'tool'\n ) {\n thinkingEndIndex = -1;\n }\n\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n\n if (\n prunedMemory.length === 0 &&\n currentTokenCount + tokenCount <= remainingContextTokens\n ) {\n context.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n prunedMemory.push(poppedMessage);\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n continue;\n }\n break;\n }\n }\n\n if (context[context.length - 1]?.getType() === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && context.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = context.length - 1; i >= 0; i--) {\n const currentType = context[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n context = context.slice(0, requiredTypeIndex);\n }\n }\n }\n\n if (instructions && originalLength > 0) {\n context.push(_messages[0] as BaseMessage);\n messages.shift();\n }\n\n remainingContextTokens -= currentTokenCount;\n const result: PruningResult = {\n remainingContextTokens,\n context: [] as BaseMessage[],\n messagesToRefine: prunedMemory,\n };\n\n if (thinkingStartIndex > -1) {\n result.thinkingStartIndex = thinkingStartIndex;\n }\n\n if (\n prunedMemory.length === 0 ||\n thinkingEndIndex < 0 ||\n (thinkingStartIndex > -1 &&\n isIndexInContext(_messages, context, thinkingStartIndex))\n ) {\n // we reverse at this step to ensure the context is in the correct order for the model, and we need to work backwards\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n if (thinkingEndIndex > -1 && thinkingStartIndex < 0) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no \"AI\" messages with thinking blocks.'\n );\n }\n\n if (!thinkingBlock) {\n throw new Error(\n 'The payload is malformed. There is a thinking sequence but no thinking block found.'\n );\n }\n\n // Since we have a thinking sequence, we need to find the last assistant message\n // in the latest AI/tool sequence to add the thinking block that falls outside of the current context\n // Latest messages are ordered first.\n let assistantIndex = -1;\n for (let i = 0; i < context.length; i++) {\n const currentMessage = context[i];\n const type = currentMessage?.getType();\n if (type === 'ai') {\n assistantIndex = i;\n }\n if (assistantIndex > -1 && (type === 'human' || type === 'system')) {\n break;\n }\n }\n\n if (assistantIndex === -1) {\n throw new Error(\n 'Context window exceeded: aggressive pruning removed all AI messages (likely due to an oversized tool response). Increase max context tokens or reduce tool output size.'\n );\n }\n\n thinkingStartIndex = originalLength - 1 - assistantIndex;\n const thinkingTokenCount = tokenCounter(\n new AIMessage({ content: [thinkingBlock] })\n );\n const newRemainingCount = remainingContextTokens - thinkingTokenCount;\n const newMessage = addThinkingBlock(\n context[assistantIndex] as AIMessage,\n thinkingBlock\n );\n context[assistantIndex] = newMessage;\n if (newRemainingCount > 0) {\n result.context = context.reverse() as BaseMessage[];\n return result;\n }\n\n const thinkingMessage: AIMessage = context[assistantIndex] as AIMessage;\n // now we need to an additional round of pruning but making the thinking block fit\n const newThinkingMessageTokenCount =\n (indexTokenCountMap[thinkingStartIndex] ?? 0) + thinkingTokenCount;\n remainingContextTokens = initialContextTokens - newThinkingMessageTokenCount;\n currentTokenCount = 3;\n let newContext: BaseMessage[] = [];\n const secondRoundMessages = [..._messages];\n let currentIndex = secondRoundMessages.length;\n while (\n secondRoundMessages.length > 0 &&\n currentTokenCount < remainingContextTokens &&\n currentIndex > thinkingStartIndex\n ) {\n currentIndex--;\n const poppedMessage = secondRoundMessages.pop();\n if (!poppedMessage) continue;\n const tokenCount = indexTokenCountMap[currentIndex] ?? 0;\n if (currentTokenCount + tokenCount <= remainingContextTokens) {\n newContext.push(poppedMessage);\n currentTokenCount += tokenCount;\n } else {\n messages.push(poppedMessage);\n break;\n }\n }\n\n const firstMessage: AIMessage = newContext[newContext.length - 1];\n const firstMessageType = newContext[newContext.length - 1].getType();\n if (firstMessageType === 'tool') {\n startType = ['ai', 'human'];\n }\n\n if (startType != null && startType.length > 0 && newContext.length > 0) {\n let requiredTypeIndex = -1;\n\n let totalTokens = 0;\n for (let i = newContext.length - 1; i >= 0; i--) {\n const currentType = newContext[i]?.getType() ?? '';\n if (\n Array.isArray(startType)\n ? startType.includes(currentType)\n : currentType === startType\n ) {\n requiredTypeIndex = i + 1;\n break;\n }\n const originalIndex = originalLength - 1 - i;\n totalTokens += indexTokenCountMap[originalIndex] ?? 0;\n }\n\n if (requiredTypeIndex > 0) {\n currentTokenCount -= totalTokens;\n newContext = newContext.slice(0, requiredTypeIndex);\n }\n }\n\n if (firstMessageType === 'ai') {\n const newMessage = addThinkingBlock(firstMessage, thinkingBlock);\n newContext[newContext.length - 1] = newMessage;\n } else {\n newContext.push(thinkingMessage);\n }\n\n if (instructions && originalLength > 0) {\n newContext.push(_messages[0] as BaseMessage);\n secondRoundMessages.shift();\n }\n\n result.context = newContext.reverse();\n return result;\n}\n\nexport function checkValidNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value) && value > 0;\n}\n\ntype ThinkingBlocks = {\n thinking_blocks?: Array<{\n type: 'thinking';\n thinking: string;\n signature: string;\n }>;\n};\n\nexport function createPruneMessages(factoryParams: PruneMessagesFactoryParams) {\n const indexTokenCountMap = { ...factoryParams.indexTokenCountMap };\n let lastTurnStartIndex = factoryParams.startIndex;\n let lastCutOffIndex = 0;\n let totalTokens = Object.values(indexTokenCountMap).reduce(\n (a = 0, b = 0) => a + b,\n 0\n ) as number;\n let runThinkingStartIndex = -1;\n return function pruneMessages(params: PruneMessagesParams): {\n context: BaseMessage[];\n indexTokenCountMap: Record<string, number | undefined>;\n } {\n if (\n factoryParams.provider === Providers.OPENAI &&\n factoryParams.thinkingEnabled === true\n ) {\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const m = params.messages[i];\n if (\n m.getType() === 'ai' &&\n typeof m.additional_kwargs.reasoning_content === 'string' &&\n Array.isArray(\n (\n m.additional_kwargs.provider_specific_fields as\n | ThinkingBlocks\n | undefined\n )?.thinking_blocks\n ) &&\n (m as AIMessage).tool_calls &&\n ((m as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n const message = m as AIMessage;\n const thinkingBlocks = (\n message.additional_kwargs.provider_specific_fields as ThinkingBlocks\n ).thinking_blocks;\n const signature =\n thinkingBlocks?.[thinkingBlocks.length - 1].signature;\n const thinkingBlock: ThinkingContentText = {\n signature,\n type: ContentTypes.THINKING,\n thinking: message.additional_kwargs.reasoning_content as string,\n };\n\n params.messages[i] = new AIMessage({\n ...message,\n content: [thinkingBlock],\n additional_kwargs: {\n ...message.additional_kwargs,\n reasoning_content: undefined,\n },\n });\n }\n }\n }\n\n let currentUsage: UsageMetadata | undefined;\n if (\n params.usageMetadata &&\n (checkValidNumber(params.usageMetadata.input_tokens) ||\n (checkValidNumber(params.usageMetadata.input_token_details) &&\n (checkValidNumber(\n params.usageMetadata.input_token_details.cache_creation\n ) ||\n checkValidNumber(\n params.usageMetadata.input_token_details.cache_read\n )))) &&\n checkValidNumber(params.usageMetadata.output_tokens)\n ) {\n currentUsage = calculateTotalTokens(params.usageMetadata);\n totalTokens = currentUsage.total_tokens;\n }\n\n const newOutputs = new Set<number>();\n for (let i = lastTurnStartIndex; i < params.messages.length; i++) {\n const message = params.messages[i];\n if (\n i === lastTurnStartIndex &&\n indexTokenCountMap[i] === undefined &&\n currentUsage\n ) {\n indexTokenCountMap[i] = currentUsage.output_tokens;\n } else if (indexTokenCountMap[i] === undefined) {\n indexTokenCountMap[i] = factoryParams.tokenCounter(message);\n if (currentUsage) {\n newOutputs.add(i);\n }\n totalTokens += indexTokenCountMap[i] ?? 0;\n }\n }\n\n // If `currentUsage` is defined, we need to distribute the current total tokens to our `indexTokenCountMap`,\n // We must distribute it in a weighted manner, so that the total token count is equal to `currentUsage.total_tokens`,\n // relative the manually counted tokens in `indexTokenCountMap`.\n // EDGE CASE: when the resulting context gets pruned, we should not distribute the usage for messages that are not in the context.\n if (currentUsage) {\n let totalIndexTokens = 0;\n if (params.messages[0].getType() === 'system') {\n totalIndexTokens += indexTokenCountMap[0] ?? 0;\n }\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (i === 0 && params.messages[0].getType() === 'system') {\n continue;\n }\n if (newOutputs.has(i)) {\n continue;\n }\n totalIndexTokens += indexTokenCountMap[i] ?? 0;\n }\n\n // Calculate ratio based only on messages that remain in the context\n const ratio = currentUsage.total_tokens / totalIndexTokens;\n const isRatioSafe = ratio >= 1 / 3 && ratio <= 2.5;\n\n // Apply the ratio adjustment only to messages at or after lastCutOffIndex, and only if the ratio is safe\n if (isRatioSafe) {\n if (\n params.messages[0].getType() === 'system' &&\n lastCutOffIndex !== 0\n ) {\n indexTokenCountMap[0] = Math.round(\n (indexTokenCountMap[0] ?? 0) * ratio\n );\n }\n\n for (let i = lastCutOffIndex; i < params.messages.length; i++) {\n if (newOutputs.has(i)) {\n continue;\n }\n indexTokenCountMap[i] = Math.round(\n (indexTokenCountMap[i] ?? 0) * ratio\n );\n }\n }\n }\n\n lastTurnStartIndex = params.messages.length;\n if (lastCutOffIndex === 0 && totalTokens <= factoryParams.maxTokens) {\n return { context: params.messages, indexTokenCountMap };\n }\n\n const { context, thinkingStartIndex } = getMessagesWithinTokenLimit({\n maxContextTokens: factoryParams.maxTokens,\n messages: params.messages,\n indexTokenCountMap,\n startType: params.startType,\n thinkingEnabled: factoryParams.thinkingEnabled,\n tokenCounter: factoryParams.tokenCounter,\n reasoningType:\n factoryParams.provider === Providers.BEDROCK\n ? ContentTypes.REASONING_CONTENT\n : ContentTypes.THINKING,\n thinkingStartIndex:\n factoryParams.thinkingEnabled === true\n ? runThinkingStartIndex\n : undefined,\n });\n runThinkingStartIndex = thinkingStartIndex ?? -1;\n /** The index is the first value of `context`, index relative to `params.messages` */\n lastCutOffIndex = Math.max(\n params.messages.length -\n (context.length - (context[0]?.getType() === 'system' ? 1 : 0)),\n 0\n );\n\n return { context, indexTokenCountMap };\n };\n}\n"],"names":["ContentTypes","AIMessage","messages","Providers"],"mappings":";;;;;AA2BA,SAAS,gBAAgB,CACvB,MAAiB,EACjB,MAAiB,EACjB,WAAmB,EAAA;IAEnB,MAAM,gBAAgB,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;IACtD,OAAO,WAAW,IAAI,gBAAgB;AACxC;AAEA,SAAS,gBAAgB,CACvB,OAAkB,EAClB,aAAyD,EAAA;IAEzD,MAAM,OAAO,GAA4B,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO;UACjE,OAAO,CAAC;AACX,UAAE;AACA,YAAA;gBACE,IAAI,EAAEA,kBAAY,CAAC,IAAI;gBACvB,IAAI,EAAE,OAAO,CAAC,OAAO;AACtB,aAAA;SACF;;IAEH,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,aAAa,CAAC,IAAI,EAAE;AAC1C,QAAA,OAAO,OAAO;;AAEhB,IAAA,OAAO,CAAC,OAAO,CAAC,aAAa,CAAC;IAC9B,OAAO,IAAIC,kBAAS,CAAC;AACnB,QAAA,GAAG,OAAO;QACV,OAAO;AACR,KAAA,CAAC;AACJ;AAEA;;;;;AAKG;AACG,SAAU,oBAAoB,CAClC,KAA6B,EAAA;IAE7B,MAAM,eAAe,GAAG,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC;AACvD,IAAA,MAAM,aAAa,GA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AACF,kBAAE,SAAS;AAChB,SAAA,CAAC;AACF,QAAA,qBAAqB,GAAG,kBAAkB,IAAI,EAAE;;QAEhD,eAAe,GAAG,IAAI,CAAC,GAAG,CACxB,MAAM,CAAC,QAAQ,CAAC,MAAM;aACnB,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,QAAQ,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EACjE,CAAC,CACF;AAED,QAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE;AACxC,KAAC;AACH;;;;;;;"}
|
|
@@ -22,24 +22,21 @@ const DEFAULT_MAX_ROUND_TRIPS = 20;
|
|
|
22
22
|
/** Default execution timeout in milliseconds */
|
|
23
23
|
const DEFAULT_TIMEOUT = 60000;
|
|
24
24
|
// ============================================================================
|
|
25
|
-
//
|
|
25
|
+
// Description Components (Single Source of Truth)
|
|
26
26
|
// ============================================================================
|
|
27
|
-
const
|
|
28
|
-
type: 'object',
|
|
29
|
-
properties: {
|
|
30
|
-
code: {
|
|
31
|
-
type: 'string',
|
|
32
|
-
minLength: 1,
|
|
33
|
-
description: `Python code that calls tools programmatically. Tools are available as async functions.
|
|
34
|
-
|
|
35
|
-
CRITICAL - STATELESS EXECUTION:
|
|
27
|
+
const STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:
|
|
36
28
|
Each call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.
|
|
37
29
|
You MUST complete your entire workflow in ONE code block: query → process → output.
|
|
38
|
-
DO NOT split work across multiple calls expecting to reuse variables
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
30
|
+
DO NOT split work across multiple calls expecting to reuse variables.`;
|
|
31
|
+
const CORE_RULES = `Rules:
|
|
32
|
+
- EVERYTHING in one call—no state persists between executions
|
|
33
|
+
- Just write code with await—auto-wrapped in async context
|
|
34
|
+
- DO NOT define async def main() or call asyncio.run()
|
|
35
|
+
- Tools are pre-defined—DO NOT write function definitions
|
|
36
|
+
- Only print() output returns to the model`;
|
|
37
|
+
const ADDITIONAL_RULES = `- Generated files are automatically available in /mnt/data/ for subsequent executions
|
|
38
|
+
- Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix`;
|
|
39
|
+
const EXAMPLES = `Example (Complete workflow in one call):
|
|
43
40
|
# Query data
|
|
44
41
|
data = await query_database(sql="SELECT * FROM users")
|
|
45
42
|
# Process it
|
|
@@ -51,14 +48,26 @@ Example (Complete workflow in one call):
|
|
|
51
48
|
|
|
52
49
|
Example (Parallel calls):
|
|
53
50
|
sf, ny = await asyncio.gather(get_weather(city="SF"), get_weather(city="NY"))
|
|
54
|
-
print(f"SF: {sf}, NY: {ny}")
|
|
51
|
+
print(f"SF: {sf}, NY: {ny}")`;
|
|
52
|
+
// ============================================================================
|
|
53
|
+
// Schema
|
|
54
|
+
// ============================================================================
|
|
55
|
+
const CODE_PARAM_DESCRIPTION = `Python code that calls tools programmatically. Tools are available as async functions.
|
|
55
56
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
- Just write
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
57
|
+
${STATELESS_WARNING}
|
|
58
|
+
|
|
59
|
+
Your code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.
|
|
60
|
+
|
|
61
|
+
${EXAMPLES}
|
|
62
|
+
|
|
63
|
+
${CORE_RULES}`;
|
|
64
|
+
const ProgrammaticToolCallingSchema = {
|
|
65
|
+
type: 'object',
|
|
66
|
+
properties: {
|
|
67
|
+
code: {
|
|
68
|
+
type: 'string',
|
|
69
|
+
minLength: 1,
|
|
70
|
+
description: CODE_PARAM_DESCRIPTION,
|
|
62
71
|
},
|
|
63
72
|
timeout: {
|
|
64
73
|
type: 'integer',
|
|
@@ -74,21 +83,14 @@ const ProgrammaticToolCallingName = _enum.Constants.PROGRAMMATIC_TOOL_CALLING;
|
|
|
74
83
|
const ProgrammaticToolCallingDescription = `
|
|
75
84
|
Run tools via Python code. Auto-wrapped in async context—just use \`await\` directly.
|
|
76
85
|
|
|
77
|
-
|
|
78
|
-
Complete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.
|
|
86
|
+
${STATELESS_WARNING}
|
|
79
87
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
- Do NOT define \`async def main()\` or call \`asyncio.run()\`—just write code with await
|
|
83
|
-
- Tools are pre-defined—DO NOT write function definitions
|
|
84
|
-
- Only \`print()\` output returns; tool results are raw dicts/lists/strings
|
|
85
|
-
- Generated files are automatically available in /mnt/data/ for subsequent executions
|
|
86
|
-
- Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix
|
|
88
|
+
${CORE_RULES}
|
|
89
|
+
${ADDITIONAL_RULES}
|
|
87
90
|
|
|
88
91
|
When to use: loops, conditionals, parallel (\`asyncio.gather\`), multi-step pipelines.
|
|
89
92
|
|
|
90
|
-
|
|
91
|
-
data = await query_db(sql="..."); df = process(data); await save_to_sheet(data=df); print("Done")
|
|
93
|
+
${EXAMPLES}
|
|
92
94
|
`.trim();
|
|
93
95
|
const ProgrammaticToolCallingDefinition = {
|
|
94
96
|
name: ProgrammaticToolCallingName,
|
|
@@ -513,25 +515,6 @@ function createProgrammaticToolCallingTool(initParams = {}) {
|
|
|
513
515
|
const proxy = initParams.proxy ?? process.env.PROXY;
|
|
514
516
|
const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';
|
|
515
517
|
const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
|
|
516
|
-
const description = `
|
|
517
|
-
Run tools via Python code. Auto-wrapped in async context—just use \`await\` directly.
|
|
518
|
-
|
|
519
|
-
CRITICAL - STATELESS: Each call is a fresh interpreter. Variables/imports do NOT persist.
|
|
520
|
-
Complete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.
|
|
521
|
-
|
|
522
|
-
Rules:
|
|
523
|
-
- Everything in ONE code block—no state carries over between executions
|
|
524
|
-
- Do NOT define \`async def main()\` or call \`asyncio.run()\`—just write code with await
|
|
525
|
-
- Tools are pre-defined—DO NOT write function definitions
|
|
526
|
-
- Only \`print()\` output returns; tool results are raw dicts/lists/strings
|
|
527
|
-
- Generated files are automatically available in /mnt/data/ for subsequent executions
|
|
528
|
-
- Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix
|
|
529
|
-
|
|
530
|
-
When to use: loops, conditionals, parallel (\`asyncio.gather\`), multi-step pipelines.
|
|
531
|
-
|
|
532
|
-
Example (complete pipeline):
|
|
533
|
-
data = await query_db(sql="..."); df = process(data); await save_to_sheet(data=df); print("Done")
|
|
534
|
-
`.trim();
|
|
535
518
|
return tools.tool(async (rawParams, config) => {
|
|
536
519
|
const params = rawParams;
|
|
537
520
|
const { code, timeout = DEFAULT_TIMEOUT } = params;
|
|
@@ -614,7 +597,7 @@ Example (complete pipeline):
|
|
|
614
597
|
}
|
|
615
598
|
}, {
|
|
616
599
|
name: _enum.Constants.PROGRAMMATIC_TOOL_CALLING,
|
|
617
|
-
description,
|
|
600
|
+
description: ProgrammaticToolCallingDescription,
|
|
618
601
|
schema: ProgrammaticToolCallingSchema,
|
|
619
602
|
responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
|
|
620
603
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProgrammaticToolCalling.cjs","sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\n/** Default execution timeout in milliseconds */\nconst DEFAULT_TIMEOUT = 60000;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nexport const ProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: `Python code that calls tools programmatically. Tools are available as async functions.\n\nCRITICAL - STATELESS EXECUTION:\nEach call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block: query → process → output.\nDO NOT split work across multiple calls expecting to reuse variables.\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\nExample (Complete workflow in one call):\n # Query data\n data = await query_database(sql=\"SELECT * FROM users\")\n # Process it\n df = pd.DataFrame(data)\n summary = df.groupby('region').sum()\n # Output results\n await write_to_sheet(spreadsheet_id=sid, data=summary.to_dict())\n print(f\"Wrote {len(summary)} rows\")\n\nExample (Parallel calls):\n sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n print(f\"SF: {sf}, NY: {ny}\")\n\nRules:\n- EVERYTHING in one call—no state persists between executions\n- Just write code with await—auto-wrapped in async context\n- DO NOT define async def main() or call asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Only print() output returns to the model`,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const ProgrammaticToolCallingName = Constants.PROGRAMMATIC_TOOL_CALLING;\n\nexport const ProgrammaticToolCallingDescription = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\nCRITICAL - STATELESS: Each call is a fresh interpreter. Variables/imports do NOT persist.\nComplete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.\n\nRules:\n- Everything in ONE code block—no state carries over between executions\n- Do NOT define \\`async def main()\\` or call \\`asyncio.run()\\`—just write code with await\n- Tools are pre-defined—DO NOT write function definitions\n- Only \\`print()\\` output returns; tool results are raw dicts/lists/strings\n- Generated files are automatically available in /mnt/data/ for subsequent executions\n- Tool names normalized: hyphens→underscores, keywords get \\`_tool\\` suffix\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\nExample (complete pipeline):\n data = await query_db(sql=\"...\"); df = process(data); await save_to_sheet(data=df); print(\"Done\")\n`.trim();\n\nexport const ProgrammaticToolCallingDefinition = {\n name: ProgrammaticToolCallingName,\n description: ProgrammaticToolCallingDescription,\n schema: ProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/** Python reserved keywords that get `_tool` suffix in Code API */\nconst PYTHON_KEYWORDS = new Set([\n 'False',\n 'None',\n 'True',\n 'and',\n 'as',\n 'assert',\n 'async',\n 'await',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'nonlocal',\n 'not',\n 'or',\n 'pass',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Normalizes a tool name to Python identifier format.\n * Must match the Code API's `normalizePythonFunctionName` exactly:\n * 1. Replace hyphens and spaces with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a Python keyword\n * @param name - The tool name to normalize\n * @returns Normalized Python-safe identifier\n */\nexport function normalizeToPythonIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s]/g, '_');\n\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (PYTHON_KEYWORDS.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the Python code.\n * Handles hyphen/underscore conversion since Python identifiers use underscores.\n * @param code - The Python code to analyze\n * @param toolNameMap - Map from normalized Python name to original tool name\n * @returns Set of original tool names found in the code\n */\nexport function extractUsedToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [pythonName, originalName] of toolNameMap) {\n const escapedName = pythonName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\s*\\\\(`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the code.\n * Handles the hyphen-to-underscore conversion for Python compatibility.\n * @param toolDefs - All available tool definitions\n * @param code - The Python code to analyze\n * @param debug - Enable debug logging\n * @returns Filtered array of tool definitions\n */\nexport function filterToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const tool of toolDefs) {\n const pythonName = normalizeToPythonIdentifier(tool.name);\n toolNameMap.set(pythonName, tool.name);\n }\n\n const usedToolNames = extractUsedToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[PTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((tool) => usedToolNames.has(tool.name));\n}\n\n/**\n * Fetches files from a previous session to make them available for the current execution.\n * Files are returned as CodeEnvFile references to be included in the request.\n * @param baseUrl - The base URL for the Code API\n * @param apiKey - The API key for authentication\n * @param sessionId - The session ID to fetch files from\n * @param proxy - Optional HTTP proxy URL\n * @returns Array of CodeEnvFile references, or empty array if fetch fails\n */\nexport async function fetchSessionFiles(\n baseUrl: string,\n apiKey: string,\n sessionId: string,\n proxy?: string\n): Promise<t.CodeEnvFile[]> {\n try {\n const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(`Failed to fetch files for session: ${response.status}`);\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files.map((file: Record<string, unknown>) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = (file.name as string).split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id: sessionId,\n id,\n name: (file.metadata as Record<string, unknown>)[\n 'original-filename'\n ] as string,\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(\n `Failed to fetch files for session: ${sessionId}, ${(error as Error).message}`\n );\n return [];\n }\n}\n\n/**\n * Makes an HTTP request to the Code API.\n * @param endpoint - The API endpoint URL\n * @param apiKey - The API key for authentication\n * @param body - The request body\n * @param proxy - Optional HTTP proxy URL\n * @returns The parsed API response\n */\nexport async function makeRequest(\n endpoint: string,\n apiKey: string,\n body: Record<string, unknown>,\n proxy?: string\n): Promise<t.ProgrammaticExecutionResponse> {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(body),\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(endpoint, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `HTTP error! status: ${response.status}, body: ${errorText}`\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n}\n\n/**\n * Unwraps tool responses that may be formatted as tuples or content blocks.\n * MCP tools return [content, artifacts], we need to extract the raw data.\n * @param result - The raw result from tool.invoke()\n * @param isMCPTool - Whether this is an MCP tool (has mcp property)\n * @returns Unwrapped raw data (string, object, or parsed JSON)\n */\nexport function unwrapToolResponse(\n result: unknown,\n isMCPTool: boolean\n): unknown {\n // Only unwrap if this is an MCP tool and result is a tuple\n if (!isMCPTool) {\n return result;\n }\n\n /**\n * Checks if a value is a content block object (has type and text).\n */\n const isContentBlock = (value: unknown): boolean => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n return typeof obj.type === 'string';\n };\n\n /**\n * Checks if an array is an array of content blocks.\n */\n const isContentBlockArray = (arr: unknown[]): boolean => {\n return arr.length > 0 && arr.every(isContentBlock);\n };\n\n /**\n * Extracts text from a single content block object.\n * Returns the text if it's a text block, otherwise returns null.\n */\n const extractTextFromBlock = (block: unknown): string | null => {\n if (typeof block !== 'object' || block === null) return null;\n const b = block as Record<string, unknown>;\n if (b.type === 'text' && typeof b.text === 'string') {\n return b.text;\n }\n return null;\n };\n\n /**\n * Extracts text from content blocks (array or single object).\n * Returns combined text or null if no text blocks found.\n */\n const extractTextFromContent = (content: unknown): string | null => {\n // Single content block object: { type: 'text', text: '...' }\n if (\n typeof content === 'object' &&\n content !== null &&\n !Array.isArray(content)\n ) {\n const text = extractTextFromBlock(content);\n if (text !== null) return text;\n }\n\n // Array of content blocks: [{ type: 'text', text: '...' }, ...]\n if (Array.isArray(content) && content.length > 0) {\n const texts = content\n .map(extractTextFromBlock)\n .filter((t): t is string => t !== null);\n if (texts.length > 0) {\n return texts.join('\\n');\n }\n }\n\n return null;\n };\n\n /**\n * Tries to parse a string as JSON if it looks like JSON.\n */\n const maybeParseJSON = (str: string): unknown => {\n const trimmed = str.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return str;\n }\n }\n return str;\n };\n\n // Handle array of content blocks at top level FIRST\n // (before checking for tuple, since both are arrays)\n if (Array.isArray(result) && isContentBlockArray(result)) {\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n }\n\n // Check if result is a tuple/array with [content, artifacts]\n if (Array.isArray(result) && result.length >= 1) {\n const [content] = result;\n\n // If first element is a string, return it (possibly parsed as JSON)\n if (typeof content === 'string') {\n return maybeParseJSON(content);\n }\n\n // Try to extract text from content blocks\n const extractedText = extractTextFromContent(content);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // If first element is an object (but not a text block), return it\n if (typeof content === 'object' && content !== null) {\n return content;\n }\n }\n\n // Handle single content block object at top level (not in tuple)\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // Not a formatted response, return as-is\n return result;\n}\n\n/**\n * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\n * Unwraps formatted responses (e.g., MCP tool tuples) to raw data.\n * @param toolCalls - Array of tool calls from the API\n * @param toolMap - Map of tool names to executable tools\n * @returns Array of tool results\n */\nexport async function executeTools(\n toolCalls: t.PTCToolCall[],\n toolMap: t.ToolMap\n): Promise<t.PTCToolResult[]> {\n const executions = toolCalls.map(async (call): Promise<t.PTCToolResult> => {\n const tool = toolMap.get(call.name);\n\n if (!tool) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,\n };\n }\n\n try {\n const result = await tool.invoke(call.input, {\n metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },\n });\n\n const isMCPTool = tool.mcp === true;\n const unwrappedResult = unwrapToolResponse(result, isMCPTool);\n\n return {\n call_id: call.id,\n result: unwrappedResult,\n is_error: false,\n };\n } catch (error) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: (error as Error).message || 'Tool execution failed',\n };\n }\n });\n\n return await Promise.all(executions);\n}\n\n/**\n * Formats the completed response for the agent.\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse\n): [string, t.ProgrammaticExecutionArtifact] {\n let formatted = '';\n\n if (response.stdout != null && response.stdout !== '') {\n formatted += `stdout:\\n${response.stdout}\\n`;\n } else {\n formatted += emptyOutputMessage;\n }\n\n if (response.stderr != null && response.stderr !== '') {\n formatted += `stderr:\\n${response.stderr}\\n`;\n }\n\n if (response.files && response.files.length > 0) {\n formatted += 'Generated files:\\n';\n\n const fileCount = response.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = response.files[i];\n const isImage = imageExtRegex.test(file.name);\n formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formatted += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formatted += `\\n\\n${accessMessage}`;\n }\n\n return [\n formatted.trim(),\n {\n session_id: response.session_id,\n files: response.files,\n },\n ];\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.\n *\n * This tool enables AI agents to write Python code that orchestrates multiple\n * tool calls programmatically, reducing LLM round-trips and token usage.\n *\n * The tool map must be provided at runtime via config.configurable.toolMap.\n *\n * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({\n * apiKey: process.env.CODE_API_KEY,\n * maxRoundTrips: 20\n * });\n *\n * const [output, artifact] = await ptcTool.invoke(\n * { code, tools },\n * { configurable: { toolMap } }\n * );\n */\nexport function createProgrammaticToolCallingTool(\n initParams: t.ProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n const description = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\nCRITICAL - STATELESS: Each call is a fresh interpreter. Variables/imports do NOT persist.\nComplete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.\n\nRules:\n- Everything in ONE code block—no state carries over between executions\n- Do NOT define \\`async def main()\\` or call \\`asyncio.run()\\`—just write code with await\n- Tools are pre-defined—DO NOT write function definitions\n- Only \\`print()\\` output returns; tool results are raw dicts/lists/strings\n- Generated files are automatically available in /mnt/data/ for subsequent executions\n- Tool names normalized: hyphens→underscores, keywords get \\`_tool\\` suffix\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\nExample (complete pipeline):\n data = await query_db(sql=\"...\"); df = process(data); await save_to_sheet(data=df); print(\"Done\")\n`.trim();\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const { toolMap, toolDefs, session_id, _injected_files } =\n (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description,\n schema: ProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":["config","Constants","HttpsProxyAgent","imageExtRegex","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool"],"mappings":";;;;;;;;;;AAAA;AAWAA,aAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,uFAAuF;AACzF,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D;AACA,MAAM,uBAAuB,GAAG,EAAE;AAElC;AACA,MAAM,eAAe,GAAG,KAAK;AAE7B;AACA;AACA;AAEa,MAAA,6BAA6B,GAAG;AAC3C,IAAA,IAAI,EAAE,QAAQ;AACd,IAAA,UAAU,EAAE;AACV,QAAA,IAAI,EAAE;AACJ,YAAA,IAAI,EAAE,QAAQ;AACd,YAAA,SAAS,EAAE,CAAC;AACZ,YAAA,WAAW,EAAE,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BwB,0CAAA,CAAA;AACtC,SAAA;AACD,QAAA,OAAO,EAAE;AACP,YAAA,IAAI,EAAE,SAAS;AACf,YAAA,OAAO,EAAE,IAAI;AAC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C;;AAG1C,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAE,CAAA;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAE;AACnC,0BAAE,EAAE,CAAC,CACV;;YAGH,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAE,CAAA,CAAC;;QACjE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,+BAAA,EAAmC,KAAe,CAAC,OAAO,CAAE,CAAA,CAC7D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEN,eAAS,CAAC,yBAAyB;QACzC,WAAW;AACX,QAAA,MAAM,EAAE,6BAA6B;QACrC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"ProgrammaticToolCalling.cjs","sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files from previous executions are automatically available and can be modified.';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\n/** Default execution timeout in milliseconds */\nconst DEFAULT_TIMEOUT = 60000;\n\n// ============================================================================\n// Description Components (Single Source of Truth)\n// ============================================================================\n\nconst STATELESS_WARNING = `CRITICAL - STATELESS EXECUTION:\nEach call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block: query → process → output.\nDO NOT split work across multiple calls expecting to reuse variables.`;\n\nconst CORE_RULES = `Rules:\n- EVERYTHING in one call—no state persists between executions\n- Just write code with await—auto-wrapped in async context\n- DO NOT define async def main() or call asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Only print() output returns to the model`;\n\nconst ADDITIONAL_RULES = `- Generated files are automatically available in /mnt/data/ for subsequent executions\n- Tool names normalized: hyphens→underscores, keywords get \\`_tool\\` suffix`;\n\nconst EXAMPLES = `Example (Complete workflow in one call):\n # Query data\n data = await query_database(sql=\"SELECT * FROM users\")\n # Process it\n df = pd.DataFrame(data)\n summary = df.groupby('region').sum()\n # Output results\n await write_to_sheet(spreadsheet_id=sid, data=summary.to_dict())\n print(f\"Wrote {len(summary)} rows\")\n\nExample (Parallel calls):\n sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n print(f\"SF: {sf}, NY: {ny}\")`;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst CODE_PARAM_DESCRIPTION = `Python code that calls tools programmatically. Tools are available as async functions.\n\n${STATELESS_WARNING}\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\n${EXAMPLES}\n\n${CORE_RULES}`;\n\nexport const ProgrammaticToolCallingSchema = {\n type: 'object',\n properties: {\n code: {\n type: 'string',\n minLength: 1,\n description: CODE_PARAM_DESCRIPTION,\n },\n timeout: {\n type: 'integer',\n minimum: 1000,\n maximum: 300000,\n default: DEFAULT_TIMEOUT,\n description:\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.',\n },\n },\n required: ['code'],\n} as const;\n\nexport const ProgrammaticToolCallingName = Constants.PROGRAMMATIC_TOOL_CALLING;\n\nexport const ProgrammaticToolCallingDescription = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\n${STATELESS_WARNING}\n\n${CORE_RULES}\n${ADDITIONAL_RULES}\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\n${EXAMPLES}\n`.trim();\n\nexport const ProgrammaticToolCallingDefinition = {\n name: ProgrammaticToolCallingName,\n description: ProgrammaticToolCallingDescription,\n schema: ProgrammaticToolCallingSchema,\n} as const;\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/** Python reserved keywords that get `_tool` suffix in Code API */\nconst PYTHON_KEYWORDS = new Set([\n 'False',\n 'None',\n 'True',\n 'and',\n 'as',\n 'assert',\n 'async',\n 'await',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'nonlocal',\n 'not',\n 'or',\n 'pass',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Normalizes a tool name to Python identifier format.\n * Must match the Code API's `normalizePythonFunctionName` exactly:\n * 1. Replace hyphens and spaces with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a Python keyword\n * @param name - The tool name to normalize\n * @returns Normalized Python-safe identifier\n */\nexport function normalizeToPythonIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s]/g, '_');\n\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (PYTHON_KEYWORDS.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the Python code.\n * Handles hyphen/underscore conversion since Python identifiers use underscores.\n * @param code - The Python code to analyze\n * @param toolNameMap - Map from normalized Python name to original tool name\n * @returns Set of original tool names found in the code\n */\nexport function extractUsedToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [pythonName, originalName] of toolNameMap) {\n const escapedName = pythonName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\s*\\\\(`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the code.\n * Handles the hyphen-to-underscore conversion for Python compatibility.\n * @param toolDefs - All available tool definitions\n * @param code - The Python code to analyze\n * @param debug - Enable debug logging\n * @returns Filtered array of tool definitions\n */\nexport function filterToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const tool of toolDefs) {\n const pythonName = normalizeToPythonIdentifier(tool.name);\n toolNameMap.set(pythonName, tool.name);\n }\n\n const usedToolNames = extractUsedToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[PTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((tool) => usedToolNames.has(tool.name));\n}\n\n/**\n * Fetches files from a previous session to make them available for the current execution.\n * Files are returned as CodeEnvFile references to be included in the request.\n * @param baseUrl - The base URL for the Code API\n * @param apiKey - The API key for authentication\n * @param sessionId - The session ID to fetch files from\n * @param proxy - Optional HTTP proxy URL\n * @returns Array of CodeEnvFile references, or empty array if fetch fails\n */\nexport async function fetchSessionFiles(\n baseUrl: string,\n apiKey: string,\n sessionId: string,\n proxy?: string\n): Promise<t.CodeEnvFile[]> {\n try {\n const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(`Failed to fetch files for session: ${response.status}`);\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files.map((file: Record<string, unknown>) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = (file.name as string).split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id: sessionId,\n id,\n name: (file.metadata as Record<string, unknown>)[\n 'original-filename'\n ] as string,\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(\n `Failed to fetch files for session: ${sessionId}, ${(error as Error).message}`\n );\n return [];\n }\n}\n\n/**\n * Makes an HTTP request to the Code API.\n * @param endpoint - The API endpoint URL\n * @param apiKey - The API key for authentication\n * @param body - The request body\n * @param proxy - Optional HTTP proxy URL\n * @returns The parsed API response\n */\nexport async function makeRequest(\n endpoint: string,\n apiKey: string,\n body: Record<string, unknown>,\n proxy?: string\n): Promise<t.ProgrammaticExecutionResponse> {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(body),\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(endpoint, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `HTTP error! status: ${response.status}, body: ${errorText}`\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n}\n\n/**\n * Unwraps tool responses that may be formatted as tuples or content blocks.\n * MCP tools return [content, artifacts], we need to extract the raw data.\n * @param result - The raw result from tool.invoke()\n * @param isMCPTool - Whether this is an MCP tool (has mcp property)\n * @returns Unwrapped raw data (string, object, or parsed JSON)\n */\nexport function unwrapToolResponse(\n result: unknown,\n isMCPTool: boolean\n): unknown {\n // Only unwrap if this is an MCP tool and result is a tuple\n if (!isMCPTool) {\n return result;\n }\n\n /**\n * Checks if a value is a content block object (has type and text).\n */\n const isContentBlock = (value: unknown): boolean => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n return typeof obj.type === 'string';\n };\n\n /**\n * Checks if an array is an array of content blocks.\n */\n const isContentBlockArray = (arr: unknown[]): boolean => {\n return arr.length > 0 && arr.every(isContentBlock);\n };\n\n /**\n * Extracts text from a single content block object.\n * Returns the text if it's a text block, otherwise returns null.\n */\n const extractTextFromBlock = (block: unknown): string | null => {\n if (typeof block !== 'object' || block === null) return null;\n const b = block as Record<string, unknown>;\n if (b.type === 'text' && typeof b.text === 'string') {\n return b.text;\n }\n return null;\n };\n\n /**\n * Extracts text from content blocks (array or single object).\n * Returns combined text or null if no text blocks found.\n */\n const extractTextFromContent = (content: unknown): string | null => {\n // Single content block object: { type: 'text', text: '...' }\n if (\n typeof content === 'object' &&\n content !== null &&\n !Array.isArray(content)\n ) {\n const text = extractTextFromBlock(content);\n if (text !== null) return text;\n }\n\n // Array of content blocks: [{ type: 'text', text: '...' }, ...]\n if (Array.isArray(content) && content.length > 0) {\n const texts = content\n .map(extractTextFromBlock)\n .filter((t): t is string => t !== null);\n if (texts.length > 0) {\n return texts.join('\\n');\n }\n }\n\n return null;\n };\n\n /**\n * Tries to parse a string as JSON if it looks like JSON.\n */\n const maybeParseJSON = (str: string): unknown => {\n const trimmed = str.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return str;\n }\n }\n return str;\n };\n\n // Handle array of content blocks at top level FIRST\n // (before checking for tuple, since both are arrays)\n if (Array.isArray(result) && isContentBlockArray(result)) {\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n }\n\n // Check if result is a tuple/array with [content, artifacts]\n if (Array.isArray(result) && result.length >= 1) {\n const [content] = result;\n\n // If first element is a string, return it (possibly parsed as JSON)\n if (typeof content === 'string') {\n return maybeParseJSON(content);\n }\n\n // Try to extract text from content blocks\n const extractedText = extractTextFromContent(content);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // If first element is an object (but not a text block), return it\n if (typeof content === 'object' && content !== null) {\n return content;\n }\n }\n\n // Handle single content block object at top level (not in tuple)\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // Not a formatted response, return as-is\n return result;\n}\n\n/**\n * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\n * Unwraps formatted responses (e.g., MCP tool tuples) to raw data.\n * @param toolCalls - Array of tool calls from the API\n * @param toolMap - Map of tool names to executable tools\n * @returns Array of tool results\n */\nexport async function executeTools(\n toolCalls: t.PTCToolCall[],\n toolMap: t.ToolMap\n): Promise<t.PTCToolResult[]> {\n const executions = toolCalls.map(async (call): Promise<t.PTCToolResult> => {\n const tool = toolMap.get(call.name);\n\n if (!tool) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,\n };\n }\n\n try {\n const result = await tool.invoke(call.input, {\n metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },\n });\n\n const isMCPTool = tool.mcp === true;\n const unwrappedResult = unwrapToolResponse(result, isMCPTool);\n\n return {\n call_id: call.id,\n result: unwrappedResult,\n is_error: false,\n };\n } catch (error) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: (error as Error).message || 'Tool execution failed',\n };\n }\n });\n\n return await Promise.all(executions);\n}\n\n/**\n * Formats the completed response for the agent.\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse\n): [string, t.ProgrammaticExecutionArtifact] {\n let formatted = '';\n\n if (response.stdout != null && response.stdout !== '') {\n formatted += `stdout:\\n${response.stdout}\\n`;\n } else {\n formatted += emptyOutputMessage;\n }\n\n if (response.stderr != null && response.stderr !== '') {\n formatted += `stderr:\\n${response.stderr}\\n`;\n }\n\n if (response.files && response.files.length > 0) {\n formatted += 'Generated files:\\n';\n\n const fileCount = response.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = response.files[i];\n const isImage = imageExtRegex.test(file.name);\n formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formatted += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formatted += `\\n\\n${accessMessage}`;\n }\n\n return [\n formatted.trim(),\n {\n session_id: response.session_id,\n files: response.files,\n },\n ];\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.\n *\n * This tool enables AI agents to write Python code that orchestrates multiple\n * tool calls programmatically, reducing LLM round-trips and token usage.\n *\n * The tool map must be provided at runtime via config.configurable.toolMap.\n *\n * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({\n * apiKey: process.env.CODE_API_KEY,\n * maxRoundTrips: 20\n * });\n *\n * const [output, artifact] = await ptcTool.invoke(\n * { code, tools },\n * { configurable: { toolMap } }\n * );\n */\nexport function createProgrammaticToolCallingTool(\n initParams: t.ProgrammaticToolCallingParams = {}\n): DynamicStructuredTool {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n return tool(\n async (rawParams, config) => {\n const params = rawParams as { code: string; timeout?: number };\n const { code, timeout = DEFAULT_TIMEOUT } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const { toolMap, toolDefs, session_id, _injected_files } =\n (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache> & {\n session_id?: string;\n _injected_files?: t.CodeEnvFile[];\n };\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n /**\n * File injection priority:\n * 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)\n * 2. Fall back to fetching from /files endpoint if session_id provided but no injected files\n */\n let files: t.CodeEnvFile[] | undefined;\n if (_injected_files && _injected_files.length > 0) {\n files = _injected_files;\n } else if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description: ProgrammaticToolCallingDescription,\n schema: ProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":["config","Constants","HttpsProxyAgent","imageExtRegex","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool"],"mappings":";;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,MAAM,IAAI,KAAK,CACb,CAAA,+BAAA,EAAmC,KAAe,CAAC,OAAO,CAAE,CAAA,CAC7D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEN,eAAS,CAAC,yBAAyB;AACzC,QAAA,WAAW,EAAE,kCAAkC;AAC/C,QAAA,MAAM,EAAE,6BAA6B;QACrC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;;;;;"}
|
|
@@ -460,17 +460,15 @@ function areToolCallsInvoked(message, invokedToolIds) {
|
|
|
460
460
|
return (message.tool_calls?.every((toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)) ?? false);
|
|
461
461
|
}
|
|
462
462
|
function toolsCondition(state, toolNode, invokedToolIds) {
|
|
463
|
-
const
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
463
|
+
const messages = Array.isArray(state) ? state : state.messages;
|
|
464
|
+
const message = messages[messages.length - 1];
|
|
465
|
+
if (message &&
|
|
466
|
+
'tool_calls' in message &&
|
|
467
467
|
(message.tool_calls?.length ?? 0) > 0 &&
|
|
468
468
|
!areToolCallsInvoked(message, invokedToolIds)) {
|
|
469
469
|
return toolNode;
|
|
470
470
|
}
|
|
471
|
-
|
|
472
|
-
return langgraph.END;
|
|
473
|
-
}
|
|
471
|
+
return langgraph.END;
|
|
474
472
|
}
|
|
475
473
|
|
|
476
474
|
exports.ToolNode = ToolNode;
|