@librechat/agents 3.0.42 → 3.0.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +134 -70
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +1 -1
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +7 -13
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +5 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +85 -0
- package/dist/cjs/messages/tools.cjs.map +1 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +55 -32
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +30 -13
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +134 -70
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +8 -14
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +82 -0
- package/dist/esm/messages/tools.mjs.map +1 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +54 -33
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +30 -13
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +37 -17
- package/dist/types/common/enum.d.ts +1 -1
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/tools.d.ts +17 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +15 -23
- package/dist/types/tools/ToolNode.d.ts +9 -7
- package/dist/types/types/tools.d.ts +5 -5
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +157 -85
- package/src/agents/__tests__/AgentContext.test.ts +805 -0
- package/src/common/enum.ts +1 -1
- package/src/graphs/Graph.ts +9 -21
- package/src/messages/__tests__/tools.test.ts +473 -0
- package/src/messages/index.ts +1 -0
- package/src/messages/tools.ts +99 -0
- package/src/scripts/code_exec_ptc.ts +78 -21
- package/src/scripts/programmatic_exec.ts +3 -3
- package/src/scripts/programmatic_exec_agent.ts +4 -4
- package/src/tools/ProgrammaticToolCalling.ts +71 -39
- package/src/tools/ToolNode.ts +33 -14
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +9 -9
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +180 -5
- package/src/types/tools.ts +3 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Checks if a tool allows the specified caller type.\n * Default is 'direct' only if allowed_callers is not specified.\n */\nfunction toolAllowsCaller(\n toolDef: t.LCTool | undefined,\n caller: t.AllowedCaller\n): boolean {\n if (!toolDef) return false;\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes(caller);\n}\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** System runnable for this agent */\n systemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n\n this.systemRunnable = this.createSystemRunnable();\n }\n\n /**\n * Create system runnable from instructions and calculate tokens if tokenCounter is available\n */\n private createSystemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n this.instructions;\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n // Handle Anthropic prompt caching\n if (\n finalInstructions != null &&\n finalInstructions !== '' &&\n this.provider === Providers.ANTHROPIC\n ) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: this.instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n\n if (this.tokenCounter) {\n this.instructionTokens += this.tokenCounter(systemMessage);\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n return undefined;\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets a map of tools that allow programmatic (code_execution) calling.\n * Filters toolMap based on toolRegistry's allowed_callers settings.\n * @returns ToolMap containing only tools that allow code_execution\n */\n getProgrammaticToolMap(): t.ToolMap {\n const programmaticMap: t.ToolMap = new Map();\n\n if (!this.toolMap) {\n return programmaticMap;\n }\n\n for (const [name, tool] of this.toolMap) {\n const toolDef = this.toolRegistry?.get(name);\n if (toolAllowsCaller(toolDef, 'code_execution')) {\n programmaticMap.set(name, tool);\n }\n }\n\n return programmaticMap;\n }\n\n /**\n * Gets tool definitions for tools that allow programmatic calling.\n * Used to send to the Code API for stub generation.\n * @returns Array of LCTool definitions for programmatic tools\n */\n getProgrammaticToolDefs(): t.LCTool[] {\n if (!this.toolRegistry) {\n return [];\n }\n\n const defs: t.LCTool[] = [];\n for (const [_name, toolDef] of this.toolRegistry) {\n if (toolAllowsCaller(toolDef, 'code_execution')) {\n defs.push(toolDef);\n }\n }\n\n return defs;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * @param toolNames - Array of discovered tool names\n */\n markToolsAsDiscovered(toolNames: string[]): void {\n for (const name of toolNames) {\n this.discoveredToolNames.add(name);\n }\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allow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AEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
|
|
1
|
+
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":[],"mappings":";;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MA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AAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;;gBAE3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;YAI1C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
|
package/dist/esm/common/enum.mjs
CHANGED
|
@@ -144,7 +144,7 @@ var Constants;
|
|
|
144
144
|
Constants["OFFICIAL_CODE_BASEURL"] = "https://api.librechat.ai/v1";
|
|
145
145
|
Constants["EXECUTE_CODE"] = "execute_code";
|
|
146
146
|
Constants["TOOL_SEARCH_REGEX"] = "tool_search_regex";
|
|
147
|
-
Constants["PROGRAMMATIC_TOOL_CALLING"] = "
|
|
147
|
+
Constants["PROGRAMMATIC_TOOL_CALLING"] = "run_tools_with_code";
|
|
148
148
|
Constants["WEB_SEARCH"] = "web_search";
|
|
149
149
|
Constants["CONTENT_AND_ARTIFACT"] = "content_and_artifact";
|
|
150
150
|
Constants["LC_TRANSFER_TO_"] = "lc_transfer_to_";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.mjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH_REGEX = 'tool_search_regex',\n PROGRAMMATIC_TOOL_CALLING = '
|
|
1
|
+
{"version":3,"file":"enum.mjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH_REGEX = 'tool_search_regex',\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n}\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',\n CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',\n}\n"],"names":[],"mappings":"AAAA;;;;;AAKG;IACS;AAAZ,CAAA,UAAY,WAAW,EAAA;;;AAIrB,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;;AAE3B,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;;AAEvC,IAAA,WAAA,CAAA,uBAAA,CAAA,GA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raph';
|
|
5
5
|
import { RunnableLambda } from '@langchain/core/runnables';
|
|
6
6
|
import { SystemMessage, AIMessageChunk, ToolMessage } from '@langchain/core/messages';
|
|
7
|
-
import { GraphNodeKeys, ContentTypes, Providers, GraphEvents,
|
|
7
|
+
import { GraphNodeKeys, ContentTypes, Providers, GraphEvents, StepTypes } from '../common/enum.mjs';
|
|
8
8
|
import { convertMessagesToContent, modifyDeltaProperties, formatAnthropicArtifactContent, formatArtifactPayload } from '../messages/core.mjs';
|
|
9
9
|
import { createPruneMessages } from '../messages/prune.mjs';
|
|
10
10
|
import { ensureThinkingBlockInMessages } from '../messages/format.mjs';
|
|
11
11
|
import { addCacheControl, addBedrockCacheControl } from '../messages/cache.mjs';
|
|
12
12
|
import { formatContentStrings } from '../messages/content.mjs';
|
|
13
|
+
import { extractToolDiscoveries } from '../messages/tools.mjs';
|
|
13
14
|
import { resetIfNotEmpty, joinKeys } from '../utils/graph.mjs';
|
|
14
15
|
import { isOpenAILike, isGoogleLike } from '../utils/llm.mjs';
|
|
15
16
|
import { sleep } from '../utils/run.mjs';
|
|
@@ -269,8 +270,6 @@ class StandardGraph extends Graph {
|
|
|
269
270
|
toolCallStepIds: this.toolCallStepIds,
|
|
270
271
|
errorHandler: (data, metadata) => StandardGraph.handleToolCallErrorStatic(this, data, metadata),
|
|
271
272
|
toolRegistry: agentContext?.toolRegistry,
|
|
272
|
-
programmaticToolMap: agentContext?.getProgrammaticToolMap(),
|
|
273
|
-
programmaticToolDefs: agentContext?.getProgrammaticToolDefs(),
|
|
274
273
|
});
|
|
275
274
|
}
|
|
276
275
|
initializeModel({ provider, tools, clientOptions, }) {
|
|
@@ -379,6 +378,12 @@ class StandardGraph extends Graph {
|
|
|
379
378
|
if (!config) {
|
|
380
379
|
throw new Error('No config provided');
|
|
381
380
|
}
|
|
381
|
+
const { messages } = state;
|
|
382
|
+
// Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)
|
|
383
|
+
const discoveredNames = extractToolDiscoveries(messages);
|
|
384
|
+
if (discoveredNames.length > 0) {
|
|
385
|
+
agentContext.markToolsAsDiscovered(discoveredNames);
|
|
386
|
+
}
|
|
382
387
|
const toolsForBinding = agentContext.getToolsForBinding();
|
|
383
388
|
let model = this.overrideModel ??
|
|
384
389
|
this.initializeModel({
|
|
@@ -396,7 +401,6 @@ class StandardGraph extends Graph {
|
|
|
396
401
|
config.signal = this.signal;
|
|
397
402
|
}
|
|
398
403
|
this.config = config;
|
|
399
|
-
const { messages } = state;
|
|
400
404
|
let messagesToUse = messages;
|
|
401
405
|
if (!agentContext.pruneMessages &&
|
|
402
406
|
agentContext.tokenCounter &&
|
|
@@ -446,16 +450,6 @@ class StandardGraph extends Graph {
|
|
|
446
450
|
finalMessages[finalMessages.length - 2].content = '';
|
|
447
451
|
}
|
|
448
452
|
const isLatestToolMessage = lastMessageY instanceof ToolMessage;
|
|
449
|
-
if (isLatestToolMessage &&
|
|
450
|
-
lastMessageY.name === Constants.TOOL_SEARCH_REGEX &&
|
|
451
|
-
typeof lastMessageY.artifact === 'object' &&
|
|
452
|
-
lastMessageY.artifact != null) {
|
|
453
|
-
const artifact = lastMessageY.artifact;
|
|
454
|
-
if (artifact.tool_references && artifact.tool_references.length > 0) {
|
|
455
|
-
const discoveredNames = artifact.tool_references.map((ref) => ref.tool_name);
|
|
456
|
-
agentContext.markToolsAsDiscovered(discoveredNames);
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
453
|
if (isLatestToolMessage &&
|
|
460
454
|
agentContext.provider === Providers.ANTHROPIC) {
|
|
461
455
|
formatAnthropicArtifactContent(finalMessages);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Graph.mjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n Constants,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n convertMessagesToContent,\n addBedrockCacheControl,\n modifyDeltaProperties,\n formatArtifactPayload,\n formatContentStrings,\n createPruneMessages,\n addCacheControl,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push('post-reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n if (agentId == null || agentId === '') {\n return [...this.contentData];\n }\n return this.contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n ((\n (clientOptions as t.AnthropicClientOptions).clientOptions\n ?.defaultHeaders as Record<string, string> | undefined\n )?.['anthropic-beta']?.includes('prompt-caching') ??\n false)\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n programmaticToolMap: agentContext?.getProgrammaticToolMap(),\n programmaticToolDefs: agentContext?.getProgrammaticToolDefs(),\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n const toolsForBinding = agentContext.getToolsForBinding();\n let model =\n this.overrideModel ??\n this.initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n let messagesToUse = messages;\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null) ||\n (agentContext.provider === Providers.OPENAI &&\n (\n (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n ?.thinking as t.AnthropicClientOptions['thinking']\n )?.type === 'enabled');\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n let finalMessages = messagesToUse;\n if (agentContext.useLegacyContent) {\n finalMessages = formatContentStrings(finalMessages);\n }\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY instanceof ToolMessage &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (\n isLatestToolMessage &&\n lastMessageY.name === Constants.TOOL_SEARCH_REGEX &&\n typeof lastMessageY.artifact === 'object' &&\n lastMessageY.artifact != null\n ) {\n const artifact = lastMessageY.artifact as {\n tool_references?: Array<{ tool_name: string }>;\n };\n if (artifact.tool_references && artifact.tool_references.length > 0) {\n const discoveredNames = artifact.tool_references.map(\n (ref) => ref.tool_name\n );\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n }\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n ((isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOptions = agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions\n ?.defaultHeaders as Record<string, string> | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalMessages = addCacheControl<BaseMessage>(finalMessages);\n }\n } else if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n if (bedrockOptions?.promptCache === true) {\n finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n }\n }\n\n /**\n * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n * This is required by Anthropic/Bedrock when thinking is enabled.\n */\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n if (isAnthropicWithThinking) {\n finalMessages = ensureThinkingBlockInMessages(\n finalMessages,\n agentContext.provider\n );\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (finalMessages.length === 0) {\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',\n })\n );\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.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 });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n /**\n * Extract and store agentId from metadata\n */\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (agentContext.agentId) {\n runStep.agentId = agentContext.agentId;\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAgEA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAEhB,KAAK,CAAA;AA0DzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;AAChB;AAEK,MAAO,aAAc,SAAQ,KAAoC,CAAA;AACrE,IAAA,aAAa;;AAEb,IAAA,cAAc;IACd,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;IACL,UAAU,GAAW,CAAC;AACtB,IAAA,MAAM;;AAEN,IAAA,aAAa,GAA8B,IAAI,GAAG,EAAE;;AAEpD,IAAA,cAAc;IAEd,WAAY,CAAA;;IAEV,KAAK,EACL,MAAM,EACN,MAAM,EACN,YAAY,EACZ,kBAAkB,GACG,EAAA;AACrB,QAAA,KAAK,EAAE;AACP,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;AAClB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;AAEpB,QAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACvB,YAAA,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC;;AAGjE,QAAA,KAAK,MAAM,WAAW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,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"Graph.mjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n START,\n END,\n Command,\n StateGraph,\n Annotation,\n messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n Runnable,\n RunnableConfig,\n RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n ToolMessage,\n SystemMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type {\n BaseMessageFields,\n UsageMetadata,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n} from '@/common';\nimport {\n formatAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n convertMessagesToContent,\n addBedrockCacheControl,\n modifyDeltaProperties,\n formatArtifactPayload,\n formatContentStrings,\n createPruneMessages,\n addCacheControl,\n extractToolDiscoveries,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isOpenAILike,\n isGoogleLike,\n joinKeys,\n sleep,\n} from '@/utils';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel({\n currentModel,\n tools,\n clientOptions,\n }: {\n currentModel?: t.ChatModel;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void>;\n abstract handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void>;\n\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n signal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n\n constructor({\n // parent-level graph inputs\n runId,\n signal,\n agents,\n tokenCounter,\n indexTokenCountMap,\n }: t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.signal = signal;\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n for (const context of this.agentContexts.values()) {\n context.reset();\n }\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push('post-reasoning');\n }\n\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n if (agentId == null || agentId === '') {\n return [...this.contentData];\n }\n return this.contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /* Graph */\n\n createSystemRunnable({\n provider,\n clientOptions,\n instructions,\n additional_instructions,\n }: {\n provider?: Providers;\n clientOptions?: t.ClientOptions;\n instructions?: string;\n additional_instructions?: string;\n }): t.SystemRunnable | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n instructions;\n if (additional_instructions != null && additional_instructions !== '') {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${additional_instructions}`\n : additional_instructions;\n }\n\n if (\n finalInstructions != null &&\n finalInstructions &&\n provider === Providers.ANTHROPIC &&\n ((\n (clientOptions as t.AnthropicClientOptions).clientOptions\n ?.defaultHeaders as Record<string, string> | undefined\n )?.['anthropic-beta']?.includes('prompt-caching') ??\n false)\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n }\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n return new CustomToolNode<t.BaseGraphState>({\n tools: (currentTools as t.GenericTool[] | undefined) ?? [],\n toolMap: currentToolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata) =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n });\n }\n\n initializeModel({\n provider,\n tools,\n clientOptions,\n }: {\n provider: Providers;\n tools?: t.GraphTools;\n clientOptions?: t.ClientOptions;\n }): Runnable {\n const ChatModelClass = getChatModelClass(provider);\n const model = new ChatModelClass(clientOptions ?? {});\n\n if (\n isOpenAILike(provider) &&\n (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n ) {\n model.temperature = (clientOptions as t.OpenAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n .presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n } else if (\n provider === Providers.VERTEXAI &&\n model instanceof ChatVertexAI\n ) {\n model.temperature = (clientOptions as t.VertexAIClientOptions)\n .temperature as number;\n model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n .topLogprobs as number;\n model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n .frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n .presencePenalty as number;\n model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n .maxOutputTokens as number;\n }\n\n if (!tools || tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(tools);\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n provider,\n clientOptions,\n }: {\n provider: Providers;\n clientOptions?: t.ClientOptions;\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(provider);\n return new ChatModelClass(clientOptions ?? {});\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n /** Execute model invocation with streaming support */\n private async attemptInvoke(\n {\n currentModel,\n finalMessages,\n provider,\n tools,\n }: {\n currentModel?: t.ChatModel;\n finalMessages: BaseMessage[];\n provider: Providers;\n tools?: t.GraphTools;\n },\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> {\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n throw new Error('No model found');\n }\n\n if ((tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n if (!model.stream) {\n throw new Error('Model does not support stream');\n }\n const stream = await model.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n await safeDispatchCustomEvent(\n GraphEvents.CHAT_MODEL_STREAM,\n { chunk, emitted: true },\n config\n );\n finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n }\n finalChunk = modifyDeltaProperties(provider, finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = await model.invoke(finalMessages, config);\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n (tool_call: ToolCall) => !!tool_call.name\n );\n }\n return { messages: [finalMessage] };\n }\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.BaseGraphState>> => {\n /**\n * Get agent context - it must exist by this point\n */\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n const { messages } = state;\n\n // Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const toolsForBinding = agentContext.getToolsForBinding();\n let model =\n this.overrideModel ??\n this.initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null &&\n agentContext.indexTokenCountMap[0] != null\n ) {\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null) ||\n (agentContext.provider === Providers.OPENAI &&\n (\n (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n ?.thinking as t.AnthropicClientOptions['thinking']\n )?.type === 'enabled');\n\n agentContext.pruneMessages = createPruneMessages({\n startIndex: this.startIndex,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n thinkingEnabled: isAnthropicWithThinking,\n indexTokenCountMap: agentContext.indexTokenCountMap,\n });\n }\n if (agentContext.pruneMessages) {\n const { context, indexTokenCountMap } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n // startOnMessageType: 'human',\n });\n agentContext.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n let finalMessages = messagesToUse;\n if (agentContext.useLegacyContent) {\n finalMessages = formatContentStrings(finalMessages);\n }\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY instanceof ToolMessage &&\n typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (\n isLatestToolMessage &&\n agentContext.provider === Providers.ANTHROPIC\n ) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n ((isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (agentContext.provider === Providers.ANTHROPIC) {\n const anthropicOptions = agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions\n ?.defaultHeaders as Record<string, string> | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalMessages = addCacheControl<BaseMessage>(finalMessages);\n }\n } else if (agentContext.provider === Providers.BEDROCK) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n if (bedrockOptions?.promptCache === true) {\n finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n }\n }\n\n /**\n * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n * This is required by Anthropic/Bedrock when thinking is enabled.\n */\n const isAnthropicWithThinking =\n (agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n null) ||\n (agentContext.provider === Providers.BEDROCK &&\n (agentContext.clientOptions as t.BedrockAnthropicInput)\n .additionalModelRequestFields?.['thinking'] != null);\n\n if (isAnthropicWithThinking) {\n finalMessages = ensureThinkingBlockInMessages(\n finalMessages,\n agentContext.provider\n );\n }\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (finalMessages.length === 0) {\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.',\n })\n );\n }\n\n try {\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: agentContext.provider,\n tools: agentContext.tools,\n },\n config\n );\n } catch (primaryError) {\n let lastError: unknown = primaryError;\n for (const fb of fallbacks) {\n try {\n let model = this.getNewModel({\n provider: fb.provider,\n clientOptions: fb.clientOptions,\n });\n const bindableTools = agentContext.tools;\n model = (\n !bindableTools || bindableTools.length === 0\n ? model\n : model.bindTools(bindableTools)\n ) as t.ChatModelInstance;\n result = await this.attemptInvoke(\n {\n currentModel: model,\n finalMessages,\n provider: fb.provider,\n tools: agentContext.tools,\n },\n config\n );\n lastError = undefined;\n break;\n } catch (e) {\n lastError = e;\n continue;\n }\n }\n if (lastError !== undefined) {\n throw lastError;\n }\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n this.cleanupSignalListener();\n return result;\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n\n const routeMessage = (\n state: t.BaseGraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n return toolsCondition(state, toolNode, this.invokedToolIds);\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n // Cast to unknown to avoid tight coupling to external types; options are opt-in\n return workflow.compile(this.compileOptions as unknown as never);\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n /** Use the default (first) agent for now */\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!a.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 });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n .addEdge(START, this.defaultAgentId)\n .compile();\n\n return workflow;\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n /**\n * Extract and store agentId from metadata\n */\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (agentContext.agentId) {\n runStep.agentId = agentContext.agentId;\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n return stepId;\n }\n\n async handleToolCallCompleted(\n data: t.ToolEndData,\n metadata?: Record<string, unknown>,\n omitOutput?: boolean\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output: _output } = data;\n if ((_output as Command | undefined)?.lg_name === 'Command') {\n return;\n }\n const output = _output as ToolMessage;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const dispatchedOutput =\n typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content);\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: omitOutput === true ? '' : dispatchedOutput,\n progress: 1,\n };\n\n await this.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n this\n );\n }\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!graph.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n ?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n }\n\n async dispatchMessageDelta(id: string, delta: t.MessageDelta): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n };\n}\n"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAgEA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAEhB,KAAK,CAAA;AA0DzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;AAChB;AAEK,MAAO,aAAc,SAAQ,KAAoC,CAAA;AACrE,IAAA,aAAa;;AAEb,IAAA,cAAc;IACd,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;IACL,UAAU,GAAW,CAAC;AACtB,IAAA,MAAM;;AAEN,IAAA,aAAa,GAA8B,IAAI,GAAG,EAAE;;AAEpD,IAAA,cAAc;IAEd,WAAY,CAAA;;IAEV,KAAK,EACL,MAAM,EACN,MAAM,EACN,YAAY,EACZ,kBAAkB,GACG,EAAA;AACrB,QAAA,KAAK,EAAE;AACP,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;AAClB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;AAEpB,QAAA,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;AACvB,YAAA,MAAM,IAAI,KAAK,CAAC,8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AE,EAAE;AACd,YAAA,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC;;AAErC,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;AACD,QAAA,MAAM,uBAAuB,CAC3B,WAAW,CAAC,iBAAiB,EAC7B,YAAY,EACZ,IAAI,CAAC,MAAM,CACZ;;AAGH,IAAA,MAAM,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AAC1D,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;AACD,QAAA,MAAM,uBAAuB,CAC3B,WAAW,CAAC,gBAAgB,EAC5B,YAAY,EACZ,IAAI,CAAC,MAAM,CACZ;;AAGH,IAAA,sBAAsB,GAAG,OACvB,MAAc,EACd,KAAuB,KACN;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;AACD,QAAA,MAAM,uBAAuB,CAC3B,WAAW,CAAC,kBAAkB,EAC9B,cAAc,EACd,IAAI,CAAC,MAAM,CACZ;AACH,KAAC;AACF;;;;"}
|
package/dist/esm/main.mjs
CHANGED
|
@@ -8,11 +8,12 @@ export { calculateTotalTokens, checkValidNumber, createPruneMessages, getMessage
|
|
|
8
8
|
export { ensureThinkingBlockInMessages, formatAgentMessages, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, labelContentByAgent, shiftIndexTokenCountMap } from './messages/format.mjs';
|
|
9
9
|
export { addBedrockCacheControl, addCacheControl, stripAnthropicCacheControl, stripBedrockCacheControl } from './messages/cache.mjs';
|
|
10
10
|
export { formatContentStrings } from './messages/content.mjs';
|
|
11
|
+
export { extractToolDiscoveries, hasToolSearchInCurrentTurn } from './messages/tools.mjs';
|
|
11
12
|
export { Graph, StandardGraph } from './graphs/Graph.mjs';
|
|
12
13
|
export { MultiAgentGraph } from './graphs/MultiAgentGraph.mjs';
|
|
13
14
|
export { Calculator } from './tools/Calculator.mjs';
|
|
14
15
|
export { createCodeExecutionTool, getCodeBaseURL, imageExtRegex } from './tools/CodeExecutor.mjs';
|
|
15
|
-
export { createProgrammaticToolCallingTool, executeTools, formatCompletedResponse, makeRequest } from './tools/ProgrammaticToolCalling.mjs';
|
|
16
|
+
export { createProgrammaticToolCallingTool, executeTools, extractUsedToolNames, filterToolsByUsage, formatCompletedResponse, makeRequest } from './tools/ProgrammaticToolCalling.mjs';
|
|
16
17
|
export { countNestedGroups, createToolSearchRegexTool, escapeRegexSpecialChars, hasNestedQuantifiers, isDangerousPattern, sanitizeRegex } from './tools/ToolSearchRegex.mjs';
|
|
17
18
|
export { handleServerToolResult, handleToolCallChunks, handleToolCalls, toolResultTypes } from './tools/handlers.mjs';
|
|
18
19
|
export { createSearchTool } from './tools/search/tool.mjs';
|
package/dist/esm/main.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"main.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;"}
|