@librechat/agents 3.1.80-dev.3 → 3.1.80
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/llm/anthropic/utils/message_inputs.cjs +27 -7
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +52 -0
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +27 -8
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +53 -2
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/types/llm/anthropic/utils/message_inputs.d.ts +15 -3
- package/dist/types/llm/vertexai/index.d.ts +29 -0
- package/package.json +10 -5
- package/src/llm/anthropic/utils/message_inputs.ts +58 -7
- package/src/llm/anthropic/utils/tool-id-normalization.test.ts +178 -0
- package/src/llm/vertexai/index.ts +69 -2
- package/src/llm/vertexai/llm.spec.ts +18 -0
- package/src/llm/vertexai/repairUsageMetadata.test.ts +54 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var node_crypto = require('node:crypto');
|
|
3
4
|
var messages = require('@langchain/core/messages');
|
|
4
5
|
var types = require('../types.cjs');
|
|
5
6
|
var _enum = require('../../../common/enum.cjs');
|
|
@@ -42,6 +43,25 @@ function _formatImage(imageUrl) {
|
|
|
42
43
|
'Example: https://example.com/image.jpg',
|
|
43
44
|
].join('\n\n'));
|
|
44
45
|
}
|
|
46
|
+
const ANTHROPIC_TOOL_USE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
|
|
47
|
+
const ANTHROPIC_TOOL_USE_ID_MAX_LENGTH = 64;
|
|
48
|
+
const ANTHROPIC_TOOL_USE_ID_HASH_LENGTH = 10;
|
|
49
|
+
function normalizeAnthropicToolCallId(id) {
|
|
50
|
+
if (id == null) {
|
|
51
|
+
return id;
|
|
52
|
+
}
|
|
53
|
+
if (id.length <= ANTHROPIC_TOOL_USE_ID_MAX_LENGTH &&
|
|
54
|
+
ANTHROPIC_TOOL_USE_ID_PATTERN.test(id)) {
|
|
55
|
+
return id;
|
|
56
|
+
}
|
|
57
|
+
const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
58
|
+
const hash = node_crypto.createHash('sha256')
|
|
59
|
+
.update(id)
|
|
60
|
+
.digest('hex')
|
|
61
|
+
.slice(0, ANTHROPIC_TOOL_USE_ID_HASH_LENGTH);
|
|
62
|
+
const prefixMaxLength = ANTHROPIC_TOOL_USE_ID_MAX_LENGTH - ANTHROPIC_TOOL_USE_ID_HASH_LENGTH - 1;
|
|
63
|
+
return `${sanitized.slice(0, prefixMaxLength)}_${hash}`;
|
|
64
|
+
}
|
|
45
65
|
function _ensureMessageContents(messages$1) {
|
|
46
66
|
// Merge runs of human/tool messages into single human messages with content blocks.
|
|
47
67
|
const updatedMsgs = [];
|
|
@@ -57,7 +77,7 @@ function _ensureMessageContents(messages$1) {
|
|
|
57
77
|
previousMessage.content.push({
|
|
58
78
|
type: 'tool_result',
|
|
59
79
|
content: message.content,
|
|
60
|
-
tool_use_id: message.tool_call_id,
|
|
80
|
+
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id),
|
|
61
81
|
});
|
|
62
82
|
}
|
|
63
83
|
else {
|
|
@@ -67,7 +87,7 @@ function _ensureMessageContents(messages$1) {
|
|
|
67
87
|
{
|
|
68
88
|
type: 'tool_result',
|
|
69
89
|
content: message.content,
|
|
70
|
-
tool_use_id: message.tool_call_id,
|
|
90
|
+
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id),
|
|
71
91
|
},
|
|
72
92
|
],
|
|
73
93
|
}));
|
|
@@ -82,7 +102,7 @@ function _ensureMessageContents(messages$1) {
|
|
|
82
102
|
...(toolMessageContent != null
|
|
83
103
|
? { content: _formatContent(message) }
|
|
84
104
|
: {}),
|
|
85
|
-
tool_use_id: message.tool_call_id,
|
|
105
|
+
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id),
|
|
86
106
|
},
|
|
87
107
|
],
|
|
88
108
|
}));
|
|
@@ -98,11 +118,10 @@ function _convertLangChainToolCallToAnthropic(toolCall) {
|
|
|
98
118
|
if (toolCall.id === undefined) {
|
|
99
119
|
throw new Error('Anthropic requires all tool calls to have an "id".');
|
|
100
120
|
}
|
|
121
|
+
const isServerTool = toolCall.id.startsWith(_enum.Constants.ANTHROPIC_SERVER_TOOL_PREFIX);
|
|
101
122
|
return {
|
|
102
|
-
type:
|
|
103
|
-
|
|
104
|
-
: 'tool_use',
|
|
105
|
-
id: toolCall.id,
|
|
123
|
+
type: isServerTool ? 'server_tool_use' : 'tool_use',
|
|
124
|
+
id: isServerTool ? toolCall.id : normalizeAnthropicToolCallId(toolCall.id),
|
|
106
125
|
name: toolCall.name,
|
|
107
126
|
input: toolCall.args,
|
|
108
127
|
};
|
|
@@ -667,4 +686,5 @@ function mergeMessages(messages) {
|
|
|
667
686
|
|
|
668
687
|
exports._convertLangChainToolCallToAnthropic = _convertLangChainToolCallToAnthropic;
|
|
669
688
|
exports._convertMessagesToAnthropicPayload = _convertMessagesToAnthropicPayload;
|
|
689
|
+
exports.normalizeAnthropicToolCallId = normalizeAnthropicToolCallId;
|
|
670
690
|
//# sourceMappingURL=message_inputs.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.cjs","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 {\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\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: (message as ToolMessage).tool_call_id,\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: (message as ToolMessage).tool_call_id,\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: (message as ToolMessage).tool_call_id,\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 return {\n type: toolCall.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ? 'server_tool_use'\n : 'tool_use',\n id: 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":["parseBase64DataUrl","messages","HumanMessage","Constants","isDataContentBlock","convertToProviderContentBlock","isAnthropicImageBlockParam","isAIMessage"],"mappings":";;;;;;AAAA;AACA;AACA;;AAEG;AA6CH,MAAM,gCAAgC,GAAG,GAAG;AAE5C,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAGA,2BAAkB,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,GA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AC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;AAC3C,QAAA,MAAM,WAAW,GAAG,QAAQ,CAAC,CAAC,CAAC;QAE/B,IACE,mBAAmB,CAAC,cAAc,CAAC;AACnC,YAAA,mBAAmB,CAAC,WAAW,CAAC,EAChC;;AAEA,YAAA,cAAc,GAAG;AACf,gBAAA,GAAG,cAAc;AACjB,gBAAA,OAAO,EAAE;AACP,oBAAA,GAAG,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC;AAC3C,oBAAA,GAAG,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.cjs","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":["parseBase64DataUrl","createHash","messages","HumanMessage","Constants","isDataContentBlock","convertToProviderContentBlock","isAnthropicImageBlockParam","isAIMessage"],"mappings":";;;;;;;AAAA;AACA;AACA;;AAEG;AA8CH,MAAM,gCAAgC,GAAG,GAAG;AAE5C,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAGA,2BAAkB,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,CAAC;IAC/B;AAAE,IAAA,MAAM;QACN,MAAM,IAAI,KAAK,CACb;AACE,YAAA,CAAA,qBAAA,EAAwB,IAAI,CAAC,SAAS,CACpC,QAAQ,CACT,CAAA,6FAAA,CAA+F;YAChG,8CAA8C;YAC9C,wCAAwC;AACzC,SAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;IACH;AAEA,IAAA,IAAI,SAAS,CAAC,QAAQ,KAAK,OAAO,IAAI,SAAS,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACrE,OAAO;AACL,YAAA,IAAI,EAAE,KAAK;AACX,YAAA,GA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AM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QAC1C;AACA,QAAA,OAAO,OAAO;AAChB,IAAA,CAAC;AAED,IAAA,MAAM,mBAAmB,GAAG,CAAC,GAAyB,KAAI;AACxD,QAAA,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM;AAAE,YAAA,OAAO,KAAK;AAErC,QAAA,IAAI,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,EAAE;AACnC,YAAA,OAAO,KAAK;QACd;QAEA,QACE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;AAC1B,YAAA,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,aAAa,CAAC;AAE5D,IAAA,CAAC;AAED,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;AAC3C,QAAA,MAAM,WAAW,GAAG,QAAQ,CAAC,CAAC,CAAC;QAE/B,IACE,mBAAmB,CAAC,cAAc,CAAC;AACnC,YAAA,mBAAmB,CAAC,WAAW,CAAC,EAChC;;AAEA,YAAA,cAAc,GAAG;AACf,gBAAA,GAAG,cAAc;AACjB,gBAAA,OAAO,EAAE;AACP,oBAAA,GAAG,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC;AAC3C,oBAAA,GAAG,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;;;;;;"}
|
|
@@ -4,6 +4,41 @@ var googleGauth = require('@langchain/google-gauth');
|
|
|
4
4
|
var googleCommon = require('@langchain/google-common');
|
|
5
5
|
var messages = require('@langchain/core/messages');
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* `@langchain/google-common`'s `_streamResponseChunks` emits usage on TWO
|
|
9
|
+
* different paths within the same stream:
|
|
10
|
+
*
|
|
11
|
+
* - Streaming chunks set `chunk.generationInfo.usage_metadata` via
|
|
12
|
+
* `responseToUsageMetadata`, which correctly sums
|
|
13
|
+
* `candidatesTokenCount + thoughtsTokenCount` and includes
|
|
14
|
+
* `output_token_details.reasoning`.
|
|
15
|
+
* - The trailing fallback chunk (emitted after the API stream exhausts)
|
|
16
|
+
* attaches its own `chunk.message.usage_metadata` built inline as
|
|
17
|
+
* `output_tokens = candidatesTokenCount` only — dropping
|
|
18
|
+
* `thoughtsTokenCount` and `output_token_details` entirely.
|
|
19
|
+
*
|
|
20
|
+
* After `AIMessageChunk.concat`, only `message.usage_metadata` survives —
|
|
21
|
+
* which is the buggy fallback value. This breaks the documented
|
|
22
|
+
* `total_tokens === input_tokens + output_tokens` invariant and silently
|
|
23
|
+
* undercharges thinking models for reasoning tokens.
|
|
24
|
+
*
|
|
25
|
+
* The repair: track the last `generationInfo.usage_metadata` we see, and
|
|
26
|
+
* when the fallback chunk arrives with its buggy `message.usage_metadata`,
|
|
27
|
+
* replace it with the tracked good value. `CustomChatGoogleGenerativeAI`
|
|
28
|
+
* solves the same problem for the Google API path differently — by
|
|
29
|
+
* overriding `_convertToUsageMetadata`.
|
|
30
|
+
*/
|
|
31
|
+
function repairStreamUsageMetadata(current, generationInfoUsage) {
|
|
32
|
+
if (!current)
|
|
33
|
+
return current;
|
|
34
|
+
if (!generationInfoUsage)
|
|
35
|
+
return current;
|
|
36
|
+
if (generationInfoUsage.total_tokens !== current.total_tokens)
|
|
37
|
+
return current;
|
|
38
|
+
if (generationInfoUsage.output_tokens <= current.output_tokens)
|
|
39
|
+
return current;
|
|
40
|
+
return generationInfoUsage;
|
|
41
|
+
}
|
|
7
42
|
/**
|
|
8
43
|
* Fixes thought signatures on functionCall parts in the formatted Gemini request.
|
|
9
44
|
*
|
|
@@ -392,6 +427,22 @@ class ChatVertexAI extends googleGauth.ChatGoogle {
|
|
|
392
427
|
}
|
|
393
428
|
return params;
|
|
394
429
|
}
|
|
430
|
+
async *_streamResponseChunks(messages$1, options, runManager) {
|
|
431
|
+
let lastGoodUsage;
|
|
432
|
+
for await (const chunk of super._streamResponseChunks(messages$1, options, runManager)) {
|
|
433
|
+
const genUsage = chunk.generationInfo?.usage_metadata;
|
|
434
|
+
if (genUsage) {
|
|
435
|
+
lastGoodUsage = genUsage;
|
|
436
|
+
}
|
|
437
|
+
if (chunk.message instanceof messages.AIMessageChunk) {
|
|
438
|
+
const repaired = repairStreamUsageMetadata(chunk.message.usage_metadata, lastGoodUsage);
|
|
439
|
+
if (repaired !== chunk.message.usage_metadata) {
|
|
440
|
+
chunk.message.usage_metadata = repaired;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
yield chunk;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
395
446
|
buildConnection(fields, client) {
|
|
396
447
|
// Note: buildConnection is called from super() BEFORE this.thinkingConfig is set,
|
|
397
448
|
// so we must read thinkingConfig from `fields` directly.
|
|
@@ -406,4 +457,5 @@ class ChatVertexAI extends googleGauth.ChatGoogle {
|
|
|
406
457
|
}
|
|
407
458
|
|
|
408
459
|
exports.ChatVertexAI = ChatVertexAI;
|
|
460
|
+
exports.repairStreamUsageMetadata = repairStreamUsageMetadata;
|
|
409
461
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../../../../src/llm/vertexai/index.ts"],"sourcesContent":["import { ChatGoogle } from '@langchain/google-gauth';\nimport { ChatConnection } from '@langchain/google-common';\nimport type {\n GeminiContent,\n GeminiRequest,\n GoogleAIModelRequestParams,\n GoogleAbstractedClient,\n} from '@langchain/google-common';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { isAIMessage } from '@langchain/core/messages';\nimport type { GoogleThinkingConfig, VertexAIClientOptions } from '@/types';\n\ntype AdditionalKwargs =\n | undefined\n | (BaseMessage['additional_kwargs'] & {\n signatures?: Array<string | undefined>;\n });\n\n/**\n * Fixes thought signatures on functionCall parts in the formatted Gemini request.\n *\n * `@langchain/google-common` stores signatures as a flat array in\n * `additional_kwargs.signatures` (one per response part) and re-attaches them\n * by index only when `signatures.length === parts.length`. This fails when:\n * - The API omits a signature (length mismatch)\n * - Streaming chunks merge with different part counts\n * - The signature for a functionCall part is an empty string\n *\n * This function correlates each \"model\" content block in the formatted request\n * back to its originating AI message, then re-attaches non-empty signatures\n * that the library failed to apply.\n */\nfunction fixThoughtSignatures(\n contents: GeminiContent[],\n input: BaseMessage[]\n): void {\n // Collect AI messages that have signatures, in order\n const aiMessages = input.filter(\n (msg) =>\n isAIMessage(msg) &&\n Array.isArray((msg.additional_kwargs as AdditionalKwargs)?.signatures) &&\n (msg.additional_kwargs.signatures as string[]).length > 0\n );\n\n // Collect \"model\" content blocks from the formatted request, in order\n const modelContents = contents.filter((c) => c.role === 'model');\n\n // They should correspond 1:1 in order (both derived from the same input sequence)\n const count = Math.min(aiMessages.length, modelContents.length);\n for (let i = 0; i < count; i++) {\n const msg = aiMessages[i];\n const content = modelContents[i];\n const signatures = (msg.additional_kwargs as AdditionalKwargs)?.signatures;\n\n // Collect non-empty signatures that aren't already attached to any part\n const attachedSignatures = new Set(\n content.parts\n .map((p) => p.thoughtSignature)\n .filter((s): s is string => s != null && s !== '')\n );\n const availableSignatures = signatures?.filter(\n (s) => s != null && s !== '' && !attachedSignatures.has(s)\n );\n\n // Assign available signatures to functionCall parts missing one, in order\n let sigIdx = 0;\n for (const part of content.parts) {\n if (\n 'functionCall' in part &&\n (part.thoughtSignature == null || part.thoughtSignature === '') &&\n sigIdx < (availableSignatures?.length ?? 0)\n ) {\n part.thoughtSignature = availableSignatures?.[sigIdx];\n sigIdx++;\n }\n }\n }\n}\n\nclass CustomChatConnection extends ChatConnection<VertexAIClientOptions> {\n thinkingConfig?: GoogleThinkingConfig;\n\n async formatData(\n input: BaseMessage[],\n parameters: GoogleAIModelRequestParams\n ): Promise<unknown> {\n const formattedData = (await super.formatData(\n input,\n parameters\n )) as GeminiRequest;\n if (formattedData.generationConfig?.thinkingConfig?.thinkingBudget === -1) {\n // -1 means \"let the model decide\" - delete the property so the API doesn't receive an invalid value\n if (\n formattedData.generationConfig.thinkingConfig.includeThoughts === false\n ) {\n formattedData.generationConfig.thinkingConfig.includeThoughts = true;\n }\n delete formattedData.generationConfig.thinkingConfig.thinkingBudget;\n }\n if (this.thinkingConfig?.thinkingLevel != null) {\n formattedData.generationConfig ??= {};\n // thinkingLevel and thinkingBudget cannot coexist — the API rejects the request.\n // Remove thinkingBudget when thinkingLevel is set.\n const { thinkingBudget: _, ...existingThinkingConfig } =\n (formattedData.generationConfig.thinkingConfig as\n | Record<string, unknown>\n | undefined) ?? {};\n (\n formattedData.generationConfig as Record<string, unknown>\n ).thinkingConfig = {\n ...existingThinkingConfig,\n thinkingLevel: this.thinkingConfig.thinkingLevel,\n ...(this.thinkingConfig.includeThoughts != null && {\n includeThoughts: this.thinkingConfig.includeThoughts,\n }),\n };\n }\n if (formattedData.contents) {\n fixThoughtSignatures(formattedData.contents, input);\n // gemini-3.1+ models reject role=\"function\"; convert to role=\"user\"\n for (const content of formattedData.contents) {\n if (content.role === 'function') {\n (content as { role: string }).role = 'user';\n }\n }\n }\n return formattedData;\n }\n}\n\n/**\n * Integration with Google Vertex AI chat models.\n *\n * Setup:\n * Install `@langchain/google-vertexai` and set your stringified\n * Vertex AI credentials as an environment variable named `GOOGLE_APPLICATION_CREDENTIALS`.\n *\n * ```bash\n * npm install @langchain/google-vertexai\n * export GOOGLE_APPLICATION_CREDENTIALS=\"path/to/credentials\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_google_vertexai.index.ChatVertexAI.html#constructor.new_ChatVertexAI)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_common_types.GoogleAIBaseLanguageModelCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * tools: [...],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatVertexAI } from '@langchain/google-vertexai';\n *\n * const llm = new ChatVertexAI({\n * model: \"gemini-1.5-pro\",\n * temperature: 0,\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\\nHere's why this is the best translation:\\n\\n* **J'adore** means \\\"I love\\\" and conveys a strong passion.\\n* **Programmer** is the French verb for \\\"to program.\\\"\\n\\nThis translation is natural and idiomatic in French. \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 63,\n * \"total_tokens\": 72\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York City, NY' },\n * id: '33c1c1f47e2f492799c77d2800a43912',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: 'What do you call a cat that loves to bowl?',\n * punchline: 'An alley cat!'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatVertexAI extends ChatGoogle {\n lc_namespace = ['langchain', 'chat_models', 'vertexai'];\n dynamicThinkingBudget = false;\n thinkingConfig?: GoogleThinkingConfig;\n\n static lc_name(): 'LibreChatVertexAI' {\n return 'LibreChatVertexAI';\n }\n\n constructor(model: string, fields?: Omit<VertexAIClientOptions, 'model'>);\n constructor(fields?: VertexAIClientOptions);\n constructor(\n modelOrFields?: string | VertexAIClientOptions,\n params?: Omit<VertexAIClientOptions, 'model'>\n ) {\n const fields =\n typeof modelOrFields === 'string'\n ? { ...(params ?? {}), model: modelOrFields }\n : modelOrFields;\n const dynamicThinkingBudget = fields?.thinkingBudget === -1;\n super({\n ...fields,\n platformType: 'gcp',\n });\n this.dynamicThinkingBudget = dynamicThinkingBudget;\n this.thinkingConfig = fields?.thinkingConfig;\n }\n invocationParams(\n options?: this['ParsedCallOptions'] | undefined\n ): GoogleAIModelRequestParams {\n const params = super.invocationParams(options);\n if (this.dynamicThinkingBudget) {\n params.maxReasoningTokens = -1;\n }\n return params;\n }\n buildConnection(\n fields: VertexAIClientOptions | undefined,\n client: GoogleAbstractedClient\n ): void {\n // Note: buildConnection is called from super() BEFORE this.thinkingConfig is set,\n // so we must read thinkingConfig from `fields` directly.\n const thinkingConfig = fields?.thinkingConfig ?? this.thinkingConfig;\n\n const connection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n connection.thinkingConfig = thinkingConfig;\n this.connection = connection;\n\n const streamedConnection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n streamedConnection.thinkingConfig = thinkingConfig;\n this.streamedConnection = streamedConnection;\n }\n}\n"],"names":["isAIMessage","ChatConnection","ChatGoog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A,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,YAAY,EAAE,KAAK;AACpB,SAAA,CAAC;AACF,QAAA,IAAI,CAAC,qBAAqB,GAAG,qBAAqB;AAClD,QAAA,IAAI,CAAC,cAAc,GAAG,MAAM,EAAE,cAAc;IAC9C;AACA,IAAA,gBAAgB,CACd,OAA+C,EAAA;QAE/C,MAAM,MAAM,GAAG,KAAK,CAAC,gBAAgB,CAAC,OAAO,CAAC;AAC9C,QAAA,IAAI,IAAI,CAAC,qBAAqB,EAAE;AAC9B,YAAA,MAAM,CAAC,kBAAkB,GAAG,EAAE;QAChC;AACA,QAAA,OAAO,MAAM;IACf;IACA,eAAe,CACb,MAAyC,EACzC,MAA8B,EAAA;;;QAI9B,MAAM,cAAc,GAAG,MAAM,EAAE,cAAc,IAAI,IAAI,CAAC,cAAc;QAEpE,MAAM,UAAU,GAAG,IAAI,oBAAoB,CACzC,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,KAAK,CACN;AACD,QAAA,UAAU,CAAC,cAAc,GAAG,cAAc;AAC1C,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;QAE5B,MAAM,kBAAkB,GAAG,IAAI,oBAAoB,CACjD,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,IAAI,CACL;AACD,QAAA,kBAAkB,CAAC,cAAc,GAAG,cAAc;AAClD,QAAA,IAAI,CAAC,kBAAkB,GAAG,kBAAkB;IAC9C;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../../../../src/llm/vertexai/index.ts"],"sourcesContent":["import { ChatGoogle } from '@langchain/google-gauth';\nimport { ChatConnection } from '@langchain/google-common';\nimport type {\n GeminiContent,\n GeminiRequest,\n GoogleAIModelRequestParams,\n GoogleAbstractedClient,\n} from '@langchain/google-common';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport { AIMessageChunk, isAIMessage } from '@langchain/core/messages';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleThinkingConfig, VertexAIClientOptions } from '@/types';\n\n/**\n * `@langchain/google-common`'s `_streamResponseChunks` emits usage on TWO\n * different paths within the same stream:\n *\n * - Streaming chunks set `chunk.generationInfo.usage_metadata` via\n * `responseToUsageMetadata`, which correctly sums\n * `candidatesTokenCount + thoughtsTokenCount` and includes\n * `output_token_details.reasoning`.\n * - The trailing fallback chunk (emitted after the API stream exhausts)\n * attaches its own `chunk.message.usage_metadata` built inline as\n * `output_tokens = candidatesTokenCount` only — dropping\n * `thoughtsTokenCount` and `output_token_details` entirely.\n *\n * After `AIMessageChunk.concat`, only `message.usage_metadata` survives —\n * which is the buggy fallback value. This breaks the documented\n * `total_tokens === input_tokens + output_tokens` invariant and silently\n * undercharges thinking models for reasoning tokens.\n *\n * The repair: track the last `generationInfo.usage_metadata` we see, and\n * when the fallback chunk arrives with its buggy `message.usage_metadata`,\n * replace it with the tracked good value. `CustomChatGoogleGenerativeAI`\n * solves the same problem for the Google API path differently — by\n * overriding `_convertToUsageMetadata`.\n */\nexport function repairStreamUsageMetadata(\n current: UsageMetadata | undefined,\n generationInfoUsage: UsageMetadata | undefined\n): UsageMetadata | undefined {\n if (!current) return current;\n if (!generationInfoUsage) return current;\n if (generationInfoUsage.total_tokens !== current.total_tokens) return current;\n if (generationInfoUsage.output_tokens <= current.output_tokens)\n return current;\n return generationInfoUsage;\n}\n\ntype AdditionalKwargs =\n | undefined\n | (BaseMessage['additional_kwargs'] & {\n signatures?: Array<string | undefined>;\n });\n\n/**\n * Fixes thought signatures on functionCall parts in the formatted Gemini request.\n *\n * `@langchain/google-common` stores signatures as a flat array in\n * `additional_kwargs.signatures` (one per response part) and re-attaches them\n * by index only when `signatures.length === parts.length`. This fails when:\n * - The API omits a signature (length mismatch)\n * - Streaming chunks merge with different part counts\n * - The signature for a functionCall part is an empty string\n *\n * This function correlates each \"model\" content block in the formatted request\n * back to its originating AI message, then re-attaches non-empty signatures\n * that the library failed to apply.\n */\nfunction fixThoughtSignatures(\n contents: GeminiContent[],\n input: BaseMessage[]\n): void {\n // Collect AI messages that have signatures, in order\n const aiMessages = input.filter(\n (msg) =>\n isAIMessage(msg) &&\n Array.isArray((msg.additional_kwargs as AdditionalKwargs)?.signatures) &&\n (msg.additional_kwargs.signatures as string[]).length > 0\n );\n\n // Collect \"model\" content blocks from the formatted request, in order\n const modelContents = contents.filter((c) => c.role === 'model');\n\n // They should correspond 1:1 in order (both derived from the same input sequence)\n const count = Math.min(aiMessages.length, modelContents.length);\n for (let i = 0; i < count; i++) {\n const msg = aiMessages[i];\n const content = modelContents[i];\n const signatures = (msg.additional_kwargs as AdditionalKwargs)?.signatures;\n\n // Collect non-empty signatures that aren't already attached to any part\n const attachedSignatures = new Set(\n content.parts\n .map((p) => p.thoughtSignature)\n .filter((s): s is string => s != null && s !== '')\n );\n const availableSignatures = signatures?.filter(\n (s) => s != null && s !== '' && !attachedSignatures.has(s)\n );\n\n // Assign available signatures to functionCall parts missing one, in order\n let sigIdx = 0;\n for (const part of content.parts) {\n if (\n 'functionCall' in part &&\n (part.thoughtSignature == null || part.thoughtSignature === '') &&\n sigIdx < (availableSignatures?.length ?? 0)\n ) {\n part.thoughtSignature = availableSignatures?.[sigIdx];\n sigIdx++;\n }\n }\n }\n}\n\nclass CustomChatConnection extends ChatConnection<VertexAIClientOptions> {\n thinkingConfig?: GoogleThinkingConfig;\n\n async formatData(\n input: BaseMessage[],\n parameters: GoogleAIModelRequestParams\n ): Promise<unknown> {\n const formattedData = (await super.formatData(\n input,\n parameters\n )) as GeminiRequest;\n if (formattedData.generationConfig?.thinkingConfig?.thinkingBudget === -1) {\n // -1 means \"let the model decide\" - delete the property so the API doesn't receive an invalid value\n if (\n formattedData.generationConfig.thinkingConfig.includeThoughts === false\n ) {\n formattedData.generationConfig.thinkingConfig.includeThoughts = true;\n }\n delete formattedData.generationConfig.thinkingConfig.thinkingBudget;\n }\n if (this.thinkingConfig?.thinkingLevel != null) {\n formattedData.generationConfig ??= {};\n // thinkingLevel and thinkingBudget cannot coexist — the API rejects the request.\n // Remove thinkingBudget when thinkingLevel is set.\n const { thinkingBudget: _, ...existingThinkingConfig } =\n (formattedData.generationConfig.thinkingConfig as\n | Record<string, unknown>\n | undefined) ?? {};\n (\n formattedData.generationConfig as Record<string, unknown>\n ).thinkingConfig = {\n ...existingThinkingConfig,\n thinkingLevel: this.thinkingConfig.thinkingLevel,\n ...(this.thinkingConfig.includeThoughts != null && {\n includeThoughts: this.thinkingConfig.includeThoughts,\n }),\n };\n }\n if (formattedData.contents) {\n fixThoughtSignatures(formattedData.contents, input);\n // gemini-3.1+ models reject role=\"function\"; convert to role=\"user\"\n for (const content of formattedData.contents) {\n if (content.role === 'function') {\n (content as { role: string }).role = 'user';\n }\n }\n }\n return formattedData;\n }\n}\n\n/**\n * Integration with Google Vertex AI chat models.\n *\n * Setup:\n * Install `@langchain/google-vertexai` and set your stringified\n * Vertex AI credentials as an environment variable named `GOOGLE_APPLICATION_CREDENTIALS`.\n *\n * ```bash\n * npm install @langchain/google-vertexai\n * export GOOGLE_APPLICATION_CREDENTIALS=\"path/to/credentials\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/_langchain_google_vertexai.index.ChatVertexAI.html#constructor.new_ChatVertexAI)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_common_types.GoogleAIBaseLanguageModelCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * tools: [...],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatVertexAI } from '@langchain/google-vertexai';\n *\n * const llm = new ChatVertexAI({\n * model: \"gemini-1.5-pro\",\n * temperature: 0,\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\\nHere's why this is the best translation:\\n\\n* **J'adore** means \\\"I love\\\" and conveys a strong passion.\\n* **Programmer** is the French verb for \\\"to program.\\\"\\n\\nThis translation is natural and idiomatic in French. \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 63,\n * \"total_tokens\": 72\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {},\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": []\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"\\\"J'adore programmer\\\" \\n\",\n * \"additional_kwargs\": {},\n * \"response_metadata\": {\n * \"finishReason\": \"stop\"\n * },\n * \"tool_calls\": [],\n * \"tool_call_chunks\": [],\n * \"invalid_tool_calls\": [],\n * \"usage_metadata\": {\n * \"input_tokens\": 9,\n * \"output_tokens\": 8,\n * \"total_tokens\": 17\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York City, NY' },\n * id: '33c1c1f47e2f492799c77d2800a43912',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: 'What do you call a cat that loves to bowl?',\n * punchline: 'An alley cat!'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 9, output_tokens: 8, total_tokens: 17 }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatVertexAI extends ChatGoogle {\n lc_namespace = ['langchain', 'chat_models', 'vertexai'];\n dynamicThinkingBudget = false;\n thinkingConfig?: GoogleThinkingConfig;\n\n static lc_name(): 'LibreChatVertexAI' {\n return 'LibreChatVertexAI';\n }\n\n constructor(model: string, fields?: Omit<VertexAIClientOptions, 'model'>);\n constructor(fields?: VertexAIClientOptions);\n constructor(\n modelOrFields?: string | VertexAIClientOptions,\n params?: Omit<VertexAIClientOptions, 'model'>\n ) {\n const fields =\n typeof modelOrFields === 'string'\n ? { ...(params ?? {}), model: modelOrFields }\n : modelOrFields;\n const dynamicThinkingBudget = fields?.thinkingBudget === -1;\n super({\n ...fields,\n platformType: 'gcp',\n });\n this.dynamicThinkingBudget = dynamicThinkingBudget;\n this.thinkingConfig = fields?.thinkingConfig;\n }\n invocationParams(\n options?: this['ParsedCallOptions'] | undefined\n ): GoogleAIModelRequestParams {\n const params = super.invocationParams(options);\n if (this.dynamicThinkingBudget) {\n params.maxReasoningTokens = -1;\n }\n return params;\n }\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n let lastGoodUsage: UsageMetadata | undefined;\n for await (const chunk of super._streamResponseChunks(\n messages,\n options,\n runManager\n )) {\n const genUsage = (\n chunk.generationInfo as { usage_metadata?: UsageMetadata } | undefined\n )?.usage_metadata;\n if (genUsage) {\n lastGoodUsage = genUsage;\n }\n if (chunk.message instanceof AIMessageChunk) {\n const repaired = repairStreamUsageMetadata(\n chunk.message.usage_metadata,\n lastGoodUsage\n );\n if (repaired !== chunk.message.usage_metadata) {\n chunk.message.usage_metadata = repaired;\n }\n }\n yield chunk;\n }\n }\n buildConnection(\n fields: VertexAIClientOptions | undefined,\n client: GoogleAbstractedClient\n ): void {\n // Note: buildConnection is called from super() BEFORE this.thinkingConfig is set,\n // so we must read thinkingConfig from `fields` directly.\n const thinkingConfig = fields?.thinkingConfig ?? this.thinkingConfig;\n\n const connection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n connection.thinkingConfig = thinkingConfig;\n this.connection = connection;\n\n const streamedConnection = new CustomChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n streamedConnection.thinkingConfig = thinkingConfig;\n this.streamedConnection = streamedConnection;\n }\n}\n"],"names":["isAIMessage","ChatConnection","ChatGoogle","messages","AIMessageChunk"],"mappings":";;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;AAuBG;AACG,SAAU,yBAAyB,CACvC,OAAkC,EAClC,mBAA8C,EAAA;AAE9C,IAAA,IAAI,CAAC,OAAO;AAAE,QAAA,OAAO,OAAO;AAC5B,IAAA,IAAI,CAAC,mBAAmB;AAAE,QAAA,OAAO,OAAO;AACxC,IAAA,IAAI,mBAAmB,CAAC,YAAY,KAAK,OAAO,CAAC,YAAY;AAAE,QAAA,OAAO,OAAO;AAC7E,IAAA,IAAI,mBAAmB,CAAC,aAAa,IAAI,OAAO,CAAC,aAAa;AAC5D,QAAA,OAAO,OAAO;AAChB,IAAA,OAAO,mBAAmB;AAC5B;AAQA;;;;;;;;;;;;;AAaG;AACH,SAAS,oBAAoB,CAC3B,QAAyB,EACzB,KAAoB,EAAA;;AAGpB,IAAA,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,CAC7B,CAAC,GAAG,KACFA,oBAAW,CAAC,GAAG,CAAC;QAChB,KAAK,CAAC,OAAO,CAAE,GAAG,CAAC,iBAAsC,EAAE,UAAU,CAAC;QACrE,GAAG,CAAC,iBAAiB,CAAC,UAAuB,CAAC,MAAM,GAAG,CAAC,CAC5D;;AAGD,IAAA,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC;;AAGhE,IAAA,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC;AAC/D,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,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;AACD,YAAA,MAAM,QAAQ,GACZ,KAAK,CAAC,cACP,EAAE,cAAc;YACjB,IAAI,QAAQ,EAAE;gBACZ,aAAa,GAAG,QAAQ;YAC1B;AACA,YAAA,IAAI,KAAK,CAAC,OAAO,YAAYC,uBAAc,EAAE;AAC3C,gBAAA,MAAM,QAAQ,GAAG,yBAAyB,CACxC,KAAK,CAAC,OAAO,CAAC,cAAc,EAC5B,aAAa,CACd;gBACD,IAAI,QAAQ,KAAK,KAAK,CAAC,OAAO,CAAC,cAAc,EAAE;AAC7C,oBAAA,KAAK,CAAC,OAAO,CAAC,cAAc,GAAG,QAAQ;gBACzC;YACF;AACA,YAAA,MAAM,KAAK;QACb;IACF;IACA,eAAe,CACb,MAAyC,EACzC,MAA8B,EAAA;;;QAI9B,MAAM,cAAc,GAAG,MAAM,EAAE,cAAc,IAAI,IAAI,CAAC,cAAc;QAEpE,MAAM,UAAU,GAAG,IAAI,oBAAoB,CACzC,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,KAAK,CACN;AACD,QAAA,UAAU,CAAC,cAAc,GAAG,cAAc;AAC1C,QAAA,IAAI,CAAC,UAAU,GAAG,UAAU;QAE5B,MAAM,kBAAkB,GAAG,IAAI,oBAAoB,CACjD,EAAE,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,EACtB,IAAI,CAAC,MAAM,EACX,MAAM,EACN,IAAI,CACL;AACD,QAAA,kBAAkB,CAAC,cAAc,GAAG,cAAc;AAClD,QAAA,IAAI,CAAC,kBAAkB,GAAG,kBAAkB;IAC9C;AACD;;;;;"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
1
2
|
import { isAIMessage, HumanMessage, isDataContentBlock, convertToProviderContentBlock, parseBase64DataUrl } from '@langchain/core/messages';
|
|
2
3
|
import { isAnthropicImageBlockParam } from '../types.mjs';
|
|
3
4
|
import { Constants } from '../../../common/enum.mjs';
|
|
@@ -40,6 +41,25 @@ function _formatImage(imageUrl) {
|
|
|
40
41
|
'Example: https://example.com/image.jpg',
|
|
41
42
|
].join('\n\n'));
|
|
42
43
|
}
|
|
44
|
+
const ANTHROPIC_TOOL_USE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
|
|
45
|
+
const ANTHROPIC_TOOL_USE_ID_MAX_LENGTH = 64;
|
|
46
|
+
const ANTHROPIC_TOOL_USE_ID_HASH_LENGTH = 10;
|
|
47
|
+
function normalizeAnthropicToolCallId(id) {
|
|
48
|
+
if (id == null) {
|
|
49
|
+
return id;
|
|
50
|
+
}
|
|
51
|
+
if (id.length <= ANTHROPIC_TOOL_USE_ID_MAX_LENGTH &&
|
|
52
|
+
ANTHROPIC_TOOL_USE_ID_PATTERN.test(id)) {
|
|
53
|
+
return id;
|
|
54
|
+
}
|
|
55
|
+
const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
56
|
+
const hash = createHash('sha256')
|
|
57
|
+
.update(id)
|
|
58
|
+
.digest('hex')
|
|
59
|
+
.slice(0, ANTHROPIC_TOOL_USE_ID_HASH_LENGTH);
|
|
60
|
+
const prefixMaxLength = ANTHROPIC_TOOL_USE_ID_MAX_LENGTH - ANTHROPIC_TOOL_USE_ID_HASH_LENGTH - 1;
|
|
61
|
+
return `${sanitized.slice(0, prefixMaxLength)}_${hash}`;
|
|
62
|
+
}
|
|
43
63
|
function _ensureMessageContents(messages) {
|
|
44
64
|
// Merge runs of human/tool messages into single human messages with content blocks.
|
|
45
65
|
const updatedMsgs = [];
|
|
@@ -55,7 +75,7 @@ function _ensureMessageContents(messages) {
|
|
|
55
75
|
previousMessage.content.push({
|
|
56
76
|
type: 'tool_result',
|
|
57
77
|
content: message.content,
|
|
58
|
-
tool_use_id: message.tool_call_id,
|
|
78
|
+
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id),
|
|
59
79
|
});
|
|
60
80
|
}
|
|
61
81
|
else {
|
|
@@ -65,7 +85,7 @@ function _ensureMessageContents(messages) {
|
|
|
65
85
|
{
|
|
66
86
|
type: 'tool_result',
|
|
67
87
|
content: message.content,
|
|
68
|
-
tool_use_id: message.tool_call_id,
|
|
88
|
+
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id),
|
|
69
89
|
},
|
|
70
90
|
],
|
|
71
91
|
}));
|
|
@@ -80,7 +100,7 @@ function _ensureMessageContents(messages) {
|
|
|
80
100
|
...(toolMessageContent != null
|
|
81
101
|
? { content: _formatContent(message) }
|
|
82
102
|
: {}),
|
|
83
|
-
tool_use_id: message.tool_call_id,
|
|
103
|
+
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id),
|
|
84
104
|
},
|
|
85
105
|
],
|
|
86
106
|
}));
|
|
@@ -96,11 +116,10 @@ function _convertLangChainToolCallToAnthropic(toolCall) {
|
|
|
96
116
|
if (toolCall.id === undefined) {
|
|
97
117
|
throw new Error('Anthropic requires all tool calls to have an "id".');
|
|
98
118
|
}
|
|
119
|
+
const isServerTool = toolCall.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX);
|
|
99
120
|
return {
|
|
100
|
-
type:
|
|
101
|
-
|
|
102
|
-
: 'tool_use',
|
|
103
|
-
id: toolCall.id,
|
|
121
|
+
type: isServerTool ? 'server_tool_use' : 'tool_use',
|
|
122
|
+
id: isServerTool ? toolCall.id : normalizeAnthropicToolCallId(toolCall.id),
|
|
104
123
|
name: toolCall.name,
|
|
105
124
|
input: toolCall.args,
|
|
106
125
|
};
|
|
@@ -663,5 +682,5 @@ function mergeMessages(messages) {
|
|
|
663
682
|
return result;
|
|
664
683
|
}
|
|
665
684
|
|
|
666
|
-
export { _convertLangChainToolCallToAnthropic, _convertMessagesToAnthropicPayload };
|
|
685
|
+
export { _convertLangChainToolCallToAnthropic, _convertMessagesToAnthropicPayload, normalizeAnthropicToolCallId };
|
|
667
686
|
//# sourceMappingURL=message_inputs.mjs.map
|