@librechat/agents 3.1.33 → 3.1.35
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/index.cjs +43 -11
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +10 -7
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +32 -0
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +115 -55
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +465 -0
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -0
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +155 -0
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -0
- package/dist/cjs/messages/core.cjs +3 -0
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +43 -11
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +10 -7
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +32 -0
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +114 -54
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +460 -0
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -0
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs +150 -0
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -0
- package/dist/esm/messages/core.mjs +3 -0
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/types/llm/anthropic/index.d.ts +7 -1
- package/dist/types/llm/anthropic/types.d.ts +5 -2
- package/dist/types/llm/anthropic/utils/message_outputs.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +29 -21
- package/package.json +4 -1
- package/src/llm/anthropic/index.ts +68 -15
- package/src/llm/anthropic/llm.spec.ts +402 -0
- package/src/llm/anthropic/types.ts +8 -2
- package/src/llm/anthropic/utils/message_inputs.ts +16 -33
- package/src/llm/anthropic/utils/message_outputs.ts +40 -1
- package/src/llm/bedrock/index.ts +147 -65
- package/src/llm/bedrock/llm.spec.ts +86 -11
- package/src/messages/core.ts +5 -0
- package/src/scripts/bedrock-merge-test.ts +107 -0
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.ts +165 -0
- package/src/utils/llmConfig.ts +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/llm/bedrock/index.ts"],"sourcesContent":["/**\n * Optimized ChatBedrockConverse wrapper that fixes contentBlockIndex conflicts\n * and adds support for latest @langchain/aws features:\n *\n * - Application Inference Profiles (PR #9129)\n * - Service Tiers (Priority/Standard/Flex) (PR #9785) - requires AWS SDK 3.966.0+\n *\n * Bedrock sends the same contentBlockIndex for both text and tool_use content blocks,\n * causing LangChain's merge logic to fail with \"field[contentBlockIndex] already exists\"\n * errors. This wrapper simply strips contentBlockIndex from response_metadata to avoid\n * the conflict.\n *\n * The contentBlockIndex field is only used internally by Bedrock's streaming protocol\n * and isn't needed by application logic - the index field on tool_call_chunks serves\n * the purpose of tracking tool call ordering.\n */\n\nimport { ChatBedrockConverse } from '@langchain/aws';\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { ChatBedrockConverseInput } from '@langchain/aws';\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Service tier type for Bedrock invocations.\n * Requires AWS SDK >= 3.966.0 to actually work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\nexport type ServiceTierType = 'priority' | 'default' | 'flex' | 'reserved';\n\n/**\n * Extended input interface with additional features:\n * - applicationInferenceProfile: Use an inference profile ARN instead of model ID\n * - serviceTier: Specify service tier (Priority, Standard, Flex, Reserved)\n */\nexport interface CustomChatBedrockConverseInput\n extends ChatBedrockConverseInput {\n /**\n * Application Inference Profile ARN to use for the model.\n * For example, \"arn:aws:bedrock:eu-west-1:123456789102:application-inference-profile/fm16bt65tzgx\"\n * When provided, this ARN will be used for the actual inference calls instead of the model ID.\n * Must still provide `model` as normal modelId to benefit from all the metadata.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-create.html\n */\n applicationInferenceProfile?: string;\n\n /**\n * Service tier for model invocation.\n * Specifies the processing tier type used for serving the request.\n * Supported values are 'priority', 'default', 'flex', and 'reserved'.\n *\n * - 'priority': Prioritized processing for lower latency\n * - 'default': Standard processing tier\n * - 'flex': Flexible processing tier with lower cost\n * - 'reserved': Reserved capacity for consistent performance\n *\n * If not provided, AWS uses the default tier.\n * Note: Requires AWS SDK >= 3.966.0 to work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\n serviceTier?: ServiceTierType;\n}\n\n/**\n * Extended call options with serviceTier override support.\n */\nexport interface CustomChatBedrockConverseCallOptions {\n serviceTier?: ServiceTierType;\n}\n\nexport class CustomChatBedrockConverse extends ChatBedrockConverse {\n /**\n * Application Inference Profile ARN to use instead of model ID.\n */\n applicationInferenceProfile?: string;\n\n /**\n * Service tier for model invocation.\n */\n serviceTier?: ServiceTierType;\n\n constructor(fields?: CustomChatBedrockConverseInput) {\n super(fields);\n this.applicationInferenceProfile = fields?.applicationInferenceProfile;\n this.serviceTier = fields?.serviceTier;\n }\n\n static lc_name(): string {\n return 'LibreChatBedrockConverse';\n }\n\n /**\n * Get the model ID to use for API calls.\n * Returns applicationInferenceProfile if set, otherwise returns this.model.\n */\n protected getModelId(): string {\n return this.applicationInferenceProfile ?? this.model;\n }\n\n /**\n * Override invocationParams to add serviceTier support.\n */\n override invocationParams(\n options?: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions\n ): ReturnType<ChatBedrockConverse['invocationParams']> & {\n serviceTier?: { type: ServiceTierType };\n } {\n const baseParams = super.invocationParams(options);\n\n /** Service tier from options or fall back to class-level setting */\n const serviceTierType = options?.serviceTier ?? this.serviceTier;\n\n return {\n ...baseParams,\n serviceTier: serviceTierType ? { type: serviceTierType } : undefined,\n };\n }\n\n /**\n * Override _generateNonStreaming to use applicationInferenceProfile as modelId.\n * Uses the same model-swapping pattern as streaming for consistency.\n */\n override async _generateNonStreaming(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n // Temporarily swap model for applicationInferenceProfile support\n const originalModel = this.model;\n if (\n this.applicationInferenceProfile != null &&\n this.applicationInferenceProfile !== ''\n ) {\n this.model = this.applicationInferenceProfile;\n }\n\n try {\n return await super._generateNonStreaming(messages, options, runManager);\n } finally {\n // Restore original model\n this.model = originalModel;\n }\n }\n\n /**\n * Override _streamResponseChunks to:\n * 1. Use applicationInferenceProfile as modelId (by temporarily swapping this.model)\n * 2. Strip contentBlockIndex from response_metadata to prevent merge conflicts\n *\n * Note: We delegate to super._streamResponseChunks() to preserve @langchain/aws's\n * internal chunk handling which correctly preserves array content for reasoning blocks.\n */\n override async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n // Temporarily swap model for applicationInferenceProfile support\n const originalModel = this.model;\n if (\n this.applicationInferenceProfile != null &&\n this.applicationInferenceProfile !== ''\n ) {\n this.model = this.applicationInferenceProfile;\n }\n\n try {\n // Use parent's streaming logic which correctly handles reasoning content\n const baseStream = super._streamResponseChunks(\n messages,\n options,\n runManager\n );\n\n for await (const chunk of baseStream) {\n // Clean contentBlockIndex from response_metadata to prevent merge conflicts\n yield this.cleanChunk(chunk);\n }\n } finally {\n // Restore original model\n this.model = originalModel;\n }\n }\n\n /**\n * Clean a chunk by removing contentBlockIndex from response_metadata.\n */\n private cleanChunk(chunk: ChatGenerationChunk): ChatGenerationChunk {\n const message = chunk.message;\n if (!(message instanceof AIMessageChunk)) {\n return chunk;\n }\n\n const metadata = message.response_metadata as Record<string, unknown>;\n const hasContentBlockIndex = this.hasContentBlockIndex(metadata);\n if (!hasContentBlockIndex) {\n return chunk;\n }\n\n const cleanedMetadata = this.removeContentBlockIndex(metadata) as Record<\n string,\n unknown\n >;\n\n return new ChatGenerationChunk({\n text: chunk.text,\n message: new AIMessageChunk({\n ...message,\n response_metadata: cleanedMetadata,\n }),\n generationInfo: chunk.generationInfo,\n });\n }\n\n /**\n * Check if contentBlockIndex exists at any level in the object\n */\n private hasContentBlockIndex(obj: unknown): boolean {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return false;\n }\n\n if ('contentBlockIndex' in obj) {\n return true;\n }\n\n for (const value of Object.values(obj)) {\n if (typeof value === 'object' && value !== null) {\n if (this.hasContentBlockIndex(value)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Recursively remove contentBlockIndex from all levels of an object\n */\n private removeContentBlockIndex(obj: unknown): unknown {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => this.removeContentBlockIndex(item));\n }\n\n if (typeof obj === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (key !== 'contentBlockIndex') {\n cleaned[key] = this.removeContentBlockIndex(value);\n }\n }\n return cleaned;\n }\n\n return obj;\n }\n}\n\nexport type { ChatBedrockConverseInput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/bedrock/index.ts"],"sourcesContent":["/**\n * Optimized ChatBedrockConverse wrapper that fixes content block merging for\n * streaming responses and adds support for latest @langchain/aws features:\n *\n * - Application Inference Profiles (PR #9129)\n * - Service Tiers (Priority/Standard/Flex) (PR #9785) - requires AWS SDK 3.966.0+\n *\n * Bedrock's `@langchain/aws` library does not include an `index` property on content\n * blocks (unlike Anthropic/OpenAI), which causes LangChain's `_mergeLists` to append\n * each streaming chunk as a separate array entry instead of merging by index.\n *\n * This wrapper takes full ownership of the stream by directly interfacing with the\n * AWS SDK client (`this.client`) and using custom handlers from `./utils/` that\n * include `contentBlockIndex` in response_metadata for every delta type. It then\n * promotes `contentBlockIndex` to an `index` property on each content block\n * (mirroring Anthropic's pattern) and strips it from metadata to avoid\n * `_mergeDicts` conflicts.\n *\n * When multiple content block types are present (e.g. reasoning + text), text deltas\n * are promoted from strings to array form with `index` so they merge correctly once\n * the accumulated content is already an array.\n */\n\nimport { ChatBedrockConverse } from '@langchain/aws';\nimport { ConverseStreamCommand } from '@aws-sdk/client-bedrock-runtime';\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { ChatBedrockConverseInput } from '@langchain/aws';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport {\n convertToConverseMessages,\n handleConverseStreamContentBlockStart,\n handleConverseStreamContentBlockDelta,\n handleConverseStreamMetadata,\n} from './utils';\n\n/**\n * Service tier type for Bedrock invocations.\n * Requires AWS SDK >= 3.966.0 to actually work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\nexport type ServiceTierType = 'priority' | 'default' | 'flex' | 'reserved';\n\n/**\n * Extended input interface with additional features:\n * - applicationInferenceProfile: Use an inference profile ARN instead of model ID\n * - serviceTier: Specify service tier (Priority, Standard, Flex, Reserved)\n */\nexport interface CustomChatBedrockConverseInput\n extends ChatBedrockConverseInput {\n /**\n * Application Inference Profile ARN to use for the model.\n * For example, \"arn:aws:bedrock:eu-west-1:123456789102:application-inference-profile/fm16bt65tzgx\"\n * When provided, this ARN will be used for the actual inference calls instead of the model ID.\n * Must still provide `model` as normal modelId to benefit from all the metadata.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-create.html\n */\n applicationInferenceProfile?: string;\n\n /**\n * Service tier for model invocation.\n * Specifies the processing tier type used for serving the request.\n * Supported values are 'priority', 'default', 'flex', and 'reserved'.\n *\n * - 'priority': Prioritized processing for lower latency\n * - 'default': Standard processing tier\n * - 'flex': Flexible processing tier with lower cost\n * - 'reserved': Reserved capacity for consistent performance\n *\n * If not provided, AWS uses the default tier.\n * Note: Requires AWS SDK >= 3.966.0 to work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\n serviceTier?: ServiceTierType;\n}\n\n/**\n * Extended call options with serviceTier override support.\n */\nexport interface CustomChatBedrockConverseCallOptions {\n serviceTier?: ServiceTierType;\n}\n\nexport class CustomChatBedrockConverse extends ChatBedrockConverse {\n /**\n * Application Inference Profile ARN to use instead of model ID.\n */\n applicationInferenceProfile?: string;\n\n /**\n * Service tier for model invocation.\n */\n serviceTier?: ServiceTierType;\n\n constructor(fields?: CustomChatBedrockConverseInput) {\n super(fields);\n this.applicationInferenceProfile = fields?.applicationInferenceProfile;\n this.serviceTier = fields?.serviceTier;\n }\n\n static lc_name(): string {\n return 'LibreChatBedrockConverse';\n }\n\n /**\n * Get the model ID to use for API calls.\n * Returns applicationInferenceProfile if set, otherwise returns this.model.\n */\n protected getModelId(): string {\n return this.applicationInferenceProfile ?? this.model;\n }\n\n /**\n * Override invocationParams to add serviceTier support.\n */\n override invocationParams(\n options?: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions\n ): ReturnType<ChatBedrockConverse['invocationParams']> & {\n serviceTier?: { type: ServiceTierType };\n } {\n const baseParams = super.invocationParams(options);\n\n /** Service tier from options or fall back to class-level setting */\n const serviceTierType = options?.serviceTier ?? this.serviceTier;\n\n return {\n ...baseParams,\n serviceTier: serviceTierType ? { type: serviceTierType } : undefined,\n };\n }\n\n /**\n * Override _generateNonStreaming to use applicationInferenceProfile as modelId.\n * Uses the same model-swapping pattern as streaming for consistency.\n */\n override async _generateNonStreaming(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const originalModel = this.model;\n if (\n this.applicationInferenceProfile != null &&\n this.applicationInferenceProfile !== ''\n ) {\n this.model = this.applicationInferenceProfile;\n }\n\n try {\n return await super._generateNonStreaming(messages, options, runManager);\n } finally {\n this.model = originalModel;\n }\n }\n\n /**\n * Own the stream end-to-end so we have direct access to every\n * `contentBlockDelta.contentBlockIndex` from the AWS SDK.\n *\n * This replaces the parent's implementation which strips contentBlockIndex\n * from text and reasoning deltas, making it impossible to merge correctly.\n */\n override async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const { converseMessages, converseSystem } =\n convertToConverseMessages(messages);\n const params = this.invocationParams(options);\n\n let { streamUsage } = this;\n if ((options as Record<string, unknown>).streamUsage !== undefined) {\n streamUsage = (options as Record<string, unknown>).streamUsage as boolean;\n }\n\n const modelId = this.getModelId();\n\n const command = new ConverseStreamCommand({\n modelId,\n messages: converseMessages,\n system: converseSystem,\n ...(params as Record<string, unknown>),\n });\n\n const response = await this.client.send(command, {\n abortSignal: options.signal,\n });\n\n if (!response.stream) {\n return;\n }\n\n const seenBlockIndices = new Set<number>();\n\n for await (const event of response.stream) {\n if (event.contentBlockStart != null) {\n const startChunk = handleConverseStreamContentBlockStart(\n event.contentBlockStart\n );\n if (startChunk != null) {\n const idx = event.contentBlockStart.contentBlockIndex;\n if (idx != null) {\n seenBlockIndices.add(idx);\n }\n yield this.enrichChunk(startChunk, seenBlockIndices);\n }\n } else if (event.contentBlockDelta != null) {\n const deltaChunk = handleConverseStreamContentBlockDelta(\n event.contentBlockDelta\n );\n\n const idx = event.contentBlockDelta.contentBlockIndex;\n if (idx != null) {\n seenBlockIndices.add(idx);\n }\n\n yield this.enrichChunk(deltaChunk, seenBlockIndices);\n\n await runManager?.handleLLMNewToken(\n deltaChunk.text,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: deltaChunk }\n );\n } else if (event.metadata != null) {\n yield handleConverseStreamMetadata(event.metadata, { streamUsage });\n } else if (event.contentBlockStop != null) {\n const stopIdx = event.contentBlockStop.contentBlockIndex;\n if (stopIdx != null) {\n seenBlockIndices.add(stopIdx);\n }\n } else {\n yield new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n response_metadata: event,\n }),\n });\n }\n }\n }\n\n /**\n * Inject `index` on content blocks for proper merge behaviour, then strip\n * `contentBlockIndex` from response_metadata to prevent `_mergeDicts` conflicts.\n *\n * Text string content is promoted to array form only when the stream contains\n * multiple content block indices (e.g. reasoning at index 0, text at index 1),\n * ensuring text merges correctly with the already-array accumulated content.\n */\n private enrichChunk(\n chunk: ChatGenerationChunk,\n seenBlockIndices: Set<number>\n ): ChatGenerationChunk {\n const message = chunk.message;\n if (!(message instanceof AIMessageChunk)) {\n return chunk;\n }\n\n const metadata = message.response_metadata as Record<string, unknown>;\n const blockIndex = this.extractContentBlockIndex(metadata);\n const hasMetadataIndex = blockIndex != null;\n\n let content: AIMessageChunk['content'] = message.content;\n let contentModified = false;\n\n if (Array.isArray(content) && blockIndex != null) {\n content = content.map((block) =>\n typeof block === 'object' && !('index' in block)\n ? { ...block, index: blockIndex }\n : block\n );\n contentModified = true;\n } else if (\n typeof content === 'string' &&\n content !== '' &&\n blockIndex != null &&\n seenBlockIndices.size > 1\n ) {\n content = [{ type: 'text', text: content, index: blockIndex }];\n contentModified = true;\n }\n\n if (!contentModified && !hasMetadataIndex) {\n return chunk;\n }\n\n const cleanedMetadata = hasMetadataIndex\n ? (this.removeContentBlockIndex(metadata) as Record<string, unknown>)\n : metadata;\n\n return new ChatGenerationChunk({\n text: chunk.text,\n message: new AIMessageChunk({\n ...message,\n content,\n response_metadata: cleanedMetadata,\n }),\n generationInfo: chunk.generationInfo,\n });\n }\n\n /**\n * Extract `contentBlockIndex` from the top level of response_metadata.\n * Our custom handlers always place it at the top level.\n */\n private extractContentBlockIndex(\n metadata: Record<string, unknown>\n ): number | undefined {\n if (\n 'contentBlockIndex' in metadata &&\n typeof metadata.contentBlockIndex === 'number'\n ) {\n return metadata.contentBlockIndex;\n }\n return undefined;\n }\n\n private removeContentBlockIndex(obj: unknown): unknown {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => this.removeContentBlockIndex(item));\n }\n\n if (typeof obj === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (key !== 'contentBlockIndex') {\n cleaned[key] = this.removeContentBlockIndex(value);\n }\n }\n return cleaned;\n }\n\n return obj;\n }\n}\n\nexport type { ChatBedrockConverseInput };\n"],"names":[],"mappings":";;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;AAqBG;AA+DG,MAAO,yBAA0B,SAAQ,mBAAmB,CAAA;AAChE;;AAEG;AACH,IAAA,2BAA2B;AAE3B;;AAEG;AACH,IAAA,WAAW;AAEX,IAAA,WAAA,CAAY,MAAuC,EAAA;QACjD,KAAK,CAAC,MAAM,CAAC;AACb,QAAA,IAAI,CAAC,2BAA2B,GAAG,MAAM,EAAE,2BAA2B;AACtE,QAAA,IAAI,CAAC,WAAW,GAAG,MAAM,EAAE,WAAW;;AAGxC,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,0BAA0B;;AAGnC;;;AAGG;IACO,UAAU,GAAA;AAClB,QAAA,OAAO,IAAI,CAAC,2BAA2B,IAAI,IAAI,CAAC,KAAK;;AAGvD;;AAE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AA,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;;AAG9D,QAAA,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;YAC3B,MAAM,OAAO,GAA4B,EAAE;AAC3C,YAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AAC9C,gBAAA,IAAI,GAAG,KAAK,mBAAmB,EAAE;oBAC/B,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC;;;AAGtD,YAAA,OAAO,OAAO;;AAGhB,QAAA,OAAO,GAAG;;AAEb;;;;"}
|
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
import { isAIMessage, parseBase64DataUrl, parseMimeType } from '@langchain/core/messages';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Utility functions for converting LangChain messages to Bedrock Converse messages.
|
|
5
|
+
* Ported from @langchain/aws common.js
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* Convert a LangChain reasoning block to a Bedrock reasoning block.
|
|
9
|
+
*/
|
|
10
|
+
function langchainReasoningBlockToBedrockReasoningBlock(content) {
|
|
11
|
+
if (content.reasoningText != null) {
|
|
12
|
+
return {
|
|
13
|
+
reasoningText: content.reasoningText,
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
if (content.redactedContent != null && content.redactedContent !== '') {
|
|
17
|
+
return {
|
|
18
|
+
redactedContent: new Uint8Array(Buffer.from(content.redactedContent, 'base64')),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
throw new Error('Invalid reasoning content');
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Concatenate consecutive reasoning blocks in content array.
|
|
25
|
+
*/
|
|
26
|
+
function concatenateLangchainReasoningBlocks(content) {
|
|
27
|
+
const result = [];
|
|
28
|
+
for (const block of content) {
|
|
29
|
+
if (block.type === 'reasoning_content') {
|
|
30
|
+
const currentReasoning = block;
|
|
31
|
+
const lastIndex = result.length - 1;
|
|
32
|
+
// Check if we can merge with the previous block
|
|
33
|
+
if (lastIndex >= 0) {
|
|
34
|
+
const lastBlock = result[lastIndex];
|
|
35
|
+
if (lastBlock.type === 'reasoning_content' &&
|
|
36
|
+
lastBlock.reasoningText != null &&
|
|
37
|
+
currentReasoning.reasoningText != null) {
|
|
38
|
+
const lastReasoning = lastBlock;
|
|
39
|
+
// Merge consecutive reasoning text blocks
|
|
40
|
+
const lastText = lastReasoning.reasoningText?.text;
|
|
41
|
+
const currentText = currentReasoning.reasoningText.text;
|
|
42
|
+
if (lastText != null &&
|
|
43
|
+
lastText !== '' &&
|
|
44
|
+
currentText != null &&
|
|
45
|
+
currentText !== '') {
|
|
46
|
+
lastReasoning.reasoningText.text = lastText + currentText;
|
|
47
|
+
}
|
|
48
|
+
else if (currentReasoning.reasoningText.signature != null &&
|
|
49
|
+
currentReasoning.reasoningText.signature !== '') {
|
|
50
|
+
lastReasoning.reasoningText.signature =
|
|
51
|
+
currentReasoning.reasoningText.signature;
|
|
52
|
+
}
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
result.push({ ...block });
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
result.push(block);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Extract image info from a base64 string or URL.
|
|
66
|
+
*/
|
|
67
|
+
function extractImageInfo(base64) {
|
|
68
|
+
// Extract the format from the base64 string
|
|
69
|
+
const formatMatch = base64.match(/^data:image\/(\w+);base64,/);
|
|
70
|
+
let format;
|
|
71
|
+
if (formatMatch) {
|
|
72
|
+
const extractedFormat = formatMatch[1].toLowerCase();
|
|
73
|
+
if (['gif', 'jpeg', 'png', 'webp'].includes(extractedFormat)) {
|
|
74
|
+
format = extractedFormat;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// Remove the data URL prefix if present
|
|
78
|
+
const base64Data = base64.replace(/^data:image\/\w+;base64,/, '');
|
|
79
|
+
// Convert base64 to Uint8Array
|
|
80
|
+
const binaryString = atob(base64Data);
|
|
81
|
+
const bytes = new Uint8Array(binaryString.length);
|
|
82
|
+
for (let i = 0; i < binaryString.length; i += 1) {
|
|
83
|
+
bytes[i] = binaryString.charCodeAt(i);
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
image: {
|
|
87
|
+
format,
|
|
88
|
+
source: {
|
|
89
|
+
bytes,
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Check if a block has a cache point.
|
|
96
|
+
*/
|
|
97
|
+
function isDefaultCachePoint(block) {
|
|
98
|
+
if (typeof block !== 'object' || block === null) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
if (!('cachePoint' in block)) {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
const cachePoint = block.cachePoint;
|
|
105
|
+
if (typeof cachePoint !== 'object' || cachePoint === null) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
if (!('type' in cachePoint)) {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
return cachePoint.type === 'default';
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Convert a LangChain content block to a Bedrock Converse content block.
|
|
115
|
+
*/
|
|
116
|
+
function convertLangChainContentBlockToConverseContentBlock({ block, onUnknown = 'throw', }) {
|
|
117
|
+
if (typeof block === 'string') {
|
|
118
|
+
return { text: block };
|
|
119
|
+
}
|
|
120
|
+
if (block.type === 'text') {
|
|
121
|
+
return { text: block.text };
|
|
122
|
+
}
|
|
123
|
+
if (block.type === 'image_url') {
|
|
124
|
+
const imageUrl = typeof block.image_url ===
|
|
125
|
+
'string'
|
|
126
|
+
? block.image_url
|
|
127
|
+
: block.image_url.url;
|
|
128
|
+
return extractImageInfo(imageUrl);
|
|
129
|
+
}
|
|
130
|
+
if (block.type === 'image') {
|
|
131
|
+
// Handle standard image block format
|
|
132
|
+
const imageBlock = block;
|
|
133
|
+
if (imageBlock.source_type === 'url' &&
|
|
134
|
+
imageBlock.url != null &&
|
|
135
|
+
imageBlock.url !== '') {
|
|
136
|
+
const parsedData = parseBase64DataUrl({
|
|
137
|
+
dataUrl: imageBlock.url,
|
|
138
|
+
asTypedArray: true,
|
|
139
|
+
});
|
|
140
|
+
if (parsedData != null) {
|
|
141
|
+
const parsedMimeType = parseMimeType(parsedData.mime_type);
|
|
142
|
+
return {
|
|
143
|
+
image: {
|
|
144
|
+
format: parsedMimeType.subtype,
|
|
145
|
+
source: {
|
|
146
|
+
bytes: parsedData.data,
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
else if (imageBlock.source_type === 'base64' &&
|
|
153
|
+
imageBlock.data != null &&
|
|
154
|
+
imageBlock.data !== '') {
|
|
155
|
+
let format;
|
|
156
|
+
if (imageBlock.mime_type != null && imageBlock.mime_type !== '') {
|
|
157
|
+
const parsedMimeType = parseMimeType(imageBlock.mime_type);
|
|
158
|
+
format = parsedMimeType.subtype;
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
image: {
|
|
162
|
+
format,
|
|
163
|
+
source: {
|
|
164
|
+
bytes: Uint8Array.from(atob(imageBlock.data), (c) => c.charCodeAt(0)),
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
// If it already has the Bedrock image structure, pass through
|
|
170
|
+
if (block.image !== undefined) {
|
|
171
|
+
return {
|
|
172
|
+
image: block.image,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
if (block.type === 'document' &&
|
|
177
|
+
block.document !== undefined) {
|
|
178
|
+
return {
|
|
179
|
+
document: block.document,
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
if (isDefaultCachePoint(block)) {
|
|
183
|
+
return {
|
|
184
|
+
cachePoint: {
|
|
185
|
+
type: 'default',
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
if (onUnknown === 'throw') {
|
|
190
|
+
throw new Error(`Unsupported content block type: ${block.type}`);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
return block;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Convert a system message to Bedrock system content blocks.
|
|
198
|
+
*/
|
|
199
|
+
function convertSystemMessageToConverseMessage(msg) {
|
|
200
|
+
if (typeof msg.content === 'string') {
|
|
201
|
+
return [{ text: msg.content }];
|
|
202
|
+
}
|
|
203
|
+
else if (Array.isArray(msg.content) && msg.content.length > 0) {
|
|
204
|
+
const contentBlocks = [];
|
|
205
|
+
for (const block of msg.content) {
|
|
206
|
+
if (typeof block === 'object' &&
|
|
207
|
+
block.type === 'text' &&
|
|
208
|
+
typeof block.text === 'string') {
|
|
209
|
+
contentBlocks.push({
|
|
210
|
+
text: block.text,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
else if (isDefaultCachePoint(block)) {
|
|
214
|
+
contentBlocks.push({
|
|
215
|
+
cachePoint: {
|
|
216
|
+
type: 'default',
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (msg.content.length === contentBlocks.length) {
|
|
225
|
+
return contentBlocks;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
throw new Error('System message content must be either a string, or an array of text blocks, optionally including a cache point.');
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Convert an AI message to a Bedrock message.
|
|
232
|
+
*/
|
|
233
|
+
function convertAIMessageToConverseMessage(msg) {
|
|
234
|
+
// Check for v1 format from other providers (PR #9766 fix)
|
|
235
|
+
if (msg.response_metadata.output_version === 'v1') {
|
|
236
|
+
return convertFromV1ToChatBedrockConverseMessage(msg);
|
|
237
|
+
}
|
|
238
|
+
const assistantMsg = {
|
|
239
|
+
role: 'assistant',
|
|
240
|
+
content: [],
|
|
241
|
+
};
|
|
242
|
+
if (typeof msg.content === 'string' && msg.content !== '') {
|
|
243
|
+
assistantMsg.content?.push({ text: msg.content });
|
|
244
|
+
}
|
|
245
|
+
else if (Array.isArray(msg.content)) {
|
|
246
|
+
const concatenatedBlocks = concatenateLangchainReasoningBlocks(msg.content);
|
|
247
|
+
const contentBlocks = [];
|
|
248
|
+
concatenatedBlocks.forEach((block) => {
|
|
249
|
+
if (block.type === 'text' && block.text !== '') {
|
|
250
|
+
// Merge whitespace/newlines with previous text blocks to avoid validation errors.
|
|
251
|
+
const text = block.text;
|
|
252
|
+
const cleanedText = text.replace(/\n/g, '').trim();
|
|
253
|
+
if (cleanedText === '') {
|
|
254
|
+
if (contentBlocks.length > 0) {
|
|
255
|
+
const lastBlock = contentBlocks[contentBlocks.length - 1];
|
|
256
|
+
if ('text' in lastBlock) {
|
|
257
|
+
const mergedTextContent = `${lastBlock.text}${text}`;
|
|
258
|
+
lastBlock.text = mergedTextContent;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
contentBlocks.push({ text });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
else if (block.type === 'reasoning_content') {
|
|
267
|
+
contentBlocks.push({
|
|
268
|
+
reasoningContent: langchainReasoningBlockToBedrockReasoningBlock(block),
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
else if (isDefaultCachePoint(block)) {
|
|
272
|
+
contentBlocks.push({
|
|
273
|
+
cachePoint: {
|
|
274
|
+
type: 'default',
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
const blockValues = Object.fromEntries(Object.entries(block).filter(([key]) => key !== 'type'));
|
|
280
|
+
throw new Error(`Unsupported content block type: ${block.type} with content of ${JSON.stringify(blockValues, null, 2)}`);
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
assistantMsg.content = [...(assistantMsg.content ?? []), ...contentBlocks];
|
|
284
|
+
}
|
|
285
|
+
// Important: this must be placed after any reasoning content blocks
|
|
286
|
+
if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {
|
|
287
|
+
const toolUseBlocks = msg.tool_calls.map((tc) => ({
|
|
288
|
+
toolUse: {
|
|
289
|
+
toolUseId: tc.id,
|
|
290
|
+
name: tc.name,
|
|
291
|
+
input: tc.args,
|
|
292
|
+
},
|
|
293
|
+
}));
|
|
294
|
+
assistantMsg.content = [
|
|
295
|
+
...(assistantMsg.content ?? []),
|
|
296
|
+
...toolUseBlocks,
|
|
297
|
+
];
|
|
298
|
+
}
|
|
299
|
+
return assistantMsg;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Convert a v1 format message from other providers to Bedrock format.
|
|
303
|
+
* This handles messages with standard content blocks like tool_call and reasoning.
|
|
304
|
+
* (Implements PR #9766 fix for output_version v1 detection)
|
|
305
|
+
*/
|
|
306
|
+
function convertFromV1ToChatBedrockConverseMessage(msg) {
|
|
307
|
+
const assistantMsg = {
|
|
308
|
+
role: 'assistant',
|
|
309
|
+
content: [],
|
|
310
|
+
};
|
|
311
|
+
if (Array.isArray(msg.content)) {
|
|
312
|
+
for (const block of msg.content) {
|
|
313
|
+
if (typeof block === 'string') {
|
|
314
|
+
assistantMsg.content?.push({ text: block });
|
|
315
|
+
}
|
|
316
|
+
else if (block.type === 'text') {
|
|
317
|
+
assistantMsg.content?.push({ text: block.text });
|
|
318
|
+
}
|
|
319
|
+
else if (block.type === 'tool_call') {
|
|
320
|
+
const toolCall = block;
|
|
321
|
+
assistantMsg.content?.push({
|
|
322
|
+
toolUse: {
|
|
323
|
+
toolUseId: toolCall.id,
|
|
324
|
+
name: toolCall.name,
|
|
325
|
+
input: toolCall.args,
|
|
326
|
+
},
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
else if (block.type === 'reasoning') {
|
|
330
|
+
const reasoning = block;
|
|
331
|
+
assistantMsg.content?.push({
|
|
332
|
+
reasoningContent: {
|
|
333
|
+
reasoningText: { text: reasoning.reasoning },
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
else if (block.type === 'reasoning_content') {
|
|
338
|
+
assistantMsg.content?.push({
|
|
339
|
+
reasoningContent: langchainReasoningBlockToBedrockReasoningBlock(block),
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
else if (typeof msg.content === 'string' && msg.content !== '') {
|
|
345
|
+
assistantMsg.content?.push({ text: msg.content });
|
|
346
|
+
}
|
|
347
|
+
// Also handle tool_calls from the message
|
|
348
|
+
if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {
|
|
349
|
+
// Check if tool calls are already in content
|
|
350
|
+
const existingToolUseIds = new Set(assistantMsg.content
|
|
351
|
+
?.filter((c) => 'toolUse' in c)
|
|
352
|
+
.map((c) => c.toolUse.toolUseId) ?? []);
|
|
353
|
+
for (const tc of msg.tool_calls) {
|
|
354
|
+
if (!existingToolUseIds.has(tc.id ?? '')) {
|
|
355
|
+
assistantMsg.content?.push({
|
|
356
|
+
toolUse: {
|
|
357
|
+
toolUseId: tc.id,
|
|
358
|
+
name: tc.name,
|
|
359
|
+
input: tc.args,
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return assistantMsg;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Convert a human message to a Bedrock message.
|
|
369
|
+
*/
|
|
370
|
+
function convertHumanMessageToConverseMessage(msg) {
|
|
371
|
+
const userMessage = {
|
|
372
|
+
role: 'user',
|
|
373
|
+
content: [],
|
|
374
|
+
};
|
|
375
|
+
if (typeof msg.content === 'string') {
|
|
376
|
+
userMessage.content = [{ text: msg.content }];
|
|
377
|
+
}
|
|
378
|
+
else if (Array.isArray(msg.content)) {
|
|
379
|
+
userMessage.content = msg.content.map((block) => convertLangChainContentBlockToConverseContentBlock({ block }));
|
|
380
|
+
}
|
|
381
|
+
return userMessage;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Convert a tool message to a Bedrock message.
|
|
385
|
+
*/
|
|
386
|
+
function convertToolMessageToConverseMessage(msg) {
|
|
387
|
+
const toolCallId = msg.tool_call_id;
|
|
388
|
+
let content;
|
|
389
|
+
if (typeof msg.content === 'string') {
|
|
390
|
+
content = [{ text: msg.content }];
|
|
391
|
+
}
|
|
392
|
+
else if (Array.isArray(msg.content)) {
|
|
393
|
+
content = msg.content.map((block) => convertLangChainContentBlockToConverseContentBlock({
|
|
394
|
+
block,
|
|
395
|
+
onUnknown: 'passthrough',
|
|
396
|
+
}));
|
|
397
|
+
}
|
|
398
|
+
else {
|
|
399
|
+
content = [{ text: String(msg.content) }];
|
|
400
|
+
}
|
|
401
|
+
return {
|
|
402
|
+
role: 'user',
|
|
403
|
+
content: [
|
|
404
|
+
{
|
|
405
|
+
toolResult: {
|
|
406
|
+
toolUseId: toolCallId,
|
|
407
|
+
content: content,
|
|
408
|
+
},
|
|
409
|
+
},
|
|
410
|
+
],
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Convert LangChain messages to Bedrock Converse messages.
|
|
415
|
+
*/
|
|
416
|
+
function convertToConverseMessages(messages) {
|
|
417
|
+
const converseSystem = messages
|
|
418
|
+
.filter((msg) => msg._getType() === 'system')
|
|
419
|
+
.flatMap((msg) => convertSystemMessageToConverseMessage(msg));
|
|
420
|
+
const converseMessages = messages
|
|
421
|
+
.filter((msg) => msg._getType() !== 'system')
|
|
422
|
+
.map((msg) => {
|
|
423
|
+
if (msg._getType() === 'ai') {
|
|
424
|
+
return convertAIMessageToConverseMessage(msg);
|
|
425
|
+
}
|
|
426
|
+
else if (msg._getType() === 'human' || msg._getType() === 'generic') {
|
|
427
|
+
return convertHumanMessageToConverseMessage(msg);
|
|
428
|
+
}
|
|
429
|
+
else if (msg._getType() === 'tool') {
|
|
430
|
+
return convertToolMessageToConverseMessage(msg);
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
throw new Error(`Unsupported message type: ${msg._getType()}`);
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
// Combine consecutive user tool result messages into a single message
|
|
437
|
+
const combinedConverseMessages = converseMessages.reduce((acc, curr) => {
|
|
438
|
+
const lastMessage = acc[acc.length - 1];
|
|
439
|
+
if (lastMessage == null) {
|
|
440
|
+
acc.push(curr);
|
|
441
|
+
return acc;
|
|
442
|
+
}
|
|
443
|
+
const lastHasToolResult = lastMessage.content?.some((c) => 'toolResult' in c) === true;
|
|
444
|
+
const currHasToolResult = curr.content?.some((c) => 'toolResult' in c) === true;
|
|
445
|
+
if (lastMessage.role === 'user' &&
|
|
446
|
+
lastHasToolResult &&
|
|
447
|
+
curr.role === 'user' &&
|
|
448
|
+
currHasToolResult) {
|
|
449
|
+
lastMessage.content = lastMessage.content?.concat(curr.content ?? []);
|
|
450
|
+
}
|
|
451
|
+
else {
|
|
452
|
+
acc.push(curr);
|
|
453
|
+
}
|
|
454
|
+
return acc;
|
|
455
|
+
}, []);
|
|
456
|
+
return { converseMessages: combinedConverseMessages, converseSystem };
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export { concatenateLangchainReasoningBlocks, convertToConverseMessages, extractImageInfo, langchainReasoningBlockToBedrockReasoningBlock };
|
|
460
|
+
//# sourceMappingURL=message_inputs.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message_inputs.mjs","sources":["../../../../../src/llm/bedrock/utils/message_inputs.ts"],"sourcesContent":["/**\n * Utility functions for converting LangChain messages to Bedrock Converse messages.\n * Ported from @langchain/aws common.js\n */\nimport {\n type BaseMessage,\n isAIMessage,\n parseBase64DataUrl,\n parseMimeType,\n MessageContentComplex,\n} from '@langchain/core/messages';\nimport type {\n BedrockMessage,\n BedrockSystemContentBlock,\n BedrockContentBlock,\n MessageContentReasoningBlock,\n} from '../types';\n\n/**\n * Convert a LangChain reasoning block to a Bedrock reasoning block.\n */\nexport function langchainReasoningBlockToBedrockReasoningBlock(\n content: MessageContentReasoningBlock\n): {\n reasoningText?: { text?: string; signature?: string };\n redactedContent?: Uint8Array;\n} {\n if (content.reasoningText != null) {\n return {\n reasoningText: content.reasoningText,\n };\n }\n if (content.redactedContent != null && content.redactedContent !== '') {\n return {\n redactedContent: new Uint8Array(\n Buffer.from(content.redactedContent, 'base64')\n ),\n };\n }\n throw new Error('Invalid reasoning content');\n}\n\n/**\n * Concatenate consecutive reasoning blocks in content array.\n */\nexport function concatenateLangchainReasoningBlocks(\n content: Array<MessageContentComplex | MessageContentReasoningBlock>\n): Array<MessageContentComplex | MessageContentReasoningBlock> {\n const result: Array<MessageContentComplex | MessageContentReasoningBlock> =\n [];\n\n for (const block of content) {\n if (block.type === 'reasoning_content') {\n const currentReasoning = block as MessageContentReasoningBlock;\n const lastIndex = result.length - 1;\n\n // Check if we can merge with the previous block\n if (lastIndex >= 0) {\n const lastBlock = result[lastIndex];\n if (\n lastBlock.type === 'reasoning_content' &&\n (lastBlock as MessageContentReasoningBlock).reasoningText != null &&\n currentReasoning.reasoningText != null\n ) {\n const lastReasoning = lastBlock as MessageContentReasoningBlock;\n // Merge consecutive reasoning text blocks\n const lastText = lastReasoning.reasoningText?.text;\n const currentText = currentReasoning.reasoningText.text;\n if (\n lastText != null &&\n lastText !== '' &&\n currentText != null &&\n currentText !== ''\n ) {\n lastReasoning.reasoningText!.text = lastText + currentText;\n } else if (\n currentReasoning.reasoningText.signature != null &&\n currentReasoning.reasoningText.signature !== ''\n ) {\n lastReasoning.reasoningText!.signature =\n currentReasoning.reasoningText.signature;\n }\n continue;\n }\n }\n\n result.push({ ...block } as MessageContentReasoningBlock);\n } else {\n result.push(block);\n }\n }\n\n return result;\n}\n\n/**\n * Extract image info from a base64 string or URL.\n */\nexport function extractImageInfo(base64: string): BedrockContentBlock {\n // Extract the format from the base64 string\n const formatMatch = base64.match(/^data:image\\/(\\w+);base64,/);\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (formatMatch) {\n const extractedFormat = formatMatch[1].toLowerCase();\n if (['gif', 'jpeg', 'png', 'webp'].includes(extractedFormat)) {\n format = extractedFormat as typeof format;\n }\n }\n\n // Remove the data URL prefix if present\n const base64Data = base64.replace(/^data:image\\/\\w+;base64,/, '');\n\n // Convert base64 to Uint8Array\n const binaryString = atob(base64Data);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i += 1) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n\n return {\n image: {\n format,\n source: {\n bytes,\n },\n },\n };\n}\n\n/**\n * Check if a block has a cache point.\n */\nfunction isDefaultCachePoint(block: unknown): boolean {\n if (typeof block !== 'object' || block === null) {\n return false;\n }\n if (!('cachePoint' in block)) {\n return false;\n }\n const cachePoint = (block as { cachePoint?: unknown }).cachePoint;\n if (typeof cachePoint !== 'object' || cachePoint === null) {\n return false;\n }\n if (!('type' in cachePoint)) {\n return false;\n }\n return (cachePoint as { type?: string }).type === 'default';\n}\n\n/**\n * Convert a LangChain content block to a Bedrock Converse content block.\n */\nfunction convertLangChainContentBlockToConverseContentBlock({\n block,\n onUnknown = 'throw',\n}: {\n block: string | MessageContentComplex;\n onUnknown?: 'throw' | 'passthrough';\n}): BedrockContentBlock {\n if (typeof block === 'string') {\n return { text: block };\n }\n\n if (block.type === 'text') {\n return { text: (block as { text: string }).text };\n }\n\n if (block.type === 'image_url') {\n const imageUrl =\n typeof (block as { image_url: string | { url: string } }).image_url ===\n 'string'\n ? (block as { image_url: string }).image_url\n : (block as { image_url: { url: string } }).image_url.url;\n return extractImageInfo(imageUrl);\n }\n\n if (block.type === 'image') {\n // Handle standard image block format\n const imageBlock = block as {\n source_type?: string;\n url?: string;\n data?: string;\n mime_type?: string;\n };\n if (\n imageBlock.source_type === 'url' &&\n imageBlock.url != null &&\n imageBlock.url !== ''\n ) {\n const parsedData = parseBase64DataUrl({\n dataUrl: imageBlock.url,\n asTypedArray: true,\n });\n if (parsedData != null) {\n const parsedMimeType = parseMimeType(parsedData.mime_type);\n return {\n image: {\n format: parsedMimeType.subtype as 'gif' | 'jpeg' | 'png' | 'webp',\n source: {\n bytes: parsedData.data as Uint8Array,\n },\n },\n };\n }\n } else if (\n imageBlock.source_type === 'base64' &&\n imageBlock.data != null &&\n imageBlock.data !== ''\n ) {\n let format: 'gif' | 'jpeg' | 'png' | 'webp' | undefined;\n if (imageBlock.mime_type != null && imageBlock.mime_type !== '') {\n const parsedMimeType = parseMimeType(imageBlock.mime_type);\n format = parsedMimeType.subtype as typeof format;\n }\n return {\n image: {\n format,\n source: {\n bytes: Uint8Array.from(atob(imageBlock.data), (c) =>\n c.charCodeAt(0)\n ),\n },\n },\n };\n }\n // If it already has the Bedrock image structure, pass through\n if ((block as { image?: unknown }).image !== undefined) {\n return {\n image: (block as { image: unknown }).image,\n } as BedrockContentBlock;\n }\n }\n\n if (\n block.type === 'document' &&\n (block as { document?: unknown }).document !== undefined\n ) {\n return {\n document: (block as { document: unknown }).document,\n } as BedrockContentBlock;\n }\n\n if (isDefaultCachePoint(block)) {\n return {\n cachePoint: {\n type: 'default',\n },\n } as BedrockContentBlock;\n }\n\n if (onUnknown === 'throw') {\n throw new Error(`Unsupported content block type: ${block.type}`);\n } else {\n return block as unknown as BedrockContentBlock;\n }\n}\n\n/**\n * Convert a system message to Bedrock system content blocks.\n */\nfunction convertSystemMessageToConverseMessage(\n msg: BaseMessage\n): BedrockSystemContentBlock[] {\n if (typeof msg.content === 'string') {\n return [{ text: msg.content }];\n } else if (Array.isArray(msg.content) && msg.content.length > 0) {\n const contentBlocks: BedrockSystemContentBlock[] = [];\n for (const block of msg.content) {\n if (\n typeof block === 'object' &&\n block.type === 'text' &&\n typeof (block as { text?: string }).text === 'string'\n ) {\n contentBlocks.push({\n text: (block as { text: string }).text,\n });\n } else if (isDefaultCachePoint(block)) {\n contentBlocks.push({\n cachePoint: {\n type: 'default',\n },\n } as BedrockSystemContentBlock);\n } else {\n break;\n }\n }\n if (msg.content.length === contentBlocks.length) {\n return contentBlocks;\n }\n }\n throw new Error(\n 'System message content must be either a string, or an array of text blocks, optionally including a cache point.'\n );\n}\n\n/**\n * Convert an AI message to a Bedrock message.\n */\nfunction convertAIMessageToConverseMessage(msg: BaseMessage): BedrockMessage {\n // Check for v1 format from other providers (PR #9766 fix)\n if (msg.response_metadata.output_version === 'v1') {\n return convertFromV1ToChatBedrockConverseMessage(msg);\n }\n\n const assistantMsg: BedrockMessage = {\n role: 'assistant',\n content: [],\n };\n\n if (typeof msg.content === 'string' && msg.content !== '') {\n assistantMsg.content?.push({ text: msg.content });\n } else if (Array.isArray(msg.content)) {\n const concatenatedBlocks = concatenateLangchainReasoningBlocks(\n msg.content as Array<MessageContentComplex | MessageContentReasoningBlock>\n );\n const contentBlocks: BedrockContentBlock[] = [];\n\n concatenatedBlocks.forEach((block) => {\n if (block.type === 'text' && (block as { text?: string }).text !== '') {\n // Merge whitespace/newlines with previous text blocks to avoid validation errors.\n const text = (block as { text: string }).text;\n const cleanedText = text.replace(/\\n/g, '').trim();\n if (cleanedText === '') {\n if (contentBlocks.length > 0) {\n const lastBlock = contentBlocks[contentBlocks.length - 1];\n if ('text' in lastBlock) {\n const mergedTextContent = `${lastBlock.text}${text}`;\n (lastBlock as { text: string }).text = mergedTextContent;\n }\n }\n } else {\n contentBlocks.push({ text });\n }\n } else if (block.type === 'reasoning_content') {\n contentBlocks.push({\n reasoningContent: langchainReasoningBlockToBedrockReasoningBlock(\n block as MessageContentReasoningBlock\n ),\n } as BedrockContentBlock);\n } else if (isDefaultCachePoint(block)) {\n contentBlocks.push({\n cachePoint: {\n type: 'default',\n },\n } as BedrockContentBlock);\n } else {\n const blockValues = Object.fromEntries(\n Object.entries(block).filter(([key]) => key !== 'type')\n );\n throw new Error(\n `Unsupported content block type: ${block.type} with content of ${JSON.stringify(blockValues, null, 2)}`\n );\n }\n });\n\n assistantMsg.content = [...(assistantMsg.content ?? []), ...contentBlocks];\n }\n\n // Important: this must be placed after any reasoning content blocks\n if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {\n const toolUseBlocks = msg.tool_calls.map((tc) => ({\n toolUse: {\n toolUseId: tc.id,\n name: tc.name,\n input: tc.args as Record<string, unknown>,\n },\n }));\n assistantMsg.content = [\n ...(assistantMsg.content ?? []),\n ...toolUseBlocks,\n ] as BedrockContentBlock[];\n }\n\n return assistantMsg;\n}\n\n/**\n * Convert a v1 format message from other providers to Bedrock format.\n * This handles messages with standard content blocks like tool_call and reasoning.\n * (Implements PR #9766 fix for output_version v1 detection)\n */\nfunction convertFromV1ToChatBedrockConverseMessage(\n msg: BaseMessage\n): BedrockMessage {\n const assistantMsg: BedrockMessage = {\n role: 'assistant',\n content: [],\n };\n\n if (Array.isArray(msg.content)) {\n for (const block of msg.content) {\n if (typeof block === 'string') {\n assistantMsg.content?.push({ text: block });\n } else if (block.type === 'text') {\n assistantMsg.content?.push({ text: (block as { text: string }).text });\n } else if (block.type === 'tool_call') {\n const toolCall = block as {\n id: string;\n name: string;\n args: Record<string, unknown>;\n };\n assistantMsg.content?.push({\n toolUse: {\n toolUseId: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as Record<string, unknown>,\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning') {\n const reasoning = block as { reasoning: string };\n assistantMsg.content?.push({\n reasoningContent: {\n reasoningText: { text: reasoning.reasoning },\n },\n } as BedrockContentBlock);\n } else if (block.type === 'reasoning_content') {\n assistantMsg.content?.push({\n reasoningContent: langchainReasoningBlockToBedrockReasoningBlock(\n block as MessageContentReasoningBlock\n ),\n } as BedrockContentBlock);\n }\n }\n } else if (typeof msg.content === 'string' && msg.content !== '') {\n assistantMsg.content?.push({ text: msg.content });\n }\n\n // Also handle tool_calls from the message\n if (isAIMessage(msg) && msg.tool_calls != null && msg.tool_calls.length > 0) {\n // Check if tool calls are already in content\n const existingToolUseIds = new Set(\n assistantMsg.content\n ?.filter((c) => 'toolUse' in c)\n .map(\n (c) => (c as { toolUse: { toolUseId: string } }).toolUse.toolUseId\n ) ?? []\n );\n\n for (const tc of msg.tool_calls) {\n if (!existingToolUseIds.has(tc.id ?? '')) {\n assistantMsg.content?.push({\n toolUse: {\n toolUseId: tc.id,\n name: tc.name,\n input: tc.args as Record<string, unknown>,\n },\n } as BedrockContentBlock);\n }\n }\n }\n\n return assistantMsg;\n}\n\n/**\n * Convert a human message to a Bedrock message.\n */\nfunction convertHumanMessageToConverseMessage(\n msg: BaseMessage\n): BedrockMessage {\n const userMessage: BedrockMessage = {\n role: 'user',\n content: [],\n };\n\n if (typeof msg.content === 'string') {\n userMessage.content = [{ text: msg.content }];\n } else if (Array.isArray(msg.content)) {\n userMessage.content = msg.content.map((block) =>\n convertLangChainContentBlockToConverseContentBlock({ block })\n );\n }\n\n return userMessage;\n}\n\n/**\n * Convert a tool message to a Bedrock message.\n */\nfunction convertToolMessageToConverseMessage(msg: BaseMessage): BedrockMessage {\n const toolCallId = (msg as { tool_call_id?: string }).tool_call_id;\n\n let content: BedrockContentBlock[];\n if (typeof msg.content === 'string') {\n content = [{ text: msg.content }];\n } else if (Array.isArray(msg.content)) {\n content = msg.content.map((block) =>\n convertLangChainContentBlockToConverseContentBlock({\n block,\n onUnknown: 'passthrough',\n })\n );\n } else {\n content = [{ text: String(msg.content) }];\n }\n\n return {\n role: 'user',\n content: [\n {\n toolResult: {\n toolUseId: toolCallId,\n content: content as { text: string }[],\n },\n },\n ],\n };\n}\n\n/**\n * Convert LangChain messages to Bedrock Converse messages.\n */\nexport function convertToConverseMessages(messages: BaseMessage[]): {\n converseMessages: BedrockMessage[];\n converseSystem: BedrockSystemContentBlock[];\n} {\n const converseSystem = messages\n .filter((msg) => msg._getType() === 'system')\n .flatMap((msg) => convertSystemMessageToConverseMessage(msg));\n\n const converseMessages = messages\n .filter((msg) => msg._getType() !== 'system')\n .map((msg) => {\n if (msg._getType() === 'ai') {\n return convertAIMessageToConverseMessage(msg);\n } else if (msg._getType() === 'human' || msg._getType() === 'generic') {\n return convertHumanMessageToConverseMessage(msg);\n } else if (msg._getType() === 'tool') {\n return convertToolMessageToConverseMessage(msg);\n } else {\n throw new Error(`Unsupported message type: ${msg._getType()}`);\n }\n });\n\n // Combine consecutive user tool result messages into a single message\n const combinedConverseMessages = converseMessages.reduce<BedrockMessage[]>(\n (acc, curr) => {\n const lastMessage = acc[acc.length - 1];\n if (lastMessage == null) {\n acc.push(curr);\n return acc;\n }\n const lastHasToolResult =\n lastMessage.content?.some((c) => 'toolResult' in c) === true;\n const currHasToolResult =\n curr.content?.some((c) => 'toolResult' in c) === true;\n if (\n lastMessage.role === 'user' &&\n lastHasToolResult &&\n curr.role === 'user' &&\n currHasToolResult\n ) {\n lastMessage.content = lastMessage.content?.concat(curr.content ?? []);\n } else {\n acc.push(curr);\n }\n return acc;\n },\n []\n );\n\n return { converseMessages: combinedConverseMessages, converseSystem };\n}\n"],"names":[],"mappings":";;AAAA;;;AAGG;AAeH;;AAEG;AACG,SAAU,8CAA8C,CAC5D,OAAqC,EAAA;AAKrC,IAAA,IAAI,OAAO,CAAC,aAAa,IAAI,IAAI,EAAE;QACjC,OAAO;YACL,aAAa,EAAE,OAAO,CAAC,aAAa;SACrC;;AAEH,IAAA,IAAI,OAAO,CAAC,eAAe,IAAI,IAAI,IAAI,OAAO,CAAC,eAAe,KAAK,EAAE,EAAE;QACrE,OAAO;AACL,YAAA,eAAe,EAAE,IAAI,UAAU,CAC7B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,QAAQ,CAAC,CAC/C;SACF;;AAEH,IAA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