@librechat/agents 3.3.3 → 3.3.5
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/agents/AgentContext.cjs +2 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/constants.cjs +21 -0
- package/dist/cjs/common/constants.cjs.map +1 -1
- package/dist/cjs/events.cjs +10 -1
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +793 -111
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +25 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
- package/dist/cjs/hooks/index.cjs +12 -0
- package/dist/cjs/hooks/index.cjs.map +1 -1
- package/dist/cjs/hooks/types.cjs +1 -0
- package/dist/cjs/hooks/types.cjs.map +1 -1
- package/dist/cjs/langfuse.cjs +8 -0
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -6
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +38 -13
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +19 -7
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +331 -5
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +41 -5
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +25 -4
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +4 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/preempt.cjs +132 -0
- package/dist/cjs/llm/preempt.cjs.map +1 -0
- package/dist/cjs/main.cjs +36 -5
- package/dist/cjs/messages/alternation.cjs +92 -0
- package/dist/cjs/messages/alternation.cjs.map +1 -0
- package/dist/cjs/messages/cache.cjs +54 -33
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/contextPruning.cjs +17 -43
- package/dist/cjs/messages/contextPruning.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +315 -23
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +290 -60
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/handoffCue.cjs +63 -0
- package/dist/cjs/messages/handoffCue.cjs.map +1 -0
- package/dist/cjs/messages/index.cjs +4 -1
- package/dist/cjs/messages/injected.cjs +60 -0
- package/dist/cjs/messages/injected.cjs.map +1 -0
- package/dist/cjs/messages/prune.cjs +503 -127
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/run.cjs +80 -7
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/handlers.cjs +18 -9
- package/dist/cjs/session/handlers.cjs.map +1 -1
- package/dist/cjs/stream.cjs +35 -10
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +28 -14
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +56 -63
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/keenable-scraper.cjs +90 -0
- package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -0
- package/dist/cjs/tools/search/tool.cjs +9 -1
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/toolOutputReferences.cjs +6 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/llm.cjs +1 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +307 -20
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/cjs/utils/toolContent.cjs +1514 -0
- package/dist/cjs/utils/toolContent.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +2 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/constants.mjs +19 -1
- package/dist/esm/common/constants.mjs.map +1 -1
- package/dist/esm/events.mjs +10 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +798 -116
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +3 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +25 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
- package/dist/esm/hooks/index.mjs +12 -1
- package/dist/esm/hooks/index.mjs.map +1 -1
- package/dist/esm/hooks/types.mjs +1 -0
- package/dist/esm/hooks/types.mjs.map +1 -1
- package/dist/esm/langfuse.mjs +9 -1
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -6
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +38 -13
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +19 -7
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +332 -8
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +41 -5
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +25 -4
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +4 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/preempt.mjs +131 -0
- package/dist/esm/llm/preempt.mjs.map +1 -0
- package/dist/esm/main.mjs +14 -11
- package/dist/esm/messages/alternation.mjs +91 -0
- package/dist/esm/messages/alternation.mjs.map +1 -0
- package/dist/esm/messages/cache.mjs +55 -34
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/contextPruning.mjs +17 -43
- package/dist/esm/messages/contextPruning.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +305 -24
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +290 -61
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/handoffCue.mjs +61 -0
- package/dist/esm/messages/handoffCue.mjs.map +1 -0
- package/dist/esm/messages/index.mjs +4 -1
- package/dist/esm/messages/injected.mjs +60 -0
- package/dist/esm/messages/injected.mjs.map +1 -0
- package/dist/esm/messages/prune.mjs +500 -128
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/run.mjs +80 -7
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/handlers.mjs +19 -10
- package/dist/esm/session/handlers.mjs.map +1 -1
- package/dist/esm/stream.mjs +34 -11
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +28 -14
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +56 -63
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/keenable-scraper.mjs +88 -0
- package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -0
- package/dist/esm/tools/search/tool.mjs +9 -1
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/toolOutputReferences.mjs +6 -0
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/llm.mjs +1 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +307 -21
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/esm/utils/toolContent.mjs +1503 -0
- package/dist/esm/utils/toolContent.mjs.map +1 -0
- package/dist/types/common/constants.d.ts +18 -0
- package/dist/types/graphs/Graph.d.ts +139 -2
- package/dist/types/hooks/HookRegistry.d.ts +15 -0
- package/dist/types/hooks/index.d.ts +12 -1
- package/dist/types/hooks/types.d.ts +45 -6
- package/dist/types/index.d.ts +1 -1
- package/dist/types/llm/invoke.d.ts +34 -1
- package/dist/types/llm/openai/index.d.ts +4 -0
- package/dist/types/llm/openai/utils/index.d.ts +2 -0
- package/dist/types/llm/openrouter/index.d.ts +5 -0
- package/dist/types/llm/preempt.d.ts +40 -0
- package/dist/types/messages/alternation.d.ts +23 -0
- package/dist/types/messages/contextPruning.d.ts +2 -1
- package/dist/types/messages/core.d.ts +36 -0
- package/dist/types/messages/format.d.ts +6 -0
- package/dist/types/messages/handoffCue.d.ts +40 -0
- package/dist/types/messages/index.d.ts +3 -0
- package/dist/types/messages/injected.d.ts +3 -0
- package/dist/types/messages/prune.d.ts +16 -12
- package/dist/types/run.d.ts +7 -0
- package/dist/types/stream.d.ts +14 -0
- package/dist/types/tools/ToolNode.d.ts +0 -7
- package/dist/types/tools/search/keenable-scraper.d.ts +15 -0
- package/dist/types/tools/search/types.d.ts +31 -2
- package/dist/types/types/graph.d.ts +8 -1
- package/dist/types/types/run.d.ts +65 -0
- package/dist/types/types/stream.d.ts +1 -26
- package/dist/types/utils/tokens.d.ts +7 -0
- package/dist/types/utils/toolContent.d.ts +107 -0
- package/package.json +1 -1
- package/src/__tests__/stream.eagerEventExecution.test.ts +74 -0
- package/src/agents/AgentContext.ts +1 -0
- package/src/{splitStream.test.ts → aggregator.test.ts} +59 -666
- package/src/common/constants.ts +21 -0
- package/src/events.ts +15 -1
- package/src/graphs/Graph.ts +1261 -198
- package/src/graphs/MultiAgentGraph.ts +6 -1
- package/src/graphs/__tests__/Graph.contextOverflow.test.ts +1139 -4
- package/src/graphs/__tests__/Graph.preemptSignal.test.ts +126 -0
- package/src/hooks/HookRegistry.ts +40 -0
- package/src/hooks/__tests__/preemptBoundary.test.ts +152 -0
- package/src/hooks/index.ts +16 -2
- package/src/hooks/types.ts +47 -3
- package/src/index.ts +1 -1
- package/src/langfuse.ts +26 -1
- package/src/llm/anthropic/utils/message_inputs.ts +158 -12
- package/src/llm/anthropic/utils/tool-id-normalization.test.ts +109 -0
- package/src/llm/bedrock/utils/message_inputs.test.ts +131 -1
- package/src/llm/bedrock/utils/message_inputs.ts +100 -24
- package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +15 -0
- package/src/llm/google/utils/common.test.ts +75 -9
- package/src/llm/google/utils/common.ts +34 -3
- package/src/llm/invoke.alternation.test.ts +87 -0
- package/src/llm/invoke.handoffCue.test.ts +112 -0
- package/src/llm/invoke.test.ts +488 -0
- package/src/llm/invoke.ts +611 -8
- package/src/llm/openai/index.ts +106 -6
- package/src/llm/openai/utils/index.ts +109 -53
- package/src/llm/openai/utils/messages.test.ts +330 -1
- package/src/llm/openrouter/index.ts +12 -2
- package/src/llm/openrouter/reasoning.test.ts +314 -0
- package/src/llm/preempt.test.ts +323 -0
- package/src/llm/preempt.ts +178 -0
- package/src/messages/__tests__/observationMasking.test.ts +93 -2
- package/src/messages/alternation.test.ts +212 -0
- package/src/messages/alternation.ts +112 -0
- package/src/messages/cache.tail.test.ts +193 -0
- package/src/messages/cache.test.ts +113 -0
- package/src/messages/cache.ts +92 -60
- package/src/messages/contextPruning.test.ts +184 -0
- package/src/messages/contextPruning.ts +49 -42
- package/src/messages/core.ts +653 -40
- package/src/messages/ensureThinkingBlock.test.ts +49 -1
- package/src/messages/foldToollessToolBlocks.test.ts +163 -5
- package/src/messages/format.ts +454 -91
- package/src/messages/formatAgentMessages.steer.test.ts +267 -0
- package/src/messages/formatAgentMessages.test.ts +604 -14
- package/src/messages/formatAgentMessages.tools.test.ts +103 -0
- package/src/messages/handoffCue.test.ts +96 -0
- package/src/messages/handoffCue.ts +78 -0
- package/src/messages/index.ts +3 -0
- package/src/messages/injected.test.ts +90 -0
- package/src/messages/injected.ts +74 -0
- package/src/messages/prune.ts +996 -183
- package/src/run.ts +91 -6
- package/src/scripts/preempt-probe.ts +330 -0
- package/src/scripts/preempt-scenarios.ts +388 -0
- package/src/session/handlers.ts +32 -12
- package/src/specs/handoffCue.test.ts +165 -0
- package/src/specs/langfuse-callbacks.test.ts +352 -2
- package/src/specs/preemptSeal.test.ts +309 -0
- package/src/specs/prune.test.ts +1083 -6
- package/src/specs/summarization-unit.test.ts +105 -0
- package/src/specs/tokens.test.ts +609 -32
- package/src/stream.dispatch.test.ts +63 -0
- package/src/stream.ts +59 -23
- package/src/summarization/__tests__/node.test.ts +77 -0
- package/src/summarization/node.ts +46 -18
- package/src/tools/ToolNode.ts +150 -99
- package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +148 -1
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +112 -3
- package/src/tools/__tests__/annotateMessagesForLLM.test.ts +32 -0
- package/src/tools/__tests__/directToolHooks.test.ts +255 -7
- package/src/tools/search/keenable-scraper.test.ts +153 -0
- package/src/tools/search/keenable-scraper.ts +137 -0
- package/src/tools/search/tool.ts +13 -2
- package/src/tools/search/types.ts +50 -3
- package/src/tools/toolOutputReferences.ts +6 -0
- package/src/types/graph.ts +12 -1
- package/src/types/run.ts +67 -0
- package/src/types/stream.ts +1 -42
- package/src/utils/llm.test.ts +18 -0
- package/src/utils/llm.ts +4 -1
- package/src/utils/tokens.ts +586 -31
- package/src/utils/toolContent.test.ts +1432 -0
- package/src/utils/toolContent.ts +2707 -0
- package/dist/cjs/splitStream.cjs +0 -151
- package/dist/cjs/splitStream.cjs.map +0 -1
- package/dist/esm/splitStream.mjs +0 -150
- package/dist/esm/splitStream.mjs.map +0 -1
- package/dist/types/mockStream.d.ts +0 -32
- package/dist/types/splitStream.d.ts +0 -37
- package/src/mockStream.ts +0 -99
- package/src/splitStream.ts +0 -234
package/dist/esm/langfuse.mjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { isPresent, parseBooleanEnv } from "./utils/misc.mjs";
|
|
2
2
|
import { resolveLangfuseConfigForSpan, resolveTraceIdSeedForSpan, withLangfuseRuntimeScope } from "./langfuseRuntimeScope.mjs";
|
|
3
3
|
import { AIMessage, AIMessageChunk } from "@langchain/core/messages";
|
|
4
|
-
import { isParentCommand } from "@langchain/langgraph";
|
|
4
|
+
import { isGraphInterrupt, isParentCommand } from "@langchain/langgraph";
|
|
5
5
|
import { CallbackHandler } from "@langfuse/langchain";
|
|
6
6
|
import { context } from "@opentelemetry/api";
|
|
7
7
|
import { getLangfuseTracerProvider, propagateAttributes } from "@langfuse/tracing";
|
|
8
8
|
//#region src/langfuse.ts
|
|
9
9
|
const TRACE_METADATA_MAX_LENGTH = 200;
|
|
10
10
|
const LANGFUSE_FORCE_FLUSH_ON_DISPOSE = "LANGFUSE_FORCE_FLUSH_ON_DISPOSE";
|
|
11
|
+
const GRAPH_INTERRUPT_CONTROL_FLOW = { controlFlow: "GraphInterrupt" };
|
|
12
|
+
const GRAPH_INTERRUPT_TOOL_OUTPUT = JSON.stringify(GRAPH_INTERRUPT_CONTROL_FLOW);
|
|
11
13
|
function getLangfuseBedrockUsage(message) {
|
|
12
14
|
const usageMetadata = message.usage_metadata;
|
|
13
15
|
const bedrockUsage = message.response_metadata.metadata?.usage;
|
|
@@ -91,6 +93,7 @@ var ScopedLangfuseCallbackHandler = class extends CallbackHandler {
|
|
|
91
93
|
}
|
|
92
94
|
handleChainError(...args) {
|
|
93
95
|
const [error, runId, parentRunId] = args;
|
|
96
|
+
if (error != null && parentRunId != null && isGraphInterrupt(error)) return super.handleChainEnd(GRAPH_INTERRUPT_CONTROL_FLOW, runId, parentRunId);
|
|
94
97
|
if (error != null && parentRunId != null && isParentCommand(error)) return super.handleChainEnd({ controlFlow: "ParentCommand" }, runId, parentRunId);
|
|
95
98
|
return super.handleChainError(...args);
|
|
96
99
|
}
|
|
@@ -112,6 +115,11 @@ var ScopedLangfuseCallbackHandler = class extends CallbackHandler {
|
|
|
112
115
|
handleToolStart(...args) {
|
|
113
116
|
return this.withRuntimeContext(() => super.handleToolStart(...args));
|
|
114
117
|
}
|
|
118
|
+
handleToolError(...args) {
|
|
119
|
+
const [error, runId, parentRunId] = args;
|
|
120
|
+
if (error != null && parentRunId != null && isGraphInterrupt(error)) return super.handleToolEnd(GRAPH_INTERRUPT_TOOL_OUTPUT, runId, parentRunId);
|
|
121
|
+
return super.handleToolError(...args);
|
|
122
|
+
}
|
|
115
123
|
handleRetrieverStart(...args) {
|
|
116
124
|
return this.withRuntimeContext(() => super.handleRetrieverStart(...args));
|
|
117
125
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"langfuse.mjs","names":["otelContext"],"sources":["../../src/langfuse.ts"],"sourcesContent":["import { CallbackHandler } from '@langfuse/langchain';\nimport { isParentCommand } from '@langchain/langgraph';\nimport { context as otelContext } from '@opentelemetry/api';\nimport { AIMessage, AIMessageChunk } from '@langchain/core/messages';\nimport {\n getLangfuseTracerProvider,\n propagateAttributes,\n} from '@langfuse/tracing';\nimport type {\n AIMessageChunkFields,\n AIMessageFields,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ChatGeneration,\n Generation,\n LLMResult,\n} from '@langchain/core/outputs';\nimport type { PropagateAttributesParams } from '@langfuse/tracing';\nimport type * as t from '@/types';\nimport {\n resolveLangfuseConfigForSpan,\n resolveTraceIdSeedForSpan,\n withLangfuseRuntimeScope,\n} from '@/langfuseRuntimeScope';\nimport { isPresent, parseBooleanEnv } from '@/utils/misc';\n\nconst TRACE_METADATA_MAX_LENGTH = 200;\nconst LANGFUSE_FORCE_FLUSH_ON_DISPOSE = 'LANGFUSE_FORCE_FLUSH_ON_DISPOSE';\n\nexport type LangfuseTraceMetadata = Record<string, string>;\nexport type LangfuseTraceAttributes = Record<string, string | number | boolean>;\ntype LangfuseMetadata = NonNullable<t.LangfuseConfig['metadata']>;\ntype LangfuseConfigTraceAttributes = NonNullable<\n t.LangfuseConfig['librechatTraceAttributes']\n>;\n\ntype LangfuseHandlerParams = {\n userId?: string;\n sessionId?: string;\n traceMetadata?: LangfuseTraceMetadata;\n tags?: string[];\n traceIdSeed?: string;\n};\n\ntype AgentLangfuseHandlerParams = LangfuseHandlerParams & {\n langfuse?: t.LangfuseConfig;\n};\n\ntype LangfuseAttributeParams = AgentLangfuseHandlerParams & {\n traceName?: string;\n};\n\ntype FlushableTracerProvider = {\n forceFlush?: () => Promise<void> | void;\n};\n\ntype BedrockResponseUsage = {\n inputTokens?: number;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n};\n\ntype BedrockResponseMetadata = {\n metadata?: {\n usage?: BedrockResponseUsage;\n };\n};\n\nfunction getLangfuseBedrockUsage(\n message: AIMessage | AIMessageChunk\n): UsageMetadata | undefined {\n const usageMetadata = message.usage_metadata;\n const bedrockUsage = (message.response_metadata as BedrockResponseMetadata)\n .metadata?.usage;\n if (\n usageMetadata == null ||\n bedrockUsage == null ||\n usageMetadata.input_tokens !== bedrockUsage.inputTokens\n ) {\n return usageMetadata;\n }\n\n const cacheRead = bedrockUsage.cacheReadInputTokens ?? 0;\n const cacheCreation = bedrockUsage.cacheWriteInputTokens ?? 0;\n if (cacheRead === 0 && cacheCreation === 0) {\n return usageMetadata;\n }\n\n return {\n ...usageMetadata,\n input_tokens: usageMetadata.input_tokens + cacheRead + cacheCreation,\n };\n}\n\nfunction cloneMessageWithUsage(\n message: AIMessage | AIMessageChunk,\n usageMetadata: UsageMetadata\n): AIMessage | AIMessageChunk {\n const fields: AIMessageFields = {\n content: message.content,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n id: message.id,\n name: message.name,\n tool_calls: message.tool_calls,\n invalid_tool_calls: message.invalid_tool_calls,\n usage_metadata: usageMetadata,\n };\n\n if (message instanceof AIMessageChunk) {\n const chunkFields: AIMessageChunkFields = {\n ...fields,\n tool_call_chunks: message.tool_call_chunks,\n };\n return new AIMessageChunk(chunkFields);\n }\n\n return new AIMessage(fields);\n}\n\nfunction normalizeGenerationForLangfuse(generation: Generation): Generation {\n if (!('message' in generation)) {\n return generation;\n }\n\n const message = (generation as ChatGeneration).message;\n if (!(message instanceof AIMessage || message instanceof AIMessageChunk)) {\n return generation;\n }\n\n const usageMetadata = getLangfuseBedrockUsage(message);\n if (usageMetadata == null || usageMetadata === message.usage_metadata) {\n return generation;\n }\n\n const chatGeneration: ChatGeneration = {\n ...(generation as ChatGeneration),\n message: cloneMessageWithUsage(message, usageMetadata),\n };\n return chatGeneration;\n}\n\nfunction normalizeBedrockUsageForLangfuse(output: LLMResult): LLMResult {\n if (output.generations.length === 0) {\n return output;\n }\n\n const listIndex = output.generations.length - 1;\n const generationList = output.generations[listIndex];\n if (generationList.length === 0) {\n return output;\n }\n\n const generationIndex = generationList.length - 1;\n const generation = generationList[generationIndex];\n const normalized = normalizeGenerationForLangfuse(generation);\n if (normalized === generation) {\n return output;\n }\n\n const generations = [...output.generations];\n generations[listIndex] = [...generationList];\n generations[listIndex][generationIndex] = normalized;\n return { ...output, generations };\n}\n\nclass ScopedLangfuseCallbackHandler extends CallbackHandler {\n private readonly langfuse?: t.LangfuseConfig;\n private readonly traceIdSeed?: string;\n\n constructor(params?: AgentLangfuseHandlerParams) {\n const { langfuse, traceIdSeed, ...handlerParams } = params ?? {};\n super(handlerParams);\n this.langfuse = langfuse;\n this.traceIdSeed = traceIdSeed;\n }\n\n private getDeterministicTraceSeed(): string | undefined {\n return this.langfuse?.deterministicTraceId === true\n ? this.traceIdSeed\n : undefined;\n }\n\n private withRuntimeContext<T>(action: () => T): T {\n const activeContext = otelContext.active();\n const langfuse =\n resolveLangfuseConfigForSpan(activeContext) ?? this.langfuse;\n const seed = this.getDeterministicTraceSeed();\n return withLangfuseRuntimeScope(\n {\n langfuse,\n traceIdSeed: resolveTraceIdSeedForSpan(activeContext) ?? seed,\n },\n action\n );\n }\n\n // LangChain may invoke callback handlers outside the caller's OTEL context.\n // Re-enter tenant scope only for callbacks that start Langfuse observations;\n // end/error/token callbacks use spans already bound to a processor at start.\n override handleChainStart(\n ...args: Parameters<CallbackHandler['handleChainStart']>\n ): ReturnType<CallbackHandler['handleChainStart']> {\n return this.withRuntimeContext(() => super.handleChainStart(...args));\n }\n\n override handleChainError(\n ...args: Parameters<CallbackHandler['handleChainError']>\n ): ReturnType<CallbackHandler['handleChainError']> {\n const [error, runId, parentRunId] = args;\n if (error != null && parentRunId != null && isParentCommand(error)) {\n return super.handleChainEnd(\n { controlFlow: 'ParentCommand' },\n runId,\n parentRunId\n );\n }\n return super.handleChainError(...args);\n }\n\n override handleAgentAction(\n ...args: Parameters<CallbackHandler['handleAgentAction']>\n ): ReturnType<CallbackHandler['handleAgentAction']> {\n return this.withRuntimeContext(() => super.handleAgentAction(...args));\n }\n\n override handleGenerationStart(\n ...args: Parameters<CallbackHandler['handleGenerationStart']>\n ): ReturnType<CallbackHandler['handleGenerationStart']> {\n return this.withRuntimeContext(() => super.handleGenerationStart(...args));\n }\n\n override handleChatModelStart(\n ...args: Parameters<CallbackHandler['handleChatModelStart']>\n ): ReturnType<CallbackHandler['handleChatModelStart']> {\n return this.withRuntimeContext(() => super.handleChatModelStart(...args));\n }\n\n override handleLLMStart(\n ...args: Parameters<CallbackHandler['handleLLMStart']>\n ): ReturnType<CallbackHandler['handleLLMStart']> {\n return this.withRuntimeContext(() => super.handleLLMStart(...args));\n }\n\n override handleLLMEnd(\n output: LLMResult,\n runId: string,\n parentRunId?: string\n ): Promise<void> {\n return super.handleLLMEnd(\n normalizeBedrockUsageForLangfuse(output),\n runId,\n parentRunId\n );\n }\n\n override handleToolStart(\n ...args: Parameters<CallbackHandler['handleToolStart']>\n ): ReturnType<CallbackHandler['handleToolStart']> {\n return this.withRuntimeContext(() => super.handleToolStart(...args));\n }\n\n override handleRetrieverStart(\n ...args: Parameters<CallbackHandler['handleRetrieverStart']>\n ): ReturnType<CallbackHandler['handleRetrieverStart']> {\n return this.withRuntimeContext(() => super.handleRetrieverStart(...args));\n }\n}\n\nfunction hasLangfuseTracingConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.toolNodeTracing != null || langfuse?.toolOutputTracing != null\n );\n}\n\nfunction hasLangfuseTraceAttributes(langfuse?: t.LangfuseConfig): boolean {\n return (\n Object.keys(createTraceMetadata(langfuse?.metadata ?? {})).length > 0 ||\n Object.keys(\n createLibreChatTraceAttributes(langfuse?.librechatTraceAttributes ?? {})\n ).length > 0 ||\n (mergeLangfuseTags(undefined, langfuse?.tags)?.length ?? 0) > 0\n );\n}\n\nexport function hasLangfuseConfigCredentials(\n langfuse?: t.LangfuseConfig\n): langfuse is t.LangfuseConfig & {\n publicKey: string;\n secretKey: string;\n} {\n return (\n langfuse != null &&\n isPresent(langfuse.publicKey) &&\n isPresent(langfuse.secretKey)\n );\n}\n\nfunction hasLangfuseConfigBaseUrl(langfuse?: t.LangfuseConfig): boolean {\n return isPresent(langfuse?.baseUrl);\n}\n\nexport function isExplicitLangfuseConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.enabled != null ||\n isPresent(langfuse?.publicKey) ||\n isPresent(langfuse?.secretKey) ||\n isPresent(langfuse?.baseUrl) ||\n hasLangfuseTraceAttributes(langfuse) ||\n hasLangfuseTracingConfig(langfuse)\n );\n}\n\nfunction createTraceMetadata(\n metadata: Record<string, unknown>\n): LangfuseTraceMetadata {\n const traceMetadata: LangfuseTraceMetadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (value == null) {\n continue;\n }\n const stringValue = typeof value === 'string' ? value : String(value);\n if (\n stringValue.trim() === '' ||\n stringValue.length > TRACE_METADATA_MAX_LENGTH\n ) {\n continue;\n }\n traceMetadata[key] = stringValue;\n }\n return traceMetadata;\n}\n\nexport function createLibreChatTraceAttributes(\n attributes: LangfuseConfigTraceAttributes\n): LangfuseTraceAttributes {\n const librechatTraceAttributes: LangfuseTraceAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value == null || key.trim() === '') {\n continue;\n }\n if (typeof value === 'string') {\n if (value.trim() === '' || value.length > TRACE_METADATA_MAX_LENGTH) {\n continue;\n }\n librechatTraceAttributes[key] = value;\n continue;\n }\n librechatTraceAttributes[key] = value;\n }\n return librechatTraceAttributes;\n}\n\nexport function createLangfuseTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n}: {\n messageId?: unknown;\n parentMessageId?: unknown;\n agentId?: unknown;\n agentName?: unknown;\n}): LangfuseTraceMetadata {\n return createTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n });\n}\n\nfunction mergeLangfuseTraceMetadata(\n traceMetadata?: LangfuseTraceMetadata,\n metadata?: LangfuseMetadata\n): LangfuseTraceMetadata | undefined {\n const merged = createTraceMetadata({\n ...(metadata ?? {}),\n ...(traceMetadata ?? {}),\n });\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction mergeLangfuseTags(\n tags?: string[],\n configTags?: string[]\n): string[] | undefined {\n const merged = [...(tags ?? []), ...(configTags ?? [])].filter(\n (tag) => tag.trim() !== ''\n );\n return merged.length > 0 ? [...new Set(merged)] : undefined;\n}\n\nexport function getLangfuseTraceName(\n traceMetadata?: LangfuseTraceMetadata,\n fallback: string = 'LibreChat Agent'\n): string {\n const agentName = traceMetadata?.agentName;\n return isPresent(agentName) ? `${fallback}: ${agentName}` : fallback;\n}\n\nexport function hasLangfuseEnvConfig(): boolean {\n return hasLangfuseEnvCredentials();\n}\n\nexport function hasLangfuseEnvCredentials(): boolean {\n return (\n isPresent(process.env.LANGFUSE_SECRET_KEY) &&\n isPresent(process.env.LANGFUSE_PUBLIC_KEY)\n );\n}\n\nexport function shouldCreateLangfuseHandler(\n langfuse?: t.LangfuseConfig\n): boolean {\n if (langfuse?.enabled === false) {\n return false;\n }\n return (\n hasLangfuseEnvConfig() ||\n hasLangfuseConfigCredentials(langfuse) ||\n (hasLangfuseConfigBaseUrl(langfuse) && hasLangfuseEnvCredentials())\n );\n}\n\nexport function createLegacyLangfuseHandler(\n params: LangfuseHandlerParams\n): CallbackHandler {\n return new ScopedLangfuseCallbackHandler(params);\n}\n\nexport function createLangfuseHandler({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n tags,\n traceIdSeed,\n}: AgentLangfuseHandlerParams): CallbackHandler | undefined {\n if (!shouldCreateLangfuseHandler(langfuse)) {\n return undefined;\n }\n return new ScopedLangfuseCallbackHandler({\n userId,\n sessionId,\n traceMetadata: mergeLangfuseTraceMetadata(\n traceMetadata,\n langfuse?.metadata\n ),\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n langfuse,\n traceIdSeed,\n });\n}\n\nfunction createPropagateAttributeParams({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n traceName,\n tags,\n}: LangfuseAttributeParams): PropagateAttributesParams {\n return {\n userId,\n sessionId,\n traceName,\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n metadata: mergeLangfuseTraceMetadata(traceMetadata, langfuse?.metadata),\n };\n}\n\nexport function withLangfuseAttributes<T>(\n params: LangfuseAttributeParams,\n action: () => T\n): T {\n if (!shouldCreateLangfuseHandler(params.langfuse)) {\n return action();\n }\n return propagateAttributes(createPropagateAttributeParams(params), action);\n}\n\nexport function hasExplicitLangfuseConfig(\n contexts: Iterable<{ langfuse?: t.LangfuseConfig }>\n): boolean {\n for (const context of contexts) {\n if (isExplicitLangfuseConfig(context.langfuse)) {\n return true;\n }\n }\n return false;\n}\n\nexport function isLangfuseCallbackHandler(value: unknown): boolean {\n return value instanceof CallbackHandler;\n}\n\nexport async function disposeLangfuseHandler(value: unknown): Promise<void> {\n if (\n value == null ||\n parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE]) !== true\n ) {\n return;\n }\n const provider = getLangfuseTracerProvider() as FlushableTracerProvider;\n await provider.forceFlush?.();\n}\n"],"mappings":";;;;;;;;AA2BA,MAAM,4BAA4B;AAClC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BAAkB,MAAM,UAAU,IAAI;EAC5C,UAAU,2BAA2B,eAAe,UAAU,QAAQ;CACxE;AACF;AAEA,SAAgB,uBACd,QACA,QACG;CACH,IAAI,CAAC,4BAA4B,OAAO,QAAQ,GAC9C,OAAO,OAAO;CAEhB,OAAO,oBAAoB,+BAA+B,MAAM,GAAG,MAAM;AAC3E;AAaA,SAAgB,0BAA0B,OAAyB;CACjE,OAAO,iBAAiB;AAC1B;AAEA,eAAsB,uBAAuB,OAA+B;CAC1E,IACE,SAAS,QACT,gBAAgB,QAAQ,IAAI,gCAAgC,MAAM,MAElE;CAGF,MADiB,0BACJ,CAAC,CAAC,aAAa;AAC9B"}
|
|
1
|
+
{"version":3,"file":"langfuse.mjs","names":["otelContext"],"sources":["../../src/langfuse.ts"],"sourcesContent":["import { CallbackHandler } from '@langfuse/langchain';\nimport { context as otelContext } from '@opentelemetry/api';\nimport { AIMessage, AIMessageChunk } from '@langchain/core/messages';\nimport { isGraphInterrupt, isParentCommand } from '@langchain/langgraph';\nimport {\n getLangfuseTracerProvider,\n propagateAttributes,\n} from '@langfuse/tracing';\nimport type {\n AIMessageChunkFields,\n AIMessageFields,\n UsageMetadata,\n} from '@langchain/core/messages';\nimport type {\n ChatGeneration,\n Generation,\n LLMResult,\n} from '@langchain/core/outputs';\nimport type { PropagateAttributesParams } from '@langfuse/tracing';\nimport type * as t from '@/types';\nimport {\n resolveLangfuseConfigForSpan,\n resolveTraceIdSeedForSpan,\n withLangfuseRuntimeScope,\n} from '@/langfuseRuntimeScope';\nimport { isPresent, parseBooleanEnv } from '@/utils/misc';\n\nconst TRACE_METADATA_MAX_LENGTH = 200;\nconst LANGFUSE_FORCE_FLUSH_ON_DISPOSE = 'LANGFUSE_FORCE_FLUSH_ON_DISPOSE';\nconst GRAPH_INTERRUPT_CONTROL_FLOW = { controlFlow: 'GraphInterrupt' } as const;\nconst GRAPH_INTERRUPT_TOOL_OUTPUT = JSON.stringify(\n GRAPH_INTERRUPT_CONTROL_FLOW\n);\n\nexport type LangfuseTraceMetadata = Record<string, string>;\nexport type LangfuseTraceAttributes = Record<string, string | number | boolean>;\ntype LangfuseMetadata = NonNullable<t.LangfuseConfig['metadata']>;\ntype LangfuseConfigTraceAttributes = NonNullable<\n t.LangfuseConfig['librechatTraceAttributes']\n>;\n\ntype LangfuseHandlerParams = {\n userId?: string;\n sessionId?: string;\n traceMetadata?: LangfuseTraceMetadata;\n tags?: string[];\n traceIdSeed?: string;\n};\n\ntype AgentLangfuseHandlerParams = LangfuseHandlerParams & {\n langfuse?: t.LangfuseConfig;\n};\n\ntype LangfuseAttributeParams = AgentLangfuseHandlerParams & {\n traceName?: string;\n};\n\ntype FlushableTracerProvider = {\n forceFlush?: () => Promise<void> | void;\n};\n\ntype BedrockResponseUsage = {\n inputTokens?: number;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n};\n\ntype BedrockResponseMetadata = {\n metadata?: {\n usage?: BedrockResponseUsage;\n };\n};\n\nfunction getLangfuseBedrockUsage(\n message: AIMessage | AIMessageChunk\n): UsageMetadata | undefined {\n const usageMetadata = message.usage_metadata;\n const bedrockUsage = (message.response_metadata as BedrockResponseMetadata)\n .metadata?.usage;\n if (\n usageMetadata == null ||\n bedrockUsage == null ||\n usageMetadata.input_tokens !== bedrockUsage.inputTokens\n ) {\n return usageMetadata;\n }\n\n const cacheRead = bedrockUsage.cacheReadInputTokens ?? 0;\n const cacheCreation = bedrockUsage.cacheWriteInputTokens ?? 0;\n if (cacheRead === 0 && cacheCreation === 0) {\n return usageMetadata;\n }\n\n return {\n ...usageMetadata,\n input_tokens: usageMetadata.input_tokens + cacheRead + cacheCreation,\n };\n}\n\nfunction cloneMessageWithUsage(\n message: AIMessage | AIMessageChunk,\n usageMetadata: UsageMetadata\n): AIMessage | AIMessageChunk {\n const fields: AIMessageFields = {\n content: message.content,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n id: message.id,\n name: message.name,\n tool_calls: message.tool_calls,\n invalid_tool_calls: message.invalid_tool_calls,\n usage_metadata: usageMetadata,\n };\n\n if (message instanceof AIMessageChunk) {\n const chunkFields: AIMessageChunkFields = {\n ...fields,\n tool_call_chunks: message.tool_call_chunks,\n };\n return new AIMessageChunk(chunkFields);\n }\n\n return new AIMessage(fields);\n}\n\nfunction normalizeGenerationForLangfuse(generation: Generation): Generation {\n if (!('message' in generation)) {\n return generation;\n }\n\n const message = (generation as ChatGeneration).message;\n if (!(message instanceof AIMessage || message instanceof AIMessageChunk)) {\n return generation;\n }\n\n const usageMetadata = getLangfuseBedrockUsage(message);\n if (usageMetadata == null || usageMetadata === message.usage_metadata) {\n return generation;\n }\n\n const chatGeneration: ChatGeneration = {\n ...(generation as ChatGeneration),\n message: cloneMessageWithUsage(message, usageMetadata),\n };\n return chatGeneration;\n}\n\nfunction normalizeBedrockUsageForLangfuse(output: LLMResult): LLMResult {\n if (output.generations.length === 0) {\n return output;\n }\n\n const listIndex = output.generations.length - 1;\n const generationList = output.generations[listIndex];\n if (generationList.length === 0) {\n return output;\n }\n\n const generationIndex = generationList.length - 1;\n const generation = generationList[generationIndex];\n const normalized = normalizeGenerationForLangfuse(generation);\n if (normalized === generation) {\n return output;\n }\n\n const generations = [...output.generations];\n generations[listIndex] = [...generationList];\n generations[listIndex][generationIndex] = normalized;\n return { ...output, generations };\n}\n\nclass ScopedLangfuseCallbackHandler extends CallbackHandler {\n private readonly langfuse?: t.LangfuseConfig;\n private readonly traceIdSeed?: string;\n\n constructor(params?: AgentLangfuseHandlerParams) {\n const { langfuse, traceIdSeed, ...handlerParams } = params ?? {};\n super(handlerParams);\n this.langfuse = langfuse;\n this.traceIdSeed = traceIdSeed;\n }\n\n private getDeterministicTraceSeed(): string | undefined {\n return this.langfuse?.deterministicTraceId === true\n ? this.traceIdSeed\n : undefined;\n }\n\n private withRuntimeContext<T>(action: () => T): T {\n const activeContext = otelContext.active();\n const langfuse =\n resolveLangfuseConfigForSpan(activeContext) ?? this.langfuse;\n const seed = this.getDeterministicTraceSeed();\n return withLangfuseRuntimeScope(\n {\n langfuse,\n traceIdSeed: resolveTraceIdSeedForSpan(activeContext) ?? seed,\n },\n action\n );\n }\n\n // LangChain may invoke callback handlers outside the caller's OTEL context.\n // Re-enter tenant scope only for callbacks that start Langfuse observations;\n // end/error/token callbacks use spans already bound to a processor at start.\n override handleChainStart(\n ...args: Parameters<CallbackHandler['handleChainStart']>\n ): ReturnType<CallbackHandler['handleChainStart']> {\n return this.withRuntimeContext(() => super.handleChainStart(...args));\n }\n\n override handleChainError(\n ...args: Parameters<CallbackHandler['handleChainError']>\n ): ReturnType<CallbackHandler['handleChainError']> {\n const [error, runId, parentRunId] = args;\n if (error != null && parentRunId != null && isGraphInterrupt(error)) {\n return super.handleChainEnd(\n GRAPH_INTERRUPT_CONTROL_FLOW,\n runId,\n parentRunId\n );\n }\n if (error != null && parentRunId != null && isParentCommand(error)) {\n return super.handleChainEnd(\n { controlFlow: 'ParentCommand' },\n runId,\n parentRunId\n );\n }\n return super.handleChainError(...args);\n }\n\n override handleAgentAction(\n ...args: Parameters<CallbackHandler['handleAgentAction']>\n ): ReturnType<CallbackHandler['handleAgentAction']> {\n return this.withRuntimeContext(() => super.handleAgentAction(...args));\n }\n\n override handleGenerationStart(\n ...args: Parameters<CallbackHandler['handleGenerationStart']>\n ): ReturnType<CallbackHandler['handleGenerationStart']> {\n return this.withRuntimeContext(() => super.handleGenerationStart(...args));\n }\n\n override handleChatModelStart(\n ...args: Parameters<CallbackHandler['handleChatModelStart']>\n ): ReturnType<CallbackHandler['handleChatModelStart']> {\n return this.withRuntimeContext(() => super.handleChatModelStart(...args));\n }\n\n override handleLLMStart(\n ...args: Parameters<CallbackHandler['handleLLMStart']>\n ): ReturnType<CallbackHandler['handleLLMStart']> {\n return this.withRuntimeContext(() => super.handleLLMStart(...args));\n }\n\n override handleLLMEnd(\n output: LLMResult,\n runId: string,\n parentRunId?: string\n ): Promise<void> {\n return super.handleLLMEnd(\n normalizeBedrockUsageForLangfuse(output),\n runId,\n parentRunId\n );\n }\n\n override handleToolStart(\n ...args: Parameters<CallbackHandler['handleToolStart']>\n ): ReturnType<CallbackHandler['handleToolStart']> {\n return this.withRuntimeContext(() => super.handleToolStart(...args));\n }\n\n override handleToolError(\n ...args: Parameters<CallbackHandler['handleToolError']>\n ): ReturnType<CallbackHandler['handleToolError']> {\n const [error, runId, parentRunId] = args;\n if (error != null && parentRunId != null && isGraphInterrupt(error)) {\n return super.handleToolEnd(\n GRAPH_INTERRUPT_TOOL_OUTPUT,\n runId,\n parentRunId\n );\n }\n return super.handleToolError(...args);\n }\n\n override handleRetrieverStart(\n ...args: Parameters<CallbackHandler['handleRetrieverStart']>\n ): ReturnType<CallbackHandler['handleRetrieverStart']> {\n return this.withRuntimeContext(() => super.handleRetrieverStart(...args));\n }\n}\n\nfunction hasLangfuseTracingConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.toolNodeTracing != null || langfuse?.toolOutputTracing != null\n );\n}\n\nfunction hasLangfuseTraceAttributes(langfuse?: t.LangfuseConfig): boolean {\n return (\n Object.keys(createTraceMetadata(langfuse?.metadata ?? {})).length > 0 ||\n Object.keys(\n createLibreChatTraceAttributes(langfuse?.librechatTraceAttributes ?? {})\n ).length > 0 ||\n (mergeLangfuseTags(undefined, langfuse?.tags)?.length ?? 0) > 0\n );\n}\n\nexport function hasLangfuseConfigCredentials(\n langfuse?: t.LangfuseConfig\n): langfuse is t.LangfuseConfig & {\n publicKey: string;\n secretKey: string;\n} {\n return (\n langfuse != null &&\n isPresent(langfuse.publicKey) &&\n isPresent(langfuse.secretKey)\n );\n}\n\nfunction hasLangfuseConfigBaseUrl(langfuse?: t.LangfuseConfig): boolean {\n return isPresent(langfuse?.baseUrl);\n}\n\nexport function isExplicitLangfuseConfig(langfuse?: t.LangfuseConfig): boolean {\n return (\n langfuse?.enabled != null ||\n isPresent(langfuse?.publicKey) ||\n isPresent(langfuse?.secretKey) ||\n isPresent(langfuse?.baseUrl) ||\n hasLangfuseTraceAttributes(langfuse) ||\n hasLangfuseTracingConfig(langfuse)\n );\n}\n\nfunction createTraceMetadata(\n metadata: Record<string, unknown>\n): LangfuseTraceMetadata {\n const traceMetadata: LangfuseTraceMetadata = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (value == null) {\n continue;\n }\n const stringValue = typeof value === 'string' ? value : String(value);\n if (\n stringValue.trim() === '' ||\n stringValue.length > TRACE_METADATA_MAX_LENGTH\n ) {\n continue;\n }\n traceMetadata[key] = stringValue;\n }\n return traceMetadata;\n}\n\nexport function createLibreChatTraceAttributes(\n attributes: LangfuseConfigTraceAttributes\n): LangfuseTraceAttributes {\n const librechatTraceAttributes: LangfuseTraceAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (value == null || key.trim() === '') {\n continue;\n }\n if (typeof value === 'string') {\n if (value.trim() === '' || value.length > TRACE_METADATA_MAX_LENGTH) {\n continue;\n }\n librechatTraceAttributes[key] = value;\n continue;\n }\n librechatTraceAttributes[key] = value;\n }\n return librechatTraceAttributes;\n}\n\nexport function createLangfuseTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n}: {\n messageId?: unknown;\n parentMessageId?: unknown;\n agentId?: unknown;\n agentName?: unknown;\n}): LangfuseTraceMetadata {\n return createTraceMetadata({\n messageId,\n parentMessageId,\n agentId,\n agentName,\n });\n}\n\nfunction mergeLangfuseTraceMetadata(\n traceMetadata?: LangfuseTraceMetadata,\n metadata?: LangfuseMetadata\n): LangfuseTraceMetadata | undefined {\n const merged = createTraceMetadata({\n ...(metadata ?? {}),\n ...(traceMetadata ?? {}),\n });\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\nfunction mergeLangfuseTags(\n tags?: string[],\n configTags?: string[]\n): string[] | undefined {\n const merged = [...(tags ?? []), ...(configTags ?? [])].filter(\n (tag) => tag.trim() !== ''\n );\n return merged.length > 0 ? [...new Set(merged)] : undefined;\n}\n\nexport function getLangfuseTraceName(\n traceMetadata?: LangfuseTraceMetadata,\n fallback: string = 'LibreChat Agent'\n): string {\n const agentName = traceMetadata?.agentName;\n return isPresent(agentName) ? `${fallback}: ${agentName}` : fallback;\n}\n\nexport function hasLangfuseEnvConfig(): boolean {\n return hasLangfuseEnvCredentials();\n}\n\nexport function hasLangfuseEnvCredentials(): boolean {\n return (\n isPresent(process.env.LANGFUSE_SECRET_KEY) &&\n isPresent(process.env.LANGFUSE_PUBLIC_KEY)\n );\n}\n\nexport function shouldCreateLangfuseHandler(\n langfuse?: t.LangfuseConfig\n): boolean {\n if (langfuse?.enabled === false) {\n return false;\n }\n return (\n hasLangfuseEnvConfig() ||\n hasLangfuseConfigCredentials(langfuse) ||\n (hasLangfuseConfigBaseUrl(langfuse) && hasLangfuseEnvCredentials())\n );\n}\n\nexport function createLegacyLangfuseHandler(\n params: LangfuseHandlerParams\n): CallbackHandler {\n return new ScopedLangfuseCallbackHandler(params);\n}\n\nexport function createLangfuseHandler({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n tags,\n traceIdSeed,\n}: AgentLangfuseHandlerParams): CallbackHandler | undefined {\n if (!shouldCreateLangfuseHandler(langfuse)) {\n return undefined;\n }\n return new ScopedLangfuseCallbackHandler({\n userId,\n sessionId,\n traceMetadata: mergeLangfuseTraceMetadata(\n traceMetadata,\n langfuse?.metadata\n ),\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n langfuse,\n traceIdSeed,\n });\n}\n\nfunction createPropagateAttributeParams({\n langfuse,\n userId,\n sessionId,\n traceMetadata,\n traceName,\n tags,\n}: LangfuseAttributeParams): PropagateAttributesParams {\n return {\n userId,\n sessionId,\n traceName,\n tags: mergeLangfuseTags(tags, langfuse?.tags),\n metadata: mergeLangfuseTraceMetadata(traceMetadata, langfuse?.metadata),\n };\n}\n\nexport function withLangfuseAttributes<T>(\n params: LangfuseAttributeParams,\n action: () => T\n): T {\n if (!shouldCreateLangfuseHandler(params.langfuse)) {\n return action();\n }\n return propagateAttributes(createPropagateAttributeParams(params), action);\n}\n\nexport function hasExplicitLangfuseConfig(\n contexts: Iterable<{ langfuse?: t.LangfuseConfig }>\n): boolean {\n for (const context of contexts) {\n if (isExplicitLangfuseConfig(context.langfuse)) {\n return true;\n }\n }\n return false;\n}\n\nexport function isLangfuseCallbackHandler(value: unknown): boolean {\n return value instanceof CallbackHandler;\n}\n\nexport async function disposeLangfuseHandler(value: unknown): Promise<void> {\n if (\n value == null ||\n parseBooleanEnv(process.env[LANGFUSE_FORCE_FLUSH_ON_DISPOSE]) !== true\n ) {\n return;\n }\n const provider = getLangfuseTracerProvider() as FlushableTracerProvider;\n await provider.forceFlush?.();\n}\n"],"mappings":";;;;;;;;AA2BA,MAAM,4BAA4B;AAClC,MAAM,kCAAkC;AACxC,MAAM,+BAA+B,EAAE,aAAa,iBAAiB;AACrE,MAAM,8BAA8B,KAAK,UACvC,4BACF;AAyCA,SAAS,wBACP,SAC2B;CAC3B,MAAM,gBAAgB,QAAQ;CAC9B,MAAM,eAAgB,QAAQ,kBAC3B,UAAU;CACb,IACE,iBAAiB,QACjB,gBAAgB,QAChB,cAAc,iBAAiB,aAAa,aAE5C,OAAO;CAGT,MAAM,YAAY,aAAa,wBAAwB;CACvD,MAAM,gBAAgB,aAAa,yBAAyB;CAC5D,IAAI,cAAc,KAAK,kBAAkB,GACvC,OAAO;CAGT,OAAO;EACL,GAAG;EACH,cAAc,cAAc,eAAe,YAAY;CACzD;AACF;AAEA,SAAS,sBACP,SACA,eAC4B;CAC5B,MAAM,SAA0B;EAC9B,SAAS,QAAQ;EACjB,mBAAmB,QAAQ;EAC3B,mBAAmB,QAAQ;EAC3B,IAAI,QAAQ;EACZ,MAAM,QAAQ;EACd,YAAY,QAAQ;EACpB,oBAAoB,QAAQ;EAC5B,gBAAgB;CAClB;CAEA,IAAI,mBAAmB,gBAKrB,OAAO,IAAI,eAAe;EAHxB,GAAG;EACH,kBAAkB,QAAQ;CAEQ,CAAC;CAGvC,OAAO,IAAI,UAAU,MAAM;AAC7B;AAEA,SAAS,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11 @@
|
|
|
1
1
|
import "../../../common/enum.mjs";
|
|
2
2
|
import "../../../common/index.mjs";
|
|
3
|
+
import { HARD_MAX_TOOL_RESULT_CHARS } from "../../../utils/truncation.mjs";
|
|
4
|
+
import { cloneToolMessageWithContent, serializeStructuredValueBounded } from "../../../utils/toolContent.mjs";
|
|
3
5
|
import { isAnthropicImageBlockParam } from "../types.mjs";
|
|
4
6
|
import { HumanMessage, convertToProviderContentBlock, isAIMessage, isDataContentBlock, parseBase64DataUrl } from "@langchain/core/messages";
|
|
5
7
|
import { createHash } from "node:crypto";
|
|
8
|
+
import { isProxy } from "node:util/types";
|
|
6
9
|
//#region src/llm/anthropic/utils/message_inputs.ts
|
|
7
10
|
/**
|
|
8
11
|
* This util file contains functions for converting LangChain messages to Anthropic messages.
|
|
@@ -65,17 +68,81 @@ function hoistToolResultCacheControl(content) {
|
|
|
65
68
|
let cacheControl;
|
|
66
69
|
return {
|
|
67
70
|
content: content.map((block) => {
|
|
68
|
-
if ("
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
if (typeof block !== "object" || block == null || isProxy(block)) return block;
|
|
72
|
+
try {
|
|
73
|
+
const descriptors = Object.getOwnPropertyDescriptors(block);
|
|
74
|
+
const cacheControlDescriptor = descriptors.cache_control;
|
|
75
|
+
if (cacheControlDescriptor.enumerable === true && "value" in cacheControlDescriptor) {
|
|
76
|
+
cacheControl ??= cacheControlDescriptor.value;
|
|
77
|
+
delete descriptors.cache_control;
|
|
78
|
+
return Object.create(Object.getPrototypeOf(block), descriptors);
|
|
79
|
+
}
|
|
80
|
+
} catch {
|
|
81
|
+
return block;
|
|
73
82
|
}
|
|
74
83
|
return block;
|
|
75
84
|
}),
|
|
76
85
|
cacheControl
|
|
77
86
|
};
|
|
78
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* A ToolMessage can already contain an Anthropic-native `tool_result` block
|
|
90
|
+
* (for example, when a tool returns provider-native structured content). The
|
|
91
|
+
* outer ToolMessage conversion supplies the one required result envelope, so
|
|
92
|
+
* unwrap an exact single nested envelope rather than sending an invalid
|
|
93
|
+
* `tool_result.content: [{ type: "tool_result", ... }]` payload.
|
|
94
|
+
*/
|
|
95
|
+
function unwrapToolMessageResultContent(content) {
|
|
96
|
+
if (!Array.isArray(content) || content.length !== 1) return {
|
|
97
|
+
content,
|
|
98
|
+
cacheControl: void 0,
|
|
99
|
+
isError: void 0
|
|
100
|
+
};
|
|
101
|
+
const block = content[0];
|
|
102
|
+
if (typeof block !== "object" || block == null || isProxy(block)) return {
|
|
103
|
+
content,
|
|
104
|
+
cacheControl: void 0,
|
|
105
|
+
isError: void 0
|
|
106
|
+
};
|
|
107
|
+
try {
|
|
108
|
+
const type = Object.getOwnPropertyDescriptor(block, "type");
|
|
109
|
+
const nestedContent = Object.getOwnPropertyDescriptor(block, "content");
|
|
110
|
+
if (type?.enumerable !== true || !("value" in type) || type.value !== "tool_result" || nestedContent != null && (nestedContent.enumerable !== true || !("value" in nestedContent))) return {
|
|
111
|
+
content,
|
|
112
|
+
cacheControl: void 0,
|
|
113
|
+
isError: void 0
|
|
114
|
+
};
|
|
115
|
+
const cacheControl = Object.getOwnPropertyDescriptor(block, "cache_control");
|
|
116
|
+
const isError = Object.getOwnPropertyDescriptor(block, "is_error");
|
|
117
|
+
const nested = nestedContent != null && "value" in nestedContent ? nestedContent.value : void 0;
|
|
118
|
+
if (typeof nested === "string") return {
|
|
119
|
+
content: nested,
|
|
120
|
+
cacheControl: cacheControl?.enumerable === true && "value" in cacheControl ? cacheControl.value : void 0,
|
|
121
|
+
isError: isError?.enumerable === true && "value" in isError && typeof isError.value === "boolean" ? isError.value : void 0
|
|
122
|
+
};
|
|
123
|
+
if (Array.isArray(nested)) return {
|
|
124
|
+
content: nested,
|
|
125
|
+
cacheControl: cacheControl?.enumerable === true && "value" in cacheControl ? cacheControl.value : void 0,
|
|
126
|
+
isError: isError?.enumerable === true && "value" in isError && typeof isError.value === "boolean" ? isError.value : void 0
|
|
127
|
+
};
|
|
128
|
+
if (nested == null) return {
|
|
129
|
+
content: void 0,
|
|
130
|
+
cacheControl: cacheControl?.enumerable === true && "value" in cacheControl ? cacheControl.value : void 0,
|
|
131
|
+
isError: isError?.enumerable === true && "value" in isError && typeof isError.value === "boolean" ? isError.value : void 0
|
|
132
|
+
};
|
|
133
|
+
return {
|
|
134
|
+
content: serializeStructuredValueBounded(nested, HARD_MAX_TOOL_RESULT_CHARS).content,
|
|
135
|
+
cacheControl: cacheControl?.enumerable === true && "value" in cacheControl ? cacheControl.value : void 0,
|
|
136
|
+
isError: isError?.enumerable === true && "value" in isError && typeof isError.value === "boolean" ? isError.value : void 0
|
|
137
|
+
};
|
|
138
|
+
} catch {
|
|
139
|
+
return {
|
|
140
|
+
content,
|
|
141
|
+
cacheControl: void 0,
|
|
142
|
+
isError: void 0
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
79
146
|
function _ensureMessageContents(messages) {
|
|
80
147
|
const updatedMsgs = [];
|
|
81
148
|
for (const message of messages) if (message._getType() === "tool") if (typeof message.content === "string") {
|
|
@@ -91,13 +158,19 @@ function _ensureMessageContents(messages) {
|
|
|
91
158
|
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id)
|
|
92
159
|
}] }));
|
|
93
160
|
} else {
|
|
94
|
-
const
|
|
161
|
+
const toolMessage = message;
|
|
162
|
+
const toolMessageContent = toolMessage.content;
|
|
163
|
+
const unwrapped = unwrapToolMessageResultContent(toolMessageContent);
|
|
164
|
+
const formattedContent = unwrapped.content == null ? void 0 : _formatContent(unwrapped.content === toolMessageContent ? toolMessage : cloneToolMessageWithContent(toolMessage, unwrapped.content));
|
|
165
|
+
const { content: hoistedContent, cacheControl: innerCacheControl } = formattedContent != null ? hoistToolResultCacheControl(formattedContent) : {
|
|
95
166
|
content: void 0,
|
|
96
167
|
cacheControl: void 0
|
|
97
168
|
};
|
|
169
|
+
const cacheControl = unwrapped.cacheControl ?? innerCacheControl;
|
|
98
170
|
updatedMsgs.push(new HumanMessage({ content: [{
|
|
99
171
|
type: "tool_result",
|
|
100
172
|
...hoistedContent != null ? { content: hoistedContent } : {},
|
|
173
|
+
...unwrapped.isError != null ? { is_error: unwrapped.isError } : {},
|
|
101
174
|
...cacheControl != null ? { cache_control: cacheControl } : {},
|
|
102
175
|
tool_use_id: normalizeAnthropicToolCallId(message.tool_call_id)
|
|
103
176
|
}] }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.mjs","names":["redactedPart"],"sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport { createHash } from 'node:crypto';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n type ToolMessage,\n isAIMessage,\n type Data,\n type StandardContentBlockConverter,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicCompactionBlockParam,\n AnthropicToolResponse,\n} from '../types';\nimport { Constants } from '@/common';\n\ntype StandardTextBlock = Data.StandardTextBlock;\ntype StandardImageBlock = Data.StandardImageBlock;\ntype StandardFileBlock = Data.StandardFileBlock;\ntype ImageUrlContentBlock = MessageContentComplex & {\n image_url: string | { url: string };\n};\ntype GoogleFunctionCallBlock = MessageContentComplex & {\n functionCall: {\n name: string;\n args: Record<string, unknown>;\n };\n};\n\nconst ANTHROPIC_EMPTY_TEXT_PLACEHOLDER = '_';\nconst CLAUDE_4_RELEASE_DATE_MODEL_PATTERN =\n /claude-(?:opus|sonnet|haiku)-4-\\d{8}(?:[-.@]|$)/i;\nconst CLAUDE_4_MINOR_MODEL_PATTERN =\n /claude-(?:opus|sonnet|haiku)-4[-.](\\d+)(?:[-.@]|$)/i;\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n}\n\nconst ANTHROPIC_TOOL_USE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\nconst ANTHROPIC_TOOL_USE_ID_MAX_LENGTH = 64;\nconst ANTHROPIC_TOOL_USE_ID_HASH_LENGTH = 10;\n\n/**\n * Normalize a tool-call ID to satisfy Anthropic's `^[a-zA-Z0-9_-]+$` and 64-char\n * constraints. Pure and deterministic — same input always yields the same output,\n * so paired `tool_use.id` and `tool_result.tool_use_id` stay matched without\n * needing a session map. IDs that already comply pass through unchanged.\n *\n * For non-compliant inputs we sanitize then append a short SHA-256 prefix of\n * the original ID to preserve uniqueness when truncation would otherwise\n * collapse distinct IDs to the same value (e.g. two long Responses-style IDs\n * sharing a 64-char prefix). The hash is computed against the raw input so\n * inputs that differ only after the truncation cutoff still produce distinct\n * outputs.\n */\nexport function normalizeAnthropicToolCallId(id: string): string;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined {\n if (id == null) {\n return id;\n }\n if (\n id.length <= ANTHROPIC_TOOL_USE_ID_MAX_LENGTH &&\n ANTHROPIC_TOOL_USE_ID_PATTERN.test(id)\n ) {\n return id;\n }\n const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, '_');\n const hash = createHash('sha256')\n .update(id)\n .digest('hex')\n .slice(0, ANTHROPIC_TOOL_USE_ID_HASH_LENGTH);\n const prefixMaxLength =\n ANTHROPIC_TOOL_USE_ID_MAX_LENGTH - ANTHROPIC_TOOL_USE_ID_HASH_LENGTH - 1;\n return `${sanitized.slice(0, prefixMaxLength)}_${hash}`;\n}\n\n/**\n * Lift any `cache_control` off the inner blocks of a tool result onto the\n * `tool_result` block itself. Anthropic documents the top-level\n * `messages.content` block as the cacheable position and does not document\n * caching of sub-content blocks; the API currently honors a nested marker, but\n * anchoring on the documented position keeps the single tail breakpoint robust\n * (and mirrors the Bedrock cachePoint hoist). The first marker found wins; it is\n * stripped from every inner block so exactly one survives, on the outer block.\n */\nfunction hoistToolResultCacheControl(\n content: string | MessageContentComplex[]\n): { content: string | MessageContentComplex[]; cacheControl: unknown } {\n if (!Array.isArray(content)) {\n return { content, cacheControl: undefined };\n }\n let cacheControl: unknown;\n const stripped = content.map((block) => {\n if ('cache_control' in block) {\n cacheControl ??= (block as Record<string, unknown>).cache_control;\n const clone = { ...(block as Record<string, unknown>) };\n delete clone.cache_control;\n return clone as MessageContentComplex;\n }\n return block;\n });\n // `stripped` is element-equal to `content` when no marker was present.\n return { content: stripped, cacheControl };\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs: BaseMessage[] = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n const toolMessageContent = (\n message as { content?: BaseMessage['content'] | null }\n ).content;\n // Hoist a tail cache_control off the inner content onto the\n // tool_result block itself (the documented cacheable position).\n const { content: hoistedContent, cacheControl } =\n toolMessageContent != null\n ? hoistToolResultCacheControl(_formatContent(message))\n : { content: undefined, cacheControl: undefined };\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n ...(hoistedContent != null ? { content: hoistedContent } : {}),\n ...(cacheControl != null\n ? { cache_control: cacheControl as { type: 'ephemeral' } }\n : {}),\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs as (SystemMessage | HumanMessage | AIMessage)[];\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n const isServerTool = toolCall.id.startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n );\n return {\n type: isServerTool ? 'server_tool_use' : 'tool_use',\n id: isServerTool ? toolCall.id : normalizeAnthropicToolCallId(toolCall.id),\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n /**\n * Reasoning blocks emitted by other providers — Bedrock's `reasoning_content`,\n * Google's `reasoning`, and LibreChat's `think`. Their signatures are\n * provider-specific and cannot be validated by Anthropic, so on a\n * cross-provider handoff (e.g. Bedrock → Anthropic) we drop them rather than\n * forwarding an unusable block. The receiving model produces its own thinking.\n */\n const foreignReasoningTypes = ['reasoning_content', 'reasoning', 'think'];\n /**\n * Google server-side tool blocks (`toolCall`/`toolResponse` parts from e.g.\n * URL context or Google Search). Only Google can execute these and validate\n * their thought signatures, so they are dropped on a cross-provider handoff\n * (e.g. Google → Anthropic); the assistant's answer text is kept.\n */\n const foreignServerToolTypes = ['toolCall', 'toolResponse'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentParts = content as MessageContentComplex[];\n const contentBlocks = contentParts.map((contentPart) => {\n /**\n * Normalize server_tool_use blocks into a clean shape the API accepts.\n * These blocks may arrive with the correct type (server_tool_use), as a\n * standardized server_tool_call, or mislabeled after state serialization.\n * Regardless of current type, if the id starts with 'srvtoolu_' we rebuild\n * a clean block with only the properties the API expects.\n */\n if (\n 'id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).id === 'string' &&\n ((contentPart as Record<string, unknown>).id as string).startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n ) &&\n 'name' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n let input = rawPart.input ?? rawPart.args;\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: rawPart.id as string,\n name: (rawPart.name ?? 'web_search') as 'web_search',\n input: (input ?? {}) as Record<string, unknown>,\n };\n return corrected;\n }\n\n /**\n * Normalize web_search_tool_result blocks into a clean shape.\n * Same rationale as above — the block may carry extra properties from\n * streaming (input, index, etc.) that the API rejects. Rebuild cleanly.\n */\n if (\n 'tool_use_id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).tool_use_id ===\n 'string' &&\n (\n (contentPart as Record<string, unknown>).tool_use_id as string\n ).startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&\n 'content' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const content = rawPart.content;\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: rawPart.tool_use_id as string,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n return null;\n }\n\n /**\n * Native ChatModelStream output standardizes client tool uses as\n * `tool_call` blocks. Convert those blocks back to Anthropic's wire shape\n * before the generic content formatter sees them.\n */\n if (\n contentPart.type === 'tool_call' &&\n 'id' in contentPart &&\n typeof contentPart.id === 'string' &&\n 'name' in contentPart &&\n typeof contentPart.name === 'string' &&\n 'args' in contentPart\n ) {\n let args = contentPart.args;\n if (typeof args === 'string') {\n try {\n args = JSON.parse(args);\n } catch {\n args = {};\n }\n }\n if (args == null || typeof args !== 'object' || Array.isArray(args)) {\n args = {};\n }\n return _convertLangChainToolCallToAnthropic({\n id: contentPart.id,\n name: contentPart.name,\n args: args as Record<string, unknown>,\n });\n }\n\n /**\n * Native Anthropic thinking is exposed through the standard reasoning\n * stream, but its signature makes it safe and necessary to round-trip.\n * Keep unsigned or cross-provider reasoning on the existing drop path.\n */\n if (\n contentPart.type === 'reasoning' &&\n isAIMessage(message) &&\n message.response_metadata.model_provider === 'anthropic' &&\n 'reasoning' in contentPart &&\n typeof contentPart.reasoning === 'string' &&\n 'signature' in contentPart &&\n typeof contentPart.signature === 'string' &&\n contentPart.signature !== ''\n ) {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking',\n thinking: contentPart.reasoning,\n signature: contentPart.signature,\n };\n return block;\n }\n\n /**\n * Skip non-server malformed blocks that have tool fields mixed with text type.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n\n // Core's v1 streaming aggregation can leave a partial tool-input delta as a\n // standalone block typed `text` carrying `input` but no `text`. The assembled\n // input is restored on the tool_use block from `message.tool_calls`, so drop it.\n if (\n contentPart.type === 'text' &&\n 'input' in contentPart &&\n !('text' in contentPart)\n ) {\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n const imageUrl = (contentPart as ImageUrlContentBlock).image_url;\n if (typeof imageUrl === 'string') {\n source = _formatImage(imageUrl);\n } else {\n source = _formatImage(imageUrl.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const thinkingPart = contentPart as AnthropicThinkingBlockParam;\n // Google thinking-enabled output reuses `type: 'thinking'` but carries\n // no Anthropic signature. Anthropic rejects an unsigned thinking block,\n // so on an assistant turn treat it as foreign reasoning and drop it\n // rather than forward an unusable block. Signed (Anthropic-native)\n // thinking is forwarded as before.\n const signature = (thinkingPart as { signature?: string }).signature;\n if (isAIMessage(message) && (signature == null || signature === '')) {\n return null;\n }\n // Opus 4.7+ omits thinking text by default (signed but text-less\n // block), so `thinking` may be absent on a signed block even though the\n // type declares it required. Coerce to '' — JSON.stringify drops an\n // undefined value, which would send a `thinking` block missing its\n // required `thinking` field and trip a 400\n // `messages.N.content.M.thinking.thinking: Field required`.\n const thinkingText =\n (thinkingPart as { thinking?: string }).thinking ?? '';\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: thinkingText,\n signature: thinkingPart.signature,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const redactedPart = contentPart as AnthropicRedactedThinkingBlockParam;\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: redactedPart.data,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'search_result') {\n const searchResultPart = contentPart as AnthropicSearchResultBlockParam;\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const,\n title: searchResultPart.title,\n source: searchResultPart.source,\n ...('cache_control' in contentPart &&\n contentPart.cache_control != null\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n content: searchResultPart.content,\n };\n return block;\n } else if (contentPart.type === 'compaction') {\n const compactionPart = contentPart as AnthropicCompactionBlockParam;\n const block: AnthropicCompactionBlockParam = {\n type: 'compaction' as const,\n content: compactionPart.content,\n ...('encrypted_content' in compactionPart\n ? { encrypted_content: compactionPart.encrypted_content }\n : {}),\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.some((t) => t === contentPart.type) &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.some((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // Orphaned partial tool-input delta with no id of its own. The assembled\n // input is restored on the tool_use block from `message.tool_calls`; drop it.\n return null;\n }\n\n if (\n contentPartCopy.type === 'tool_use' &&\n 'id' in contentPartCopy &&\n typeof contentPartCopy.id === 'string' &&\n contentPartCopy.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n contentPartCopy.type = 'server_tool_use';\n }\n\n // Core's streaming aggregation can leave the inline tool_use input empty\n // (the assembled arguments live in `message.tool_calls` or, for persisted\n // messages, in sibling input_json_delta blocks). Restore it when missing.\n if (\n contentPartCopy.type === 'tool_use' &&\n typeof contentPartCopy.id === 'string' &&\n (contentPartCopy.input === '' || contentPartCopy.input == null)\n ) {\n const matchingToolCall = isAIMessage(message)\n ? message.tool_calls?.find(\n (toolCall) => toolCall.id === contentPartCopy.id\n )\n : undefined;\n if (matchingToolCall) {\n contentPartCopy.input = matchingToolCall.args;\n } else {\n const blockIndex = (contentPart as Record<string, unknown>).index;\n const merged = contentParts\n .filter((part) => {\n const p = part as Record<string, unknown>;\n return (\n p.type === 'input_json_delta' &&\n p.index === blockIndex &&\n typeof p.input === 'string'\n );\n })\n .reduce(\n (acc, part) => acc + (part as Record<string, unknown>).input,\n ''\n );\n if (merged !== '') {\n contentPartCopy.input = merged;\n }\n }\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\n */\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (\n 'functionCall' in contentPart &&\n contentPart.functionCall != null &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const functionCallPart = contentPart as GoogleFunctionCallBlock;\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === functionCallPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${functionCallPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: functionCallPart.functionCall.args,\n };\n } else if (\n isAIMessage(message) &&\n foreignReasoningTypes.some((t) => t === contentPart.type)\n ) {\n // Foreign reasoning on an ASSISTANT turn (Bedrock `reasoning_content`,\n // Google `reasoning`, LibreChat `think`) carries provider-specific\n // signatures Anthropic cannot validate; drop it so a cross-provider\n // handoff doesn't crash. The same types on a user/tool turn are real\n // input and fall through to the throw below rather than being silently\n // dropped — as does any other unknown block (user media, Google\n // code-execution), which must be surfaced, not discarded.\n return null;\n } else if (\n isAIMessage(message) &&\n foreignServerToolTypes.some((t) => t === contentPart.type)\n ) {\n // Google server-side tool call/response (e.g. URL context) — only\n // Google can execute it or validate its thought signature; drop it\n // on a cross-provider handoff rather than crash.\n return null;\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n const filteredContentBlocks = contentBlocks.filter(\n (block) =>\n block !== null &&\n !(\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string' &&\n block.text.trim() === ''\n )\n );\n return filteredContentBlocks.length > 0\n ? filteredContentBlocks\n : [{ type: 'text' as const, text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER }];\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n const isAI = isAIMessage(message);\n const toolCalls = isAI ? (message.tool_calls ?? []) : [];\n if (isAI && toolCalls.length > 0) {\n if (typeof message.content === 'string') {\n const clientToolCalls = toolCalls.filter(\n (tc) =>\n !(\n tc.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ?? false\n )\n );\n if (message.content === '') {\n return {\n role,\n content:\n clientToolCalls.length > 0\n ? clientToolCalls.map(_convertLangChainToolCallToAnthropic)\n : [\n {\n type: 'text' as const,\n text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER,\n },\n ],\n };\n } else {\n return {\n role,\n content: [\n { type: 'text' as const, text: message.content },\n ...clientToolCalls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const formattedContent = _formatContent(message);\n const formattedBlocks = Array.isArray(formattedContent)\n ? formattedContent\n : [];\n // Tool calls already materialized as content blocks by `_formatContent`.\n // Derived from the FORMATTED output (not the raw content by type) so\n // that Google `functionCall` parts — which `_formatContent` converts\n // into `tool_use` — count as represented and are not appended twice.\n const representedToolIds = new Set(\n formattedBlocks\n .filter(\n (block) =>\n block != null &&\n (block.type === 'tool_use' || block.type === 'server_tool_use')\n )\n .map((block) => (block as { id?: string }).id)\n );\n // Client tool calls present in `tool_calls` but absent from the\n // formatted content — e.g. a Bedrock extended-thinking turn records the\n // tool only on `tool_calls` and leaves `content` as just the reasoning\n // block. Without materializing them, dropping that reasoning block\n // silently loses the (handoff) tool call instead of forwarding it.\n const unrepresentedToolCalls = toolCalls.filter(\n (toolCall) =>\n !(\n toolCall.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ??\n false\n ) && !representedToolIds.has(toolCall.id)\n );\n if (unrepresentedToolCalls.length === 0) {\n return { role, content: formattedContent };\n }\n const existingBlocks = formattedBlocks.filter(\n (block) =>\n !(\n block != null &&\n block.type === 'text' &&\n 'text' in block &&\n block.text === ANTHROPIC_EMPTY_TEXT_PLACEHOLDER\n )\n );\n return {\n role,\n content: [\n ...existingBlocks,\n ...unrepresentedToolCalls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nexport function modelDisallowsAssistantPrefill(model?: string): boolean {\n const modelId = model ?? '';\n if (CLAUDE_4_RELEASE_DATE_MODEL_PATTERN.test(modelId)) {\n return false;\n }\n\n const match = CLAUDE_4_MINOR_MODEL_PATTERN.exec(modelId);\n if (!match) {\n return false;\n }\n return Number(match[1]) >= 6;\n}\n\nfunction messagesHaveCacheControl(\n messages: AnthropicMessageCreateParams['messages']\n): boolean {\n return messages.some(\n (message) =>\n Array.isArray(message.content) &&\n message.content.some((block) => 'cache_control' in block)\n );\n}\n\n/** Anthropic rejects cache_control on these reasoning blocks. */\nconst NON_CACHEABLE_PAYLOAD_BLOCK_TYPES = new Set([\n 'thinking',\n 'redacted_thinking',\n]);\n\n/**\n * Place one ephemeral `cache_control` on the last cacheable block of the final\n * message of an already-converted Anthropic payload. Used to re-anchor the tail\n * breakpoint after a trailing assistant prefill is stripped. Operates on the\n * post-conversion payload, where blocks the converter drops (foreign reasoning,\n * input_json_delta) are already gone — only native thinking blocks must be\n * skipped. Returns a new array only when it actually places a marker.\n */\nfunction reanchorTailCacheControl(\n messages: AnthropicMessageCreateParams['messages'],\n ttl?: '1h'\n): AnthropicMessageCreateParams['messages'] {\n if (messages.length === 0) {\n return messages;\n }\n const cacheControl =\n ttl === '1h'\n ? ({ type: 'ephemeral', ttl: '1h' } as const)\n : ({ type: 'ephemeral' } as const);\n const lastIndex = messages.length - 1;\n const tail = messages[lastIndex];\n const content = tail.content;\n\n if (typeof content === 'string') {\n if (content.trim() === '') {\n return messages;\n }\n const next = [...messages];\n next[lastIndex] = {\n ...tail,\n content: [{ type: 'text', text: content, cache_control: cacheControl }],\n } as (typeof messages)[number];\n return next;\n }\n\n if (!Array.isArray(content)) {\n return messages;\n }\n\n let anchor = -1;\n for (let i = 0; i < content.length; i++) {\n const type = (content[i] as { type?: string }).type;\n if (type == null || NON_CACHEABLE_PAYLOAD_BLOCK_TYPES.has(type)) {\n continue;\n }\n if (\n type === 'text' &&\n ((content[i] as { text?: string }).text ?? '').trim() === ''\n ) {\n continue;\n }\n anchor = i;\n }\n if (anchor < 0) {\n return messages;\n }\n\n const next = [...messages];\n next[lastIndex] = {\n ...tail,\n content: content.map((block, i) =>\n i === anchor ? { ...block, cache_control: cacheControl } : block\n ),\n } as (typeof messages)[number];\n return next;\n}\n\n/**\n * Find the extended-cache TTL (`'1h'`) carried by an existing `cache_control`\n * breakpoint, so {@link reanchorTailCacheControl} can re-apply the same TTL the\n * stripped prefill had. Returns `undefined` for the legacy 5-minute default\n * (no `ttl`), keeping that path byte-identical to before.\n */\nfunction findCacheControlTtl(\n messages: AnthropicMessageCreateParams['messages']\n): '1h' | undefined {\n for (const message of messages) {\n if (!Array.isArray(message.content)) {\n continue;\n }\n for (const block of message.content) {\n const cacheControl = (block as { cache_control?: { ttl?: unknown } })\n .cache_control;\n if (cacheControl?.ttl === '1h') {\n return '1h';\n }\n }\n }\n return undefined;\n}\n\nexport function stripUnsupportedAssistantPrefill<\n T extends Pick<AnthropicMessageCreateParams, 'messages'> & { model?: string },\n>(request: T): T {\n if (!modelDisallowsAssistantPrefill(request.model)) {\n return request;\n }\n\n const messages = request.messages;\n if (\n messages.length <= 1 ||\n messages[messages.length - 1]?.role !== 'assistant'\n ) {\n return request;\n }\n\n const nextMessages = [...messages];\n while (\n nextMessages.length > 1 &&\n nextMessages[nextMessages.length - 1]?.role === 'assistant'\n ) {\n nextMessages.pop();\n }\n\n /**\n * If a single tail prompt-cache breakpoint rode the stripped assistant\n * prefill, the survivors may now carry no `cache_control` at all, dropping\n * message caching for this request. Re-anchor the breakpoint on the new tail\n * (only when one was actually lost, so caching-off requests stay untouched).\n */\n const reanchored =\n messagesHaveCacheControl(messages) &&\n !messagesHaveCacheControl(nextMessages)\n ? reanchorTailCacheControl(nextMessages, findCacheControlTtl(messages))\n : nextMessages;\n\n return {\n ...request,\n messages: reanchored,\n };\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\n if (messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n type ContentBlocks = Exclude<\n AnthropicMessageCreateParams['messages'][number]['content'],\n string\n >;\n const normalizeContent = (\n content: AnthropicMessageCreateParams['messages'][number]['content']\n ): ContentBlocks => {\n if (typeof content === 'string') {\n return [{ type: 'text', text: content }];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"mappings":";;;;;;;;;AAkDA,MAAM,mCAAmC;AACzC,MAAM,sCACJ;AACF,MAAM,+BACJ;AAEF,SAAS,aAAa,UAAkB;CACtC,MAAM,SAAS,mBAAmB,EAAE,SAAS,SAAS,CAAC;CACvD,IAAI,QACF,OAAO;EACL,MAAM;EACN,YAAY,OAAO;EACnB,MAAM,OAAO;CACf;CAEF,IAAI;CAEJ,IAAI;EACF,YAAY,IAAI,IAAI,QAAQ;CAC9B,QAAQ;EACN,MAAM,IAAI,MACR;GACE,wBAAwB,KAAK,UAC3B,QACF,EAAE;GACF;GACA;EACF,CAAC,CAAC,KAAK,MAAM,CACf;CACF;CAEA,IAAI,UAAU,aAAa,WAAW,UAAU,aAAa,UAC3D,OAAO;EACL,MAAM;EACN,KAAK;CACP;CAGF,MAAM,IAAI,MACR;EACE,+BAA+B,KAAK,UAClC,UAAU,QACZ,EAAE;EACF;EACA;CACF,CAAC,CAAC,KA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AO,CAAC;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;EAEzC,OAAO;CACT;CAEA,MAAM,uBAAuB,QAA8B;EACzD,IAAI,IAAI,SAAS,QAAQ,OAAO;EAEhC,IAAI,OAAO,IAAI,YAAY,UACzB,OAAO;EAGT,OACE,MAAM,QAAQ,IAAI,OAAO,KACzB,IAAI,QAAQ,OAAO,SAAS,KAAK,SAAS,aAAa;CAE3D;CAEA,KAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,GAAG;EAC3C,MAAM,cAAc,SAAS;EAE7B,IACE,oBAAoB,cAAc,KAClC,oBAAoB,WAAW,GAG/B,iBAAiB;GACf,GAAG;GACH,SAAS,CACP,GAAG,iBAAiB,eAAe,OAAO,GAC1C,GAAG,iBAAiB,YAAY,OAAO,CACzC;EACF;OACK;GACL,OAAO,KAAK,cAAc;GAC1B,iBAAiB;EACnB;CACF;CAEA,OAAO,KAAK,cAAc;CAC1B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"message_inputs.mjs","names":["redactedPart"],"sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport { createHash } from 'node:crypto';\nimport { isProxy } from 'node:util/types';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n ToolMessage,\n isAIMessage,\n type Data,\n type StandardContentBlockConverter,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicCompactionBlockParam,\n AnthropicToolResponse,\n} from '../types';\nimport {\n cloneToolMessageWithContent,\n serializeStructuredValueBounded,\n} from '@/utils/toolContent';\nimport { HARD_MAX_TOOL_RESULT_CHARS } from '@/utils/truncation';\nimport { Constants } from '@/common';\n\ntype StandardTextBlock = Data.StandardTextBlock;\ntype StandardImageBlock = Data.StandardImageBlock;\ntype StandardFileBlock = Data.StandardFileBlock;\ntype ImageUrlContentBlock = MessageContentComplex & {\n image_url: string | { url: string };\n};\ntype GoogleFunctionCallBlock = MessageContentComplex & {\n functionCall: {\n name: string;\n args: Record<string, unknown>;\n };\n};\n\nconst ANTHROPIC_EMPTY_TEXT_PLACEHOLDER = '_';\nconst CLAUDE_4_RELEASE_DATE_MODEL_PATTERN =\n /claude-(?:opus|sonnet|haiku)-4-\\d{8}(?:[-.@]|$)/i;\nconst CLAUDE_4_MINOR_MODEL_PATTERN =\n /claude-(?:opus|sonnet|haiku)-4[-.](\\d+)(?:[-.@]|$)/i;\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n}\n\nconst ANTHROPIC_TOOL_USE_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\nconst ANTHROPIC_TOOL_USE_ID_MAX_LENGTH = 64;\nconst ANTHROPIC_TOOL_USE_ID_HASH_LENGTH = 10;\n\n/**\n * Normalize a tool-call ID to satisfy Anthropic's `^[a-zA-Z0-9_-]+$` and 64-char\n * constraints. Pure and deterministic — same input always yields the same output,\n * so paired `tool_use.id` and `tool_result.tool_use_id` stay matched without\n * needing a session map. IDs that already comply pass through unchanged.\n *\n * For non-compliant inputs we sanitize then append a short SHA-256 prefix of\n * the original ID to preserve uniqueness when truncation would otherwise\n * collapse distinct IDs to the same value (e.g. two long Responses-style IDs\n * sharing a 64-char prefix). The hash is computed against the raw input so\n * inputs that differ only after the truncation cutoff still produce distinct\n * outputs.\n */\nexport function normalizeAnthropicToolCallId(id: string): string;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined;\nexport function normalizeAnthropicToolCallId(\n id: string | undefined\n): string | undefined {\n if (id == null) {\n return id;\n }\n if (\n id.length <= ANTHROPIC_TOOL_USE_ID_MAX_LENGTH &&\n ANTHROPIC_TOOL_USE_ID_PATTERN.test(id)\n ) {\n return id;\n }\n const sanitized = id.replace(/[^a-zA-Z0-9_-]/g, '_');\n const hash = createHash('sha256')\n .update(id)\n .digest('hex')\n .slice(0, ANTHROPIC_TOOL_USE_ID_HASH_LENGTH);\n const prefixMaxLength =\n ANTHROPIC_TOOL_USE_ID_MAX_LENGTH - ANTHROPIC_TOOL_USE_ID_HASH_LENGTH - 1;\n return `${sanitized.slice(0, prefixMaxLength)}_${hash}`;\n}\n\n/**\n * Lift any `cache_control` off the inner blocks of a tool result onto the\n * `tool_result` block itself. Anthropic documents the top-level\n * `messages.content` block as the cacheable position and does not document\n * caching of sub-content blocks; the API currently honors a nested marker, but\n * anchoring on the documented position keeps the single tail breakpoint robust\n * (and mirrors the Bedrock cachePoint hoist). The first marker found wins; it is\n * stripped from every inner block so exactly one survives, on the outer block.\n */\nfunction hoistToolResultCacheControl(\n content: string | MessageContentComplex[]\n): { content: string | MessageContentComplex[]; cacheControl: unknown } {\n if (!Array.isArray(content)) {\n return { content, cacheControl: undefined };\n }\n let cacheControl: unknown;\n const stripped = content.map((block) => {\n if (typeof block !== 'object' || block == null || isProxy(block)) {\n return block;\n }\n try {\n const descriptors = Object.getOwnPropertyDescriptors(block);\n const cacheControlDescriptor = descriptors.cache_control;\n if (\n cacheControlDescriptor.enumerable === true &&\n 'value' in cacheControlDescriptor\n ) {\n cacheControl ??= cacheControlDescriptor.value;\n delete descriptors.cache_control;\n return Object.create(\n Object.getPrototypeOf(block),\n descriptors\n ) as MessageContentComplex;\n }\n } catch {\n return block;\n }\n return block;\n });\n // `stripped` is element-equal to `content` when no marker was present.\n return { content: stripped, cacheControl };\n}\n\n/**\n * A ToolMessage can already contain an Anthropic-native `tool_result` block\n * (for example, when a tool returns provider-native structured content). The\n * outer ToolMessage conversion supplies the one required result envelope, so\n * unwrap an exact single nested envelope rather than sending an invalid\n * `tool_result.content: [{ type: \"tool_result\", ... }]` payload.\n */\nfunction unwrapToolMessageResultContent(content: ToolMessage['content']): {\n content: string | MessageContentComplex[] | undefined;\n cacheControl: unknown;\n isError: boolean | undefined;\n} {\n if (!Array.isArray(content) || content.length !== 1) {\n return { content, cacheControl: undefined, isError: undefined };\n }\n\n const block = content[0];\n if (typeof block !== 'object' || block == null || isProxy(block)) {\n return { content, cacheControl: undefined, isError: undefined };\n }\n\n try {\n const type = Object.getOwnPropertyDescriptor(block, 'type');\n const nestedContent = Object.getOwnPropertyDescriptor(block, 'content');\n if (\n type?.enumerable !== true ||\n !('value' in type) ||\n type.value !== 'tool_result' ||\n (nestedContent != null &&\n (nestedContent.enumerable !== true || !('value' in nestedContent)))\n ) {\n return { content, cacheControl: undefined, isError: undefined };\n }\n\n const cacheControl = Object.getOwnPropertyDescriptor(\n block,\n 'cache_control'\n );\n const isError = Object.getOwnPropertyDescriptor(block, 'is_error');\n const nested =\n nestedContent != null && 'value' in nestedContent\n ? nestedContent.value\n : undefined;\n if (typeof nested === 'string') {\n return {\n content: nested,\n cacheControl:\n cacheControl?.enumerable === true && 'value' in cacheControl\n ? cacheControl.value\n : undefined,\n isError:\n isError?.enumerable === true &&\n 'value' in isError &&\n typeof isError.value === 'boolean'\n ? isError.value\n : undefined,\n };\n }\n if (Array.isArray(nested)) {\n return {\n content: nested as MessageContentComplex[],\n cacheControl:\n cacheControl?.enumerable === true && 'value' in cacheControl\n ? cacheControl.value\n : undefined,\n isError:\n isError?.enumerable === true &&\n 'value' in isError &&\n typeof isError.value === 'boolean'\n ? isError.value\n : undefined,\n };\n }\n if (nested == null) {\n return {\n content: undefined,\n cacheControl:\n cacheControl?.enumerable === true && 'value' in cacheControl\n ? cacheControl.value\n : undefined,\n isError:\n isError?.enumerable === true &&\n 'value' in isError &&\n typeof isError.value === 'boolean'\n ? isError.value\n : undefined,\n };\n }\n return {\n content: serializeStructuredValueBounded(\n nested,\n HARD_MAX_TOOL_RESULT_CHARS\n ).content,\n cacheControl:\n cacheControl?.enumerable === true && 'value' in cacheControl\n ? cacheControl.value\n : undefined,\n isError:\n isError?.enumerable === true &&\n 'value' in isError &&\n typeof isError.value === 'boolean'\n ? isError.value\n : undefined,\n };\n } catch {\n return { content, cacheControl: undefined, isError: undefined };\n }\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs: BaseMessage[] = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n const toolMessage = message as ToolMessage;\n const toolMessageContent = toolMessage.content;\n const unwrapped = unwrapToolMessageResultContent(toolMessageContent);\n const formattedContent =\n unwrapped.content == null\n ? undefined\n : _formatContent(\n unwrapped.content === toolMessageContent\n ? toolMessage\n : cloneToolMessageWithContent(\n toolMessage,\n unwrapped.content as Parameters<\n typeof cloneToolMessageWithContent\n >[1]\n )\n );\n // Hoist a tail cache_control off the inner content onto the\n // tool_result block itself (the documented cacheable position).\n const { content: hoistedContent, cacheControl: innerCacheControl } =\n formattedContent != null\n ? hoistToolResultCacheControl(formattedContent)\n : { content: undefined, cacheControl: undefined };\n const cacheControl = unwrapped.cacheControl ?? innerCacheControl;\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n ...(hoistedContent != null ? { content: hoistedContent } : {}),\n ...(unwrapped.isError != null\n ? { is_error: unwrapped.isError }\n : {}),\n ...(cacheControl != null\n ? { cache_control: cacheControl as { type: 'ephemeral' } }\n : {}),\n tool_use_id: normalizeAnthropicToolCallId(\n (message as ToolMessage).tool_call_id\n ),\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs as (SystemMessage | HumanMessage | AIMessage)[];\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n const isServerTool = toolCall.id.startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n );\n return {\n type: isServerTool ? 'server_tool_use' : 'tool_use',\n id: isServerTool ? toolCall.id : normalizeAnthropicToolCallId(toolCall.id),\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n /**\n * Reasoning blocks emitted by other providers — Bedrock's `reasoning_content`,\n * Google's `reasoning`, and LibreChat's `think`. Their signatures are\n * provider-specific and cannot be validated by Anthropic, so on a\n * cross-provider handoff (e.g. Bedrock → Anthropic) we drop them rather than\n * forwarding an unusable block. The receiving model produces its own thinking.\n */\n const foreignReasoningTypes = ['reasoning_content', 'reasoning', 'think'];\n /**\n * Google server-side tool blocks (`toolCall`/`toolResponse` parts from e.g.\n * URL context or Google Search). Only Google can execute these and validate\n * their thought signatures, so they are dropped on a cross-provider handoff\n * (e.g. Google → Anthropic); the assistant's answer text is kept.\n */\n const foreignServerToolTypes = ['toolCall', 'toolResponse'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentParts = content as MessageContentComplex[];\n const contentBlocks = contentParts.map((contentPart) => {\n /**\n * Normalize server_tool_use blocks into a clean shape the API accepts.\n * These blocks may arrive with the correct type (server_tool_use), as a\n * standardized server_tool_call, or mislabeled after state serialization.\n * Regardless of current type, if the id starts with 'srvtoolu_' we rebuild\n * a clean block with only the properties the API expects.\n */\n if (\n 'id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).id === 'string' &&\n ((contentPart as Record<string, unknown>).id as string).startsWith(\n Constants.ANTHROPIC_SERVER_TOOL_PREFIX\n ) &&\n 'name' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n let input = rawPart.input ?? rawPart.args;\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id: rawPart.id as string,\n name: (rawPart.name ?? 'web_search') as 'web_search',\n input: (input ?? {}) as Record<string, unknown>,\n };\n return corrected;\n }\n\n /**\n * Normalize web_search_tool_result blocks into a clean shape.\n * Same rationale as above — the block may carry extra properties from\n * streaming (input, index, etc.) that the API rejects. Rebuild cleanly.\n */\n if (\n 'tool_use_id' in contentPart &&\n typeof (contentPart as Record<string, unknown>).tool_use_id ===\n 'string' &&\n (\n (contentPart as Record<string, unknown>).tool_use_id as string\n ).startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) &&\n 'content' in contentPart\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const content = rawPart.content;\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: rawPart.tool_use_id as string,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n return null;\n }\n\n /**\n * Native ChatModelStream output standardizes client tool uses as\n * `tool_call` blocks. Convert those blocks back to Anthropic's wire shape\n * before the generic content formatter sees them.\n */\n if (\n contentPart.type === 'tool_call' &&\n 'id' in contentPart &&\n typeof contentPart.id === 'string' &&\n 'name' in contentPart &&\n typeof contentPart.name === 'string' &&\n 'args' in contentPart\n ) {\n let args = contentPart.args;\n if (typeof args === 'string') {\n try {\n args = JSON.parse(args);\n } catch {\n args = {};\n }\n }\n if (args == null || typeof args !== 'object' || Array.isArray(args)) {\n args = {};\n }\n return _convertLangChainToolCallToAnthropic({\n id: contentPart.id,\n name: contentPart.name,\n args: args as Record<string, unknown>,\n });\n }\n\n /**\n * Native Anthropic thinking is exposed through the standard reasoning\n * stream, but its signature makes it safe and necessary to round-trip.\n * Keep unsigned or cross-provider reasoning on the existing drop path.\n */\n if (\n contentPart.type === 'reasoning' &&\n isAIMessage(message) &&\n message.response_metadata.model_provider === 'anthropic' &&\n 'reasoning' in contentPart &&\n typeof contentPart.reasoning === 'string' &&\n 'signature' in contentPart &&\n typeof contentPart.signature === 'string' &&\n contentPart.signature !== ''\n ) {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking',\n thinking: contentPart.reasoning,\n signature: contentPart.signature,\n };\n return block;\n }\n\n /**\n * Skip non-server malformed blocks that have tool fields mixed with text type.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n return null;\n }\n\n // Core's v1 streaming aggregation can leave a partial tool-input delta as a\n // standalone block typed `text` carrying `input` but no `text`. The assembled\n // input is restored on the tool_use block from `message.tool_calls`, so drop it.\n if (\n contentPart.type === 'text' &&\n 'input' in contentPart &&\n !('text' in contentPart)\n ) {\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n const imageUrl = (contentPart as ImageUrlContentBlock).image_url;\n if (typeof imageUrl === 'string') {\n source = _formatImage(imageUrl);\n } else {\n source = _formatImage(imageUrl.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const thinkingPart = contentPart as AnthropicThinkingBlockParam;\n // Google thinking-enabled output reuses `type: 'thinking'` but carries\n // no Anthropic signature. Anthropic rejects an unsigned thinking block,\n // so on an assistant turn treat it as foreign reasoning and drop it\n // rather than forward an unusable block. Signed (Anthropic-native)\n // thinking is forwarded as before.\n const signature = (thinkingPart as { signature?: string }).signature;\n if (isAIMessage(message) && (signature == null || signature === '')) {\n return null;\n }\n // Opus 4.7+ omits thinking text by default (signed but text-less\n // block), so `thinking` may be absent on a signed block even though the\n // type declares it required. Coerce to '' — JSON.stringify drops an\n // undefined value, which would send a `thinking` block missing its\n // required `thinking` field and trip a 400\n // `messages.N.content.M.thinking.thinking: Field required`.\n const thinkingText =\n (thinkingPart as { thinking?: string }).thinking ?? '';\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: thinkingText,\n signature: thinkingPart.signature,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const redactedPart = contentPart as AnthropicRedactedThinkingBlockParam;\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: redactedPart.data,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'search_result') {\n const searchResultPart = contentPart as AnthropicSearchResultBlockParam;\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const,\n title: searchResultPart.title,\n source: searchResultPart.source,\n ...('cache_control' in contentPart &&\n contentPart.cache_control != null\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n content: searchResultPart.content,\n };\n return block;\n } else if (contentPart.type === 'compaction') {\n const compactionPart = contentPart as AnthropicCompactionBlockParam;\n const block: AnthropicCompactionBlockParam = {\n type: 'compaction' as const,\n content: compactionPart.content,\n ...('encrypted_content' in compactionPart\n ? { encrypted_content: compactionPart.encrypted_content }\n : {}),\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.some((t) => t === contentPart.type) &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n ...('citations' in contentPart && contentPart.citations != null\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.some((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // Orphaned partial tool-input delta with no id of its own. The assembled\n // input is restored on the tool_use block from `message.tool_calls`; drop it.\n return null;\n }\n\n if (\n contentPartCopy.type === 'tool_use' &&\n 'id' in contentPartCopy &&\n typeof contentPartCopy.id === 'string' &&\n contentPartCopy.id.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX)\n ) {\n contentPartCopy.type = 'server_tool_use';\n }\n\n // Core's streaming aggregation can leave the inline tool_use input empty\n // (the assembled arguments live in `message.tool_calls` or, for persisted\n // messages, in sibling input_json_delta blocks). Restore it when missing.\n if (\n contentPartCopy.type === 'tool_use' &&\n typeof contentPartCopy.id === 'string' &&\n (contentPartCopy.input === '' || contentPartCopy.input == null)\n ) {\n const matchingToolCall = isAIMessage(message)\n ? message.tool_calls?.find(\n (toolCall) => toolCall.id === contentPartCopy.id\n )\n : undefined;\n if (matchingToolCall) {\n contentPartCopy.input = matchingToolCall.args;\n } else {\n const blockIndex = (contentPart as Record<string, unknown>).index;\n const merged = contentParts\n .filter((part) => {\n const p = part as Record<string, unknown>;\n return (\n p.type === 'input_json_delta' &&\n p.index === blockIndex &&\n typeof p.input === 'string'\n );\n })\n .reduce(\n (acc, part) => acc + (part as Record<string, unknown>).input,\n ''\n );\n if (merged !== '') {\n contentPartCopy.input = merged;\n }\n }\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\n */\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl != null ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (\n 'functionCall' in contentPart &&\n contentPart.functionCall != null &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const functionCallPart = contentPart as GoogleFunctionCallBlock;\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === functionCallPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${functionCallPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: functionCallPart.functionCall.args,\n };\n } else if (\n isAIMessage(message) &&\n foreignReasoningTypes.some((t) => t === contentPart.type)\n ) {\n // Foreign reasoning on an ASSISTANT turn (Bedrock `reasoning_content`,\n // Google `reasoning`, LibreChat `think`) carries provider-specific\n // signatures Anthropic cannot validate; drop it so a cross-provider\n // handoff doesn't crash. The same types on a user/tool turn are real\n // input and fall through to the throw below rather than being silently\n // dropped — as does any other unknown block (user media, Google\n // code-execution), which must be surfaced, not discarded.\n return null;\n } else if (\n isAIMessage(message) &&\n foreignServerToolTypes.some((t) => t === contentPart.type)\n ) {\n // Google server-side tool call/response (e.g. URL context) — only\n // Google can execute it or validate its thought signature; drop it\n // on a cross-provider handoff rather than crash.\n return null;\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n const filteredContentBlocks = contentBlocks.filter(\n (block) =>\n block !== null &&\n !(\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string' &&\n block.text.trim() === ''\n )\n );\n return filteredContentBlocks.length > 0\n ? filteredContentBlocks\n : [{ type: 'text' as const, text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER }];\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n const isAI = isAIMessage(message);\n const toolCalls = isAI ? (message.tool_calls ?? []) : [];\n if (isAI && toolCalls.length > 0) {\n if (typeof message.content === 'string') {\n const clientToolCalls = toolCalls.filter(\n (tc) =>\n !(\n tc.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ?? false\n )\n );\n if (message.content === '') {\n return {\n role,\n content:\n clientToolCalls.length > 0\n ? clientToolCalls.map(_convertLangChainToolCallToAnthropic)\n : [\n {\n type: 'text' as const,\n text: ANTHROPIC_EMPTY_TEXT_PLACEHOLDER,\n },\n ],\n };\n } else {\n return {\n role,\n content: [\n { type: 'text' as const, text: message.content },\n ...clientToolCalls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const formattedContent = _formatContent(message);\n const formattedBlocks = Array.isArray(formattedContent)\n ? formattedContent\n : [];\n // Tool calls already materialized as content blocks by `_formatContent`.\n // Derived from the FORMATTED output (not the raw content by type) so\n // that Google `functionCall` parts — which `_formatContent` converts\n // into `tool_use` — count as represented and are not appended twice.\n const representedToolIds = new Set(\n formattedBlocks\n .filter(\n (block) =>\n block != null &&\n (block.type === 'tool_use' || block.type === 'server_tool_use')\n )\n .map((block) => (block as { id?: string }).id)\n );\n // Client tool calls present in `tool_calls` but absent from the\n // formatted content — e.g. a Bedrock extended-thinking turn records the\n // tool only on `tool_calls` and leaves `content` as just the reasoning\n // block. Without materializing them, dropping that reasoning block\n // silently loses the (handoff) tool call instead of forwarding it.\n const unrepresentedToolCalls = toolCalls.filter(\n (toolCall) =>\n !(\n toolCall.id?.startsWith(Constants.ANTHROPIC_SERVER_TOOL_PREFIX) ??\n false\n ) && !representedToolIds.has(toolCall.id)\n );\n if (unrepresentedToolCalls.length === 0) {\n return { role, content: formattedContent };\n }\n const existingBlocks = formattedBlocks.filter(\n (block) =>\n !(\n block != null &&\n block.type === 'text' &&\n 'text' in block &&\n block.text === ANTHROPIC_EMPTY_TEXT_PLACEHOLDER\n )\n );\n return {\n role,\n content: [\n ...existingBlocks,\n ...unrepresentedToolCalls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nexport function modelDisallowsAssistantPrefill(model?: string): boolean {\n const modelId = model ?? '';\n if (CLAUDE_4_RELEASE_DATE_MODEL_PATTERN.test(modelId)) {\n return false;\n }\n\n const match = CLAUDE_4_MINOR_MODEL_PATTERN.exec(modelId);\n if (!match) {\n return false;\n }\n return Number(match[1]) >= 6;\n}\n\nfunction messagesHaveCacheControl(\n messages: AnthropicMessageCreateParams['messages']\n): boolean {\n return messages.some(\n (message) =>\n Array.isArray(message.content) &&\n message.content.some((block) => 'cache_control' in block)\n );\n}\n\n/** Anthropic rejects cache_control on these reasoning blocks. */\nconst NON_CACHEABLE_PAYLOAD_BLOCK_TYPES = new Set([\n 'thinking',\n 'redacted_thinking',\n]);\n\n/**\n * Place one ephemeral `cache_control` on the last cacheable block of the final\n * message of an already-converted Anthropic payload. Used to re-anchor the tail\n * breakpoint after a trailing assistant prefill is stripped. Operates on the\n * post-conversion payload, where blocks the converter drops (foreign reasoning,\n * input_json_delta) are already gone — only native thinking blocks must be\n * skipped. Returns a new array only when it actually places a marker.\n */\nfunction reanchorTailCacheControl(\n messages: AnthropicMessageCreateParams['messages'],\n ttl?: '1h'\n): AnthropicMessageCreateParams['messages'] {\n if (messages.length === 0) {\n return messages;\n }\n const cacheControl =\n ttl === '1h'\n ? ({ type: 'ephemeral', ttl: '1h' } as const)\n : ({ type: 'ephemeral' } as const);\n const lastIndex = messages.length - 1;\n const tail = messages[lastIndex];\n const content = tail.content;\n\n if (typeof content === 'string') {\n if (content.trim() === '') {\n return messages;\n }\n const next = [...messages];\n next[lastIndex] = {\n ...tail,\n content: [{ type: 'text', text: content, cache_control: cacheControl }],\n } as (typeof messages)[number];\n return next;\n }\n\n if (!Array.isArray(content)) {\n return messages;\n }\n\n let anchor = -1;\n for (let i = 0; i < content.length; i++) {\n const type = (content[i] as { type?: string }).type;\n if (type == null || NON_CACHEABLE_PAYLOAD_BLOCK_TYPES.has(type)) {\n continue;\n }\n if (\n type === 'text' &&\n ((content[i] as { text?: string }).text ?? '').trim() === ''\n ) {\n continue;\n }\n anchor = i;\n }\n if (anchor < 0) {\n return messages;\n }\n\n const next = [...messages];\n next[lastIndex] = {\n ...tail,\n content: content.map((block, i) =>\n i === anchor ? { ...block, cache_control: cacheControl } : block\n ),\n } as (typeof messages)[number];\n return next;\n}\n\n/**\n * Find the extended-cache TTL (`'1h'`) carried by an existing `cache_control`\n * breakpoint, so {@link reanchorTailCacheControl} can re-apply the same TTL the\n * stripped prefill had. Returns `undefined` for the legacy 5-minute default\n * (no `ttl`), keeping that path byte-identical to before.\n */\nfunction findCacheControlTtl(\n messages: AnthropicMessageCreateParams['messages']\n): '1h' | undefined {\n for (const message of messages) {\n if (!Array.isArray(message.content)) {\n continue;\n }\n for (const block of message.content) {\n const cacheControl = (block as { cache_control?: { ttl?: unknown } })\n .cache_control;\n if (cacheControl?.ttl === '1h') {\n return '1h';\n }\n }\n }\n return undefined;\n}\n\nexport function stripUnsupportedAssistantPrefill<\n T extends Pick<AnthropicMessageCreateParams, 'messages'> & { model?: string },\n>(request: T): T {\n if (!modelDisallowsAssistantPrefill(request.model)) {\n return request;\n }\n\n const messages = request.messages;\n if (\n messages.length <= 1 ||\n messages[messages.length - 1]?.role !== 'assistant'\n ) {\n return request;\n }\n\n const nextMessages = [...messages];\n while (\n nextMessages.length > 1 &&\n nextMessages[nextMessages.length - 1]?.role === 'assistant'\n ) {\n nextMessages.pop();\n }\n\n /**\n * If a single tail prompt-cache breakpoint rode the stripped assistant\n * prefill, the survivors may now carry no `cache_control` at all, dropping\n * message caching for this request. Re-anchor the breakpoint on the new tail\n * (only when one was actually lost, so caching-off requests stay untouched).\n */\n const reanchored =\n messagesHaveCacheControl(messages) &&\n !messagesHaveCacheControl(nextMessages)\n ? reanchorTailCacheControl(nextMessages, findCacheControlTtl(messages))\n : nextMessages;\n\n return {\n ...request,\n messages: reanchored,\n };\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\n if (messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n type ContentBlocks = Exclude<\n AnthropicMessageCreateParams['messages'][number]['content'],\n string\n >;\n const normalizeContent = (\n content: AnthropicMessageCreateParams['messages'][number]['content']\n ): ContentBlocks => {\n if (typeof content === 'string') {\n return [{ type: 'text', text: content }];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"mappings":";;;;;;;;;;;;AAwDA,MAAM,mCAAmC;AACzC,MAAM,sCACJ;AACF,MAAM,+BACJ;AAEF,SAAS,aAAa,UAAkB;CACtC,MAAM,SAAS,mBAAmB,EAAE,SAAS,SAAS,CAAC;CACvD,IAAI,QACF,OAAO;EACL,MAAM;EACN,YAAY,OAAO;EACnB,MAAM,OAAO;CACf;CAEF,IAAI;CAEJ,IAAI;EACF,YAAY,IAAI,IAAI,QAAQ;CAC9B,QAAQ;EACN,MAAM,IAAI,MACR;GACE,wBAAwB,KAAK,UAC3B,QACF,EAAE;GACF;GACA;EACF,CAAC,CAAC,KAAK,MAAM,CACf;CACF;CAEA,IAAI,UAAU,aAAa,WAAW,UAAU,aAAa,UAC3D,OAAO;EACL,MAAM;EACN,KAAK;CACP;CAGF,MAAM,IAAI,MACR;EACE,+BAA+B,KAAK,UAClC,UAAU,QACZ,EAAE;EACF;EACA;CACF,CAAC,CAAC,KAAK,MA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