@librechat/agents 3.0.79 → 3.0.81

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.
@@ -3,9 +3,6 @@
3
3
  var aws = require('@langchain/aws');
4
4
  var messages = require('@langchain/core/messages');
5
5
  var outputs = require('@langchain/core/outputs');
6
- var clientBedrockRuntime = require('@aws-sdk/client-bedrock-runtime');
7
- var message_inputs = require('./utils/message_inputs.cjs');
8
- var message_outputs = require('./utils/message_outputs.cjs');
9
6
 
10
7
  /**
11
8
  * Optimized ChatBedrockConverse wrapper that fixes contentBlockIndex conflicts
@@ -52,7 +49,7 @@ class CustomChatBedrockConverse extends aws.ChatBedrockConverse {
52
49
  */
53
50
  invocationParams(options) {
54
51
  const baseParams = super.invocationParams(options);
55
- // Get serviceTier from options or fall back to class-level setting
52
+ /** Service tier from options or fall back to class-level setting */
56
53
  const serviceTierType = options?.serviceTier ?? this.serviceTier;
57
54
  return {
58
55
  ...baseParams,
@@ -61,86 +58,50 @@ class CustomChatBedrockConverse extends aws.ChatBedrockConverse {
61
58
  }
62
59
  /**
63
60
  * Override _generateNonStreaming to use applicationInferenceProfile as modelId.
61
+ * Uses the same model-swapping pattern as streaming for consistency.
64
62
  */
65
- async _generateNonStreaming(messages, options, _runManager) {
66
- const { converseMessages, converseSystem } = message_inputs.convertToConverseMessages(messages);
67
- const params = this.invocationParams(options);
68
- const command = new clientBedrockRuntime.ConverseCommand({
69
- modelId: this.getModelId(),
70
- messages: converseMessages,
71
- system: converseSystem,
72
- requestMetadata: options.requestMetadata,
73
- ...params,
74
- });
75
- const response = await this.client.send(command, {
76
- abortSignal: options.signal,
77
- });
78
- const { output, ...responseMetadata } = response;
79
- if (!output?.message) {
80
- throw new Error('No message found in Bedrock response.');
63
+ async _generateNonStreaming(messages, options, runManager) {
64
+ // Temporarily swap model for applicationInferenceProfile support
65
+ const originalModel = this.model;
66
+ if (this.applicationInferenceProfile != null &&
67
+ this.applicationInferenceProfile !== '') {
68
+ this.model = this.applicationInferenceProfile;
69
+ }
70
+ try {
71
+ return await super._generateNonStreaming(messages, options, runManager);
72
+ }
73
+ finally {
74
+ // Restore original model
75
+ this.model = originalModel;
81
76
  }
82
- const message = message_outputs.convertConverseMessageToLangChainMessage(output.message, responseMetadata);
83
- return {
84
- generations: [
85
- {
86
- text: typeof message.content === 'string' ? message.content : '',
87
- message,
88
- },
89
- ],
90
- };
91
77
  }
92
78
  /**
93
79
  * Override _streamResponseChunks to:
94
- * 1. Use applicationInferenceProfile as modelId
95
- * 2. Include serviceTier in request
96
- * 3. Strip contentBlockIndex from response_metadata to prevent merge conflicts
80
+ * 1. Use applicationInferenceProfile as modelId (by temporarily swapping this.model)
81
+ * 2. Strip contentBlockIndex from response_metadata to prevent merge conflicts
82
+ *
83
+ * Note: We delegate to super._streamResponseChunks() to preserve @langchain/aws's
84
+ * internal chunk handling which correctly preserves array content for reasoning blocks.
97
85
  */
98
86
  async *_streamResponseChunks(messages, options, runManager) {
99
- const { converseMessages, converseSystem } = message_inputs.convertToConverseMessages(messages);
100
- const params = this.invocationParams(options);
101
- let { streamUsage } = this;
102
- if (options.streamUsage !== undefined) {
103
- streamUsage = options.streamUsage;
87
+ // Temporarily swap model for applicationInferenceProfile support
88
+ const originalModel = this.model;
89
+ if (this.applicationInferenceProfile != null &&
90
+ this.applicationInferenceProfile !== '') {
91
+ this.model = this.applicationInferenceProfile;
104
92
  }
105
- const command = new clientBedrockRuntime.ConverseStreamCommand({
106
- modelId: this.getModelId(),
107
- messages: converseMessages,
108
- system: converseSystem,
109
- requestMetadata: options.requestMetadata,
110
- ...params,
111
- });
112
- const response = await this.client.send(command, {
113
- abortSignal: options.signal,
114
- });
115
- if (response.stream) {
116
- for await (const event of response.stream) {
117
- if (event.contentBlockStart != null) {
118
- const chunk = message_outputs.handleConverseStreamContentBlockStart(event.contentBlockStart);
119
- if (chunk !== undefined) {
120
- const cleanedChunk = this.cleanChunk(chunk);
121
- yield cleanedChunk;
122
- await runManager?.handleLLMNewToken(cleanedChunk.text || '');
123
- }
124
- }
125
- else if (event.contentBlockDelta != null) {
126
- const chunk = message_outputs.handleConverseStreamContentBlockDelta(event.contentBlockDelta);
127
- if (chunk !== undefined) {
128
- const cleanedChunk = this.cleanChunk(chunk);
129
- yield cleanedChunk;
130
- await runManager?.handleLLMNewToken(cleanedChunk.text || '');
131
- }
132
- }
133
- else if (event.metadata != null) {
134
- const chunk = message_outputs.handleConverseStreamMetadata(event.metadata, {
135
- streamUsage,
136
- });
137
- if (chunk !== undefined) {
138
- const cleanedChunk = this.cleanChunk(chunk);
139
- yield cleanedChunk;
140
- }
141
- }
93
+ try {
94
+ // Use parent's streaming logic which correctly handles reasoning content
95
+ const baseStream = super._streamResponseChunks(messages, options, runManager);
96
+ for await (const chunk of baseStream) {
97
+ // Clean contentBlockIndex from response_metadata to prevent merge conflicts
98
+ yield this.cleanChunk(chunk);
142
99
  }
143
100
  }
101
+ finally {
102
+ // Restore original model
103
+ this.model = originalModel;
104
+ }
144
105
  }
145
106
  /**
146
107
  * Clean a chunk by removing contentBlockIndex from response_metadata.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","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';\nimport {\n ConverseCommand,\n ConverseStreamCommand,\n} from '@aws-sdk/client-bedrock-runtime';\nimport {\n convertToConverseMessages,\n convertConverseMessageToLangChainMessage,\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 // Get serviceTier 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 */\n override async _generateNonStreaming(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions,\n _runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const { converseMessages, converseSystem } =\n convertToConverseMessages(messages);\n const params = this.invocationParams(options);\n\n const command = new ConverseCommand({\n modelId: this.getModelId(),\n messages: converseMessages,\n system: converseSystem,\n requestMetadata: options.requestMetadata,\n ...params,\n });\n\n const response = await this.client.send(command, {\n abortSignal: options.signal,\n });\n\n const { output, ...responseMetadata } = response;\n if (!output?.message) {\n throw new Error('No message found in Bedrock response.');\n }\n\n const message = convertConverseMessageToLangChainMessage(\n output.message,\n responseMetadata\n );\n\n return {\n generations: [\n {\n text: typeof message.content === 'string' ? message.content : '',\n message,\n },\n ],\n };\n }\n\n /**\n * Override _streamResponseChunks to:\n * 1. Use applicationInferenceProfile as modelId\n * 2. Include serviceTier in request\n * 3. Strip contentBlockIndex from response_metadata to prevent merge conflicts\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.streamUsage !== undefined) {\n streamUsage = options.streamUsage;\n }\n\n const command = new ConverseStreamCommand({\n modelId: this.getModelId(),\n messages: converseMessages,\n system: converseSystem,\n requestMetadata: options.requestMetadata,\n ...params,\n });\n\n const response = await this.client.send(command, {\n abortSignal: options.signal,\n });\n\n if (response.stream) {\n for await (const event of response.stream) {\n if (event.contentBlockStart != null) {\n const chunk = handleConverseStreamContentBlockStart(\n event.contentBlockStart\n ) as ChatGenerationChunk | undefined;\n if (chunk !== undefined) {\n const cleanedChunk = this.cleanChunk(chunk);\n yield cleanedChunk;\n await runManager?.handleLLMNewToken(cleanedChunk.text || '');\n }\n } else if (event.contentBlockDelta != null) {\n const chunk = handleConverseStreamContentBlockDelta(\n event.contentBlockDelta\n ) as ChatGenerationChunk | undefined;\n if (chunk !== undefined) {\n const cleanedChunk = this.cleanChunk(chunk);\n yield cleanedChunk;\n await runManager?.handleLLMNewToken(cleanedChunk.text || '');\n }\n } else if (event.metadata != null) {\n const chunk = handleConverseStreamMetadata(event.metadata, {\n streamUsage,\n }) as ChatGenerationChunk | undefined;\n if (chunk !== undefined) {\n const cleanedChunk = this.cleanChunk(chunk);\n yield cleanedChunk;\n }\n }\n }\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 };\n"],"names":["ChatBedrockConverse","convertToConverseMessages","ConverseCommand","convertConverseMessageToLangChainMessage","ConverseStreamCommand","handleConverseStreamContentBlockStart","handleConverseStreamContentBlockDelta","handleConverseStreamMetadata","AIMessageChunk","ChatGenerationChunk"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAmEG,MAAO,yBAA0B,SAAQA,uBAAmB,CAAA;AAChE;;AAEG;AACH,IAAA,2BAA2B;AAE3B;;AAEG;AACH,IAAA,WAAW;AAEX,IAAA,WAAA,CAAY,MAAuC,EAAA;QACjD,KAAK,CA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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;;;;"}
1
+ {"version":3,"file":"index.cjs","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 };\n"],"names":["ChatBedrockConverse","AIMessageChunk","ChatGenerationChunk"],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAwDG,MAAO,yBAA0B,SAAQA,uBAAmB,CAAA;AAChE;;AAEG;AACH,IAAA,2BAA2B;AAE3B;;AAEG;AACH,IAAA,WAAW;AAEX,IAAA,WAAA,CAAY,MAA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A,IAAI,mBAAmB,IAAI,GAAG,EAAE;AAC9B,YAAA,OAAO,IAAI;;QAGb,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE;YACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE;AAC/C,gBAAA,IAAI,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC,EAAE;AACpC,oBAAA,OAAO,IAAI;;;;AAKjB,QAAA,OAAO,KAAK;;AAGd;;AAEG;AACK,IAAA,uBAAuB,CAAC,GAAY,EAAA;QAC1C,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,EAAE;AACrC,YAAA,OAAO,GAAG;;AAGZ,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AACtB,YAAA,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;;;;"}
@@ -2,13 +2,54 @@
2
2
 
3
3
  var _enum = require('../common/enum.cjs');
4
4
 
5
+ /**
6
+ * Deep clones a message's content to prevent mutation of the original.
7
+ * Handles both string and array content types.
8
+ */
9
+ function deepCloneContent(content) {
10
+ if (typeof content === 'string') {
11
+ return content;
12
+ }
13
+ if (Array.isArray(content)) {
14
+ return content.map((block) => ({ ...block }));
15
+ }
16
+ return content;
17
+ }
18
+ /**
19
+ * Creates a shallow clone of a message with deep-cloned content.
20
+ * This ensures modifications to content don't affect the original message.
21
+ */
22
+ function cloneMessageWithContent(message) {
23
+ if (message.content === undefined) {
24
+ return { ...message };
25
+ }
26
+ return {
27
+ ...message,
28
+ content: deepCloneContent(message.content),
29
+ };
30
+ }
31
+ /**
32
+ * Checks if a message's content needs cache control stripping.
33
+ * Returns true if content has cachePoint blocks or cache_control fields.
34
+ */
35
+ function needsCacheStripping(content) {
36
+ for (let i = 0; i < content.length; i++) {
37
+ const block = content[i];
38
+ if (isCachePoint(block))
39
+ return true;
40
+ if ('cache_control' in block)
41
+ return true;
42
+ }
43
+ return false;
44
+ }
5
45
  /**
6
46
  * Anthropic API: Adds cache control to the appropriate user messages in the payload.
7
47
  * Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,
8
48
  * then adds fresh cache control to the last 2 user messages in a single backward pass.
9
49
  * This ensures we don't accumulate stale cache points across multiple turns.
50
+ * Returns a new array - only clones messages that require modification.
10
51
  * @param messages - The array of message objects.
11
- * @returns - The updated array of message objects with cache control added.
52
+ * @returns - A new array of message objects with cache control added.
12
53
  */
13
54
  function addCacheControl(messages) {
14
55
  if (!Array.isArray(messages) || messages.length < 2) {
@@ -17,10 +58,21 @@ function addCacheControl(messages) {
17
58
  const updatedMessages = [...messages];
18
59
  let userMessagesModified = 0;
19
60
  for (let i = updatedMessages.length - 1; i >= 0; i--) {
20
- const message = updatedMessages[i];
21
- const isUserMessage = ('getType' in message && message.getType() === 'human') ||
22
- ('role' in message && message.role === 'user');
23
- if (Array.isArray(message.content)) {
61
+ const originalMessage = updatedMessages[i];
62
+ const isUserMessage = ('getType' in originalMessage && originalMessage.getType() === 'human') ||
63
+ ('role' in originalMessage && originalMessage.role === 'user');
64
+ const hasArrayContent = Array.isArray(originalMessage.content);
65
+ const needsStripping = hasArrayContent &&
66
+ needsCacheStripping(originalMessage.content);
67
+ const needsCacheAdd = userMessagesModified < 2 &&
68
+ isUserMessage &&
69
+ (typeof originalMessage.content === 'string' || hasArrayContent);
70
+ if (!needsStripping && !needsCacheAdd) {
71
+ continue;
72
+ }
73
+ const message = cloneMessageWithContent(originalMessage);
74
+ updatedMessages[i] = message;
75
+ if (hasArrayContent) {
24
76
  message.content = message.content.filter((block) => !isCachePoint(block));
25
77
  for (let j = 0; j < message.content.length; j++) {
26
78
  const block = message.content[j];
@@ -63,9 +115,20 @@ function addCacheControl(messages) {
63
115
  function isCachePoint(block) {
64
116
  return 'cachePoint' in block && !('type' in block);
65
117
  }
118
+ /**
119
+ * Checks if a message's content has Anthropic cache_control fields.
120
+ */
121
+ function hasAnthropicCacheControl(content) {
122
+ for (let i = 0; i < content.length; i++) {
123
+ if ('cache_control' in content[i])
124
+ return true;
125
+ }
126
+ return false;
127
+ }
66
128
  /**
67
129
  * Removes all Anthropic cache_control fields from messages
68
130
  * Used when switching from Anthropic to Bedrock provider
131
+ * Returns a new array - only clones messages that require modification.
69
132
  */
70
133
  function stripAnthropicCacheControl(messages) {
71
134
  if (!Array.isArray(messages)) {
@@ -73,22 +136,36 @@ function stripAnthropicCacheControl(messages) {
73
136
  }
74
137
  const updatedMessages = [...messages];
75
138
  for (let i = 0; i < updatedMessages.length; i++) {
76
- const message = updatedMessages[i];
77
- const content = message.content;
78
- if (Array.isArray(content)) {
79
- for (let j = 0; j < content.length; j++) {
80
- const block = content[j];
81
- if ('cache_control' in block) {
82
- delete block.cache_control;
83
- }
139
+ const originalMessage = updatedMessages[i];
140
+ const content = originalMessage.content;
141
+ if (!Array.isArray(content) || !hasAnthropicCacheControl(content)) {
142
+ continue;
143
+ }
144
+ const message = cloneMessageWithContent(originalMessage);
145
+ updatedMessages[i] = message;
146
+ for (let j = 0; j < message.content.length; j++) {
147
+ const block = message.content[j];
148
+ if ('cache_control' in block) {
149
+ delete block.cache_control;
84
150
  }
85
151
  }
86
152
  }
87
153
  return updatedMessages;
88
154
  }
155
+ /**
156
+ * Checks if a message's content has Bedrock cachePoint blocks.
157
+ */
158
+ function hasBedrockCachePoint(content) {
159
+ for (let i = 0; i < content.length; i++) {
160
+ if (isCachePoint(content[i]))
161
+ return true;
162
+ }
163
+ return false;
164
+ }
89
165
  /**
90
166
  * Removes all Bedrock cachePoint blocks from messages
91
167
  * Used when switching from Bedrock to Anthropic provider
168
+ * Returns a new array - only clones messages that require modification.
92
169
  */
93
170
  function stripBedrockCacheControl(messages) {
94
171
  if (!Array.isArray(messages)) {
@@ -96,11 +173,14 @@ function stripBedrockCacheControl(messages) {
96
173
  }
97
174
  const updatedMessages = [...messages];
98
175
  for (let i = 0; i < updatedMessages.length; i++) {
99
- const message = updatedMessages[i];
100
- const content = message.content;
101
- if (Array.isArray(content)) {
102
- message.content = content.filter((block) => !isCachePoint(block));
176
+ const originalMessage = updatedMessages[i];
177
+ const content = originalMessage.content;
178
+ if (!Array.isArray(content) || !hasBedrockCachePoint(content)) {
179
+ continue;
103
180
  }
181
+ const message = cloneMessageWithContent(originalMessage);
182
+ updatedMessages[i] = message;
183
+ message.content = message.content.filter((block) => !isCachePoint(block));
104
184
  }
105
185
  return updatedMessages;
106
186
  }
@@ -111,23 +191,37 @@ function stripBedrockCacheControl(messages) {
111
191
  * Strips ALL existing cache control (both Bedrock and Anthropic formats) from all messages,
112
192
  * then adds fresh cache points to the last 2 messages in a single backward pass.
113
193
  * This ensures we don't accumulate stale cache points across multiple turns.
194
+ * Returns a new array - only clones messages that require modification.
114
195
  * @param messages - The array of message objects.
115
- * @returns - The updated array of message objects with cache points added.
196
+ * @returns - A new array of message objects with cache points added.
116
197
  */
117
198
  function addBedrockCacheControl(messages) {
118
199
  if (!Array.isArray(messages) || messages.length < 2) {
119
200
  return messages;
120
201
  }
121
- const updatedMessages = messages.slice();
202
+ const updatedMessages = [...messages];
122
203
  let messagesModified = 0;
123
204
  for (let i = updatedMessages.length - 1; i >= 0; i--) {
124
- const message = updatedMessages[i];
125
- const isToolMessage = 'getType' in message &&
126
- typeof message.getType === 'function' &&
127
- message.getType() === 'tool';
128
- const content = message.content;
129
- if (Array.isArray(content)) {
130
- message.content = content.filter((block) => !isCachePoint(block));
205
+ const originalMessage = updatedMessages[i];
206
+ const isToolMessage = 'getType' in originalMessage &&
207
+ typeof originalMessage.getType === 'function' &&
208
+ originalMessage.getType() === 'tool';
209
+ const content = originalMessage.content;
210
+ const hasArrayContent = Array.isArray(content);
211
+ const needsStripping = hasArrayContent &&
212
+ needsCacheStripping(content);
213
+ const isEmptyString = typeof content === 'string' && content === '';
214
+ const needsCacheAdd = messagesModified < 2 &&
215
+ !isToolMessage &&
216
+ !isEmptyString &&
217
+ (typeof content === 'string' || hasArrayContent);
218
+ if (!needsStripping && !needsCacheAdd) {
219
+ continue;
220
+ }
221
+ const message = cloneMessageWithContent(originalMessage);
222
+ updatedMessages[i] = message;
223
+ if (hasArrayContent) {
224
+ message.content = message.content.filter((block) => !isCachePoint(block));
131
225
  for (let j = 0; j < message.content.length; j++) {
132
226
  const block = message.content[j];
133
227
  if ('cache_control' in block) {
@@ -135,15 +229,12 @@ function addBedrockCacheControl(messages) {
135
229
  }
136
230
  }
137
231
  }
138
- if (messagesModified >= 2 || isToolMessage) {
139
- continue;
140
- }
141
- if (typeof content === 'string' && content === '') {
232
+ if (messagesModified >= 2 || isToolMessage || isEmptyString) {
142
233
  continue;
143
234
  }
144
- if (typeof content === 'string') {
235
+ if (typeof message.content === 'string') {
145
236
  message.content = [
146
- { type: _enum.ContentTypes.TEXT, text: content },
237
+ { type: _enum.ContentTypes.TEXT, text: message.content },
147
238
  { cachePoint: { type: 'default' } },
148
239
  ];
149
240
  messagesModified++;
@@ -1 +1 @@
1
- {"version":3,"file":"cache.cjs","sources":["../../../src/messages/cache.ts"],"sourcesContent":["import { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { AnthropicMessage } from '@/types/messages';\nimport type Anthropic from '@anthropic-ai/sdk';\nimport { ContentTypes } from '@/common/enum';\n\ntype MessageWithContent = {\n content?: string | MessageContentComplex[];\n};\n\n/**\n * Anthropic API: Adds cache control to the appropriate user messages in the payload.\n * Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,\n * then adds fresh cache control to the last 2 user messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * @param messages - The array of message objects.\n * @returns - The updated array of message objects with cache control added.\n */\nexport function addCacheControl<T extends AnthropicMessage | BaseMessage>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages = [...messages];\n let userMessagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const message = updatedMessages[i];\n const isUserMessage =\n ('getType' in message && message.getType() === 'human') ||\n ('role' in message && message.role === 'user');\n\n if (Array.isArray(message.content)) {\n message.content = message.content.filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof message.content;\n\n for (let j = 0; j < message.content.length; j++) {\n const block = message.content[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n if (userMessagesModified >= 2 || !isUserMessage) {\n continue;\n }\n\n if (typeof message.content === 'string') {\n message.content = [\n {\n type: 'text',\n text: message.content,\n cache_control: { type: 'ephemeral' },\n },\n ];\n userMessagesModified++;\n } else if (Array.isArray(message.content)) {\n for (let j = message.content.length - 1; j >= 0; j--) {\n const contentPart = message.content[j];\n if ('type' in contentPart && contentPart.type === 'text') {\n (contentPart as Anthropic.TextBlockParam).cache_control = {\n type: 'ephemeral',\n };\n userMessagesModified++;\n break;\n }\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a content block is a cache point\n */\nfunction isCachePoint(block: MessageContentComplex): boolean {\n return 'cachePoint' in block && !('type' in block);\n}\n\n/**\n * Removes all Anthropic cache_control fields from messages\n * Used when switching from Anthropic to Bedrock provider\n */\nexport function stripAnthropicCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const message = updatedMessages[i];\n const content = message.content;\n\n if (Array.isArray(content)) {\n for (let j = 0; j < content.length; j++) {\n const block = content[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Removes all Bedrock cachePoint blocks from messages\n * Used when switching from Bedrock to Anthropic provider\n */\nexport function stripBedrockCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const message = updatedMessages[i];\n const content = message.content;\n\n if (Array.isArray(content)) {\n message.content = content.filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof content;\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Adds Bedrock Converse API cache points to the last two messages.\n * Inserts `{ cachePoint: { type: 'default' } }` as a separate content block\n * immediately after the last text block in each targeted message.\n * Strips ALL existing cache control (both Bedrock and Anthropic formats) from all messages,\n * then adds fresh cache points to the last 2 messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * @param messages - The array of message objects.\n * @returns - The updated array of message objects with cache points added.\n */\nexport function addBedrockCacheControl<\n T extends Partial<BaseMessage> & MessageWithContent,\n>(messages: T[]): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = messages.slice();\n let messagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const message = updatedMessages[i];\n const isToolMessage =\n 'getType' in message &&\n typeof message.getType === 'function' &&\n message.getType() === 'tool';\n\n const content = message.content;\n\n if (Array.isArray(content)) {\n message.content = content.filter(\n (block) => !isCachePoint(block)\n ) as typeof content;\n\n for (let j = 0; j < message.content.length; j++) {\n const block = message.content[j] as Record<string, unknown>;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n if (messagesModified >= 2 || isToolMessage) {\n continue;\n }\n\n if (typeof content === 'string' && content === '') {\n continue;\n }\n\n if (typeof content === 'string') {\n message.content = [\n { type: ContentTypes.TEXT, text: content },\n { cachePoint: { type: 'default' } },\n ] as MessageContentComplex[];\n messagesModified++;\n continue;\n }\n\n if (Array.isArray(message.content)) {\n let hasCacheableContent = false;\n for (const block of message.content) {\n if (block.type === ContentTypes.TEXT) {\n if (typeof block.text === 'string' && block.text !== '') {\n hasCacheableContent = true;\n break;\n }\n }\n }\n\n if (!hasCacheableContent) {\n continue;\n }\n\n let inserted = false;\n for (let j = message.content.length - 1; j >= 0; j--) {\n const block = message.content[j] as MessageContentComplex;\n const type = (block as { type?: string }).type;\n if (type === ContentTypes.TEXT || type === 'text') {\n const text = (block as { text?: string }).text;\n if (text === '' || text === undefined) {\n continue;\n }\n message.content.splice(j + 1, 0, {\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n inserted = true;\n break;\n }\n }\n if (!inserted) {\n message.content.push({\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n }\n messagesModified++;\n }\n }\n\n return updatedMessages;\n}\n"],"names":["ContentTypes"],"mappings":";;;;AASA;;;;;;;AAOG;AACG,SAAU,eAAe,CAC7B,QAAa,EAAA;AAEb,IAAA,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;AACnD,QAAA,OAAO,QAAQ;;AAGjB,IAAA,MAAM,eAAe,GAAG,CAAC,GAAG,QAAQ,CAAC;IACrC,IAAI,oBAAoB,GAAG,CAAC;AAE5B,IAAA,KAAK,IAAI,CAAC,GAAG,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;AACpD,QAAA,MAAM,OAAO,GAAG,eAAe,CAAC,CAAC,CAAC;AAClC,QAAA,MAAM,aAAa,GACjB,CAAC,SAAS,IAAI,OAAO,IAAI,OAAO,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AC,CAA0B;AACzD,gBAAA,MAAM,IAAI,GAAI,KAA2B,CAAC,IAAI;gBAC9C,IAAI,IAAI,KAAKA,kBAAY,CAAC,IAAI,IAAI,IAAI,KAAK,MAAM,EAAE;AACjD,oBAAA,MAAM,IAAI,GAAI,KAA2B,CAAC,IAAI;oBAC9C,IAAI,IAAI,KAAK,EAAE,IAAI,IAAI,KAAK,SAAS,EAAE;wBACrC;;oBAEF,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;AAC/B,wBAAA,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,qBAAA,CAAC;oBAC3B,QAAQ,GAAG,IAAI;oBACf;;;YAGJ,IAAI,CAAC,QAAQ,EAAE;AACb,gBAAA,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC;AACnB,oBAAA,UAAU,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE;AACP,iBAAA,CAAC;;AAE7B,YAAA,gBAAgB,EAAE;;;AAItB,IAAA,OAAO,eAAe;AACxB;;;;;;;"}
1
+ {"version":3,"file":"cache.cjs","sources":["../../../src/messages/cache.ts"],"sourcesContent":["import { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { AnthropicMessage } from '@/types/messages';\nimport type Anthropic from '@anthropic-ai/sdk';\nimport { ContentTypes } from '@/common/enum';\n\ntype MessageWithContent = {\n content?: string | MessageContentComplex[];\n};\n\n/**\n * Deep clones a message's content to prevent mutation of the original.\n * Handles both string and array content types.\n */\nfunction deepCloneContent<T extends string | MessageContentComplex[]>(\n content: T\n): T {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content.map((block) => ({ ...block })) as T;\n }\n return content;\n}\n\n/**\n * Creates a shallow clone of a message with deep-cloned content.\n * This ensures modifications to content don't affect the original message.\n */\nfunction cloneMessageWithContent<T extends MessageWithContent>(message: T): T {\n if (message.content === undefined) {\n return { ...message };\n }\n return {\n ...message,\n content: deepCloneContent(message.content),\n };\n}\n\n/**\n * Checks if a message's content needs cache control stripping.\n * Returns true if content has cachePoint blocks or cache_control fields.\n */\nfunction needsCacheStripping(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n const block = content[i];\n if (isCachePoint(block)) return true;\n if ('cache_control' in block) return true;\n }\n return false;\n}\n\n/**\n * Anthropic API: Adds cache control to the appropriate user messages in the payload.\n * Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,\n * then adds fresh cache control to the last 2 user messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * Returns a new array - only clones messages that require modification.\n * @param messages - The array of message objects.\n * @returns - A new array of message objects with cache control added.\n */\nexport function addCacheControl<T extends AnthropicMessage | BaseMessage>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n let userMessagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const originalMessage = updatedMessages[i];\n const isUserMessage =\n ('getType' in originalMessage && originalMessage.getType() === 'human') ||\n ('role' in originalMessage && originalMessage.role === 'user');\n\n const hasArrayContent = Array.isArray(originalMessage.content);\n const needsStripping =\n hasArrayContent &&\n needsCacheStripping(originalMessage.content as MessageContentComplex[]);\n const needsCacheAdd =\n userMessagesModified < 2 &&\n isUserMessage &&\n (typeof originalMessage.content === 'string' || hasArrayContent);\n\n if (!needsStripping && !needsCacheAdd) {\n continue;\n }\n\n const message = cloneMessageWithContent(\n originalMessage as MessageWithContent\n ) as T;\n updatedMessages[i] = message;\n\n if (hasArrayContent) {\n message.content = (message.content as MessageContentComplex[]).filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof message.content;\n\n for (\n let j = 0;\n j < (message.content as MessageContentComplex[]).length;\n j++\n ) {\n const block = (message.content as MessageContentComplex[])[j] as Record<\n string,\n unknown\n >;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n if (userMessagesModified >= 2 || !isUserMessage) {\n continue;\n }\n\n if (typeof message.content === 'string') {\n message.content = [\n {\n type: 'text',\n text: message.content,\n cache_control: { type: 'ephemeral' },\n },\n ];\n userMessagesModified++;\n } else if (Array.isArray(message.content)) {\n for (let j = message.content.length - 1; j >= 0; j--) {\n const contentPart = message.content[j];\n if ('type' in contentPart && contentPart.type === 'text') {\n (contentPart as Anthropic.TextBlockParam).cache_control = {\n type: 'ephemeral',\n };\n userMessagesModified++;\n break;\n }\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a content block is a cache point\n */\nfunction isCachePoint(block: MessageContentComplex): boolean {\n return 'cachePoint' in block && !('type' in block);\n}\n\n/**\n * Checks if a message's content has Anthropic cache_control fields.\n */\nfunction hasAnthropicCacheControl(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n if ('cache_control' in content[i]) return true;\n }\n return false;\n}\n\n/**\n * Removes all Anthropic cache_control fields from messages\n * Used when switching from Anthropic to Bedrock provider\n * Returns a new array - only clones messages that require modification.\n */\nexport function stripAnthropicCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n\n if (!Array.isArray(content) || !hasAnthropicCacheControl(content)) {\n continue;\n }\n\n const message = cloneMessageWithContent(originalMessage);\n updatedMessages[i] = message;\n\n for (\n let j = 0;\n j < (message.content as MessageContentComplex[]).length;\n j++\n ) {\n const block = (message.content as MessageContentComplex[])[j] as Record<\n string,\n unknown\n >;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n return updatedMessages;\n}\n\n/**\n * Checks if a message's content has Bedrock cachePoint blocks.\n */\nfunction hasBedrockCachePoint(content: MessageContentComplex[]): boolean {\n for (let i = 0; i < content.length; i++) {\n if (isCachePoint(content[i])) return true;\n }\n return false;\n}\n\n/**\n * Removes all Bedrock cachePoint blocks from messages\n * Used when switching from Bedrock to Anthropic provider\n * Returns a new array - only clones messages that require modification.\n */\nexport function stripBedrockCacheControl<T extends MessageWithContent>(\n messages: T[]\n): T[] {\n if (!Array.isArray(messages)) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n\n for (let i = 0; i < updatedMessages.length; i++) {\n const originalMessage = updatedMessages[i];\n const content = originalMessage.content;\n\n if (!Array.isArray(content) || !hasBedrockCachePoint(content)) {\n continue;\n }\n\n const message = cloneMessageWithContent(originalMessage);\n updatedMessages[i] = message;\n\n message.content = (message.content as MessageContentComplex[]).filter(\n (block) => !isCachePoint(block as MessageContentComplex)\n ) as typeof content;\n }\n\n return updatedMessages;\n}\n\n/**\n * Adds Bedrock Converse API cache points to the last two messages.\n * Inserts `{ cachePoint: { type: 'default' } }` as a separate content block\n * immediately after the last text block in each targeted message.\n * Strips ALL existing cache control (both Bedrock and Anthropic formats) from all messages,\n * then adds fresh cache points to the last 2 messages in a single backward pass.\n * This ensures we don't accumulate stale cache points across multiple turns.\n * Returns a new array - only clones messages that require modification.\n * @param messages - The array of message objects.\n * @returns - A new array of message objects with cache points added.\n */\nexport function addBedrockCacheControl<\n T extends Partial<BaseMessage> & MessageWithContent,\n>(messages: T[]): T[] {\n if (!Array.isArray(messages) || messages.length < 2) {\n return messages;\n }\n\n const updatedMessages: T[] = [...messages];\n let messagesModified = 0;\n\n for (let i = updatedMessages.length - 1; i >= 0; i--) {\n const originalMessage = updatedMessages[i];\n const isToolMessage =\n 'getType' in originalMessage &&\n typeof originalMessage.getType === 'function' &&\n originalMessage.getType() === 'tool';\n\n const content = originalMessage.content;\n const hasArrayContent = Array.isArray(content);\n const needsStripping =\n hasArrayContent &&\n needsCacheStripping(content as MessageContentComplex[]);\n const isEmptyString = typeof content === 'string' && content === '';\n const needsCacheAdd =\n messagesModified < 2 &&\n !isToolMessage &&\n !isEmptyString &&\n (typeof content === 'string' || hasArrayContent);\n\n if (!needsStripping && !needsCacheAdd) {\n continue;\n }\n\n const message = cloneMessageWithContent(originalMessage);\n updatedMessages[i] = message;\n\n if (hasArrayContent) {\n message.content = (message.content as MessageContentComplex[]).filter(\n (block) => !isCachePoint(block)\n ) as typeof content;\n\n for (\n let j = 0;\n j < (message.content as MessageContentComplex[]).length;\n j++\n ) {\n const block = (message.content as MessageContentComplex[])[j] as Record<\n string,\n unknown\n >;\n if ('cache_control' in block) {\n delete block.cache_control;\n }\n }\n }\n\n if (messagesModified >= 2 || isToolMessage || isEmptyString) {\n continue;\n }\n\n if (typeof message.content === 'string') {\n message.content = [\n { type: ContentTypes.TEXT, text: message.content },\n { cachePoint: { type: 'default' } },\n ] as MessageContentComplex[];\n messagesModified++;\n continue;\n }\n\n if (Array.isArray(message.content)) {\n let hasCacheableContent = false;\n for (const block of message.content) {\n if (block.type === ContentTypes.TEXT) {\n if (typeof block.text === 'string' && block.text !== '') {\n hasCacheableContent = true;\n break;\n }\n }\n }\n\n if (!hasCacheableContent) {\n continue;\n }\n\n let inserted = false;\n for (let j = message.content.length - 1; j >= 0; j--) {\n const block = message.content[j] as MessageContentComplex;\n const type = (block as { type?: string }).type;\n if (type === ContentTypes.TEXT || type === 'text') {\n const text = (block as { text?: string }).text;\n if (text === '' || text === undefined) {\n continue;\n }\n message.content.splice(j + 1, 0, {\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n inserted = true;\n break;\n }\n }\n if (!inserted) {\n message.content.push({\n cachePoint: { type: 'default' },\n } as MessageContentComplex);\n }\n messagesModified++;\n }\n }\n\n return updatedMessages;\n}\n"],"names":["ContentTypes"],"mappings":";;;;AASA;;;AAGG;AACH,SAAS,gBAAgB,CACvB,OAAU,EAAA;AAEV,IAAA,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC/B,QAAA,OAAO,OAAO;;AAEhB,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;AAC1B,QAAA,OAAO,OAAO,CAAC,GA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