@librechat/agents 3.1.88 → 3.1.90
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/graphs/Graph.cjs +25 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/hooks/executeHooks.cjs +14 -7
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +8 -2
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +34 -0
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/main.cjs +9 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/stream.cjs +115 -8
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +10 -9
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +12 -8
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +35 -11
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/CodeSessionFileSummary.cjs +63 -0
- package/dist/cjs/tools/CodeSessionFileSummary.cjs.map +1 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -12
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +32 -12
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +319 -29
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/tools/toolOutputReferences.cjs +8 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
- package/dist/cjs/utils/events.cjs +3 -1
- package/dist/cjs/utils/events.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +25 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/hooks/executeHooks.mjs +14 -7
- package/dist/esm/hooks/executeHooks.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +9 -3
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +33 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/stream.mjs +115 -8
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +11 -10
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +13 -9
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +29 -12
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/CodeSessionFileSummary.mjs +60 -0
- package/dist/esm/tools/CodeSessionFileSummary.mjs.map +1 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -13
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +32 -12
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +320 -31
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/tools/toolOutputReferences.mjs +8 -1
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
- package/dist/esm/utils/events.mjs +3 -1
- package/dist/esm/utils/events.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +8 -0
- package/dist/types/llm/anthropic/index.d.ts +3 -1
- package/dist/types/llm/anthropic/utils/message_inputs.d.ts +4 -0
- package/dist/types/tools/BashExecutor.d.ts +3 -3
- package/dist/types/tools/CodeExecutor.d.ts +10 -3
- package/dist/types/tools/CodeSessionFileSummary.d.ts +3 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +4 -4
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +8 -5
- package/dist/types/types/tools.d.ts +11 -3
- package/dist/types/utils/events.d.ts +1 -1
- package/package.json +1 -1
- package/src/__tests__/stream.eagerEventExecution.test.ts +1073 -221
- package/src/graphs/Graph.ts +27 -5
- package/src/hooks/__tests__/executeHooks.test.ts +38 -0
- package/src/hooks/executeHooks.ts +27 -7
- package/src/llm/anthropic/index.ts +27 -3
- package/src/llm/anthropic/llm.spec.ts +60 -1
- package/src/llm/anthropic/utils/message_inputs.ts +46 -0
- package/src/specs/subagent.test.ts +87 -1
- package/src/stream.ts +163 -12
- package/src/tools/BashExecutor.ts +21 -10
- package/src/tools/BashProgrammaticToolCalling.ts +21 -9
- package/src/tools/CodeExecutor.ts +55 -12
- package/src/tools/CodeSessionFileSummary.ts +80 -0
- package/src/tools/ProgrammaticToolCalling.ts +25 -12
- package/src/tools/ToolNode.ts +142 -116
- package/src/tools/__tests__/BashExecutor.test.ts +9 -0
- package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +43 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +100 -16
- package/src/tools/__tests__/SubagentExecutor.test.ts +540 -6
- package/src/tools/__tests__/ToolNode.eagerEventExecution.test.ts +278 -14
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +52 -0
- package/src/tools/__tests__/subagentHooks.test.ts +237 -0
- package/src/tools/subagent/SubagentExecutor.ts +514 -36
- package/src/types/tools.ts +11 -3
- package/src/utils/events.ts +4 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.mjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport { createHash } from 'node:crypto';\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n type ToolMessage,\n isAIMessage,\n type Data,\n type StandardContentBlockConverter,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicCompactionBlockParam,\n AnthropicToolResponse,\n} from '../types';\nimport { Constants } from '@/common';\n\ntype StandardTextBlock = Data.StandardTextBlock;\ntype StandardImageBlock = Data.StandardImageBlock;\ntype StandardFileBlock = Data.StandardFileBlock;\ntype ImageUrlContentBlock = MessageContentComplex & {\n image_url: string | { url: string };\n};\ntype GoogleFunctionCallBlock = MessageContentComplex & {\n functionCall: {\n name: string;\n args: Record<string, unknown>;\n };\n};\n\nconst ANTHROPIC_EMPTY_TEXT_PLACEHOLDER = '_';\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n}\n\nconst ANTHROPIC_TOOL_USE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\nconst ANTHROPIC_TOOL_USE_ID_MAX_LENGTH = 64;\nconst ANTHROPIC_TOOL_USE_ID_HASH_LENGTH = 10;\n\n/**\n * Normalize a tool-call ID to satisfy Anthropic's `^[a-zA-Z0-9_-]+$` and 64-char\n * constraints. Pure and deterministic — same input always yields the same output,\n * so paired `tool_use.id` and `tool_result.tool_use_id` stay matched without\n * needing a session map. IDs that already comply pass through unchanged.\n *\n * For non-compliant inputs we sanitize then append a short SHA-256 prefix of\n * the original ID to preserve uniqueness when truncation would otherwise\n * collapse distinct IDs to the same value (e.g. two long Responses-style IDs\n * sharing a 64-char prefix). The hash is computed against the raw input so\n * inputs that differ only after the truncation cutoff still produce distinct\n * outputs.\n */\nexport function normalizeAnthropicToolCallId(id: string): string;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined {\n if (id == null) {\n return id;\n }\n if (\n id.length <= ANTHROPIC_TOOL_USE_ID_MAX_LENGTH &&\n ANTHROPIC_TOOL_USE_ID_PATTERN.test(id)\n ) {\n return id;\n }\n const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, '_');\n const hash = createHash('sha256')\n .update(id)\n .digest('hex')\n .slice(0, ANTHROPIC_TOOL_USE_ID_HASH_LENGTH);\n const prefixMaxLength =\n ANTHROPIC_TOOL_USE_ID_MAX_LENGTH - ANTHROPIC_TOOL_USE_ID_HASH_LENGTH - 1;\n return `${sanitized.slice(0, prefixMaxLength)}_${hash}`;\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs: BaseMessage[] = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n const toolMessageContent = (\n message as { content?: BaseMessage['content'] | null }\n ).content;\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n ...(toolMessageContent != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs as (SystemMessage | HumanMessage | AIMessage)[];\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n const isServerTool = toolCall.id.startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n );\n return {\n type: isServerTool ? 'server_tool_use' : 'tool_use',\n id: isServerTool ? toolCall.id : normalizeAnthropicToolCallId(toolCall.id),\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentParts = content as MessageContentComplex[];\n const contentBlocks = contentParts.map((contentPart) => {\n /**\n * Normalize server_tool_use blocks into a clean shape the API accepts.\n * These blocks may arrive with the correct type (server_tool_use) or mislabeled\n * as text/tool_use after chunk concatenation or state serialization.\n * Regardless of current type, if the id starts with 'srvtoolu_' we rebuild\n * a clean block with only the properties the API expects.\n */\n if (\n 'id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).id === 'string' &&\n ((contentPart as Record<string, unknown>).id as string).startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n ) &&\n 'name' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n let input = rawPart.input;\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: rawPart.id as string,\n name: (rawPart.name ?? 'web_search') as 'web_search',\n input: (input ?? {}) as Record<string, unknown>,\n };\n return corrected;\n }\n\n /**\n * Normalize web_search_tool_result blocks into a clean shape.\n * Same rationale as above — the block may carry extra properties from\n * streaming (input, index, etc.) that the API rejects. Rebuild cleanly.\n */\n if (\n 'tool_use_id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).tool_use_id ===\n 'string' &&\n (\n (contentPart as Record<string, unknown>).tool_use_id as string\n ).startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&\n 'content' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const content = rawPart.content;\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: rawPart.tool_use_id as string,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n return null;\n }\n\n /**\n * Skip non-server malformed blocks that have tool fields mixed with text type.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n const imageUrl = (contentPart as ImageUrlContentBlock).image_url;\n if (typeof imageUrl === 'string') {\n source = _formatImage(imageUrl);\n } else {\n source = _formatImage(imageUrl.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const thinkingPart = contentPart as AnthropicThinkingBlockParam;\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: thinkingPart.thinking,\n signature: thinkingPart.signature,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const redactedPart = contentPart as AnthropicRedactedThinkingBlockParam;\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: redactedPart.data,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'search_result') {\n const searchResultPart = contentPart as AnthropicSearchResultBlockParam;\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const,\n title: searchResultPart.title,\n source: searchResultPart.source,\n ...('cache_control' in contentPart &&\n contentPart.cache_control != null\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n content: searchResultPart.content,\n };\n return block;\n } else if (contentPart.type === 'compaction') {\n const compactionPart = contentPart as AnthropicCompactionBlockParam;\n const block: AnthropicCompactionBlockParam = {\n type: 'compaction' as const,\n content: compactionPart.content,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.some((t) => t === contentPart.type) &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.some((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if (\n contentPartCopy.type === 'tool_use' &&\n 'id' in contentPartCopy &&\n typeof contentPartCopy.id === 'string' &&\n contentPartCopy.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n contentPartCopy.type = 'server_tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\n */\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (\n 'functionCall' in contentPart &&\n contentPart.functionCall != null &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const functionCallPart = contentPart as GoogleFunctionCallBlock;\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === functionCallPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${functionCallPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: functionCallPart.functionCall.args,\n };\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n const filteredContentBlocks = contentBlocks.filter(\n (block) =>\n block !== null &&\n !(\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string' &&\n block.text.trim() === ''\n )\n );\n return filteredContentBlocks.length > 0\n ? filteredContentBlocks\n : [{ type: 'text' as const, text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER }];\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n const isAI = isAIMessage(message);\n const toolCalls = isAI ? (message.tool_calls ?? []) : [];\n if (isAI && toolCalls.length > 0) {\n if (typeof message.content === 'string') {\n const clientToolCalls = toolCalls.filter(\n (tc) =>\n !(\n tc.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ?? false\n )\n );\n if (message.content === '') {\n return {\n role,\n content:\n clientToolCalls.length > 0\n ? clientToolCalls.map(_convertLangChainToolCallToAnthropic)\n : [\n {\n type: 'text' as const,\n text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER,\n },\n ],\n };\n } else {\n return {\n role,\n content: [\n { type: 'text' as const, text: message.content },\n ...clientToolCalls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !toolCalls.every(\n (toolCall) =>\n !!content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta' ||\n contentPart.type === 'server_tool_use') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\n if (messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n type ContentBlocks = Exclude<\n AnthropicMessageCreateParams['messages'][number]['content'],\n string\n >;\n const normalizeContent = (\n content: AnthropicMessageCreateParams['messages'][number]['content']\n ): ContentBlocks => {\n if (typeof content === 'string') {\n return [{ type: 'text', text: content }];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AACA;;AAEG;AA8CH,MAAM,gCAAgC,GAAG,GAAG;AAE5C,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAG,kBAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACxD,IAAI,MAAM,EAAE;QACV,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,MAAM,CAAC,SAAS;YAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB;IACH;AACA,IAAA,IAAI,SAAc;AAElB,IAAA,IAAI;AACF,QAAA,SAAS,GAAG,IAAI,GAAG,CAAC,QAAQ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,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC;AACzC,iBAAA;aACF;QACH;aAAO;AACL,YAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;YAC3B,cAAc,GAAG,WAAW;QAC9B;IACF;AAEA,IAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;AAC3B,IAAA,OAAO,MAAM;AACf;;;;"}
|
|
1
|
+
{"version":3,"file":"message_inputs.mjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport { createHash } from 'node:crypto';\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n type ToolMessage,\n isAIMessage,\n type Data,\n type StandardContentBlockConverter,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicCompactionBlockParam,\n AnthropicToolResponse,\n} from '../types';\nimport { Constants } from '@/common';\n\ntype StandardTextBlock = Data.StandardTextBlock;\ntype StandardImageBlock = Data.StandardImageBlock;\ntype StandardFileBlock = Data.StandardFileBlock;\ntype ImageUrlContentBlock = MessageContentComplex & {\n image_url: string | { url: string };\n};\ntype GoogleFunctionCallBlock = MessageContentComplex & {\n functionCall: {\n name: string;\n args: Record<string, unknown>;\n };\n};\n\nconst ANTHROPIC_EMPTY_TEXT_PLACEHOLDER = '_';\nconst CLAUDE_4_RELEASE_DATE_MODEL_PATTERN =\n /claude-(?:opus|sonnet|haiku)-4-\\d{8}(?:[-.@]|$)/i;\nconst CLAUDE_4_MINOR_MODEL_PATTERN =\n /claude-(?:opus|sonnet|haiku)-4[-.](\\d+)(?:[-.@]|$)/i;\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n}\n\nconst ANTHROPIC_TOOL_USE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\nconst ANTHROPIC_TOOL_USE_ID_MAX_LENGTH = 64;\nconst ANTHROPIC_TOOL_USE_ID_HASH_LENGTH = 10;\n\n/**\n * Normalize a tool-call ID to satisfy Anthropic's `^[a-zA-Z0-9_-]+$` and 64-char\n * constraints. Pure and deterministic — same input always yields the same output,\n * so paired `tool_use.id` and `tool_result.tool_use_id` stay matched without\n * needing a session map. IDs that already comply pass through unchanged.\n *\n * For non-compliant inputs we sanitize then append a short SHA-256 prefix of\n * the original ID to preserve uniqueness when truncation would otherwise\n * collapse distinct IDs to the same value (e.g. two long Responses-style IDs\n * sharing a 64-char prefix). The hash is computed against the raw input so\n * inputs that differ only after the truncation cutoff still produce distinct\n * outputs.\n */\nexport function normalizeAnthropicToolCallId(id: string): string;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined {\n if (id == null) {\n return id;\n }\n if (\n id.length <= ANTHROPIC_TOOL_USE_ID_MAX_LENGTH &&\n ANTHROPIC_TOOL_USE_ID_PATTERN.test(id)\n ) {\n return id;\n }\n const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, '_');\n const hash = createHash('sha256')\n .update(id)\n .digest('hex')\n .slice(0, ANTHROPIC_TOOL_USE_ID_HASH_LENGTH);\n const prefixMaxLength =\n ANTHROPIC_TOOL_USE_ID_MAX_LENGTH - ANTHROPIC_TOOL_USE_ID_HASH_LENGTH - 1;\n return `${sanitized.slice(0, prefixMaxLength)}_${hash}`;\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs: BaseMessage[] = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n const toolMessageContent = (\n message as { content?: BaseMessage['content'] | null }\n ).content;\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n ...(toolMessageContent != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs as (SystemMessage | HumanMessage | AIMessage)[];\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n const isServerTool = toolCall.id.startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n );\n return {\n type: isServerTool ? 'server_tool_use' : 'tool_use',\n id: isServerTool ? toolCall.id : normalizeAnthropicToolCallId(toolCall.id),\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentParts = content as MessageContentComplex[];\n const contentBlocks = contentParts.map((contentPart) => {\n /**\n * Normalize server_tool_use blocks into a clean shape the API accepts.\n * These blocks may arrive with the correct type (server_tool_use) or mislabeled\n * as text/tool_use after chunk concatenation or state serialization.\n * Regardless of current type, if the id starts with 'srvtoolu_' we rebuild\n * a clean block with only the properties the API expects.\n */\n if (\n 'id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).id === 'string' &&\n ((contentPart as Record<string, unknown>).id as string).startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n ) &&\n 'name' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n let input = rawPart.input;\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: rawPart.id as string,\n name: (rawPart.name ?? 'web_search') as 'web_search',\n input: (input ?? {}) as Record<string, unknown>,\n };\n return corrected;\n }\n\n /**\n * Normalize web_search_tool_result blocks into a clean shape.\n * Same rationale as above — the block may carry extra properties from\n * streaming (input, index, etc.) that the API rejects. Rebuild cleanly.\n */\n if (\n 'tool_use_id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).tool_use_id ===\n 'string' &&\n (\n (contentPart as Record<string, unknown>).tool_use_id as string\n ).startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&\n 'content' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const content = rawPart.content;\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: rawPart.tool_use_id as string,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n return null;\n }\n\n /**\n * Skip non-server malformed blocks that have tool fields mixed with text type.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n const imageUrl = (contentPart as ImageUrlContentBlock).image_url;\n if (typeof imageUrl === 'string') {\n source = _formatImage(imageUrl);\n } else {\n source = _formatImage(imageUrl.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const thinkingPart = contentPart as AnthropicThinkingBlockParam;\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: thinkingPart.thinking,\n signature: thinkingPart.signature,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const redactedPart = contentPart as AnthropicRedactedThinkingBlockParam;\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: redactedPart.data,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'search_result') {\n const searchResultPart = contentPart as AnthropicSearchResultBlockParam;\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const,\n title: searchResultPart.title,\n source: searchResultPart.source,\n ...('cache_control' in contentPart &&\n contentPart.cache_control != null\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n content: searchResultPart.content,\n };\n return block;\n } else if (contentPart.type === 'compaction') {\n const compactionPart = contentPart as AnthropicCompactionBlockParam;\n const block: AnthropicCompactionBlockParam = {\n type: 'compaction' as const,\n content: compactionPart.content,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.some((t) => t === contentPart.type) &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.some((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if (\n contentPartCopy.type === 'tool_use' &&\n 'id' in contentPartCopy &&\n typeof contentPartCopy.id === 'string' &&\n contentPartCopy.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n contentPartCopy.type = 'server_tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\n */\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (\n 'functionCall' in contentPart &&\n contentPart.functionCall != null &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const functionCallPart = contentPart as GoogleFunctionCallBlock;\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === functionCallPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${functionCallPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: functionCallPart.functionCall.args,\n };\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n const filteredContentBlocks = contentBlocks.filter(\n (block) =>\n block !== null &&\n !(\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string' &&\n block.text.trim() === ''\n )\n );\n return filteredContentBlocks.length > 0\n ? filteredContentBlocks\n : [{ type: 'text' as const, text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER }];\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n const isAI = isAIMessage(message);\n const toolCalls = isAI ? (message.tool_calls ?? []) : [];\n if (isAI && toolCalls.length > 0) {\n if (typeof message.content === 'string') {\n const clientToolCalls = toolCalls.filter(\n (tc) =>\n !(\n tc.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ?? false\n )\n );\n if (message.content === '') {\n return {\n role,\n content:\n clientToolCalls.length > 0\n ? clientToolCalls.map(_convertLangChainToolCallToAnthropic)\n : [\n {\n type: 'text' as const,\n text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER,\n },\n ],\n };\n } else {\n return {\n role,\n content: [\n { type: 'text' as const, text: message.content },\n ...clientToolCalls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !toolCalls.every(\n (toolCall) =>\n !!content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta' ||\n contentPart.type === 'server_tool_use') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nexport function modelDisallowsAssistantPrefill(model?: string): boolean {\n const modelId = model ?? '';\n if (CLAUDE_4_RELEASE_DATE_MODEL_PATTERN.test(modelId)) {\n return false;\n }\n\n const match = CLAUDE_4_MINOR_MODEL_PATTERN.exec(modelId);\n if (!match) {\n return false;\n }\n return Number(match[1]) >= 6;\n}\n\nexport function stripUnsupportedAssistantPrefill<\n T extends Pick<AnthropicMessageCreateParams, 'messages'> & { model?: string },\n>(request: T): T {\n if (!modelDisallowsAssistantPrefill(request.model)) {\n return request;\n }\n\n const messages = request.messages;\n if (\n messages.length <= 1 ||\n messages[messages.length - 1]?.role !== 'assistant'\n ) {\n return request;\n }\n\n const nextMessages = [...messages];\n while (\n nextMessages.length > 1 &&\n nextMessages[nextMessages.length - 1]?.role === 'assistant'\n ) {\n nextMessages.pop();\n }\n\n return {\n ...request,\n messages: nextMessages,\n };\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\n if (messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n type ContentBlocks = Exclude<\n AnthropicMessageCreateParams['messages'][number]['content'],\n string\n >;\n const normalizeContent = (\n content: AnthropicMessageCreateParams['messages'][number]['content']\n ): ContentBlocks => {\n if (typeof content === 'string') {\n return [{ type: 'text', text: content }];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AACA;;AAEG;AA8CH,MAAM,gCAAgC,GAAG,GAAG;AAC5C,MAAM,mCAAmC,GACvC,kDAAkD;AACpD,MAAM,4BAA4B,GAChC,qDAAqD;AAEvD,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAG,kBAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACxD,IAAI,MAAM,EAAE;QACV,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,MAAM,CAAC,SAAS;YAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB;IACH;AACA,IAAA,IAAI,SAAc;AAElB,IAAA,IAAI;AACF,QAAA,SAAS,GAAG,IAAI,GAAG,CAAC,QAA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AAC3B,IAAA,OAAO,MAAM;AACf;;;;"}
|
package/dist/esm/main.mjs
CHANGED
|
@@ -18,7 +18,7 @@ export { Graph, StandardGraph } from './graphs/Graph.mjs';
|
|
|
18
18
|
export { MultiAgentGraph } from './graphs/MultiAgentGraph.mjs';
|
|
19
19
|
export { _resetUnrecognizedTriggerWarnings, shouldTriggerSummarization } from './summarization/index.mjs';
|
|
20
20
|
export { Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName } from './tools/Calculator.mjs';
|
|
21
|
-
export { CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, buildCodeApiHttpErrorMessage, createCodeExecutionTool, emptyOutputMessage, getCodeBaseURL, resolveCodeApiAuthHeaders } from './tools/CodeExecutor.mjs';
|
|
21
|
+
export { BASH_SHELL_GUIDANCE, CODE_ARTIFACT_PATH_GUIDANCE, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, FAILED_EXECUTION_FILE_REMINDER, TMP_SCRATCH_OUTPUT_REMINDER, appendFailedExecutionFileReminder, appendTmpScratchReminder, buildCodeApiHttpErrorMessage, createCodeExecutionTool, emptyOutputMessage, getCodeBaseURL, resolveCodeApiAuthHeaders } from './tools/CodeExecutor.mjs';
|
|
22
22
|
export { BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashToolOutputReferencesGuide, buildBashExecutionToolDescription, createBashExecutionTool } from './tools/BashExecutor.mjs';
|
|
23
23
|
export { ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, executeTools, extractUsedToolNames, fetchSessionFiles, filterToolsByUsage, formatCompletedResponse, makeRequest, normalizeToPythonIdentifier, unwrapToolResponse } from './tools/ProgrammaticToolCalling.mjs';
|
|
24
24
|
export { BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, extractUsedBashToolNames, filterBashToolsByUsage, normalizeToBashIdentifier } from './tools/BashProgrammaticToolCalling.mjs';
|
|
@@ -78,4 +78,5 @@ export { getChatModelClass } from './llm/providers.mjs';
|
|
|
78
78
|
export { initializeModel } from './llm/init.mjs';
|
|
79
79
|
export { attemptInvoke, tryFallbackProviders } from './llm/invoke.mjs';
|
|
80
80
|
export { getMaxOutputTokensKey, isThinkingEnabled } from './llm/request.mjs';
|
|
81
|
+
export { appendCodeSessionFileSummary, stripCodeSessionFileSummary } from './tools/CodeSessionFileSummary.mjs';
|
|
81
82
|
//# sourceMappingURL=main.mjs.map
|
package/dist/esm/main.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -3,10 +3,12 @@ import { handleServerToolResult, handleToolCalls, handleToolCallChunks } from '.
|
|
|
3
3
|
import './messages/core.mjs';
|
|
4
4
|
import { getMessageId } from './messages/ids.mjs';
|
|
5
5
|
import '@langchain/core/messages';
|
|
6
|
+
import { calculateMaxToolResultChars, truncateToolResultContent } from './utils/truncation.mjs';
|
|
6
7
|
import { safeDispatchCustomEvent } from './utils/events.mjs';
|
|
7
8
|
import 'uuid';
|
|
8
9
|
import { normalizeError, buildToolExecutionRequestPlan, coerceRecordArgs } from './tools/eagerEventExecution.mjs';
|
|
9
10
|
import { getStreamedToolCallSeal, getStreamedToolCallAdapter } from './tools/streamedToolCallSeals.mjs';
|
|
11
|
+
import { TOOL_OUTPUT_REF_PATTERN } from './tools/toolOutputReferences.mjs';
|
|
10
12
|
|
|
11
13
|
const LOCAL_CODING_BUNDLE_NAME_SET = new Set(LOCAL_CODING_BUNDLE_NAMES);
|
|
12
14
|
/**
|
|
@@ -57,9 +59,19 @@ function getNonEmptyValue(possibleValues) {
|
|
|
57
59
|
return undefined;
|
|
58
60
|
}
|
|
59
61
|
function isBatchSensitiveToolExecution(graph) {
|
|
60
|
-
return
|
|
61
|
-
|
|
62
|
-
|
|
62
|
+
return graph.hookRegistry != null || graph.humanInTheLoop?.enabled === true;
|
|
63
|
+
}
|
|
64
|
+
function hasToolOutputReference(value) {
|
|
65
|
+
if (typeof value === 'string') {
|
|
66
|
+
return TOOL_OUTPUT_REF_PATTERN.test(value);
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(value)) {
|
|
69
|
+
return value.some((item) => hasToolOutputReference(item));
|
|
70
|
+
}
|
|
71
|
+
if (value !== null && typeof value === 'object') {
|
|
72
|
+
return Object.values(value).some((item) => hasToolOutputReference(item));
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
63
75
|
}
|
|
64
76
|
function isDirectGraphTool(name, agentContext) {
|
|
65
77
|
if (name.startsWith(Constants.LC_TRANSFER_TO_)) {
|
|
@@ -122,7 +134,8 @@ function isEagerToolExecutionEnabledForBatch(args) {
|
|
|
122
134
|
metadata?.[Constants.BASH_PROGRAMMATIC_TOOL_CALLING] === true) {
|
|
123
135
|
return false;
|
|
124
136
|
}
|
|
125
|
-
if (graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null
|
|
137
|
+
if (graph.handlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) == null &&
|
|
138
|
+
graph.eventToolExecutionAvailable !== true) {
|
|
126
139
|
return false;
|
|
127
140
|
}
|
|
128
141
|
return true;
|
|
@@ -159,7 +172,30 @@ function hasPotentialDirectToolInStreamContext(args) {
|
|
|
159
172
|
if ((agentContext?.graphTools?.length ?? 0) > 0) {
|
|
160
173
|
return true;
|
|
161
174
|
}
|
|
162
|
-
return
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
function hasDirectToolCallChunkInBatch(args) {
|
|
178
|
+
const { graph, agentContext, toolCallChunks } = args;
|
|
179
|
+
return (toolCallChunks?.some((toolCallChunk) => toolCallChunk.name != null &&
|
|
180
|
+
toolCallChunk.name !== '' &&
|
|
181
|
+
(isDirectGraphTool(toolCallChunk.name, agentContext) ||
|
|
182
|
+
isDirectLocalTool(toolCallChunk.name, graph))) === true);
|
|
183
|
+
}
|
|
184
|
+
function hasDirectToolCallChunkStateInStep(args) {
|
|
185
|
+
const { graph, agentContext, stepKey } = args;
|
|
186
|
+
const prefix = `${stepKey}\u0000`;
|
|
187
|
+
for (const [key, state] of graph.eagerEventToolCallChunks) {
|
|
188
|
+
if (!key.startsWith(prefix)) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const name = state.name;
|
|
192
|
+
if (name != null &&
|
|
193
|
+
name !== '' &&
|
|
194
|
+
(isDirectGraphTool(name, agentContext) || isDirectLocalTool(name, graph))) {
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return false;
|
|
163
199
|
}
|
|
164
200
|
function createEagerToolExecutionPlan(args) {
|
|
165
201
|
const { graph, metadata, agentContext, toolCalls, skipExisting = false, } = args;
|
|
@@ -173,6 +209,10 @@ function createEagerToolExecutionPlan(args) {
|
|
|
173
209
|
if (hasDirectToolCallInBatch({ graph, agentContext, toolCalls })) {
|
|
174
210
|
return undefined;
|
|
175
211
|
}
|
|
212
|
+
if (graph.toolOutputReferences?.enabled === true &&
|
|
213
|
+
toolCalls.some((toolCall) => hasToolOutputReference(toolCall.args))) {
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
176
216
|
const candidateToolCalls = skipExisting
|
|
177
217
|
? toolCalls.filter((toolCall) => {
|
|
178
218
|
if (toolCall.id == null || toolCall.id === '') {
|
|
@@ -225,6 +265,7 @@ function startEagerToolExecutions(args) {
|
|
|
225
265
|
if (entries == null || entries.length === 0) {
|
|
226
266
|
return;
|
|
227
267
|
}
|
|
268
|
+
const records = [];
|
|
228
269
|
const promise = new Promise((resolve, reject) => {
|
|
229
270
|
let dispatchSettled = false;
|
|
230
271
|
let resultSettled = false;
|
|
@@ -253,17 +294,78 @@ function startEagerToolExecutions(args) {
|
|
|
253
294
|
maybeResolve();
|
|
254
295
|
})
|
|
255
296
|
.catch(reject);
|
|
256
|
-
}).then(
|
|
297
|
+
}).then(async (results) => {
|
|
298
|
+
await dispatchEagerToolCompletions({
|
|
299
|
+
graph,
|
|
300
|
+
agentContext,
|
|
301
|
+
records,
|
|
302
|
+
results,
|
|
303
|
+
});
|
|
304
|
+
return { results };
|
|
305
|
+
}, (error) => ({
|
|
257
306
|
error: normalizeError(error),
|
|
258
307
|
}));
|
|
259
308
|
for (const entry of entries) {
|
|
260
|
-
|
|
309
|
+
const record = {
|
|
261
310
|
toolCallId: entry.id,
|
|
262
311
|
toolName: entry.toolName,
|
|
263
312
|
args: entry.coercedArgs,
|
|
264
313
|
request: entry.request,
|
|
265
314
|
promise,
|
|
266
|
-
}
|
|
315
|
+
};
|
|
316
|
+
records.push(record);
|
|
317
|
+
graph.eagerEventToolExecutions.set(entry.id, record);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
async function dispatchEagerToolCompletions(args) {
|
|
321
|
+
const { graph, agentContext, records, results } = args;
|
|
322
|
+
const recordById = new Map(records.map((record) => [record.toolCallId, record]));
|
|
323
|
+
const maxToolResultChars = agentContext?.maxToolResultChars ??
|
|
324
|
+
calculateMaxToolResultChars(agentContext?.maxContextTokens);
|
|
325
|
+
for (const result of results) {
|
|
326
|
+
const record = recordById.get(result.toolCallId);
|
|
327
|
+
if (record == null) {
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (graph.eagerEventToolExecutions.get(result.toolCallId) !== record) {
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
const stepId = record.request.stepId ??
|
|
334
|
+
graph.toolCallStepIds.get(result.toolCallId) ??
|
|
335
|
+
'';
|
|
336
|
+
if (stepId === '') {
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
const output = result.status === 'error'
|
|
340
|
+
? `Error: ${result.errorMessage ?? 'Unknown error'}\n Please fix your mistakes.`
|
|
341
|
+
: truncateToolResultContent(typeof result.content === 'string'
|
|
342
|
+
? result.content
|
|
343
|
+
: JSON.stringify(result.content), maxToolResultChars);
|
|
344
|
+
try {
|
|
345
|
+
const dispatched = await safeDispatchCustomEvent(GraphEvents.ON_RUN_STEP_COMPLETED, {
|
|
346
|
+
result: {
|
|
347
|
+
id: stepId,
|
|
348
|
+
index: record.request.turn ?? 0,
|
|
349
|
+
type: 'tool_call',
|
|
350
|
+
eager: true,
|
|
351
|
+
tool_call: {
|
|
352
|
+
args: JSON.stringify(record.request.args),
|
|
353
|
+
name: record.toolName,
|
|
354
|
+
id: result.toolCallId,
|
|
355
|
+
output,
|
|
356
|
+
progress: 1,
|
|
357
|
+
},
|
|
358
|
+
},
|
|
359
|
+
}, graph.config);
|
|
360
|
+
if (dispatched === false) {
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
record.completionDispatched = true;
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
// Let ToolNode dispatch the completion through the normal path later.
|
|
367
|
+
console.warn(`[stream] eager completion dispatch failed for toolCallId=${result.toolCallId}:`, error instanceof Error ? error.message : error);
|
|
368
|
+
}
|
|
267
369
|
}
|
|
268
370
|
}
|
|
269
371
|
function getEagerToolChunkKey(stepKey, toolCallChunk) {
|
|
@@ -459,6 +561,8 @@ function getStreamedReadyToolCalls(args) {
|
|
|
459
561
|
function startReadyStreamedEagerToolExecutions(args) {
|
|
460
562
|
const { graph, metadata, agentContext, stepKey, toolCallChunks, seal, allowSequentialSeal, sealAll, } = args;
|
|
461
563
|
if (hasPotentialDirectToolInStreamContext({ graph, agentContext }) ||
|
|
564
|
+
hasDirectToolCallChunkInBatch({ graph, agentContext, toolCallChunks }) ||
|
|
565
|
+
hasDirectToolCallChunkStateInStep({ graph, agentContext, stepKey }) ||
|
|
462
566
|
!isEagerToolExecutionEnabledForBatch({ graph, metadata, agentContext })) {
|
|
463
567
|
return;
|
|
464
568
|
}
|
|
@@ -888,6 +992,9 @@ function createContentAggregator() {
|
|
|
888
992
|
return;
|
|
889
993
|
}
|
|
890
994
|
const existingContent = contentParts[index];
|
|
995
|
+
if (!finalUpdate && existingContent?.tool_call?.progress === 1) {
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
891
998
|
/** When args are a valid object, they are likely already invoked */
|
|
892
999
|
let args = finalUpdate ||
|
|
893
1000
|
typeof existingContent?.tool_call?.args === 'object' ||
|