@librechat/agents 3.2.46 → 3.2.52

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.
Files changed (57) hide show
  1. package/dist/cjs/graphs/MultiAgentGraph.cjs +6 -6
  2. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  3. package/dist/cjs/llm/anthropic/index.cjs +4 -3
  4. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/utils/tools.cjs +2 -1
  6. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  7. package/dist/cjs/llm/bedrock/cachePoints.cjs +28 -0
  8. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -0
  9. package/dist/cjs/llm/bedrock/index.cjs +10 -1
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  12. package/dist/cjs/run.cjs +21 -3
  13. package/dist/cjs/run.cjs.map +1 -1
  14. package/dist/cjs/tools/ToolNode.cjs +26 -5
  15. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  16. package/dist/esm/graphs/MultiAgentGraph.mjs +7 -7
  17. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  18. package/dist/esm/llm/anthropic/index.mjs +4 -3
  19. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  20. package/dist/esm/llm/anthropic/utils/tools.mjs +2 -1
  21. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  22. package/dist/esm/llm/bedrock/cachePoints.mjs +28 -0
  23. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -0
  24. package/dist/esm/llm/bedrock/index.mjs +10 -1
  25. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  26. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  27. package/dist/esm/run.mjs +21 -3
  28. package/dist/esm/run.mjs.map +1 -1
  29. package/dist/esm/tools/ToolNode.mjs +26 -5
  30. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  31. package/dist/types/llm/anthropic/utils/tools.d.ts +1 -1
  32. package/dist/types/llm/bedrock/cachePoints.d.ts +9 -0
  33. package/dist/types/run.d.ts +15 -1
  34. package/dist/types/tools/ToolNode.d.ts +9 -2
  35. package/package.json +16 -21
  36. package/src/graphs/MultiAgentGraph.ts +7 -12
  37. package/src/llm/anthropic/index.ts +13 -2
  38. package/src/llm/anthropic/inherited-content-utils.spec.ts +244 -0
  39. package/src/llm/anthropic/inherited-stream-events.spec.ts +752 -0
  40. package/src/llm/anthropic/inherited-strict.spec.ts +302 -0
  41. package/src/llm/anthropic/llm.spec.ts +65 -0
  42. package/src/llm/anthropic/utils/tools.ts +7 -1
  43. package/src/llm/bedrock/cachePoints.ts +86 -0
  44. package/src/llm/bedrock/index.ts +9 -0
  45. package/src/llm/bedrock/inherited-cache.spec.ts +144 -0
  46. package/src/llm/bedrock/inherited.spec.ts +724 -0
  47. package/src/llm/google/inherited-stream-events.spec.ts +350 -0
  48. package/src/llm/openai/inherited-deepseek.spec.ts +347 -0
  49. package/src/llm/openai/inherited-xai.spec.ts +416 -0
  50. package/src/llm/openai/llm.spec.ts +1568 -0
  51. package/src/llm/openrouter/index.ts +1 -3
  52. package/src/llm/vertexai/inherited-stream-events.spec.ts +271 -0
  53. package/src/run.ts +31 -3
  54. package/src/scripts/handoff-test.ts +5 -6
  55. package/src/tools/ToolNode.ts +43 -5
  56. package/src/tools/__tests__/ToolNode.runtimeState.test.ts +120 -0
  57. package/src/tools/__tests__/hitl.test.ts +162 -0
@@ -191,10 +191,10 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
191
191
  const hasHandoffInput = edge.prompt != null && typeof edge.prompt === "string";
192
192
  const handoffInputDescription = hasHandoffInput ? edge.prompt : void 0;
193
193
  const promptKey = edge.promptKey ?? "instructions";
194
- tools.push((0, _langchain_core_tools.tool)(async (rawInput, config) => {
194
+ tools.push((0, _langchain_core_tools.tool)(async (rawInput, runtime) => {
195
195
  const input = rawInput;
196
- const state = (0, _langchain_langgraph.getCurrentTaskInput)();
197
- const toolCallId = config?.toolCall?.id ?? "unknown";
196
+ const state = runtime.state;
197
+ const toolCallId = runtime.toolCall?.id ?? "unknown";
198
198
  /** Evaluated condition */
199
199
  const result = edge.condition(state);
200
200
  let destination;
@@ -249,9 +249,9 @@ var MultiAgentGraph = class extends require_Graph.StandardGraph {
249
249
  const hasHandoffInput = edge.prompt != null && typeof edge.prompt === "string";
250
250
  const handoffInputDescription = hasHandoffInput ? edge.prompt : void 0;
251
251
  const promptKey = edge.promptKey ?? "instructions";
252
- tools.push((0, _langchain_core_tools.tool)(async (rawInput, config) => {
252
+ tools.push((0, _langchain_core_tools.tool)(async (rawInput, runtime) => {
253
253
  const input = rawInput;
254
- const toolCallId = config?.toolCall?.id ?? "unknown";
254
+ const toolCallId = runtime.toolCall?.id ?? "unknown";
255
255
  let content = `Successfully transferred to ${destination}`;
256
256
  if (hasHandoffInput && promptKey in input && input[promptKey] != null) content += `\n\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;
257
257
  const toolMessage = new _langchain_core_messages.ToolMessage({
@@ -273,7 +273,7 @@ handoff_source_name: sourceAgentName }
273
273
  * 2. Create a filtered AIMessage with ONLY this tool_call
274
274
  * 3. Include all messages before the AIMessage plus the filtered pair
275
275
  */
276
- const messages = (0, _langchain_langgraph.getCurrentTaskInput)().messages;
276
+ const messages = runtime.state.messages;
277
277
  let filteredMessages = messages;
278
278
  let aiMessageIndex = -1;
279
279
  /** Find the AIMessage containing this tool call */
@@ -1 +1 @@
1
- {"version":3,"file":"MultiAgentGraph.cjs","names":["StandardGraph","ToolMessage","Command","aiMsg","AIMessage","StateGraph","Annotation","END","HumanMessage","START","PromptTemplate"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n getCurrentTaskInput,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRunnableConfig } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const state = getCurrentTaskInput() as t.BaseGraphState;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, config) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId =\n (config as ToolRunnableConfig | undefined)?.toolCall?.id ??\n 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = getCurrentTaskInput() as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(HANDOFF_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = handoffContext;\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.compileOptions as unknown as never);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,MAAM,+BAA+B;;;;;;;;;;;;;;;AAgBrC,IAAa,kBAAb,cAAqCA,cAAAA,cAAc;CACjD;CACA,gCAAqC,IAAI,IAAI;CAC7C,cAAqC,CAAC;CACtC,eAAsC,CAAC;;;;;;;;;;;CAWvC,sCAAmD,IAAI,IAAI;CAE3D,YAAY,OAA+B;EACzC,MAAM,KAAK;EACX,KAAK,QAAQ,MAAM;EACnB,KAAK,mBAAmB;EACxB,KAAK,gBAAgB;EACrB,KAAK,aAAa;EAClB,KAAK,mBAAmB;CAC1B;;;;;;;;;;;;CAaA,qBAAmC;EACjC,MAAM,QAAQ,IAAI,IAAI,KAAK,cAAc,KAAK,CAAC;EAC/C,MAAM,0BAAU,IAAI,IAAY;EAChC,KAAK,MAAM,QAAQ,KAAK,OAAO;GAC7B,MAAM,eAAe,CACnB,GAAI,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK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B,KAAK,aAAa,QAAQ,MAAM;MAEzD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;KACD,MAAM,oBAAoB,KAAK,YAAY,QAAQ,MAAM;MAEvD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
1
+ {"version":3,"file":"MultiAgentGraph.cjs","names":["StandardGraph","ToolMessage","Command","aiMsg","AIMessage","StateGraph","Annotation","END","HumanMessage","START","PromptTemplate"],"sources":["../../../src/graphs/MultiAgentGraph.ts"],"sourcesContent":["import { tool } from '@langchain/core/tools';\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport {\n AIMessage,\n ToolMessage,\n HumanMessage,\n getBufferString,\n} from '@langchain/core/messages';\nimport {\n END,\n START,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport type { BaseMessage, AIMessageChunk } from '@langchain/core/messages';\nimport type { LangGraphRunnableConfig } from '@langchain/langgraph';\nimport type { ToolRuntime } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { StandardGraph } from './Graph';\nimport { Constants } from '@/common';\n\n/** Pattern to extract instructions from transfer ToolMessage content */\nconst HANDOFF_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\\s*(.+)/is;\n\n/**\n * MultiAgentGraph extends StandardGraph to support dynamic multi-agent workflows\n * with handoffs, fan-in/fan-out, and other composable patterns.\n *\n * Key behavior:\n * - Agents with ONLY handoff edges: Can dynamically route to any handoff destination\n * - Agents with ONLY direct edges: Always follow their direct edges\n * - Agents with BOTH: Use Command for exclusive routing (handoff OR direct, not both)\n * - If handoff occurs: Only the handoff destination executes\n * - If no handoff: Direct edges execute (potentially in parallel)\n *\n * This enables the common pattern where an agent either delegates (handoff)\n * OR continues its workflow (direct edges), but not both simultaneously.\n */\nexport class MultiAgentGraph extends StandardGraph {\n private edges: t.GraphEdge[];\n private startingNodes: Set<string> = new Set();\n private directEdges: t.GraphEdge[] = [];\n private handoffEdges: t.GraphEdge[] = [];\n /**\n * Map of agentId to parallel group info.\n * Contains groupId (incrementing number reflecting execution order) for agents in parallel groups.\n * Sequential agents (not in any parallel group) have undefined entry.\n *\n * Example for: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: undefined (sequential, order 0)\n * - analyst1, analyst2, analyst3: { groupId: 1 } (parallel group, order 1)\n * - summarizer: undefined (sequential, order 2)\n */\n private agentParallelGroups: Map<string, number> = new Map();\n\n constructor(input: t.MultiAgentGraphInput) {\n super(input);\n this.edges = input.edges;\n this.validateEdgeAgents();\n this.categorizeEdges();\n this.analyzeGraph();\n this.createHandoffTools();\n }\n\n /**\n * Fails fast when an edge references an agent that is not in\n * `agentContexts`. Without this check, the underlying LangGraph\n * `StateGraph.compile()` would throw the opaque\n * `Found edge ending at unknown node \"<id>\"` error after graph\n * construction — far from the true root cause.\n *\n * This catches the common misuse of passing `edges` into a multi-agent\n * config without also passing the corresponding sub-agent configs in\n * `agents` (e.g. a host that forgot to pre-load handoff targets).\n */\n private validateEdgeAgents(): void {\n const known = new Set(this.agentContexts.keys());\n const unknown = new Set<string>();\n for (const edge of this.edges) {\n const participants = [\n ...(Array.isArray(edge.from) ? edge.from : [edge.from]),\n ...(Array.isArray(edge.to) ? edge.to : [edge.to]),\n ];\n for (const id of participants) {\n if (typeof id === 'string' && !known.has(id)) {\n unknown.add(id);\n }\n }\n }\n if (unknown.size === 0) {\n return;\n }\n const missing = Array.from(unknown)\n .map((id) => `\"${id}\"`)\n .join(', ');\n throw new Error(\n `MultiAgentGraph: edges reference agent(s) not present in agents: [${missing}]. ` +\n 'Ensure every agent referenced by an edge is also included in the `agents` array, ' +\n 'or filter orphaned edges before constructing the graph.'\n );\n }\n\n /**\n * Categorize edges into handoff and direct types\n */\n private categorizeEdges(): void {\n for (const edge of this.edges) {\n // Default behavior: edges with conditions or explicit 'handoff' type are handoff edges\n // Edges with explicit 'direct' type or multi-destination without conditions are direct edges\n if (edge.edgeType === 'direct') {\n this.directEdges.push(edge);\n } else if (edge.edgeType === 'handoff' || edge.condition != null) {\n this.handoffEdges.push(edge);\n } else {\n // Default: single-to-single edges are handoff, single-to-multiple are direct\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n\n if (sources.length === 1 && destinations.length > 1) {\n // Fan-out pattern defaults to direct\n this.directEdges.push(edge);\n } else {\n // Everything else defaults to handoff\n this.handoffEdges.push(edge);\n }\n }\n }\n }\n\n /**\n * Analyze graph structure to determine starting nodes and connections\n */\n private analyzeGraph(): void {\n const hasIncomingEdge = new Set<string>();\n\n // Track all nodes that have incoming edges\n for (const edge of this.edges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n destinations.forEach((dest) => hasIncomingEdge.add(dest));\n }\n\n // Starting nodes are those without incoming edges\n for (const agentId of this.agentContexts.keys()) {\n if (!hasIncomingEdge.has(agentId)) {\n this.startingNodes.add(agentId);\n }\n }\n\n // If no starting nodes found, use the first agent\n if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {\n this.startingNodes.add(this.agentContexts.keys().next().value!);\n }\n\n // Determine if graph has parallel execution capability\n this.computeParallelCapability();\n }\n\n /**\n * Compute parallel groups by traversing the graph in execution order.\n * Assigns incrementing group IDs that reflect the sequential order of execution.\n *\n * For: researcher -> [analyst1, analyst2, analyst3] -> summarizer\n * - researcher: no group (first sequential node)\n * - analyst1, analyst2, analyst3: groupId 1 (first parallel group)\n * - summarizer: no group (next sequential node)\n *\n * This allows frontend to render in order:\n * Row 0: researcher\n * Row 1: [analyst1, analyst2, analyst3] (grouped)\n * Row 2: summarizer\n */\n private computeParallelCapability(): void {\n let groupCounter = 1; // Start at 1, 0 reserved for \"no group\"\n\n // Check 1: Multiple starting nodes means parallel from the start (group 1)\n if (this.startingNodes.size > 1) {\n for (const agentId of this.startingNodes) {\n this.agentParallelGroups.set(agentId, groupCounter);\n }\n groupCounter++;\n }\n\n // Check 2: Traverse direct edges in order to find fan-out patterns\n // Build a simple execution order by following edges from starting nodes\n const visited = new Set<string>();\n const queue: string[] = [...this.startingNodes];\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (visited.has(current)) continue;\n visited.add(current);\n\n // Find direct edges from this node\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n // Fan-out: multiple destinations = parallel group\n if (destinations.length > 1) {\n for (const dest of destinations) {\n // Only set if not already in a group (first group wins)\n if (!this.agentParallelGroups.has(dest)) {\n this.agentParallelGroups.set(dest, groupCounter);\n }\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n groupCounter++;\n } else {\n // Single destination - add to queue for traversal\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n\n // Also follow handoff edges for traversal (but they don't create parallel groups)\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (!sources.includes(current)) continue;\n\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const dest of destinations) {\n if (!visited.has(dest)) {\n queue.push(dest);\n }\n }\n }\n }\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Returns undefined if the agent is not part of a parallel group.\n * Group IDs are incrementing numbers reflecting execution order.\n */\n getParallelGroupId(agentId: string): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Override to indicate this is a multi-agent graph.\n * Enables agentId to be included in RunStep for frontend agent labeling.\n */\n protected override isMultiAgentGraph(): boolean {\n return true;\n }\n\n /**\n * Override base class method to provide parallel group IDs for run steps.\n */\n protected override getParallelGroupIdForAgent(\n agentId: string\n ): number | undefined {\n return this.agentParallelGroups.get(agentId);\n }\n\n /**\n * Create handoff tools for agents based on handoff edges only\n */\n private createHandoffTools(): void {\n // Group handoff edges by source agent(s)\n const handoffsByAgent = new Map<string, t.GraphEdge[]>();\n\n // Only process handoff edges for tool creation\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n sources.forEach((source) => {\n if (!handoffsByAgent.has(source)) {\n handoffsByAgent.set(source, []);\n }\n handoffsByAgent.get(source)!.push(edge);\n });\n }\n\n // Create handoff tools for each agent\n for (const [agentId, edges] of handoffsByAgent) {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) continue;\n\n // Create handoff tools for this agent's outgoing edges\n const handoffTools: t.GenericTool[] = [];\n const sourceAgentName = agentContext.name ?? agentId;\n for (const edge of edges) {\n handoffTools.push(\n ...this.createHandoffToolsForEdge(edge, agentId, sourceAgentName)\n );\n }\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n agentContext.graphTools.push(...handoffTools);\n }\n }\n\n /**\n * Create handoff tools for an edge (handles multiple destinations)\n * @param edge - The graph edge defining the handoff\n * @param sourceAgentId - The ID of the agent that will perform the handoff\n * @param sourceAgentName - The human-readable name of the source agent\n */\n private createHandoffToolsForEdge(\n edge: t.GraphEdge,\n sourceAgentId: string,\n sourceAgentName: string\n ): t.GenericTool[] {\n const tools: t.GenericTool[] = [];\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n\n /** If there's a condition, create a single conditional handoff tool */\n if (edge.condition != null) {\n const toolName = 'conditional_transfer';\n const toolDescription =\n edge.description ?? 'Conditionally transfer control based on state';\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput ? edge.prompt : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const state = runtime.state as t.BaseGraphState;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n /** Evaluated condition */\n const result = edge.condition!(state);\n let destination: string;\n\n if (typeof result === 'boolean') {\n /** If true, use first destination; if false, don't transfer */\n if (!result) return null;\n destination = destinations[0];\n } else if (typeof result === 'string') {\n destination = result;\n } else {\n /** Array of destinations - for now, use the first */\n destination = Array.isArray(result) ? result[0] : destinations[0];\n }\n\n let content = `Conditionally transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store destination for programmatic access in handoff detection */\n handoff_destination: destination,\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n return new Command({\n goto: destination,\n update: { messages: state.messages.concat(toolMessage) },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n } else {\n /** Create individual tools for each destination */\n for (const destination of destinations) {\n const toolName = `${Constants.LC_TRANSFER_TO_}${destination}`;\n const toolDescription =\n edge.description ?? `Transfer control to agent '${destination}'`;\n\n /** Check if we have a prompt for handoff input */\n const hasHandoffInput =\n edge.prompt != null && typeof edge.prompt === 'string';\n const handoffInputDescription = hasHandoffInput\n ? edge.prompt\n : undefined;\n const promptKey = edge.promptKey ?? 'instructions';\n\n tools.push(\n tool(\n async (rawInput, runtime: ToolRuntime) => {\n const input = rawInput as Record<string, unknown>;\n const toolCallId = runtime.toolCall?.id ?? 'unknown';\n\n let content = `Successfully transferred to ${destination}`;\n if (\n hasHandoffInput &&\n promptKey in input &&\n input[promptKey] != null\n ) {\n content += `\\n\\n${promptKey.charAt(0).toUpperCase() + promptKey.slice(1)}: ${input[promptKey]}`;\n }\n\n const toolMessage = new ToolMessage({\n content,\n name: toolName,\n tool_call_id: toolCallId,\n additional_kwargs: {\n /** Store source agent name for receiving agent to know who handed off */\n handoff_source_name: sourceAgentName,\n },\n });\n\n const state = runtime.state as t.BaseGraphState;\n\n /**\n * For parallel handoff support:\n * Build messages that include ONLY this tool call's context.\n * This prevents errors when LLM calls multiple transfers simultaneously -\n * each destination gets a valid AIMessage with matching tool_call and tool_result.\n *\n * Strategy:\n * 1. Find the AIMessage containing this tool call\n * 2. Create a filtered AIMessage with ONLY this tool_call\n * 3. Include all messages before the AIMessage plus the filtered pair\n */\n const messages = state.messages;\n let filteredMessages = messages;\n let aiMessageIndex = -1;\n\n /** Find the AIMessage containing this tool call */\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() === 'ai') {\n const aiMsg = msg as AIMessage;\n const hasThisCall = aiMsg.tool_calls?.some(\n (tc) => tc.id === toolCallId\n );\n if (hasThisCall === true) {\n aiMessageIndex = i;\n break;\n }\n }\n }\n\n if (aiMessageIndex >= 0) {\n const originalAiMsg = messages[aiMessageIndex] as AIMessage;\n const thisToolCall = originalAiMsg.tool_calls?.find(\n (tc) => tc.id === toolCallId\n );\n\n if (\n thisToolCall != null &&\n (originalAiMsg.tool_calls?.length ?? 0) > 1\n ) {\n /**\n * Multiple tool calls - create filtered AIMessage with ONLY this call.\n * This ensures valid message structure for parallel handoffs.\n */\n const filteredAiMsg = new AIMessage({\n content: originalAiMsg.content,\n tool_calls: [thisToolCall],\n id: originalAiMsg.id,\n });\n\n filteredMessages = [\n ...messages.slice(0, aiMessageIndex),\n filteredAiMsg,\n toolMessage,\n ];\n } else {\n /** Single tool call - use messages as-is */\n filteredMessages = messages.concat(toolMessage);\n }\n } else {\n /** Fallback - append tool message */\n filteredMessages = messages.concat(toolMessage);\n }\n\n return new Command({\n goto: destination,\n update: { messages: filteredMessages },\n graph: Command.PARENT,\n });\n },\n {\n name: toolName,\n schema: hasHandoffInput\n ? {\n type: 'object',\n properties: {\n [promptKey]: {\n type: 'string',\n description: handoffInputDescription as string,\n },\n },\n required: [],\n }\n : { type: 'object', properties: {}, required: [] },\n description: toolDescription,\n }\n )\n );\n }\n }\n\n return tools;\n }\n\n /**\n * Create a complete agent subgraph (similar to createReactAgent)\n */\n private createAgentSubgraph(agentId: string): t.CompiledAgentWorfklow {\n /** This is essentially the same as `createAgentNode` from `StandardGraph` */\n return this.createAgentNode(agentId);\n }\n\n /**\n * Detects if the current agent is receiving a handoff and processes the messages accordingly.\n * Returns filtered messages with the transfer tool call/message removed, plus any instructions,\n * source agent, and parallel sibling information extracted from the transfer.\n *\n * Supports both single handoffs (last message is the transfer) and parallel handoffs\n * (multiple transfer ToolMessages, need to find the one targeting this agent).\n *\n * @param messages - Current state messages\n * @param agentId - The agent ID to check for handoff reception\n * @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings\n */\n private processHandoffReception(\n messages: BaseMessage[],\n agentId: string\n ): {\n filteredMessages: BaseMessage[];\n instructions: string | null;\n sourceAgentName: string | null;\n parallelSiblings: string[];\n } | null {\n if (messages.length === 0) return null;\n\n /**\n * Search for a transfer ToolMessage targeting this agent.\n * For parallel handoffs, multiple transfer messages may exist - find ours.\n * Search backwards from the end to find the most recent transfer to this agent.\n */\n let toolMessage: ToolMessage | null = null;\n let toolMessageIndex = -1;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg.getType() !== 'tool') continue;\n\n const candidateMsg = msg as ToolMessage;\n const toolName = candidateMsg.name;\n\n if (typeof toolName !== 'string') continue;\n\n /** Check for standard transfer pattern */\n const isTransferMessage = toolName.startsWith(Constants.LC_TRANSFER_TO_);\n const isConditionalTransfer = toolName === 'conditional_transfer';\n\n if (!isTransferMessage && !isConditionalTransfer) continue;\n\n /** Extract destination from tool name or additional_kwargs */\n let destinationAgent: string | null = null;\n\n if (isTransferMessage) {\n destinationAgent = toolName.replace(Constants.LC_TRANSFER_TO_, '');\n } else if (isConditionalTransfer) {\n const handoffDest = candidateMsg.additional_kwargs.handoff_destination;\n destinationAgent = typeof handoffDest === 'string' ? handoffDest : null;\n }\n\n /** Check if this transfer targets our agent */\n if (destinationAgent === agentId) {\n toolMessage = candidateMsg;\n toolMessageIndex = i;\n break;\n }\n }\n\n /** No transfer targeting this agent found */\n if (toolMessage === null || toolMessageIndex < 0) return null;\n\n /** Extract instructions from the ToolMessage content */\n const contentStr =\n typeof toolMessage.content === 'string'\n ? toolMessage.content\n : JSON.stringify(toolMessage.content);\n\n const instructionsMatch = contentStr.match(HANDOFF_INSTRUCTIONS_PATTERN);\n const instructions = instructionsMatch?.[1]?.trim() ?? null;\n\n /** Extract source agent name from additional_kwargs */\n const handoffSourceName = toolMessage.additional_kwargs.handoff_source_name;\n const sourceAgentName =\n typeof handoffSourceName === 'string' ? handoffSourceName : null;\n\n /** Extract parallel siblings (set by ToolNode for parallel handoffs) */\n const rawSiblings = toolMessage.additional_kwargs.handoff_parallel_siblings;\n const siblingIds: string[] = Array.isArray(rawSiblings)\n ? rawSiblings.filter((s): s is string => typeof s === 'string')\n : [];\n /** Convert IDs to display names */\n const parallelSiblings = siblingIds.map((id) => {\n const ctx = this.agentContexts.get(id);\n return ctx?.name ?? id;\n });\n\n /** Get the tool_call_id to find and filter the AI message's tool call */\n const toolCallId = toolMessage.tool_call_id;\n\n /**\n * Collect all transfer tool_call_ids to filter out.\n * For parallel handoffs, we filter ALL transfer messages (not just ours)\n * to give the receiving agent a clean context without handoff noise.\n */\n const transferToolCallIds = new Set<string>([toolCallId]);\n for (const msg of messages) {\n if (msg.getType() !== 'tool') continue;\n const tm = msg as ToolMessage;\n const tName = tm.name;\n if (typeof tName !== 'string') continue;\n if (\n tName.startsWith(Constants.LC_TRANSFER_TO_) ||\n tName === 'conditional_transfer'\n ) {\n transferToolCallIds.add(tm.tool_call_id);\n }\n }\n\n /** Filter out all transfer messages */\n const filteredMessages: BaseMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n const msgType = msg.getType();\n\n /** Skip transfer ToolMessages */\n if (msgType === 'tool') {\n const tm = msg as ToolMessage;\n if (transferToolCallIds.has(tm.tool_call_id)) {\n continue;\n }\n }\n\n if (msgType === 'ai') {\n /** Check if this AI message contains any transfer tool calls */\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const toolCalls = aiMsg.tool_calls;\n\n if (toolCalls && toolCalls.length > 0) {\n /** Filter out all transfer tool calls */\n const remainingToolCalls = toolCalls.filter(\n (tc) => tc.id == null || !transferToolCallIds.has(tc.id)\n );\n\n const hasTransferCalls = remainingToolCalls.length < toolCalls.length;\n\n if (hasTransferCalls) {\n if (\n remainingToolCalls.length > 0 ||\n (typeof aiMsg.content === 'string' && aiMsg.content.trim())\n ) {\n /** Keep the message but without transfer tool calls */\n const filteredAiMsg = new AIMessage({\n content: aiMsg.content,\n tool_calls: remainingToolCalls,\n id: aiMsg.id,\n });\n filteredMessages.push(filteredAiMsg);\n }\n /** If no remaining content or tool calls, skip this message entirely */\n continue;\n }\n }\n }\n\n /** Keep all other messages */\n filteredMessages.push(msg);\n }\n\n return {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n };\n }\n\n /**\n * Create the multi-agent workflow with dynamic handoffs\n */\n override createWorkflow(): t.CompiledMultiAgentWorkflow {\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n /** Channel for passing filtered messages to agents when excludeResults is true */\n agentMessages: Annotation<BaseMessage[]>({\n /** Replaces state entirely */\n reducer: (a, b) => b,\n default: () => [],\n }),\n });\n\n const builder = new StateGraph(StateAnnotation);\n\n // Add all agents as complete subgraphs\n for (const [agentId] of this.agentContexts) {\n // Get all possible destinations for this agent\n const handoffDestinations = new Set<string>();\n const directDestinations = new Set<string>();\n\n // Check handoff edges for destinations\n for (const edge of this.handoffEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => handoffDestinations.add(dest));\n }\n }\n\n // Check direct edges for destinations\n for (const edge of this.directEdges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n if (sources.includes(agentId) === true) {\n const dests = Array.isArray(edge.to) ? edge.to : [edge.to];\n dests.forEach((dest) => directDestinations.add(dest));\n }\n }\n\n /** Check if this agent has BOTH handoff and direct edges */\n const hasHandoffEdges = handoffDestinations.size > 0;\n const hasDirectEdges = directDestinations.size > 0;\n const needsCommandRouting = hasHandoffEdges && hasDirectEdges;\n\n /** Collect all possible destinations for this agent */\n const allDestinations = new Set([\n ...handoffDestinations,\n ...directDestinations,\n ]);\n if (handoffDestinations.size > 0 || directDestinations.size === 0) {\n allDestinations.add(END);\n }\n\n /** Agent subgraph (includes agent + tools) */\n const agentSubgraph = this.createAgentSubgraph(agentId);\n\n /** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */\n const agentWrapper = async (\n state: t.MultiAgentGraphState,\n config?: LangGraphRunnableConfig\n ): Promise<t.MultiAgentGraphState | Command> => {\n let result: t.MultiAgentGraphState;\n\n /**\n * Check if this agent is receiving a handoff.\n * If so, filter out the transfer messages and inject instructions as preamble.\n * This prevents the receiving agent from seeing the transfer as \"completed work\"\n * and prematurely producing an end token.\n */\n const handoffContext = this.processHandoffReception(\n state.messages,\n agentId\n );\n\n if (handoffContext !== null) {\n const {\n filteredMessages,\n instructions,\n sourceAgentName,\n parallelSiblings,\n } = handoffContext;\n\n /**\n * Set handoff context on the receiving agent.\n * Uses pre-computed graph position for depth and parallel info.\n */\n const agentContext = this.agentContexts.get(agentId);\n if (\n agentContext &&\n sourceAgentName != null &&\n sourceAgentName !== ''\n ) {\n agentContext.setHandoffContext(sourceAgentName, parallelSiblings);\n }\n\n /** Build messages for the receiving agent */\n let messagesForAgent = filteredMessages;\n\n /**\n * If there are instructions, inject them as a HumanMessage to\n * ground the receiving agent.\n *\n * When the last filtered message is a ToolMessage (e.g. from a\n * non-handoff tool the router called before handing off), a\n * synthetic AIMessage is inserted first to satisfy the\n * tool → assistant role ordering required by chat APIs. Without\n * this bridge, appending a HumanMessage directly after a\n * ToolMessage causes \"400 Unexpected role 'user' after role\n * 'tool'\" errors (see issue #54).\n */\n const hasInstructions = instructions !== null && instructions !== '';\n if (hasInstructions) {\n const lastMsg =\n filteredMessages.length > 0\n ? filteredMessages[filteredMessages.length - 1]\n : null;\n\n if (lastMsg != null && lastMsg.getType() === 'tool') {\n messagesForAgent = [\n ...filteredMessages,\n new AIMessage(\n `[Processed tool result and transferring to ${agentId}]`\n ),\n new HumanMessage(instructions),\n ];\n } else {\n messagesForAgent = [\n ...filteredMessages,\n new HumanMessage(instructions),\n ];\n }\n }\n\n /** Update token map if we have a token counter */\n if (agentContext?.tokenCounter && hasInstructions) {\n const freshTokenMap: Record<string, number> = {};\n for (\n let i = 0;\n i < Math.min(filteredMessages.length, this.startIndex);\n i++\n ) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n /** Add tokens for the bridge AIMessage + instructions HumanMessage */\n for (\n let i = filteredMessages.length;\n i < messagesForAgent.length;\n i++\n ) {\n freshTokenMap[i] = agentContext.tokenCounter(messagesForAgent[i]);\n }\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: messagesForAgent,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n agentMessages: [],\n };\n } else if (\n state.agentMessages != null &&\n state.agentMessages.length > 0\n ) {\n /**\n * When using agentMessages (excludeResults=true), we need to update\n * the token map to account for the new prompt message\n */\n const agentContext = this.agentContexts.get(agentId);\n if (agentContext && agentContext.tokenCounter) {\n /** The agentMessages contains:\n * 1. Filtered messages (0 to startIndex) - already have token counts\n * 2. New prompt message - needs token counting\n */\n const freshTokenMap: Record<string, number> = {};\n\n /** Copy existing token counts for filtered messages (0 to startIndex) */\n for (let i = 0; i < this.startIndex; i++) {\n const tokenCount = agentContext.indexTokenCountMap[i];\n if (tokenCount !== undefined) {\n freshTokenMap[i] = tokenCount;\n }\n }\n\n /** Calculate tokens only for the new prompt message (last message) */\n const promptMessageIndex = state.agentMessages.length - 1;\n if (promptMessageIndex >= this.startIndex) {\n const promptMessage = state.agentMessages[promptMessageIndex];\n freshTokenMap[promptMessageIndex] =\n agentContext.tokenCounter(promptMessage);\n }\n\n /** Update the agent's token map with instructions added */\n agentContext.updateTokenMapWithInstructions(freshTokenMap);\n }\n\n /** Temporary state with messages replaced by `agentMessages` */\n const transformedState: t.MultiAgentGraphState = {\n ...state,\n messages: state.agentMessages,\n };\n result = await agentSubgraph.invoke(transformedState, config);\n result = {\n ...result,\n /** Clear agentMessages for next agent */\n agentMessages: [],\n };\n } else {\n result = await agentSubgraph.invoke(state, config);\n }\n\n /** If agent has both handoff and direct edges, use Command for exclusive routing */\n if (needsCommandRouting) {\n /** Check if a handoff occurred */\n const lastMessage = result.messages[\n result.messages.length - 1\n ] as BaseMessage | null;\n if (\n lastMessage != null &&\n lastMessage.getType() === 'tool' &&\n typeof lastMessage.name === 'string' &&\n lastMessage.name.startsWith(Constants.LC_TRANSFER_TO_)\n ) {\n /** Handoff occurred - extract destination and navigate there exclusively */\n const handoffDest = lastMessage.name.replace(\n Constants.LC_TRANSFER_TO_,\n ''\n );\n return new Command({\n update: result,\n goto: handoffDest,\n });\n } else {\n /** No handoff - proceed with direct edges */\n const directDests = Array.from(directDestinations);\n if (directDests.length === 1) {\n return new Command({\n update: result,\n goto: directDests[0],\n });\n } else if (directDests.length > 1) {\n /** Multiple direct destinations - they'll run in parallel */\n return new Command({\n update: result,\n goto: directDests,\n });\n }\n }\n }\n\n /** No special routing needed - return state normally */\n return result;\n };\n\n /** Wrapped agent as a node with its possible destinations */\n builder.addNode(agentId, agentWrapper, {\n ends: Array.from(allDestinations),\n });\n }\n\n // Add starting edges for all starting nodes\n for (const startNode of this.startingNodes) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(START, startNode);\n }\n\n /**\n * Add direct edges for automatic transitions\n * Group edges by destination to handle fan-in scenarios\n */\n const edgesByDestination = new Map<string, t.GraphEdge[]>();\n\n for (const edge of this.directEdges) {\n const destinations = Array.isArray(edge.to) ? edge.to : [edge.to];\n for (const destination of destinations) {\n if (!edgesByDestination.has(destination)) {\n edgesByDestination.set(destination, []);\n }\n edgesByDestination.get(destination)!.push(edge);\n }\n }\n\n for (const [destination, edges] of edgesByDestination) {\n /** Checks if this is a fan-in scenario with prompt instructions */\n const edgesWithPrompt = edges.filter(\n (edge) => edge.prompt != null && edge.prompt !== ''\n );\n\n if (edgesWithPrompt.length > 0) {\n /**\n * Single wrapper node for destination (Fan-in with prompt)\n */\n const wrapperNodeId = `fan_in_${destination}_prompt`;\n /**\n * First edge's `prompt`\n * (they should all be the same for fan-in)\n */\n const prompt = edgesWithPrompt[0].prompt;\n /**\n * First edge's `excludeResults` flag\n * (they should all be the same for fan-in)\n */\n const excludeResults = edgesWithPrompt[0].excludeResults;\n\n builder.addNode(wrapperNodeId, async (state: t.BaseGraphState) => {\n let promptText: string | undefined;\n let effectiveExcludeResults = excludeResults;\n\n if (typeof prompt === 'function') {\n promptText = await prompt(state.messages, this.startIndex);\n } else if (prompt != null) {\n if (prompt.includes('{results}')) {\n const resultsMessages = state.messages.slice(this.startIndex);\n const resultsString = getBufferString(resultsMessages);\n const promptTemplate = PromptTemplate.fromTemplate(prompt);\n const result = await promptTemplate.invoke({\n results: resultsString,\n });\n promptText = result.value;\n effectiveExcludeResults =\n excludeResults !== false && promptText !== '';\n } else {\n promptText = prompt;\n }\n }\n\n if (promptText != null && promptText !== '') {\n if (\n effectiveExcludeResults == null ||\n effectiveExcludeResults === false\n ) {\n return {\n messages: [new HumanMessage(promptText)],\n };\n }\n\n /** When `excludeResults` is true, use agentMessages channel\n * to pass filtered messages + prompt to the destination agent\n */\n const filteredMessages = state.messages.slice(0, this.startIndex);\n const promptMessage = new HumanMessage(promptText);\n return {\n messages: [promptMessage],\n agentMessages: messagesStateReducer(filteredMessages, [\n promptMessage,\n ]),\n };\n }\n\n /** No prompt needed, return empty update */\n return {};\n });\n\n /** Add edges from all sources to the wrapper, then wrapper to destination */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, wrapperNodeId);\n }\n }\n\n /** Single edge from wrapper to destination */\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(wrapperNodeId, destination);\n } else {\n /** No prompt instructions, add direct edges (skip if source uses Command routing) */\n for (const edge of edges) {\n const sources = Array.isArray(edge.from) ? edge.from : [edge.from];\n for (const source of sources) {\n /** Check if this source node has both handoff and direct edges */\n const sourceHandoffEdges = this.handoffEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n const sourceDirectEdges = this.directEdges.filter((e) => {\n const eSources = Array.isArray(e.from) ? e.from : [e.from];\n return eSources.includes(source);\n });\n\n /** Skip adding edge if source uses Command routing (has both types) */\n if (sourceHandoffEdges.length > 0 && sourceDirectEdges.length > 0) {\n continue;\n }\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n /** @ts-ignore */\n builder.addEdge(source, destination);\n }\n }\n }\n }\n\n return builder.compile(this.comp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AAK,UAAU;MAChE,MAAM,gBAAgB,IAAIA,yBAAAA,aAAa,UAAU;MACjD,OAAO;OACL,UAAU,CAAC,aAAa;OACxB,gBAAA,GAAA,qBAAA,qBAAA,CAAoC,kBAAkB,CACpD,aACF,CAAC;MACH;KACF;;KAGA,OAAO,CAAC;IACV,CAAC;;IAGD,KAAK,MAAM,QAAQ,OAAO;KACxB,MAAM,UAAU,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;KACjE,KAAK,MAAM,UAAU;;KAGnB,QAAQ,QAAQ,QAAQ,aAAa;IAEzC;;;IAKA,QAAQ,QAAQ,eAAe,WAAW;GAC5C;;GAEE,KAAK,MAAM,QAAQ,OAAO;IACxB,MAAM,UAAU,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;IACjE,KAAK,MAAM,UAAU,SAAS;;KAE5B,MAAM,qBAAqB,KAAK,aAAa,QAAQ,MAAM;MAEzD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;KACD,MAAM,oBAAoB,KAAK,YAAY,QAAQ,MAAM;MAEvD,QADiB,MAAM,QAAQ,EAAE,IAAI,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,EAAA,CACzC,SAAS,MAAM;KACjC,CAAC;;KAGD,IAAI,mBAAmB,SAAS,KAAK,kBAAkB,SAAS,GAC9D;;KAKF,QAAQ,QAAQ,QAAQ,WAAW;IACrC;GACF;EAEJ;EAEA,OAAO,QAAQ,QAAQ,KAAK,cAAkC;CAChE;AACF"}
@@ -216,16 +216,17 @@ var CustomAnthropic = class extends _langchain_anthropic.ChatAnthropicMessages {
216
216
  const compactionBetas = getCompactionBetas(contextManagement);
217
217
  const taskBudgetBetas = getTaskBudgetBetas(this.model, mergedOutputConfig);
218
218
  const sharedParams = {
219
- tools: this.formatStructuredToolToAnthropic(options?.tools),
219
+ tools: this.formatStructuredToolToAnthropic(options?.tools, { strict: options?.strict }),
220
220
  tool_choice,
221
- thinking: this.thinking,
221
+ thinking: this.thinkingExplicitlySet ? this.thinking : void 0,
222
222
  context_management: contextManagement,
223
223
  ...this.invocationKwargs,
224
224
  container: callOptions?.container,
225
225
  betas: combineBetas(this.betas, callOptions?.betas, toolBetas, compactionBetas, taskBudgetBetas),
226
226
  output_config: mergedOutputConfig,
227
227
  inference_geo: inferenceGeo,
228
- mcp_servers: callOptions?.mcp_servers
228
+ mcp_servers: callOptions?.mcp_servers,
229
+ cache_control: options?.cache_control
229
230
  };
230
231
  validateInvocationParamCompatibility({
231
232
  model: this.model,
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["AIMessageChunk","ChatAnthropicMessages","handleToolChoice","ChatGenerationChunk","stripUnsupportedAssistantPrefill","_convertMessagesToAnthropicPayload","_makeMessageChunkFromAnthropicEvent"],"sources":["../../../../src/llm/anthropic/index.ts"],"sourcesContent":["import { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatAnthropicMessages } from '@langchain/anthropic';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { BaseChatModelParams } from '@langchain/core/language_models/chat_models';\nimport type {\n BaseMessage,\n MessageContentComplex,\n} from '@langchain/core/messages';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { AnthropicInput } from '@langchain/anthropic';\nimport type { Anthropic } from '@anthropic-ai/sdk';\nimport type {\n AnthropicMessageCreateParams,\n AnthropicStreamingMessageCreateParams,\n AnthropicOutputConfig,\n AnthropicBeta,\n ChatAnthropicToolType,\n AnthropicMCPServerURLDefinition,\n AnthropicContextManagementConfigParam,\n AnthropicRequestOptions,\n} from '@/llm/anthropic/types';\nimport {\n _convertMessagesToAnthropicPayload,\n stripUnsupportedAssistantPrefill,\n} from './utils/message_inputs';\nimport { _makeMessageChunkFromAnthropicEvent } from './utils/message_outputs';\nimport { handleToolChoice } from './utils/tools';\n\nconst DEFAULT_STREAM_DELAY = 25;\nconst MAX_STREAM_QUEUE_CHUNKS = 256;\nconst MAX_STREAM_QUEUE_TEXT_CHARS = 8192;\nconst STREAM_CHUNK_MIN_SIZE = 4;\nconst STREAM_BOUNDARIES = new Set([' ', '.', ',', '!', '?', ';', ':']);\n\ntype StreamTokenType = 'string' | 'input' | 'content';\n\nconst ANTHROPIC_TOOL_BETAS: Partial<Record<string, AnthropicBeta>> = {\n tool_search_tool_regex_20251119: 'advanced-tool-use-2025-11-20',\n tool_search_tool_bm25_20251119: 'advanced-tool-use-2025-11-20',\n memory_20250818: 'context-management-2025-06-27',\n web_fetch_20250910: 'web-fetch-2025-09-10',\n code_execution_20250825: 'code-execution-2025-08-25',\n computer_20251124: 'computer-use-2025-11-24',\n computer_20250124: 'computer-use-2025-01-24',\n mcp_toolset: 'mcp-client-2025-11-20',\n};\n\nfunction _toolsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(params.tools && params.tools.length > 0);\n}\nexport function _documentsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n for (const message of params.messages) {\n if (typeof message.content === 'string') {\n continue;\n }\n for (const block of message.content) {\n const maybeBlock: unknown = block;\n if (\n typeof maybeBlock === 'object' &&\n maybeBlock !== null &&\n 'type' in maybeBlock &&\n maybeBlock.type === 'document' &&\n 'citations' in maybeBlock &&\n maybeBlock.citations != null &&\n typeof maybeBlock.citations === 'object' &&\n 'enabled' in maybeBlock.citations &&\n maybeBlock.citations.enabled === true\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction _thinkingInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(\n params.thinking &&\n (params.thinking.type === 'enabled' || params.thinking.type === 'adaptive')\n );\n}\n\nfunction _compactionInParams(\n params: (\n | AnthropicMessageCreateParams\n | AnthropicStreamingMessageCreateParams\n ) & {\n context_management?: AnthropicContextManagementConfigParam;\n }\n): boolean {\n return (\n params.context_management?.edits?.some(\n (edit) => edit.type === 'compact_20260112'\n ) === true\n );\n}\n\nfunction isThinkingEnabled(thinking: Anthropic.ThinkingConfigParam): boolean {\n return thinking.type === 'enabled' || thinking.type === 'adaptive';\n}\n\nfunction isOpus47Model(model?: string): boolean {\n return /^claude-opus-4-7(?:-|$)/.test(model ?? '');\n}\n\nfunction combineBetas(\n ...betaGroups: (AnthropicBeta[] | undefined)[]\n): AnthropicBeta[] {\n const betas = new Set<AnthropicBeta>();\n for (const betaGroup of betaGroups) {\n for (const beta of betaGroup ?? []) {\n betas.add(beta);\n }\n }\n return [...betas];\n}\n\nfunction getToolBetas(tools?: ChatAnthropicToolType[]): AnthropicBeta[] {\n const betas = new Set<AnthropicBeta>();\n for (const tool of tools ?? []) {\n if (typeof tool !== 'object' || !('type' in tool)) {\n continue;\n }\n const beta = ANTHROPIC_TOOL_BETAS[String(tool.type)];\n if (beta != null) {\n betas.add(beta);\n }\n }\n return [...betas];\n}\n\nfunction getCompactionBetas(\n contextManagement?: AnthropicContextManagementConfigParam\n): AnthropicBeta[] {\n return contextManagement?.edits?.some(\n (edit) => edit.type === 'compact_20260112'\n ) === true\n ? ['compact-2026-01-12']\n : [];\n}\n\nfunction getTaskBudgetBetas(\n model: string,\n outputConfig?: AnthropicOutputConfig\n): AnthropicBeta[] {\n return isOpus47Model(model) &&\n outputConfig != null &&\n 'task_budget' in outputConfig &&\n outputConfig.task_budget != null\n ? ['task-budgets-2026-03-13']\n : [];\n}\n\nfunction isSetSamplingValue(value?: number | null): value is number {\n return value != null && value !== -1;\n}\n\nfunction isNonDefaultTemperature(value?: number): boolean {\n return isSetSamplingValue(value) && value !== 1;\n}\n\nfunction validateInvocationParamCompatibility({\n model,\n thinking,\n topK,\n topP,\n temperature,\n}: {\n model: string;\n thinking: Anthropic.ThinkingConfigParam;\n topK?: number;\n topP?: number | null;\n temperature?: number;\n}): void {\n const opus47 = isOpus47Model(model);\n if (opus47 && thinking.type === 'enabled') {\n throw new Error(\n 'thinking.type=\"enabled\" is not supported for claude-opus-4-7; use thinking.type=\"adaptive\" instead'\n );\n }\n if (opus47 && 'budget_tokens' in thinking) {\n throw new Error(\n 'thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead'\n );\n }\n if (opus47) {\n if (isSetSamplingValue(topK)) {\n throw new Error(\n 'topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead'\n );\n }\n if (isSetSamplingValue(topP) && topP !== 1) {\n throw new Error(\n 'topP is not supported for claude-opus-4-7 when set to non-default values'\n );\n }\n if (isNonDefaultTemperature(temperature)) {\n throw new Error(\n 'temperature is not supported for claude-opus-4-7 when set to non-default values'\n );\n }\n }\n if (!isThinkingEnabled(thinking)) {\n return;\n }\n if (isSetSamplingValue(topK)) {\n throw new Error('topK is not supported when thinking is enabled');\n }\n if (isSetSamplingValue(topP)) {\n throw new Error('topP is not supported when thinking is enabled');\n }\n if (isNonDefaultTemperature(temperature)) {\n throw new Error('temperature is not supported when thinking is enabled');\n }\n}\n\nfunction getSamplingParams({\n model,\n thinking,\n topK,\n topP,\n temperature,\n}: {\n model: string;\n thinking: Anthropic.ThinkingConfigParam;\n topK?: number;\n topP?: number | null;\n temperature?: number;\n}): {\n temperature?: number;\n top_k?: number;\n top_p?: number;\n} {\n if (isThinkingEnabled(thinking) || isOpus47Model(model)) {\n return {};\n }\n return {\n ...(isSetSamplingValue(temperature) ? { temperature } : {}),\n ...(isSetSamplingValue(topK) ? { top_k: topK } : {}),\n ...(isSetSamplingValue(topP) ? { top_p: topP } : {}),\n };\n}\n\nfunction findStreamChunkBoundary(text: string, minSize: number): number {\n if (minSize >= text.length) {\n return text.length;\n }\n\n for (let position = minSize; position < text.length; position++) {\n if (STREAM_BOUNDARIES.has(text[position])) {\n return position + 1;\n }\n }\n\n return text.length;\n}\n\nfunction splitStreamToken(text: string): string[] {\n const chunks: string[] = [];\n let currentIndex = 0;\n\n while (currentIndex < text.length) {\n const remainingText = text.slice(currentIndex);\n const chunkSize = findStreamChunkBoundary(\n remainingText,\n STREAM_CHUNK_MIN_SIZE\n );\n chunks.push(text.slice(currentIndex, currentIndex + chunkSize));\n currentIndex += chunkSize;\n }\n\n return chunks;\n}\n\nfunction getCadencedStreamDelay({\n targetDelay,\n lastVisibleTextAt,\n now,\n}: {\n targetDelay: number;\n lastVisibleTextAt?: number;\n now: number;\n}): number {\n if (targetDelay <= 0 || lastVisibleTextAt == null) {\n return 0;\n }\n return Math.max(0, targetDelay - (now - lastVisibleTextAt));\n}\n\nasync function waitForStreamDelay(\n delay: number,\n signal?: AbortSignal\n): Promise<void> {\n if (delay <= 0 || isSignalAborted(signal)) {\n return;\n }\n await new Promise<void>((resolve) => {\n const timeoutRef: { current?: ReturnType<typeof setTimeout> } = {};\n const onAbort = (): void => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n signal?.removeEventListener('abort', onAbort);\n resolve();\n };\n timeoutRef.current = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, delay);\n signal?.addEventListener('abort', onAbort, { once: true });\n if (isSignalAborted(signal)) {\n onAbort();\n }\n });\n}\n\nfunction isSignalAborted(signal?: AbortSignal): boolean {\n return signal?.aborted === true;\n}\n\nfunction extractToken(\n chunk: AIMessageChunk\n): [string, StreamTokenType] | [undefined] {\n if (typeof chunk.content === 'string') {\n return [chunk.content, 'string'];\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n 'input' in chunk.content[0]\n ) {\n return typeof chunk.content[0].input === 'string'\n ? [chunk.content[0].input, 'input']\n : [JSON.stringify(chunk.content[0].input), 'input'];\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n 'text' in chunk.content[0]\n ) {\n const text = chunk.content[0].text;\n return typeof text === 'string' ? [text, 'content'] : [undefined];\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n 'thinking' in chunk.content[0]\n ) {\n const thinking = chunk.content[0].thinking;\n return typeof thinking === 'string' ? [thinking, 'content'] : [undefined];\n }\n return [undefined];\n}\n\nfunction cloneChunk(\n text: string,\n tokenType: StreamTokenType,\n chunk: AIMessageChunk\n): AIMessageChunk {\n if (tokenType === 'string') {\n return new AIMessageChunk(Object.assign({}, chunk, { content: text }));\n } else if (tokenType === 'input') {\n return chunk;\n }\n const content = chunk.content[0] as MessageContentComplex;\n if (content.type === 'text') {\n return new AIMessageChunk(\n Object.assign({}, chunk, {\n content: [Object.assign({}, content, { text })],\n })\n );\n } else if (content.type === 'text_delta') {\n return new AIMessageChunk(\n Object.assign({}, chunk, {\n content: [Object.assign({}, content, { text })],\n })\n );\n } else if (\n typeof content.type === 'string' &&\n content.type.startsWith('thinking')\n ) {\n return new AIMessageChunk(\n Object.assign({}, chunk, {\n content: [Object.assign({}, content, { thinking: text })],\n })\n );\n }\n\n return chunk;\n}\n\nfunction withIncrementalMessageDeltaUsage(\n chunk: AIMessageChunk,\n previousOutputTokens: number\n): { chunk: AIMessageChunk; outputTokens: number } {\n const usage = chunk.usage_metadata;\n if (usage == null) {\n return { chunk, outputTokens: previousOutputTokens };\n }\n\n const outputTokens = Math.max(0, usage.output_tokens - previousOutputTokens);\n return {\n chunk: new AIMessageChunk(\n Object.assign({}, chunk, {\n usage_metadata: {\n ...usage,\n output_tokens: outputTokens,\n total_tokens: usage.input_tokens + outputTokens,\n },\n })\n ),\n outputTokens: usage.output_tokens,\n };\n}\n\nexport type CustomAnthropicInput = AnthropicInput & {\n _lc_stream_delay?: number;\n outputConfig?: AnthropicOutputConfig;\n inferenceGeo?: string;\n contextManagement?: AnthropicContextManagementConfigParam;\n} & BaseChatModelParams;\n\nexport type CustomAnthropicCallOptions = {\n outputConfig?: AnthropicOutputConfig;\n outputFormat?: Anthropic.Messages.JSONOutputFormat;\n inferenceGeo?: string;\n betas?: AnthropicBeta[];\n container?: string;\n mcp_servers?: AnthropicMCPServerURLDefinition[];\n};\n\ntype CustomAnthropicInvocationParams = {\n betas?: AnthropicBeta[];\n container?: string;\n context_management?: AnthropicContextManagementConfigParam;\n inference_geo?: string;\n mcp_servers?: AnthropicMCPServerURLDefinition[];\n output_config?: AnthropicOutputConfig;\n};\n\ntype QueuedGenerationChunk = {\n chunk: ChatGenerationChunk;\n token: string;\n smooth: boolean;\n textLength: number;\n};\n\nexport class CustomAnthropic extends ChatAnthropicMessages {\n _lc_stream_delay: number;\n private tools_in_params?: boolean;\n top_k: number | undefined;\n outputConfig?: AnthropicOutputConfig;\n inferenceGeo?: string;\n contextManagement?: AnthropicContextManagementConfigParam;\n constructor(fields?: CustomAnthropicInput) {\n super(fields);\n this.resetTokenEvents();\n this.setDirectFields(fields);\n this._lc_stream_delay = Math.max(\n 0,\n fields?._lc_stream_delay ?? DEFAULT_STREAM_DELAY\n );\n this.outputConfig = fields?.outputConfig;\n this.inferenceGeo = fields?.inferenceGeo;\n this.contextManagement = fields?.contextManagement;\n }\n\n static lc_name(): 'LibreChatAnthropic' {\n return 'LibreChatAnthropic';\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(\n options?: this['ParsedCallOptions'] & CustomAnthropicCallOptions\n ): Omit<\n AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams,\n 'messages'\n > &\n CustomAnthropicInvocationParams {\n const tool_choice:\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | undefined = handleToolChoice(options?.tool_choice);\n\n const callOptions = options as CustomAnthropicCallOptions | undefined;\n const mergedOutputConfig: AnthropicOutputConfig | undefined = (():\n | AnthropicOutputConfig\n | undefined => {\n const base = {\n ...this.outputConfig,\n ...callOptions?.outputConfig,\n };\n if (callOptions?.outputFormat && !base.format) {\n base.format = callOptions.outputFormat;\n }\n return Object.keys(base).length > 0 ? base : undefined;\n })();\n\n const inferenceGeo = callOptions?.inferenceGeo ?? this.inferenceGeo;\n\n const contextManagement = this.contextManagement;\n const toolBetas = getToolBetas(options?.tools);\n const compactionBetas = getCompactionBetas(contextManagement);\n const taskBudgetBetas = getTaskBudgetBetas(this.model, mergedOutputConfig);\n const formattedTools = this.formatStructuredToolToAnthropic(options?.tools);\n\n const sharedParams = {\n tools: formattedTools,\n tool_choice,\n thinking: this.thinking,\n context_management: contextManagement,\n ...this.invocationKwargs,\n container: callOptions?.container,\n betas: combineBetas(\n this.betas,\n callOptions?.betas,\n toolBetas,\n compactionBetas,\n taskBudgetBetas\n ),\n output_config: mergedOutputConfig,\n inference_geo: inferenceGeo,\n mcp_servers: callOptions?.mcp_servers,\n };\n validateInvocationParamCompatibility({\n model: this.model,\n thinking: this.thinking,\n topK: this.top_k,\n topP: this.topP,\n temperature: this.temperature,\n });\n\n return {\n model: this.model,\n stop_sequences: options?.stop ?? this.stopSequences,\n stream: this.streaming,\n max_tokens: this.maxTokens,\n ...getSamplingParams({\n model: this.model,\n thinking: this.thinking,\n topK: this.top_k,\n topP: this.topP,\n temperature: this.temperature,\n }),\n ...sharedParams,\n };\n }\n\n resetTokenEvents(): void {\n this.tools_in_params = undefined;\n }\n\n setDirectFields(fields?: CustomAnthropicInput): void {\n this.temperature = fields?.temperature ?? undefined;\n this.topP = fields?.topP ?? undefined;\n this.top_k = fields?.topK;\n if (this.temperature === -1 || this.temperature === 1) {\n this.temperature = undefined;\n }\n if (this.topP === -1) {\n this.topP = undefined;\n }\n if (this.top_k === -1) {\n this.top_k = undefined;\n }\n }\n\n private createGenerationChunk({\n token,\n chunk,\n shouldStreamUsage,\n }: {\n token?: string;\n chunk: AIMessageChunk;\n shouldStreamUsage: boolean;\n }): ChatGenerationChunk {\n const usage_metadata = shouldStreamUsage ? chunk.usage_metadata : undefined;\n return new ChatGenerationChunk({\n message: new AIMessageChunk({\n // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().\n content: chunk.content,\n additional_kwargs: chunk.additional_kwargs,\n tool_call_chunks: chunk.tool_call_chunks,\n response_metadata: chunk.response_metadata,\n usage_metadata,\n id: chunk.id,\n }),\n text: token ?? '',\n });\n }\n\n protected override async createStreamWithRetry(\n request: AnthropicStreamingMessageCreateParams,\n options?: AnthropicRequestOptions\n ): ReturnType<ChatAnthropicMessages['createStreamWithRetry']> {\n return super.createStreamWithRetry(\n stripUnsupportedAssistantPrefill(request),\n options\n );\n }\n\n protected override async completionWithRetry(\n request: AnthropicMessageCreateParams,\n options: AnthropicRequestOptions\n ): ReturnType<ChatAnthropicMessages['completionWithRetry']> {\n return super.completionWithRetry(\n stripUnsupportedAssistantPrefill(request),\n options\n );\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n this.resetTokenEvents();\n const params = this.invocationParams(options);\n const formattedMessages = _convertMessagesToAnthropicPayload(messages);\n const payload = stripUnsupportedAssistantPrefill({\n ...params,\n ...formattedMessages,\n stream: true,\n } as const);\n const coerceContentToString =\n !_toolsInParams(payload) &&\n !_documentsInParams(payload) &&\n !_thinkingInParams(payload) &&\n !_compactionInParams(payload);\n\n const stream = await this.createStreamWithRetry(payload, {\n headers: options.headers,\n signal: options.signal,\n });\n\n const shouldStreamUsage = options.streamUsage ?? this.streamUsage;\n let messageDeltaOutputTokens = 0;\n const queuedChunks: QueuedGenerationChunk[] = [];\n const producerState: {\n done: boolean;\n error?: unknown;\n } = { done: false };\n let queuedChunkIndex = 0;\n let bufferedTextLength = 0;\n let consumerClosed = false;\n let notifyConsumer: (() => void) | undefined;\n let notifyProducer: (() => void) | undefined;\n\n const notifyConsumerForChunk = (): void => {\n notifyConsumer?.();\n notifyConsumer = undefined;\n };\n\n const notifyProducerForSpace = (): void => {\n notifyProducer?.();\n notifyProducer = undefined;\n };\n\n const hasQueuedChunks = (): boolean =>\n queuedChunkIndex < queuedChunks.length;\n\n const getQueuedChunkCount = (): number =>\n queuedChunks.length - queuedChunkIndex;\n\n const isQueueAtCapacity = (): boolean =>\n getQueuedChunkCount() >= MAX_STREAM_QUEUE_CHUNKS ||\n bufferedTextLength >= MAX_STREAM_QUEUE_TEXT_CHARS;\n\n const waitForNextChunk = async (): Promise<void> => {\n if (\n hasQueuedChunks() ||\n producerState.done ||\n producerState.error != null\n ) {\n return;\n }\n await new Promise<void>((resolve) => {\n notifyConsumer = resolve;\n });\n };\n\n const waitForQueueSpace = async (): Promise<void> => {\n while (\n isQueueAtCapacity() &&\n !consumerClosed &&\n !isSignalAborted(options.signal)\n ) {\n await new Promise<void>((resolve) => {\n const signal = options.signal;\n const onAbort = (): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n };\n const onSpace = (): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n };\n notifyProducer = onSpace;\n signal?.addEventListener('abort', onAbort, { once: true });\n if (isSignalAborted(signal)) {\n onAbort();\n }\n });\n }\n };\n\n const dequeue = (): QueuedGenerationChunk | undefined => {\n if (!hasQueuedChunks()) {\n return undefined;\n }\n const queuedChunk = queuedChunks[queuedChunkIndex];\n queuedChunkIndex++;\n if (\n queuedChunkIndex > 128 &&\n queuedChunkIndex * 2 >= queuedChunks.length\n ) {\n queuedChunks.splice(0, queuedChunkIndex);\n queuedChunkIndex = 0;\n }\n return queuedChunk;\n };\n\n const enqueue = async (\n queuedChunk: QueuedGenerationChunk\n ): Promise<void> => {\n await waitForQueueSpace();\n if (consumerClosed || isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n queuedChunks.push(queuedChunk);\n if (queuedChunk.smooth) {\n bufferedTextLength += queuedChunk.textLength;\n }\n notifyConsumerForChunk();\n };\n\n const enqueueChunk = async ({\n token,\n chunk,\n smooth,\n }: {\n token: string;\n chunk: AIMessageChunk;\n smooth: boolean;\n }): Promise<void> => {\n await enqueue({\n token,\n smooth,\n textLength: smooth ? token.length : 0,\n chunk: this.createGenerationChunk({\n token,\n chunk,\n shouldStreamUsage,\n }),\n });\n };\n\n const enqueueTextChunks = (\n token: string,\n tokenType: StreamTokenType,\n chunk: AIMessageChunk\n ): Promise<void> => {\n if (token === '') {\n return Promise.resolve();\n }\n if (this._lc_stream_delay <= 0) {\n return enqueueChunk({ token, chunk, smooth: false });\n }\n\n const tokenChunks = splitStreamToken(token);\n if (tokenChunks.length <= 1) {\n return enqueueChunk({ token, chunk, smooth: true });\n }\n\n let emittedUsage = false;\n return tokenChunks.reduce(async (previous, currentToken) => {\n await previous;\n const newChunk = cloneChunk(currentToken, tokenType, chunk);\n const chunkForToken =\n emittedUsage && newChunk.usage_metadata != null\n ? new AIMessageChunk(\n Object.assign({}, newChunk, { usage_metadata: undefined })\n )\n : newChunk;\n\n await enqueueChunk({\n token: currentToken,\n chunk: chunkForToken,\n smooth: true,\n });\n\n if (newChunk.usage_metadata != null && !emittedUsage) {\n emittedUsage = true;\n }\n }, Promise.resolve());\n };\n\n const producer = (async (): Promise<void> => {\n try {\n for await (const data of stream) {\n if (isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n\n const result = _makeMessageChunkFromAnthropicEvent(\n data as Anthropic.Beta.Messages.BetaRawMessageStreamEvent,\n {\n streamUsage: shouldStreamUsage,\n coerceContentToString,\n }\n );\n if (!result) {\n continue;\n }\n\n let { chunk } = result;\n if (data.type === 'message_delta') {\n const incremental = withIncrementalMessageDeltaUsage(\n chunk,\n messageDeltaOutputTokens\n );\n chunk = incremental.chunk;\n messageDeltaOutputTokens = incremental.outputTokens;\n }\n\n const [token = '', tokenType] = extractToken(chunk);\n if (\n !tokenType ||\n tokenType === 'input' ||\n (token === '' && (chunk.usage_metadata != null || chunk.id != null))\n ) {\n await enqueueChunk({ token, chunk, smooth: false });\n continue;\n }\n\n await enqueueTextChunks(token, tokenType, chunk);\n }\n } catch (error) {\n producerState.error = error;\n } finally {\n producerState.done = true;\n notifyConsumerForChunk();\n }\n })();\n\n let hasEmittedText = false;\n let lastVisibleTextAt: number | undefined;\n let keepStreaming = true;\n try {\n while (keepStreaming) {\n if (isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n\n await waitForNextChunk();\n const queuedChunk = dequeue();\n\n if (!queuedChunk) {\n if (producerState.error != null) {\n throw producerState.error;\n }\n if (producerState.done) {\n keepStreaming = false;\n }\n continue;\n }\n\n if (queuedChunk.smooth) {\n bufferedTextLength = Math.max(\n 0,\n bufferedTextLength - queuedChunk.textLength\n );\n notifyProducerForSpace();\n await waitForStreamDelay(\n getCadencedStreamDelay({\n targetDelay: hasEmittedText ? this._lc_stream_delay : 0,\n lastVisibleTextAt,\n now: Date.now(),\n }),\n options.signal\n );\n if (isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n hasEmittedText = true;\n lastVisibleTextAt = Date.now();\n } else {\n notifyProducerForSpace();\n }\n\n yield queuedChunk.chunk;\n await runManager?.handleLLMNewToken(\n queuedChunk.token,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: queuedChunk.chunk }\n );\n }\n } finally {\n consumerClosed = true;\n if (!producerState.done) {\n stream.controller.abort();\n notifyProducerForSpace();\n }\n await producer;\n this.resetTokenEvents();\n }\n }\n}\n"],"mappings":";;;;;;;AA4BA,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAIrE,MAAM,uBAA+D;CACnE,iCAAiC;CACjC,gCAAgC;CAChC,iBAAiB;CACjB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,mBAAmB;CACnB,aAAa;AACf;AAEA,SAAS,eACP,QACS;CACT,OAAO,CAAC,EAAE,OAAO,SAAS,OAAO,MAAM,SAAS;AAClD;AACA,SAAgB,mBACd,QACS;CACT,KAAK,MAAM,WAAW,OAAO,UAAU;EACrC,IAAI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s","names":["AIMessageChunk","ChatAnthropicMessages","handleToolChoice","ChatGenerationChunk","stripUnsupportedAssistantPrefill","_convertMessagesToAnthropicPayload","_makeMessageChunkFromAnthropicEvent"],"sources":["../../../../src/llm/anthropic/index.ts"],"sourcesContent":["import { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatAnthropicMessages } from '@langchain/anthropic';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { BaseChatModelParams } from '@langchain/core/language_models/chat_models';\nimport type {\n BaseMessage,\n MessageContentComplex,\n} from '@langchain/core/messages';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { AnthropicInput } from '@langchain/anthropic';\nimport type { Anthropic } from '@anthropic-ai/sdk';\nimport type {\n AnthropicMessageCreateParams,\n AnthropicStreamingMessageCreateParams,\n AnthropicOutputConfig,\n AnthropicBeta,\n ChatAnthropicToolType,\n AnthropicMCPServerURLDefinition,\n AnthropicContextManagementConfigParam,\n AnthropicRequestOptions,\n} from '@/llm/anthropic/types';\nimport {\n _convertMessagesToAnthropicPayload,\n stripUnsupportedAssistantPrefill,\n} from './utils/message_inputs';\nimport { _makeMessageChunkFromAnthropicEvent } from './utils/message_outputs';\nimport { handleToolChoice } from './utils/tools';\n\nconst DEFAULT_STREAM_DELAY = 25;\nconst MAX_STREAM_QUEUE_CHUNKS = 256;\nconst MAX_STREAM_QUEUE_TEXT_CHARS = 8192;\nconst STREAM_CHUNK_MIN_SIZE = 4;\nconst STREAM_BOUNDARIES = new Set([' ', '.', ',', '!', '?', ';', ':']);\n\ntype StreamTokenType = 'string' | 'input' | 'content';\n\nconst ANTHROPIC_TOOL_BETAS: Partial<Record<string, AnthropicBeta>> = {\n tool_search_tool_regex_20251119: 'advanced-tool-use-2025-11-20',\n tool_search_tool_bm25_20251119: 'advanced-tool-use-2025-11-20',\n memory_20250818: 'context-management-2025-06-27',\n web_fetch_20250910: 'web-fetch-2025-09-10',\n code_execution_20250825: 'code-execution-2025-08-25',\n computer_20251124: 'computer-use-2025-11-24',\n computer_20250124: 'computer-use-2025-01-24',\n mcp_toolset: 'mcp-client-2025-11-20',\n};\n\nfunction _toolsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(params.tools && params.tools.length > 0);\n}\nexport function _documentsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n for (const message of params.messages) {\n if (typeof message.content === 'string') {\n continue;\n }\n for (const block of message.content) {\n const maybeBlock: unknown = block;\n if (\n typeof maybeBlock === 'object' &&\n maybeBlock !== null &&\n 'type' in maybeBlock &&\n maybeBlock.type === 'document' &&\n 'citations' in maybeBlock &&\n maybeBlock.citations != null &&\n typeof maybeBlock.citations === 'object' &&\n 'enabled' in maybeBlock.citations &&\n maybeBlock.citations.enabled === true\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction _thinkingInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(\n params.thinking &&\n (params.thinking.type === 'enabled' || params.thinking.type === 'adaptive')\n );\n}\n\nfunction _compactionInParams(\n params: (\n | AnthropicMessageCreateParams\n | AnthropicStreamingMessageCreateParams\n ) & {\n context_management?: AnthropicContextManagementConfigParam;\n }\n): boolean {\n return (\n params.context_management?.edits?.some(\n (edit) => edit.type === 'compact_20260112'\n ) === true\n );\n}\n\nfunction isThinkingEnabled(thinking: Anthropic.ThinkingConfigParam): boolean {\n return thinking.type === 'enabled' || thinking.type === 'adaptive';\n}\n\nfunction isOpus47Model(model?: string): boolean {\n return /^claude-opus-4-7(?:-|$)/.test(model ?? '');\n}\n\nfunction combineBetas(\n ...betaGroups: (AnthropicBeta[] | undefined)[]\n): AnthropicBeta[] {\n const betas = new Set<AnthropicBeta>();\n for (const betaGroup of betaGroups) {\n for (const beta of betaGroup ?? []) {\n betas.add(beta);\n }\n }\n return [...betas];\n}\n\nfunction getToolBetas(tools?: ChatAnthropicToolType[]): AnthropicBeta[] {\n const betas = new Set<AnthropicBeta>();\n for (const tool of tools ?? []) {\n if (typeof tool !== 'object' || !('type' in tool)) {\n continue;\n }\n const beta = ANTHROPIC_TOOL_BETAS[String(tool.type)];\n if (beta != null) {\n betas.add(beta);\n }\n }\n return [...betas];\n}\n\nfunction getCompactionBetas(\n contextManagement?: AnthropicContextManagementConfigParam\n): AnthropicBeta[] {\n return contextManagement?.edits?.some(\n (edit) => edit.type === 'compact_20260112'\n ) === true\n ? ['compact-2026-01-12']\n : [];\n}\n\nfunction getTaskBudgetBetas(\n model: string,\n outputConfig?: AnthropicOutputConfig\n): AnthropicBeta[] {\n return isOpus47Model(model) &&\n outputConfig != null &&\n 'task_budget' in outputConfig &&\n outputConfig.task_budget != null\n ? ['task-budgets-2026-03-13']\n : [];\n}\n\nfunction isSetSamplingValue(value?: number | null): value is number {\n return value != null && value !== -1;\n}\n\nfunction isNonDefaultTemperature(value?: number): boolean {\n return isSetSamplingValue(value) && value !== 1;\n}\n\nfunction validateInvocationParamCompatibility({\n model,\n thinking,\n topK,\n topP,\n temperature,\n}: {\n model: string;\n thinking: Anthropic.ThinkingConfigParam;\n topK?: number;\n topP?: number | null;\n temperature?: number;\n}): void {\n const opus47 = isOpus47Model(model);\n if (opus47 && thinking.type === 'enabled') {\n throw new Error(\n 'thinking.type=\"enabled\" is not supported for claude-opus-4-7; use thinking.type=\"adaptive\" instead'\n );\n }\n if (opus47 && 'budget_tokens' in thinking) {\n throw new Error(\n 'thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead'\n );\n }\n if (opus47) {\n if (isSetSamplingValue(topK)) {\n throw new Error(\n 'topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead'\n );\n }\n if (isSetSamplingValue(topP) && topP !== 1) {\n throw new Error(\n 'topP is not supported for claude-opus-4-7 when set to non-default values'\n );\n }\n if (isNonDefaultTemperature(temperature)) {\n throw new Error(\n 'temperature is not supported for claude-opus-4-7 when set to non-default values'\n );\n }\n }\n if (!isThinkingEnabled(thinking)) {\n return;\n }\n if (isSetSamplingValue(topK)) {\n throw new Error('topK is not supported when thinking is enabled');\n }\n if (isSetSamplingValue(topP)) {\n throw new Error('topP is not supported when thinking is enabled');\n }\n if (isNonDefaultTemperature(temperature)) {\n throw new Error('temperature is not supported when thinking is enabled');\n }\n}\n\nfunction getSamplingParams({\n model,\n thinking,\n topK,\n topP,\n temperature,\n}: {\n model: string;\n thinking: Anthropic.ThinkingConfigParam;\n topK?: number;\n topP?: number | null;\n temperature?: number;\n}): {\n temperature?: number;\n top_k?: number;\n top_p?: number;\n} {\n if (isThinkingEnabled(thinking) || isOpus47Model(model)) {\n return {};\n }\n return {\n ...(isSetSamplingValue(temperature) ? { temperature } : {}),\n ...(isSetSamplingValue(topK) ? { top_k: topK } : {}),\n ...(isSetSamplingValue(topP) ? { top_p: topP } : {}),\n };\n}\n\nfunction findStreamChunkBoundary(text: string, minSize: number): number {\n if (minSize >= text.length) {\n return text.length;\n }\n\n for (let position = minSize; position < text.length; position++) {\n if (STREAM_BOUNDARIES.has(text[position])) {\n return position + 1;\n }\n }\n\n return text.length;\n}\n\nfunction splitStreamToken(text: string): string[] {\n const chunks: string[] = [];\n let currentIndex = 0;\n\n while (currentIndex < text.length) {\n const remainingText = text.slice(currentIndex);\n const chunkSize = findStreamChunkBoundary(\n remainingText,\n STREAM_CHUNK_MIN_SIZE\n );\n chunks.push(text.slice(currentIndex, currentIndex + chunkSize));\n currentIndex += chunkSize;\n }\n\n return chunks;\n}\n\nfunction getCadencedStreamDelay({\n targetDelay,\n lastVisibleTextAt,\n now,\n}: {\n targetDelay: number;\n lastVisibleTextAt?: number;\n now: number;\n}): number {\n if (targetDelay <= 0 || lastVisibleTextAt == null) {\n return 0;\n }\n return Math.max(0, targetDelay - (now - lastVisibleTextAt));\n}\n\nasync function waitForStreamDelay(\n delay: number,\n signal?: AbortSignal\n): Promise<void> {\n if (delay <= 0 || isSignalAborted(signal)) {\n return;\n }\n await new Promise<void>((resolve) => {\n const timeoutRef: { current?: ReturnType<typeof setTimeout> } = {};\n const onAbort = (): void => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n signal?.removeEventListener('abort', onAbort);\n resolve();\n };\n timeoutRef.current = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, delay);\n signal?.addEventListener('abort', onAbort, { once: true });\n if (isSignalAborted(signal)) {\n onAbort();\n }\n });\n}\n\nfunction isSignalAborted(signal?: AbortSignal): boolean {\n return signal?.aborted === true;\n}\n\nfunction extractToken(\n chunk: AIMessageChunk\n): [string, StreamTokenType] | [undefined] {\n if (typeof chunk.content === 'string') {\n return [chunk.content, 'string'];\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n 'input' in chunk.content[0]\n ) {\n return typeof chunk.content[0].input === 'string'\n ? [chunk.content[0].input, 'input']\n : [JSON.stringify(chunk.content[0].input), 'input'];\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n 'text' in chunk.content[0]\n ) {\n const text = chunk.content[0].text;\n return typeof text === 'string' ? [text, 'content'] : [undefined];\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n 'thinking' in chunk.content[0]\n ) {\n const thinking = chunk.content[0].thinking;\n return typeof thinking === 'string' ? [thinking, 'content'] : [undefined];\n }\n return [undefined];\n}\n\nfunction cloneChunk(\n text: string,\n tokenType: StreamTokenType,\n chunk: AIMessageChunk\n): AIMessageChunk {\n if (tokenType === 'string') {\n return new AIMessageChunk(Object.assign({}, chunk, { content: text }));\n } else if (tokenType === 'input') {\n return chunk;\n }\n const content = chunk.content[0] as MessageContentComplex;\n if (content.type === 'text') {\n return new AIMessageChunk(\n Object.assign({}, chunk, {\n content: [Object.assign({}, content, { text })],\n })\n );\n } else if (content.type === 'text_delta') {\n return new AIMessageChunk(\n Object.assign({}, chunk, {\n content: [Object.assign({}, content, { text })],\n })\n );\n } else if (\n typeof content.type === 'string' &&\n content.type.startsWith('thinking')\n ) {\n return new AIMessageChunk(\n Object.assign({}, chunk, {\n content: [Object.assign({}, content, { thinking: text })],\n })\n );\n }\n\n return chunk;\n}\n\nfunction withIncrementalMessageDeltaUsage(\n chunk: AIMessageChunk,\n previousOutputTokens: number\n): { chunk: AIMessageChunk; outputTokens: number } {\n const usage = chunk.usage_metadata;\n if (usage == null) {\n return { chunk, outputTokens: previousOutputTokens };\n }\n\n const outputTokens = Math.max(0, usage.output_tokens - previousOutputTokens);\n return {\n chunk: new AIMessageChunk(\n Object.assign({}, chunk, {\n usage_metadata: {\n ...usage,\n output_tokens: outputTokens,\n total_tokens: usage.input_tokens + outputTokens,\n },\n })\n ),\n outputTokens: usage.output_tokens,\n };\n}\n\nexport type CustomAnthropicInput = AnthropicInput & {\n _lc_stream_delay?: number;\n outputConfig?: AnthropicOutputConfig;\n inferenceGeo?: string;\n contextManagement?: AnthropicContextManagementConfigParam;\n} & BaseChatModelParams;\n\nexport type CustomAnthropicCallOptions = {\n outputConfig?: AnthropicOutputConfig;\n outputFormat?: Anthropic.Messages.JSONOutputFormat;\n inferenceGeo?: string;\n betas?: AnthropicBeta[];\n container?: string;\n mcp_servers?: AnthropicMCPServerURLDefinition[];\n};\n\ntype CustomAnthropicInvocationParams = {\n betas?: AnthropicBeta[];\n container?: string;\n context_management?: AnthropicContextManagementConfigParam;\n inference_geo?: string;\n mcp_servers?: AnthropicMCPServerURLDefinition[];\n output_config?: AnthropicOutputConfig;\n};\n\ntype QueuedGenerationChunk = {\n chunk: ChatGenerationChunk;\n token: string;\n smooth: boolean;\n textLength: number;\n};\n\nexport class CustomAnthropic extends ChatAnthropicMessages {\n _lc_stream_delay: number;\n private tools_in_params?: boolean;\n top_k: number | undefined;\n outputConfig?: AnthropicOutputConfig;\n inferenceGeo?: string;\n contextManagement?: AnthropicContextManagementConfigParam;\n constructor(fields?: CustomAnthropicInput) {\n super(fields);\n this.resetTokenEvents();\n this.setDirectFields(fields);\n this._lc_stream_delay = Math.max(\n 0,\n fields?._lc_stream_delay ?? DEFAULT_STREAM_DELAY\n );\n this.outputConfig = fields?.outputConfig;\n this.inferenceGeo = fields?.inferenceGeo;\n this.contextManagement = fields?.contextManagement;\n }\n\n static lc_name(): 'LibreChatAnthropic' {\n return 'LibreChatAnthropic';\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(\n options?: this['ParsedCallOptions'] & CustomAnthropicCallOptions\n ): Omit<\n AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams,\n 'messages'\n > &\n CustomAnthropicInvocationParams {\n const tool_choice:\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined = handleToolChoice(options?.tool_choice);\n\n const callOptions = options as CustomAnthropicCallOptions | undefined;\n const mergedOutputConfig: AnthropicOutputConfig | undefined = (():\n | AnthropicOutputConfig\n | undefined => {\n const base = {\n ...this.outputConfig,\n ...callOptions?.outputConfig,\n };\n if (callOptions?.outputFormat && !base.format) {\n base.format = callOptions.outputFormat;\n }\n return Object.keys(base).length > 0 ? base : undefined;\n })();\n\n const inferenceGeo = callOptions?.inferenceGeo ?? this.inferenceGeo;\n\n const contextManagement = this.contextManagement;\n const toolBetas = getToolBetas(options?.tools);\n const compactionBetas = getCompactionBetas(contextManagement);\n const taskBudgetBetas = getTaskBudgetBetas(this.model, mergedOutputConfig);\n const formattedTools = this.formatStructuredToolToAnthropic(\n options?.tools,\n {\n strict: options?.strict,\n }\n );\n\n const sharedParams = {\n tools: formattedTools,\n tool_choice,\n // Match upstream: omit `thinking` unless the user set it, so we don't send\n // `{ type: 'disabled' }` (an unsupported param on some models) by default.\n thinking: this.thinkingExplicitlySet ? this.thinking : undefined,\n context_management: contextManagement,\n ...this.invocationKwargs,\n container: callOptions?.container,\n betas: combineBetas(\n this.betas,\n callOptions?.betas,\n toolBetas,\n compactionBetas,\n taskBudgetBetas\n ),\n output_config: mergedOutputConfig,\n inference_geo: inferenceGeo,\n mcp_servers: callOptions?.mcp_servers,\n // Top-level request cache_control (1.5.x): API auto-advances the cache\n // breakpoint across turns. Additive — independent of our block-level cache.\n cache_control: options?.cache_control,\n };\n validateInvocationParamCompatibility({\n model: this.model,\n thinking: this.thinking,\n topK: this.top_k,\n topP: this.topP,\n temperature: this.temperature,\n });\n\n return {\n model: this.model,\n stop_sequences: options?.stop ?? this.stopSequences,\n stream: this.streaming,\n max_tokens: this.maxTokens,\n ...getSamplingParams({\n model: this.model,\n thinking: this.thinking,\n topK: this.top_k,\n topP: this.topP,\n temperature: this.temperature,\n }),\n ...sharedParams,\n };\n }\n\n resetTokenEvents(): void {\n this.tools_in_params = undefined;\n }\n\n setDirectFields(fields?: CustomAnthropicInput): void {\n this.temperature = fields?.temperature ?? undefined;\n this.topP = fields?.topP ?? undefined;\n this.top_k = fields?.topK;\n if (this.temperature === -1 || this.temperature === 1) {\n this.temperature = undefined;\n }\n if (this.topP === -1) {\n this.topP = undefined;\n }\n if (this.top_k === -1) {\n this.top_k = undefined;\n }\n }\n\n private createGenerationChunk({\n token,\n chunk,\n shouldStreamUsage,\n }: {\n token?: string;\n chunk: AIMessageChunk;\n shouldStreamUsage: boolean;\n }): ChatGenerationChunk {\n const usage_metadata = shouldStreamUsage ? chunk.usage_metadata : undefined;\n return new ChatGenerationChunk({\n message: new AIMessageChunk({\n // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().\n content: chunk.content,\n additional_kwargs: chunk.additional_kwargs,\n tool_call_chunks: chunk.tool_call_chunks,\n response_metadata: chunk.response_metadata,\n usage_metadata,\n id: chunk.id,\n }),\n text: token ?? '',\n });\n }\n\n protected override async createStreamWithRetry(\n request: AnthropicStreamingMessageCreateParams,\n options?: AnthropicRequestOptions\n ): ReturnType<ChatAnthropicMessages['createStreamWithRetry']> {\n return super.createStreamWithRetry(\n stripUnsupportedAssistantPrefill(request),\n options\n );\n }\n\n protected override async completionWithRetry(\n request: AnthropicMessageCreateParams,\n options: AnthropicRequestOptions\n ): ReturnType<ChatAnthropicMessages['completionWithRetry']> {\n return super.completionWithRetry(\n stripUnsupportedAssistantPrefill(request),\n options\n );\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n this.resetTokenEvents();\n const params = this.invocationParams(options);\n const formattedMessages = _convertMessagesToAnthropicPayload(messages);\n const payload = stripUnsupportedAssistantPrefill({\n ...params,\n ...formattedMessages,\n stream: true,\n } as const);\n const coerceContentToString =\n !_toolsInParams(payload) &&\n !_documentsInParams(payload) &&\n !_thinkingInParams(payload) &&\n !_compactionInParams(payload);\n\n const stream = await this.createStreamWithRetry(payload, {\n headers: options.headers,\n signal: options.signal,\n });\n\n const shouldStreamUsage = options.streamUsage ?? this.streamUsage;\n let messageDeltaOutputTokens = 0;\n const queuedChunks: QueuedGenerationChunk[] = [];\n const producerState: {\n done: boolean;\n error?: unknown;\n } = { done: false };\n let queuedChunkIndex = 0;\n let bufferedTextLength = 0;\n let consumerClosed = false;\n let notifyConsumer: (() => void) | undefined;\n let notifyProducer: (() => void) | undefined;\n\n const notifyConsumerForChunk = (): void => {\n notifyConsumer?.();\n notifyConsumer = undefined;\n };\n\n const notifyProducerForSpace = (): void => {\n notifyProducer?.();\n notifyProducer = undefined;\n };\n\n const hasQueuedChunks = (): boolean =>\n queuedChunkIndex < queuedChunks.length;\n\n const getQueuedChunkCount = (): number =>\n queuedChunks.length - queuedChunkIndex;\n\n const isQueueAtCapacity = (): boolean =>\n getQueuedChunkCount() >= MAX_STREAM_QUEUE_CHUNKS ||\n bufferedTextLength >= MAX_STREAM_QUEUE_TEXT_CHARS;\n\n const waitForNextChunk = async (): Promise<void> => {\n if (\n hasQueuedChunks() ||\n producerState.done ||\n producerState.error != null\n ) {\n return;\n }\n await new Promise<void>((resolve) => {\n notifyConsumer = resolve;\n });\n };\n\n const waitForQueueSpace = async (): Promise<void> => {\n while (\n isQueueAtCapacity() &&\n !consumerClosed &&\n !isSignalAborted(options.signal)\n ) {\n await new Promise<void>((resolve) => {\n const signal = options.signal;\n const onAbort = (): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n };\n const onSpace = (): void => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n };\n notifyProducer = onSpace;\n signal?.addEventListener('abort', onAbort, { once: true });\n if (isSignalAborted(signal)) {\n onAbort();\n }\n });\n }\n };\n\n const dequeue = (): QueuedGenerationChunk | undefined => {\n if (!hasQueuedChunks()) {\n return undefined;\n }\n const queuedChunk = queuedChunks[queuedChunkIndex];\n queuedChunkIndex++;\n if (\n queuedChunkIndex > 128 &&\n queuedChunkIndex * 2 >= queuedChunks.length\n ) {\n queuedChunks.splice(0, queuedChunkIndex);\n queuedChunkIndex = 0;\n }\n return queuedChunk;\n };\n\n const enqueue = async (\n queuedChunk: QueuedGenerationChunk\n ): Promise<void> => {\n await waitForQueueSpace();\n if (consumerClosed || isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n queuedChunks.push(queuedChunk);\n if (queuedChunk.smooth) {\n bufferedTextLength += queuedChunk.textLength;\n }\n notifyConsumerForChunk();\n };\n\n const enqueueChunk = async ({\n token,\n chunk,\n smooth,\n }: {\n token: string;\n chunk: AIMessageChunk;\n smooth: boolean;\n }): Promise<void> => {\n await enqueue({\n token,\n smooth,\n textLength: smooth ? token.length : 0,\n chunk: this.createGenerationChunk({\n token,\n chunk,\n shouldStreamUsage,\n }),\n });\n };\n\n const enqueueTextChunks = (\n token: string,\n tokenType: StreamTokenType,\n chunk: AIMessageChunk\n ): Promise<void> => {\n if (token === '') {\n return Promise.resolve();\n }\n if (this._lc_stream_delay <= 0) {\n return enqueueChunk({ token, chunk, smooth: false });\n }\n\n const tokenChunks = splitStreamToken(token);\n if (tokenChunks.length <= 1) {\n return enqueueChunk({ token, chunk, smooth: true });\n }\n\n let emittedUsage = false;\n return tokenChunks.reduce(async (previous, currentToken) => {\n await previous;\n const newChunk = cloneChunk(currentToken, tokenType, chunk);\n const chunkForToken =\n emittedUsage && newChunk.usage_metadata != null\n ? new AIMessageChunk(\n Object.assign({}, newChunk, { usage_metadata: undefined })\n )\n : newChunk;\n\n await enqueueChunk({\n token: currentToken,\n chunk: chunkForToken,\n smooth: true,\n });\n\n if (newChunk.usage_metadata != null && !emittedUsage) {\n emittedUsage = true;\n }\n }, Promise.resolve());\n };\n\n const producer = (async (): Promise<void> => {\n try {\n for await (const data of stream) {\n if (isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n\n const result = _makeMessageChunkFromAnthropicEvent(\n data as Anthropic.Beta.Messages.BetaRawMessageStreamEvent,\n {\n streamUsage: shouldStreamUsage,\n coerceContentToString,\n }\n );\n if (!result) {\n continue;\n }\n\n let { chunk } = result;\n if (data.type === 'message_delta') {\n const incremental = withIncrementalMessageDeltaUsage(\n chunk,\n messageDeltaOutputTokens\n );\n chunk = incremental.chunk;\n messageDeltaOutputTokens = incremental.outputTokens;\n }\n\n const [token = '', tokenType] = extractToken(chunk);\n if (\n !tokenType ||\n tokenType === 'input' ||\n (token === '' && (chunk.usage_metadata != null || chunk.id != null))\n ) {\n await enqueueChunk({ token, chunk, smooth: false });\n continue;\n }\n\n await enqueueTextChunks(token, tokenType, chunk);\n }\n } catch (error) {\n producerState.error = error;\n } finally {\n producerState.done = true;\n notifyConsumerForChunk();\n }\n })();\n\n let hasEmittedText = false;\n let lastVisibleTextAt: number | undefined;\n let keepStreaming = true;\n try {\n while (keepStreaming) {\n if (isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n\n await waitForNextChunk();\n const queuedChunk = dequeue();\n\n if (!queuedChunk) {\n if (producerState.error != null) {\n throw producerState.error;\n }\n if (producerState.done) {\n keepStreaming = false;\n }\n continue;\n }\n\n if (queuedChunk.smooth) {\n bufferedTextLength = Math.max(\n 0,\n bufferedTextLength - queuedChunk.textLength\n );\n notifyProducerForSpace();\n await waitForStreamDelay(\n getCadencedStreamDelay({\n targetDelay: hasEmittedText ? this._lc_stream_delay : 0,\n lastVisibleTextAt,\n now: Date.now(),\n }),\n options.signal\n );\n if (isSignalAborted(options.signal)) {\n stream.controller.abort();\n throw new Error('AbortError: User aborted the request.');\n }\n hasEmittedText = true;\n lastVisibleTextAt = Date.now();\n } else {\n notifyProducerForSpace();\n }\n\n yield queuedChunk.chunk;\n await runManager?.handleLLMNewToken(\n queuedChunk.token,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: queuedChunk.chunk }\n );\n }\n } finally {\n consumerClosed = true;\n if (!producerState.done) {\n stream.controller.abort();\n notifyProducerForSpace();\n }\n await producer;\n this.resetTokenEvents();\n }\n }\n}\n"],"mappings":";;;;;;;AA4BA,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,MAAM,8BAA8B;AACpC,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAIrE,MAAM,uBAA+D;CACnE,iCAAiC;CACjC,gCAAgC;CAChC,iBAAiB;CACjB,oBAAoB;CACpB,yBAAyB;CACzB,mBAAmB;CACnB,mBAAmB;CACnB,aAAa;AACf;AAEA,SAAS,eACP,QACS;CACT,OAAO,CAAC,EAAE,OAAO,SAAS,OAAO,MAAM,SAAS;AAClD;AACA,SAAgB,mBACd,QACS;CACT,KAAK,MAAM,WAAW,OAAO,UAAU;EACrC,IAAI,OAAO,QAAQ,YAAY,UAC7B;EAEF,KAAK,MAAM,SAAS,QAAQ,SAAS;GACnC,MAAM,aAAsB;GAC5B,IACE,OAAO,eAAe,YACtB,eAAe,QACf,UAAU,cACV,WAAW,SAAS,cACpB,eAAe,cACf,WAAW,aAAa,QACxB,OAAO,WAAW,cAAc,YAChC,aAAa,WAAW,aACxB,WAAW,UA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U;IACR,cAAc,OAAO;IACrB,uBAAuB;GACzB;EACF,EAAA,CAAG;EAEH,IAAI,iBAAiB;EACrB,IAAI;EACJ,IAAI,gBAAgB;EACpB,IAAI;GACF,OAAO,eAAe;IACpB,IAAI,gBAAgB,QAAQ,MAAM,GAAG;KACnC,OAAO,WAAW,MAAM;KACxB,MAAM,IAAI,MAAM,uCAAuC;IACzD;IAEA,MAAM,iBAAiB;IACvB,MAAM,cAAc,QAAQ;IAE5B,IAAI,CAAC,aAAa;KAChB,IAAI,cAAc,SAAS,MACzB,MAAM,cAAc;KAEtB,IAAI,cAAc,MAChB,gBAAgB;KAElB;IACF;IAEA,IAAI,YAAY,QAAQ;KACtB,qBAAqB,KAAK,IACxB,GACA,qBAAqB,YAAY,UACnC;KACA,uBAAuB;KACvB,MAAM,mBACJ,uBAAuB;MACrB,aAAa,iBAAiB,KAAK,mBAAmB;MACtD;MACA,KAAK,KAAK,IAAI;KAChB,CAAC,GACD,QAAQ,MACV;KACA,IAAI,gBAAgB,QAAQ,MAAM,GAAG;MACnC,OAAO,WAAW,MAAM;MACxB,MAAM,IAAI,MAAM,uCAAuC;KACzD;KACA,iBAAiB;KACjB,oBAAoB,KAAK,IAAI;IAC/B,OACE,uBAAuB;IAGzB,MAAM,YAAY;IAClB,MAAM,YAAY,kBAChB,YAAY,OACZ,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,OAAO,YAAY,MAAM,CAC7B;GACF;EACF,UAAU;GACR,iBAAiB;GACjB,IAAI,CAAC,cAAc,MAAM;IACvB,OAAO,WAAW,MAAM;IACxB,uBAAuB;GACzB;GACA,MAAM;GACN,KAAK,iBAAiB;EACxB;CACF;AACF"}
@@ -1,8 +1,9 @@
1
1
  //#region src/llm/anthropic/utils/tools.ts
2
2
  function handleToolChoice(toolChoice) {
3
3
  if (toolChoice == null) return;
4
- else if (toolChoice === "any") return { type: "any" };
4
+ else if (toolChoice === "any" || toolChoice === "required") return { type: "any" };
5
5
  else if (toolChoice === "auto") return { type: "auto" };
6
+ else if (toolChoice === "none") return { type: "none" };
6
7
  else if (typeof toolChoice === "string") return {
7
8
  type: "tool",
8
9
  name: toolChoice
@@ -1 +1 @@
1
- {"version":3,"file":"tools.cjs","names":[],"sources":["../../../../../src/llm/anthropic/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from '@anthropic-ai/sdk';\nimport { AnthropicToolChoice } from '../types.js';\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | undefined {\n if (toolChoice == null) {\n return undefined;\n } else if (toolChoice === 'any') {\n return {\n type: 'any',\n };\n } else if (toolChoice === 'auto') {\n return {\n type: 'auto',\n };\n } else if (typeof toolChoice === 'string') {\n return {\n type: 'tool',\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n"],"mappings":";AAGA,SAAgB,iBACd,YAKY;CACZ,IAAI,cAAc,MAChB;MACK,IAAI,eAAe,OACxB,OAAO,EACL,MAAM,MACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,OAAO,eAAe,UAC/B,OAAO;EACL,MAAM;EACN,MAAM;CACR;MAEA,OAAO;AAEX"}
1
+ {"version":3,"file":"tools.cjs","names":[],"sources":["../../../../../src/llm/anthropic/utils/tools.ts"],"sourcesContent":["import type { Anthropic } from '@anthropic-ai/sdk';\nimport { AnthropicToolChoice } from '../types.js';\n\nexport function handleToolChoice(\n toolChoice?: AnthropicToolChoice\n):\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined {\n if (toolChoice == null) {\n return undefined;\n } else if (toolChoice === 'any' || toolChoice === 'required') {\n // \"required\" is the OpenAI-style alias for forcing tool use.\n return {\n type: 'any',\n };\n } else if (toolChoice === 'auto') {\n return {\n type: 'auto',\n };\n } else if (toolChoice === 'none') {\n return {\n type: 'none',\n };\n } else if (typeof toolChoice === 'string') {\n return {\n type: 'tool',\n name: toolChoice,\n };\n } else {\n return toolChoice;\n }\n}\n"],"mappings":";AAGA,SAAgB,iBACd,YAMY;CACZ,IAAI,cAAc,MAChB;MACK,IAAI,eAAe,SAAS,eAAe,YAEhD,OAAO,EACL,MAAM,MACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,eAAe,QACxB,OAAO,EACL,MAAM,OACR;MACK,IAAI,OAAO,eAAe,UAC/B,OAAO;EACL,MAAM;EACN,MAAM;CACR;MAEA,OAAO;AAEX"}
@@ -0,0 +1,28 @@
1
+ //#region src/llm/bedrock/cachePoints.ts
2
+ function isConverseCachePoint(block) {
3
+ return Boolean(typeof block === "object" && block !== null && "cachePoint" in block && block.cachePoint && typeof block.cachePoint === "object" && block.cachePoint !== null && "type" in block.cachePoint);
4
+ }
5
+ function createConverseCachePointBlock(cacheControl, isNovaModel) {
6
+ const ttl = !isNovaModel && cacheControl.ttl && cacheControl.ttl !== "5m" ? cacheControl.ttl : void 0;
7
+ return { cachePoint: {
8
+ type: "default",
9
+ ...ttl ? { ttl } : {}
10
+ } };
11
+ }
12
+ function applyCachePointsToConversePayload(fields) {
13
+ const { cacheControl, system, messages, params, modelId } = fields;
14
+ if (!cacheControl) return;
15
+ const isNovaModel = modelId.toLowerCase().includes("amazon.nova");
16
+ const cacheBlock = createConverseCachePointBlock(cacheControl, isNovaModel);
17
+ if (system.length > 0 && !system.some((block) => isConverseCachePoint(block))) system.push(cacheBlock);
18
+ const lastContent = messages[messages.length - 1].content;
19
+ if (Array.isArray(lastContent)) {
20
+ if (!(isNovaModel && lastContent.some((block) => typeof block === "object" && block !== null && ("toolResult" in block || "toolUse" in block))) && !lastContent.some((block) => isConverseCachePoint(block))) lastContent.push(cacheBlock);
21
+ }
22
+ const tools = params?.toolConfig?.tools;
23
+ if (!isNovaModel && Array.isArray(tools) && !tools.some((tool) => isConverseCachePoint(tool))) tools.push(cacheBlock);
24
+ }
25
+ //#endregion
26
+ exports.applyCachePointsToConversePayload = applyCachePointsToConversePayload;
27
+
28
+ //# sourceMappingURL=cachePoints.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cachePoints.cjs","names":[],"sources":["../../../../src/llm/bedrock/cachePoints.ts"],"sourcesContent":["// Vendored from @langchain/aws@1.4.2 (utils/message_inputs.ts) because the\n// upstream `applyCachePointsToConversePayload` export is internal.\nimport type {\n BedrockPromptCacheControl,\n ConverseCommandParams,\n} from '@langchain/aws';\nimport type * as Bedrock from '@aws-sdk/client-bedrock-runtime';\n\nfunction isConverseCachePoint(block: unknown): boolean {\n return Boolean(\n typeof block === 'object' &&\n block !== null &&\n 'cachePoint' in block &&\n block.cachePoint &&\n typeof block.cachePoint === 'object' &&\n block.cachePoint !== null &&\n 'type' in block.cachePoint\n );\n}\n\nfunction createConverseCachePointBlock(\n cacheControl: BedrockPromptCacheControl,\n isNovaModel: boolean\n): { cachePoint: { type: 'default'; ttl?: '1h' } } {\n const ttl =\n !isNovaModel && cacheControl.ttl && cacheControl.ttl !== '5m'\n ? cacheControl.ttl\n : undefined;\n return {\n cachePoint: {\n type: 'default',\n ...(ttl ? { ttl } : {}),\n },\n };\n}\n\nexport function applyCachePointsToConversePayload(fields: {\n cacheControl?: BedrockPromptCacheControl;\n system: Bedrock.SystemContentBlock[];\n messages: Bedrock.Message[];\n params?: Partial<ConverseCommandParams>;\n modelId: string;\n}): void {\n const { cacheControl, system, messages, params, modelId } = fields;\n if (!cacheControl) {\n return;\n }\n\n const isNovaModel = modelId.toLowerCase().includes('amazon.nova');\n const cacheBlock = createConverseCachePointBlock(cacheControl, isNovaModel);\n\n if (\n system.length > 0 &&\n !system.some((block) => isConverseCachePoint(block))\n ) {\n system.push(cacheBlock);\n }\n\n const lastMessage = messages[messages.length - 1];\n const lastContent = lastMessage.content;\n if (Array.isArray(lastContent)) {\n const hasNovaToolBlock =\n isNovaModel &&\n lastContent.some(\n (block) =>\n typeof block === 'object' &&\n block !== null &&\n ('toolResult' in block || 'toolUse' in block)\n );\n if (\n !hasNovaToolBlock &&\n !lastContent.some((block) => isConverseCachePoint(block))\n ) {\n lastContent.push(cacheBlock);\n }\n }\n\n const tools = params?.toolConfig?.tools;\n if (\n !isNovaModel &&\n Array.isArray(tools) &&\n !tools.some((tool) => isConverseCachePoint(tool))\n ) {\n tools.push(cacheBlock as unknown as Bedrock.Tool);\n }\n}\n"],"mappings":";AAQA,SAAS,qBAAqB,OAAyB;CACrD,OAAO,QACL,OAAO,UAAU,YACf,UAAU,QACV,gBAAgB,SAChB,MAAM,cACN,OAAO,MAAM,eAAe,YAC5B,MAAM,eAAe,QACrB,UAAU,MAAM,UACpB;AACF;AAEA,SAAS,8BACP,cACA,aACiD;CACjD,MAAM,MACJ,CAAC,eAAe,aAAa,OAAO,aAAa,QAAQ,OACrD,aAAa,MACb,KAAA;CACN,OAAO,EACL,YAAY;EACV,MAAM;EACN,GAAI,MAAM,EAAE,IAAI,IAAI,CAAC;CACvB,EACF;AACF;AAEA,SAAgB,kCAAkC,QAMzC;CACP,MAAM,EAAE,cAAc,QAAQ,UAAU,QAAQ,YAAY;CAC5D,IAAI,CAAC,cACH;CAGF,MAAM,cAAc,QAAQ,YAAY,CAAC,CAAC,SAAS,aAAa;CAChE,MAAM,aAAa,8BAA8B,cAAc,WAAW;CAE1E,IACE,OAAO,SAAS,KAChB,CAAC,OAAO,MAAM,UAAU,qBAAqB,KAAK,CAAC,GAEnD,OAAO,KAAK,UAAU;CAIxB,MAAM,cADc,SAAS,SAAS,SAAS,EAChB,CAAC;CAChC,IAAI,MAAM,QAAQ,WAAW;MAUzB,EARA,eACA,YAAY,MACT,UACC,OAAO,UAAU,YACjB,UAAU,SACT,gBAAgB,SAAS,aAAa,MAC3C,MAGA,CAAC,YAAY,MAAM,UAAU,qBAAqB,KAAK,CAAC,GAExD,YAAY,KAAK,UAAU;CAAA;CAI/B,MAAM,QAAQ,QAAQ,YAAY;CAClC,IACE,CAAC,eACD,MAAM,QAAQ,KAAK,KACnB,CAAC,MAAM,MAAM,SAAS,qBAAqB,IAAI,CAAC,GAEhD,MAAM,KAAK,UAAqC;AAEpD"}