@librechat/agents 3.0.48 → 3.0.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/llm/openrouter/index.cjs +10 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/stream.cjs +22 -16
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +32 -31
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +10 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/stream.mjs +22 -16
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +32 -31
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/package.json +6 -2
- package/src/llm/openrouter/index.ts +11 -1
- package/src/stream.ts +21 -20
- package/src/tools/ProgrammaticToolCalling.ts +35 -34
- package/src/utils/llmConfig.ts +3 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProgrammaticToolCalling.cjs","sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\n/** Default execution timeout in milliseconds */\nconst DEFAULT_TIMEOUT = 60000;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst ProgrammaticToolCallingSchema = z.object({\n code: z\n .string()\n .min(1)\n .describe(\n `Python code that calls tools programmatically. Tools are available as async functions.\n\nYour code is automatically wrapped in an async main() and executed. Just write your logic with await—no boilerplate needed.\n\nExample (Simple call):\n result = await get_weather(city=\"San Francisco\")\n print(result)\n\nExample (Parallel):\n sf, ny, lon = await asyncio.gather(\n get_weather(city=\"SF\"),\n get_weather(city=\"NYC\"),\n get_weather(city=\"London\")\n )\n print(f\"SF: {sf}, NY: {ny}, London: {lon}\")\n\nExample (Loop):\n team = await get_team_members()\n for member in team:\n expenses = await get_expenses(user_id=member['id'])\n print(f\"{member['name']}: \\${sum(e['amount'] for e in expenses):.2f}\")\n\nRules:\n- Just write code with await—it's auto-wrapped in async context\n- DO NOT define async def main() or call asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions for them\n- Only print() output returns to the model\n- Tool results are raw dicts/lists/strings (already unwrapped)`\n ),\n session_id: z\n .string()\n .optional()\n .describe(\n 'Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'\n ),\n timeout: z\n .number()\n .int()\n .min(1000)\n .max(300000)\n .optional()\n .default(DEFAULT_TIMEOUT)\n .describe(\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.'\n ),\n});\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/** Python reserved keywords that get `_tool` suffix in Code API */\nconst PYTHON_KEYWORDS = new Set([\n 'False',\n 'None',\n 'True',\n 'and',\n 'as',\n 'assert',\n 'async',\n 'await',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'nonlocal',\n 'not',\n 'or',\n 'pass',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Normalizes a tool name to Python identifier format.\n * Must match the Code API's `normalizePythonFunctionName` exactly:\n * 1. Replace hyphens and spaces with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a Python keyword\n * @param name - The tool name to normalize\n * @returns Normalized Python-safe identifier\n */\nexport function normalizeToPythonIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s]/g, '_');\n\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (PYTHON_KEYWORDS.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the Python code.\n * Handles hyphen/underscore conversion since Python identifiers use underscores.\n * @param code - The Python code to analyze\n * @param toolNameMap - Map from normalized Python name to original tool name\n * @returns Set of original tool names found in the code\n */\nexport function extractUsedToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [pythonName, originalName] of toolNameMap) {\n const escapedName = pythonName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\s*\\\\(`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the code.\n * Handles the hyphen-to-underscore conversion for Python compatibility.\n * @param toolDefs - All available tool definitions\n * @param code - The Python code to analyze\n * @param debug - Enable debug logging\n * @returns Filtered array of tool definitions\n */\nexport function filterToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const tool of toolDefs) {\n const pythonName = normalizeToPythonIdentifier(tool.name);\n toolNameMap.set(pythonName, tool.name);\n }\n\n const usedToolNames = extractUsedToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[PTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((tool) => usedToolNames.has(tool.name));\n}\n\n/**\n * Fetches files from a previous session to make them available for the current execution.\n * Files are returned as CodeEnvFile references to be included in the request.\n * @param baseUrl - The base URL for the Code API\n * @param apiKey - The API key for authentication\n * @param sessionId - The session ID to fetch files from\n * @param proxy - Optional HTTP proxy URL\n * @returns Array of CodeEnvFile references, or empty array if fetch fails\n */\nexport async function fetchSessionFiles(\n baseUrl: string,\n apiKey: string,\n sessionId: string,\n proxy?: string\n): Promise<t.CodeEnvFile[]> {\n try {\n const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(`Failed to fetch files for session: ${response.status}`);\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files.map((file: Record<string, unknown>) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = (file.name as string).split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id: sessionId,\n id,\n name: (file.metadata as Record<string, unknown>)[\n 'original-filename'\n ] as string,\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(\n `Failed to fetch files for session: ${sessionId}, ${(error as Error).message}`\n );\n return [];\n }\n}\n\n/**\n * Makes an HTTP request to the Code API.\n * @param endpoint - The API endpoint URL\n * @param apiKey - The API key for authentication\n * @param body - The request body\n * @param proxy - Optional HTTP proxy URL\n * @returns The parsed API response\n */\nexport async function makeRequest(\n endpoint: string,\n apiKey: string,\n body: Record<string, unknown>,\n proxy?: string\n): Promise<t.ProgrammaticExecutionResponse> {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(body),\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(endpoint, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `HTTP error! status: ${response.status}, body: ${errorText}`\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n}\n\n/**\n * Unwraps tool responses that may be formatted as tuples or content blocks.\n * MCP tools return [content, artifacts], we need to extract the raw data.\n * @param result - The raw result from tool.invoke()\n * @param isMCPTool - Whether this is an MCP tool (has mcp property)\n * @returns Unwrapped raw data (string, object, or parsed JSON)\n */\nexport function unwrapToolResponse(\n result: unknown,\n isMCPTool: boolean\n): unknown {\n // Only unwrap if this is an MCP tool and result is a tuple\n if (!isMCPTool) {\n return result;\n }\n\n /**\n * Checks if a value is a content block object (has type and text).\n */\n const isContentBlock = (value: unknown): boolean => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n return typeof obj.type === 'string';\n };\n\n /**\n * Checks if an array is an array of content blocks.\n */\n const isContentBlockArray = (arr: unknown[]): boolean => {\n return arr.length > 0 && arr.every(isContentBlock);\n };\n\n /**\n * Extracts text from a single content block object.\n * Returns the text if it's a text block, otherwise returns null.\n */\n const extractTextFromBlock = (block: unknown): string | null => {\n if (typeof block !== 'object' || block === null) return null;\n const b = block as Record<string, unknown>;\n if (b.type === 'text' && typeof b.text === 'string') {\n return b.text;\n }\n return null;\n };\n\n /**\n * Extracts text from content blocks (array or single object).\n * Returns combined text or null if no text blocks found.\n */\n const extractTextFromContent = (content: unknown): string | null => {\n // Single content block object: { type: 'text', text: '...' }\n if (\n typeof content === 'object' &&\n content !== null &&\n !Array.isArray(content)\n ) {\n const text = extractTextFromBlock(content);\n if (text !== null) return text;\n }\n\n // Array of content blocks: [{ type: 'text', text: '...' }, ...]\n if (Array.isArray(content) && content.length > 0) {\n const texts = content\n .map(extractTextFromBlock)\n .filter((t): t is string => t !== null);\n if (texts.length > 0) {\n return texts.join('\\n');\n }\n }\n\n return null;\n };\n\n /**\n * Tries to parse a string as JSON if it looks like JSON.\n */\n const maybeParseJSON = (str: string): unknown => {\n const trimmed = str.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return str;\n }\n }\n return str;\n };\n\n // Handle array of content blocks at top level FIRST\n // (before checking for tuple, since both are arrays)\n if (Array.isArray(result) && isContentBlockArray(result)) {\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n }\n\n // Check if result is a tuple/array with [content, artifacts]\n if (Array.isArray(result) && result.length >= 1) {\n const [content] = result;\n\n // If first element is a string, return it (possibly parsed as JSON)\n if (typeof content === 'string') {\n return maybeParseJSON(content);\n }\n\n // Try to extract text from content blocks\n const extractedText = extractTextFromContent(content);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // If first element is an object (but not a text block), return it\n if (typeof content === 'object' && content !== null) {\n return content;\n }\n }\n\n // Handle single content block object at top level (not in tuple)\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // Not a formatted response, return as-is\n return result;\n}\n\n/**\n * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\n * Unwraps formatted responses (e.g., MCP tool tuples) to raw data.\n * @param toolCalls - Array of tool calls from the API\n * @param toolMap - Map of tool names to executable tools\n * @returns Array of tool results\n */\nexport async function executeTools(\n toolCalls: t.PTCToolCall[],\n toolMap: t.ToolMap\n): Promise<t.PTCToolResult[]> {\n const executions = toolCalls.map(async (call): Promise<t.PTCToolResult> => {\n const tool = toolMap.get(call.name);\n\n if (!tool) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,\n };\n }\n\n try {\n const result = await tool.invoke(call.input, {\n metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },\n });\n\n const isMCPTool = tool.mcp === true;\n const unwrappedResult = unwrapToolResponse(result, isMCPTool);\n\n return {\n call_id: call.id,\n result: unwrappedResult,\n is_error: false,\n };\n } catch (error) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: (error as Error).message || 'Tool execution failed',\n };\n }\n });\n\n return await Promise.all(executions);\n}\n\n/**\n * Formats the completed response for the agent.\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse\n): [string, t.ProgrammaticExecutionArtifact] {\n let formatted = '';\n\n if (response.stdout != null && response.stdout !== '') {\n formatted += `stdout:\\n${response.stdout}\\n`;\n } else {\n formatted += emptyOutputMessage;\n }\n\n if (response.stderr != null && response.stderr !== '') {\n formatted += `stderr:\\n${response.stderr}\\n`;\n }\n\n if (response.files && response.files.length > 0) {\n formatted += 'Generated files:\\n';\n\n const fileCount = response.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = response.files[i];\n const isImage = imageExtRegex.test(file.name);\n formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formatted += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formatted += `\\nsession_id: ${response.session_id}\\n\\n${accessMessage}`;\n }\n\n return [\n formatted.trim(),\n {\n session_id: response.session_id,\n files: response.files,\n },\n ];\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.\n *\n * This tool enables AI agents to write Python code that orchestrates multiple\n * tool calls programmatically, reducing LLM round-trips and token usage.\n *\n * The tool map must be provided at runtime via config.configurable.toolMap.\n *\n * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({\n * apiKey: process.env.CODE_API_KEY,\n * maxRoundTrips: 20\n * });\n *\n * const [output, artifact] = await ptcTool.invoke(\n * { code, tools },\n * { configurable: { toolMap } }\n * );\n */\nexport function createProgrammaticToolCallingTool(\n initParams: t.ProgrammaticToolCallingParams = {}\n): DynamicStructuredTool<typeof ProgrammaticToolCallingSchema> {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n const description = `\nRun tools via Python code. Your code is auto-wrapped in async context—just use \\`await\\` directly.\n\nCRITICAL: Do NOT define \\`async def main()\\` or call \\`asyncio.run()\\`. Just write code with await.\n\nRules:\n- Tools are pre-defined as async functions—DO NOT define them yourself\n- Use \\`await\\` for tool calls, \\`asyncio.gather()\\` for parallel\n- Only \\`print()\\` output returns to the model; tool results are raw dicts/lists/strings\n- Stateless: variables/imports don't persist; use \\`session_id\\` param for file access\n- Files mount at \\`/mnt/data/\\` (READ-ONLY); write changes to NEW filenames\n- Tool names normalized: hyphens→underscores, keywords get \\`_tool\\` suffix\n\nWhen to use (vs. direct tool calls): loops, conditionals, parallel execution, aggregation.\n\nExamples:\n result = await get_weather(city=\"NYC\"); print(result)\n sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n`.trim();\n\n return tool<typeof ProgrammaticToolCallingSchema>(\n async (params, config) => {\n const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const { toolMap, toolDefs } = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache>;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n // Fetch files from previous session if session_id is provided\n let files: t.CodeEnvFile[] | undefined;\n if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description,\n schema: ProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":["config","z","HttpsProxyAgent","Constants","imageExtRegex","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool"],"mappings":";;;;;;;;;;;AAAA;AAYAA,aAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,mKAAmK;AACrK,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D;AACA,MAAM,uBAAuB,GAAG,EAAE;AAElC;AACA,MAAM,eAAe,GAAG,KAAK;AAE7B;AACA;AACA;AAEA,M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MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAE,CAAA;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAE;AACnC,0BAAE,EAAE,CAAC,CACV;;YAGH,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAE,CAAA,CAAC;;QACjE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,+BAAA,EAAmC,KAAe,CAAC,OAAO,CAAE,CAAA,CAC7D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEL,eAAS,CAAC,yBAAyB;QACzC,WAAW;AACX,QAAA,MAAM,EAAE,6BAA6B;QACrC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"ProgrammaticToolCalling.cjs","sources":["../../../src/tools/ProgrammaticToolCalling.ts"],"sourcesContent":["// src/tools/ProgrammaticToolCalling.ts\nimport { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { imageExtRegex, getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst imageMessage = 'Image is already displayed to the user';\nconst otherMessage = 'File is already downloaded by the user';\nconst accessMessage =\n 'Note: Files are READ-ONLY. Save changes to NEW filenames. To access these files in future executions, provide the `session_id` as a parameter (not in your code).';\nconst emptyOutputMessage =\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\n\n/** Default max round-trips to prevent infinite loops */\nconst DEFAULT_MAX_ROUND_TRIPS = 20;\n\n/** Default execution timeout in milliseconds */\nconst DEFAULT_TIMEOUT = 60000;\n\n// ============================================================================\n// Schema\n// ============================================================================\n\nconst ProgrammaticToolCallingSchema = z.object({\n code: z\n .string()\n .min(1)\n .describe(\n `Python code that calls tools programmatically. Tools are available as async functions.\n\nCRITICAL - STATELESS EXECUTION:\nEach call is a fresh Python interpreter. Variables, imports, and data do NOT persist between calls.\nYou MUST complete your entire workflow in ONE code block: query → process → output.\nDO NOT split work across multiple calls expecting to reuse variables.\n\nYour code is auto-wrapped in async context. Just write logic with await—no boilerplate needed.\n\nExample (Complete workflow in one call):\n # Query data\n data = await query_database(sql=\"SELECT * FROM users\")\n # Process it\n df = pd.DataFrame(data)\n summary = df.groupby('region').sum()\n # Output results\n await write_to_sheet(spreadsheet_id=sid, data=summary.to_dict())\n print(f\"Wrote {len(summary)} rows\")\n\nExample (Parallel calls):\n sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n print(f\"SF: {sf}, NY: {ny}\")\n\nRules:\n- EVERYTHING in one call—no state persists between executions\n- Just write code with await—auto-wrapped in async context\n- DO NOT define async def main() or call asyncio.run()\n- Tools are pre-defined—DO NOT write function definitions\n- Only print() output returns to the model`\n ),\n session_id: z\n .string()\n .optional()\n .describe(\n 'Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'\n ),\n timeout: z\n .number()\n .int()\n .min(1000)\n .max(300000)\n .optional()\n .default(DEFAULT_TIMEOUT)\n .describe(\n 'Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.'\n ),\n});\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/** Python reserved keywords that get `_tool` suffix in Code API */\nconst PYTHON_KEYWORDS = new Set([\n 'False',\n 'None',\n 'True',\n 'and',\n 'as',\n 'assert',\n 'async',\n 'await',\n 'break',\n 'class',\n 'continue',\n 'def',\n 'del',\n 'elif',\n 'else',\n 'except',\n 'finally',\n 'for',\n 'from',\n 'global',\n 'if',\n 'import',\n 'in',\n 'is',\n 'lambda',\n 'nonlocal',\n 'not',\n 'or',\n 'pass',\n 'raise',\n 'return',\n 'try',\n 'while',\n 'with',\n 'yield',\n]);\n\n/**\n * Normalizes a tool name to Python identifier format.\n * Must match the Code API's `normalizePythonFunctionName` exactly:\n * 1. Replace hyphens and spaces with underscores\n * 2. Remove any other invalid characters\n * 3. Prefix with underscore if starts with number\n * 4. Append `_tool` if it's a Python keyword\n * @param name - The tool name to normalize\n * @returns Normalized Python-safe identifier\n */\nexport function normalizeToPythonIdentifier(name: string): string {\n let normalized = name.replace(/[-\\s]/g, '_');\n\n normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');\n\n if (/^[0-9]/.test(normalized)) {\n normalized = '_' + normalized;\n }\n\n if (PYTHON_KEYWORDS.has(normalized)) {\n normalized = normalized + '_tool';\n }\n\n return normalized;\n}\n\n/**\n * Extracts tool names that are actually called in the Python code.\n * Handles hyphen/underscore conversion since Python identifiers use underscores.\n * @param code - The Python code to analyze\n * @param toolNameMap - Map from normalized Python name to original tool name\n * @returns Set of original tool names found in the code\n */\nexport function extractUsedToolNames(\n code: string,\n toolNameMap: Map<string, string>\n): Set<string> {\n const usedTools = new Set<string>();\n\n for (const [pythonName, originalName] of toolNameMap) {\n const escapedName = pythonName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const pattern = new RegExp(`\\\\b${escapedName}\\\\s*\\\\(`, 'g');\n\n if (pattern.test(code)) {\n usedTools.add(originalName);\n }\n }\n\n return usedTools;\n}\n\n/**\n * Filters tool definitions to only include tools actually used in the code.\n * Handles the hyphen-to-underscore conversion for Python compatibility.\n * @param toolDefs - All available tool definitions\n * @param code - The Python code to analyze\n * @param debug - Enable debug logging\n * @returns Filtered array of tool definitions\n */\nexport function filterToolsByUsage(\n toolDefs: t.LCTool[],\n code: string,\n debug = false\n): t.LCTool[] {\n const toolNameMap = new Map<string, string>();\n for (const tool of toolDefs) {\n const pythonName = normalizeToPythonIdentifier(tool.name);\n toolNameMap.set(pythonName, tool.name);\n }\n\n const usedToolNames = extractUsedToolNames(code, toolNameMap);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`\n );\n if (usedToolNames.size > 0) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`\n );\n }\n }\n\n if (usedToolNames.size === 0) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n '[PTC Debug] No tools detected in code - sending all tools as fallback'\n );\n }\n return toolDefs;\n }\n\n return toolDefs.filter((tool) => usedToolNames.has(tool.name));\n}\n\n/**\n * Fetches files from a previous session to make them available for the current execution.\n * Files are returned as CodeEnvFile references to be included in the request.\n * @param baseUrl - The base URL for the Code API\n * @param apiKey - The API key for authentication\n * @param sessionId - The session ID to fetch files from\n * @param proxy - Optional HTTP proxy URL\n * @returns Array of CodeEnvFile references, or empty array if fetch fails\n */\nexport async function fetchSessionFiles(\n baseUrl: string,\n apiKey: string,\n sessionId: string,\n proxy?: string\n): Promise<t.CodeEnvFile[]> {\n try {\n const filesEndpoint = `${baseUrl}/files/${sessionId}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(`Failed to fetch files for session: ${response.status}`);\n }\n\n const files = await response.json();\n if (!Array.isArray(files) || files.length === 0) {\n return [];\n }\n\n return files.map((file: Record<string, unknown>) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = (file.name as string).split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id: sessionId,\n id,\n name: (file.metadata as Record<string, unknown>)[\n 'original-filename'\n ] as string,\n };\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn(\n `Failed to fetch files for session: ${sessionId}, ${(error as Error).message}`\n );\n return [];\n }\n}\n\n/**\n * Makes an HTTP request to the Code API.\n * @param endpoint - The API endpoint URL\n * @param apiKey - The API key for authentication\n * @param body - The request body\n * @param proxy - Optional HTTP proxy URL\n * @returns The parsed API response\n */\nexport async function makeRequest(\n endpoint: string,\n apiKey: string,\n body: Record<string, unknown>,\n proxy?: string\n): Promise<t.ProgrammaticExecutionResponse> {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'LibreChat/1.0',\n 'X-API-Key': apiKey,\n },\n body: JSON.stringify(body),\n };\n\n if (proxy != null && proxy !== '') {\n fetchOptions.agent = new HttpsProxyAgent(proxy);\n }\n\n const response = await fetch(endpoint, fetchOptions);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `HTTP error! status: ${response.status}, body: ${errorText}`\n );\n }\n\n return (await response.json()) as t.ProgrammaticExecutionResponse;\n}\n\n/**\n * Unwraps tool responses that may be formatted as tuples or content blocks.\n * MCP tools return [content, artifacts], we need to extract the raw data.\n * @param result - The raw result from tool.invoke()\n * @param isMCPTool - Whether this is an MCP tool (has mcp property)\n * @returns Unwrapped raw data (string, object, or parsed JSON)\n */\nexport function unwrapToolResponse(\n result: unknown,\n isMCPTool: boolean\n): unknown {\n // Only unwrap if this is an MCP tool and result is a tuple\n if (!isMCPTool) {\n return result;\n }\n\n /**\n * Checks if a value is a content block object (has type and text).\n */\n const isContentBlock = (value: unknown): boolean => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const obj = value as Record<string, unknown>;\n return typeof obj.type === 'string';\n };\n\n /**\n * Checks if an array is an array of content blocks.\n */\n const isContentBlockArray = (arr: unknown[]): boolean => {\n return arr.length > 0 && arr.every(isContentBlock);\n };\n\n /**\n * Extracts text from a single content block object.\n * Returns the text if it's a text block, otherwise returns null.\n */\n const extractTextFromBlock = (block: unknown): string | null => {\n if (typeof block !== 'object' || block === null) return null;\n const b = block as Record<string, unknown>;\n if (b.type === 'text' && typeof b.text === 'string') {\n return b.text;\n }\n return null;\n };\n\n /**\n * Extracts text from content blocks (array or single object).\n * Returns combined text or null if no text blocks found.\n */\n const extractTextFromContent = (content: unknown): string | null => {\n // Single content block object: { type: 'text', text: '...' }\n if (\n typeof content === 'object' &&\n content !== null &&\n !Array.isArray(content)\n ) {\n const text = extractTextFromBlock(content);\n if (text !== null) return text;\n }\n\n // Array of content blocks: [{ type: 'text', text: '...' }, ...]\n if (Array.isArray(content) && content.length > 0) {\n const texts = content\n .map(extractTextFromBlock)\n .filter((t): t is string => t !== null);\n if (texts.length > 0) {\n return texts.join('\\n');\n }\n }\n\n return null;\n };\n\n /**\n * Tries to parse a string as JSON if it looks like JSON.\n */\n const maybeParseJSON = (str: string): unknown => {\n const trimmed = str.trim();\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n return JSON.parse(trimmed);\n } catch {\n return str;\n }\n }\n return str;\n };\n\n // Handle array of content blocks at top level FIRST\n // (before checking for tuple, since both are arrays)\n if (Array.isArray(result) && isContentBlockArray(result)) {\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n }\n\n // Check if result is a tuple/array with [content, artifacts]\n if (Array.isArray(result) && result.length >= 1) {\n const [content] = result;\n\n // If first element is a string, return it (possibly parsed as JSON)\n if (typeof content === 'string') {\n return maybeParseJSON(content);\n }\n\n // Try to extract text from content blocks\n const extractedText = extractTextFromContent(content);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // If first element is an object (but not a text block), return it\n if (typeof content === 'object' && content !== null) {\n return content;\n }\n }\n\n // Handle single content block object at top level (not in tuple)\n const extractedText = extractTextFromContent(result);\n if (extractedText !== null) {\n return maybeParseJSON(extractedText);\n }\n\n // Not a formatted response, return as-is\n return result;\n}\n\n/**\n * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\n * Unwraps formatted responses (e.g., MCP tool tuples) to raw data.\n * @param toolCalls - Array of tool calls from the API\n * @param toolMap - Map of tool names to executable tools\n * @returns Array of tool results\n */\nexport async function executeTools(\n toolCalls: t.PTCToolCall[],\n toolMap: t.ToolMap\n): Promise<t.PTCToolResult[]> {\n const executions = toolCalls.map(async (call): Promise<t.PTCToolResult> => {\n const tool = toolMap.get(call.name);\n\n if (!tool) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,\n };\n }\n\n try {\n const result = await tool.invoke(call.input, {\n metadata: { [Constants.PROGRAMMATIC_TOOL_CALLING]: true },\n });\n\n const isMCPTool = tool.mcp === true;\n const unwrappedResult = unwrapToolResponse(result, isMCPTool);\n\n return {\n call_id: call.id,\n result: unwrappedResult,\n is_error: false,\n };\n } catch (error) {\n return {\n call_id: call.id,\n result: null,\n is_error: true,\n error_message: (error as Error).message || 'Tool execution failed',\n };\n }\n });\n\n return await Promise.all(executions);\n}\n\n/**\n * Formats the completed response for the agent.\n * @param response - The completed API response\n * @returns Tuple of [formatted string, artifact]\n */\nexport function formatCompletedResponse(\n response: t.ProgrammaticExecutionResponse\n): [string, t.ProgrammaticExecutionArtifact] {\n let formatted = '';\n\n if (response.stdout != null && response.stdout !== '') {\n formatted += `stdout:\\n${response.stdout}\\n`;\n } else {\n formatted += emptyOutputMessage;\n }\n\n if (response.stderr != null && response.stderr !== '') {\n formatted += `stderr:\\n${response.stderr}\\n`;\n }\n\n if (response.files && response.files.length > 0) {\n formatted += 'Generated files:\\n';\n\n const fileCount = response.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = response.files[i];\n const isImage = imageExtRegex.test(file.name);\n formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formatted += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formatted += `\\nsession_id: ${response.session_id}\\n\\n${accessMessage}`;\n }\n\n return [\n formatted.trim(),\n {\n session_id: response.session_id,\n files: response.files,\n },\n ];\n}\n\n// ============================================================================\n// Tool Factory\n// ============================================================================\n\n/**\n * Creates a Programmatic Tool Calling tool for complex multi-tool workflows.\n *\n * This tool enables AI agents to write Python code that orchestrates multiple\n * tool calls programmatically, reducing LLM round-trips and token usage.\n *\n * The tool map must be provided at runtime via config.configurable.toolMap.\n *\n * @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)\n * @returns A LangChain DynamicStructuredTool for programmatic tool calling\n *\n * @example\n * const ptcTool = createProgrammaticToolCallingTool({\n * apiKey: process.env.CODE_API_KEY,\n * maxRoundTrips: 20\n * });\n *\n * const [output, artifact] = await ptcTool.invoke(\n * { code, tools },\n * { configurable: { toolMap } }\n * );\n */\nexport function createProgrammaticToolCallingTool(\n initParams: t.ProgrammaticToolCallingParams = {}\n): DynamicStructuredTool<typeof ProgrammaticToolCallingSchema> {\n const apiKey =\n (initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n\n if (!apiKey) {\n throw new Error(\n 'No API key provided for programmatic tool calling. ' +\n 'Set CODE_API_KEY environment variable or pass apiKey in initParams.'\n );\n }\n\n const baseUrl = initParams.baseUrl ?? getCodeBaseURL();\n const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;\n const proxy = initParams.proxy ?? process.env.PROXY;\n const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';\n const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;\n\n const description = `\nRun tools via Python code. Auto-wrapped in async context—just use \\`await\\` directly.\n\nCRITICAL - STATELESS: Each call is a fresh interpreter. Variables/imports do NOT persist.\nComplete your ENTIRE workflow in ONE call: fetch → process → save. No splitting across calls.\n\nRules:\n- Everything in ONE code block—no state carries over between executions\n- Do NOT define \\`async def main()\\` or call \\`asyncio.run()\\`—just write code with await\n- Tools are pre-defined—DO NOT write function definitions\n- Only \\`print()\\` output returns; tool results are raw dicts/lists/strings\n- Use \\`session_id\\` param for file persistence across calls\n- Tool names normalized: hyphens→underscores, keywords get \\`_tool\\` suffix\n\nWhen to use: loops, conditionals, parallel (\\`asyncio.gather\\`), multi-step pipelines.\n\nExample (complete pipeline):\n data = await query_db(sql=\"...\"); df = process(data); await save_to_sheet(data=df); print(\"Done\")\n`.trim();\n\n return tool<typeof ProgrammaticToolCallingSchema>(\n async (params, config) => {\n const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;\n\n // Extra params injected by ToolNode (follows web_search pattern)\n const { toolMap, toolDefs } = (config.toolCall ?? {}) as ToolCall &\n Partial<t.ProgrammaticCache>;\n\n if (toolMap == null || toolMap.size === 0) {\n throw new Error(\n 'No toolMap provided. ' +\n 'ToolNode should inject this from AgentContext when invoked through the graph.'\n );\n }\n\n if (toolDefs == null || toolDefs.length === 0) {\n throw new Error(\n 'No tool definitions provided. ' +\n 'Either pass tools in the input or ensure ToolNode injects toolDefs.'\n );\n }\n\n let roundTrip = 0;\n\n try {\n // ====================================================================\n // Phase 1: Filter tools and make initial request\n // ====================================================================\n\n const effectiveTools = filterToolsByUsage(toolDefs, code, debug);\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Sending ${effectiveTools.length} tools to API ` +\n `(filtered from ${toolDefs.length})`\n );\n }\n\n // Fetch files from previous session if session_id is provided\n let files: t.CodeEnvFile[] | undefined;\n if (session_id != null && session_id.length > 0) {\n files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);\n }\n\n let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\n ...(files && files.length > 0 ? { files } : {}),\n },\n proxy\n );\n\n // ====================================================================\n // Phase 2: Handle response loop\n // ====================================================================\n\n while (response.status === 'tool_call_required') {\n roundTrip++;\n\n if (roundTrip > maxRoundTrips) {\n throw new Error(\n `Exceeded maximum round trips (${maxRoundTrips}). ` +\n 'This may indicate an infinite loop, excessive tool calls, ' +\n 'or a logic error in your code.'\n );\n }\n\n if (debug) {\n // eslint-disable-next-line no-console\n console.log(\n `[PTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`\n );\n }\n\n const toolResults = await executeTools(\n response.tool_calls ?? [],\n toolMap\n );\n\n response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n continuation_token: response.continuation_token,\n tool_results: toolResults,\n },\n proxy\n );\n }\n\n // ====================================================================\n // Phase 3: Handle final state\n // ====================================================================\n\n if (response.status === 'completed') {\n return formatCompletedResponse(response);\n }\n\n if (response.status === 'error') {\n throw new Error(\n `Execution error: ${response.error}` +\n (response.stderr != null && response.stderr !== ''\n ? `\\n\\nStderr:\\n${response.stderr}`\n : '')\n );\n }\n\n throw new Error(`Unexpected response status: ${response.status}`);\n } catch (error) {\n throw new Error(\n `Programmatic execution failed: ${(error as Error).message}`\n );\n }\n },\n {\n name: Constants.PROGRAMMATIC_TOOL_CALLING,\n description,\n schema: ProgrammaticToolCallingSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n"],"names":["config","z","HttpsProxyAgent","Constants","imageExtRegex","EnvVar","getEnvironmentVariable","getCodeBaseURL","tool"],"mappings":";;;;;;;;;;;AAAA;AAYAA,aAAM,EAAE;AAER;AACA;AACA;AAEA,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,mKAAmK;AACrK,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D;AACA,MAAM,uBAAuB,GAAG,EAAE;AAElC;AACA,M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QAAQ,CAAC;;AAG1C,YAAA,IAAI,QAAQ,CAAC,MAAM,KAAK,OAAO,EAAE;AAC/B,gBAAA,MAAM,IAAI,KAAK,CACb,oBAAoB,QAAQ,CAAC,KAAK,CAAE,CAAA;qBACjC,QAAQ,CAAC,MAAM,IAAI,IAAI,IAAI,QAAQ,CAAC,MAAM,KAAK;AAC9C,0BAAE,CAAA,aAAA,EAAgB,QAAQ,CAAC,MAAM,CAAE;AACnC,0BAAE,EAAE,CAAC,CACV;;YAGH,MAAM,IAAI,KAAK,CAAC,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAE,CAAA,CAAC;;QACjE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,+BAAA,EAAmC,KAAe,CAAC,OAAO,CAAE,CAAA,CAC7D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEL,eAAS,CAAC,yBAAyB;QACzC,WAAW;AACX,QAAA,MAAM,EAAE,6BAA6B;QACrC,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;;;;;;;"}
|
|
@@ -65,6 +65,8 @@ class ChatOpenRouter extends ChatOpenAI {
|
|
|
65
65
|
// Accumulate reasoning_details from each delta
|
|
66
66
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
67
67
|
const deltaAny = delta;
|
|
68
|
+
// Extract current chunk's reasoning text for streaming (before accumulation)
|
|
69
|
+
let currentChunkReasoningText = '';
|
|
68
70
|
if (deltaAny.reasoning_details != null &&
|
|
69
71
|
Array.isArray(deltaAny.reasoning_details)) {
|
|
70
72
|
for (const detail of deltaAny.reasoning_details) {
|
|
@@ -79,7 +81,9 @@ class ChatOpenRouter extends ChatOpenAI {
|
|
|
79
81
|
});
|
|
80
82
|
}
|
|
81
83
|
else if (detail.type === 'reasoning.text') {
|
|
82
|
-
//
|
|
84
|
+
// Extract current chunk's text for streaming
|
|
85
|
+
currentChunkReasoningText += detail.text || '';
|
|
86
|
+
// For text reasoning, accumulate text by index for final message
|
|
83
87
|
const idx = detail.index ?? 0;
|
|
84
88
|
const existing = reasoningTextByIndex.get(idx);
|
|
85
89
|
if (existing) {
|
|
@@ -98,6 +102,11 @@ class ChatOpenRouter extends ChatOpenAI {
|
|
|
98
102
|
}
|
|
99
103
|
}
|
|
100
104
|
const chunk = this._convertOpenAIDeltaToBaseMessageChunk(delta, data, defaultRole);
|
|
105
|
+
// For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),
|
|
106
|
+
// set the current chunk's reasoning text to additional_kwargs.reasoning for streaming
|
|
107
|
+
if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {
|
|
108
|
+
chunk.additional_kwargs.reasoning = currentChunkReasoningText;
|
|
109
|
+
}
|
|
101
110
|
// IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent
|
|
102
111
|
// LangChain's chunk concatenation from corrupting the array
|
|
103
112
|
// Check if this is the final chunk (has finish_reason)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../../../../src/llm/openrouter/index.ts"],"sourcesContent":["import { ChatOpenAI } from '@/llm/openai';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport { AIMessageChunk as AIMessageChunkClass } from '@langchain/core/messages';\nimport type {\n FunctionMessageChunk,\n SystemMessageChunk,\n HumanMessageChunk,\n ToolMessageChunk,\n ChatMessageChunk,\n AIMessageChunk,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type {\n ChatOpenAICallOptions,\n OpenAIChatInput,\n OpenAIClient,\n} from '@langchain/openai';\nimport { _convertMessagesToOpenAIParams } from '@/llm/openai/utils';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\nexport interface ChatOpenRouterCallOptions extends ChatOpenAICallOptions {\n include_reasoning?: boolean;\n modelKwargs?: OpenAIChatInput['modelKwargs'];\n}\nexport class ChatOpenRouter extends ChatOpenAI {\n constructor(_fields: Partial<ChatOpenRouterCallOptions>) {\n const { include_reasoning, modelKwargs = {}, ...fields } = _fields;\n super({\n ...fields,\n modelKwargs: {\n ...modelKwargs,\n include_reasoning,\n },\n });\n }\n static lc_name(): 'LibreChatOpenRouter' {\n return 'LibreChatOpenRouter';\n }\n protected override _convertOpenAIDeltaToBaseMessageChunk(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>,\n rawResponse: OpenAIClient.ChatCompletionChunk,\n defaultRole?:\n | 'function'\n | 'user'\n | 'system'\n | 'developer'\n | 'assistant'\n | 'tool'\n ):\n | AIMessageChunk\n | HumanMessageChunk\n | SystemMessageChunk\n | FunctionMessageChunk\n | ToolMessageChunk\n | ChatMessageChunk {\n const messageChunk = super._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n rawResponse,\n defaultRole\n );\n if (delta.reasoning != null) {\n messageChunk.additional_kwargs.reasoning = delta.reasoning;\n }\n if (delta.reasoning_details != null) {\n messageChunk.additional_kwargs.reasoning_details =\n delta.reasoning_details;\n }\n return messageChunk;\n }\n\n async *_streamResponseChunks2(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const messagesMapped: OpenAICompletionParam[] =\n _convertMessagesToOpenAIParams(messages, this.model, {\n includeReasoningDetails: true,\n convertReasoningDetailsToContent: true,\n });\n\n const params = {\n ...this.invocationParams(options, {\n streaming: true,\n }),\n messages: messagesMapped,\n stream: true as const,\n };\n let defaultRole: OpenAIRoleEnum | undefined;\n\n const streamIterable = await this.completionWithRetry(params, options);\n let usage: OpenAIClient.Completions.CompletionUsage | undefined;\n\n // Store reasoning_details keyed by unique identifier to prevent incorrect merging\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningTextByIndex: Map<number, Record<string, any>> = new Map();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningEncryptedById: Map<string, Record<string, any>> = new Map();\n\n for await (const data of streamIterable) {\n const choice = data.choices[0] as\n | Partial<OpenAIClient.Chat.Completions.ChatCompletionChunk.Choice>\n | undefined;\n if (data.usage) {\n usage = data.usage;\n }\n if (!choice) {\n continue;\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n // Accumulate reasoning_details from each delta\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const deltaAny = delta as Record<string, any>;\n if (\n deltaAny.reasoning_details != null &&\n Array.isArray(deltaAny.reasoning_details)\n ) {\n for (const detail of deltaAny.reasoning_details) {\n // For encrypted reasoning (thought signatures), store by ID - MUST be separate\n if (detail.type === 'reasoning.encrypted' && detail.id) {\n reasoningEncryptedById.set(detail.id, {\n type: detail.type,\n id: detail.id,\n data: detail.data,\n format: detail.format,\n index: detail.index,\n });\n } else if (detail.type === 'reasoning.text') {\n // For text reasoning, accumulate text by index\n const idx = detail.index ?? 0;\n const existing = reasoningTextByIndex.get(idx);\n if (existing) {\n // Only append text, keep other fields from first entry\n existing.text = (existing.text || '') + (detail.text || '');\n } else {\n reasoningTextByIndex.set(idx, {\n type: detail.type,\n text: detail.text || '',\n format: detail.format,\n index: idx,\n });\n }\n }\n }\n }\n\n const chunk = this._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n data,\n defaultRole\n );\n\n // IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent\n // LangChain's chunk concatenation from corrupting the array\n // Check if this is the final chunk (has finish_reason)\n if (choice.finish_reason != null) {\n // Build properly structured reasoning_details array\n // Text entries first (but we only need the encrypted ones for thought signatures)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalReasoningDetails: Record<string, any>[] = [\n ...reasoningTextByIndex.values(),\n ...reasoningEncryptedById.values(),\n ];\n\n if (finalReasoningDetails.length > 0) {\n chunk.additional_kwargs.reasoning_details = finalReasoningDetails;\n }\n } else {\n // Clear reasoning_details from intermediate chunks to prevent concatenation issues\n delete chunk.additional_kwargs.reasoning_details;\n }\n\n defaultRole = delta.role ?? defaultRole;\n const newTokenIndices = {\n prompt: options.promptIndex ?? 0,\n completion: choice.index ?? 0,\n };\n if (typeof chunk.content !== 'string') {\n // eslint-disable-next-line no-console\n console.log(\n '[WARNING]: Received non-string content from OpenAI. This is currently not supported.'\n );\n continue;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const generationInfo: Record<string, any> = { ...newTokenIndices };\n if (choice.finish_reason != null) {\n generationInfo.finish_reason = choice.finish_reason;\n generationInfo.system_fingerprint = data.system_fingerprint;\n generationInfo.model_name = data.model;\n generationInfo.service_tier = data.service_tier;\n }\n if (this.logprobs == true) {\n generationInfo.logprobs = choice.logprobs;\n }\n const generationChunk = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n generationInfo,\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n await runManager?.handleLLMNewToken(\n generationChunk.text || '',\n newTokenIndices,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n if (usage) {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunkClass({\n content: '',\n response_metadata: {\n usage: { ...usage },\n },\n usage_metadata: {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n total_tokens: usage.total_tokens,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n },\n }),\n text: '',\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n }\n if (options.signal?.aborted === true) {\n throw new Error('AbortError');\n }\n }\n}\n"],"names":["AIMessageChunkClass"],"mappings":";;;;;AAmCM,MAAO,cAAe,SAAQ,UAAU,CAAA;AAC5C,IAAA,WAAA,CAAY,OAA2C,EAAA;AACrD,QAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO;AAClE,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,WAAW,EAAE;AACX,gBAAA,GAAG,WAAW;gBACd,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;;AAEJ,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,qBAAqB;;IAEX,qCAAqC;;IAEtD,KAA0B,EAC1B,WAA6C,EAC7C,WAMU,EAAA;AAQV,QAAA,MAAM,YAAY,GAAG,KAAK,CAAC,qCAAqC,CAC9D,KAAK,EACL,WAAW,EACX,WAAW,CACZ;AACD,QAAA,IAAI,KAAK,CAAC,SAAS,IAAI,IAAI,EAAE;YAC3B,YAAY,CAAC,iBAAiB,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS;;AAE5D,QAAA,IAAI,KAAK,CAAC,iBAAiB,IAAI,IAAI,EAAE;YACnC,YAAY,CAAC,iBAAiB,CAAC,iBAAiB;gBAC9C,KAAK,CAAC,iBAAiB;;AAE3B,QAAA,OAAO,YAAY;;IAGrB,OAAO,sBAAsB,CAC3B,QAAuB,EACvB,OAAkC,EAClC,UAAqC,EAAA;QAErC,MAAM,cAAc,GAClB,8BAA8B,CAAC,QAAQ,EAAE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AM,GAAG,CAAC,IAAI;AAChD,4BAAA,oBAAoB,EAAE,kBAAkB;yBACzC,CAAC;AACH,qBAAA;iBACF,CAAC;AACF,gBAAA,IAAI,EAAE,EAAE;AACT,aAAA,CAAC;AACF,YAAA,MAAM,eAAe;AACrB,YAAA,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACjC,gBAAA,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,KACxB,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAC3C;;;QAGL,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE;AACpC,YAAA,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC;;;AAGlC;;;;"}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../../../../src/llm/openrouter/index.ts"],"sourcesContent":["import { ChatOpenAI } from '@/llm/openai';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport { AIMessageChunk as AIMessageChunkClass } from '@langchain/core/messages';\nimport type {\n FunctionMessageChunk,\n SystemMessageChunk,\n HumanMessageChunk,\n ToolMessageChunk,\n ChatMessageChunk,\n AIMessageChunk,\n BaseMessage,\n} from '@langchain/core/messages';\nimport type {\n ChatOpenAICallOptions,\n OpenAIChatInput,\n OpenAIClient,\n} from '@langchain/openai';\nimport { _convertMessagesToOpenAIParams } from '@/llm/openai/utils';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\nexport interface ChatOpenRouterCallOptions extends ChatOpenAICallOptions {\n include_reasoning?: boolean;\n modelKwargs?: OpenAIChatInput['modelKwargs'];\n}\nexport class ChatOpenRouter extends ChatOpenAI {\n constructor(_fields: Partial<ChatOpenRouterCallOptions>) {\n const { include_reasoning, modelKwargs = {}, ...fields } = _fields;\n super({\n ...fields,\n modelKwargs: {\n ...modelKwargs,\n include_reasoning,\n },\n });\n }\n static lc_name(): 'LibreChatOpenRouter' {\n return 'LibreChatOpenRouter';\n }\n protected override _convertOpenAIDeltaToBaseMessageChunk(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>,\n rawResponse: OpenAIClient.ChatCompletionChunk,\n defaultRole?:\n | 'function'\n | 'user'\n | 'system'\n | 'developer'\n | 'assistant'\n | 'tool'\n ):\n | AIMessageChunk\n | HumanMessageChunk\n | SystemMessageChunk\n | FunctionMessageChunk\n | ToolMessageChunk\n | ChatMessageChunk {\n const messageChunk = super._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n rawResponse,\n defaultRole\n );\n if (delta.reasoning != null) {\n messageChunk.additional_kwargs.reasoning = delta.reasoning;\n }\n if (delta.reasoning_details != null) {\n messageChunk.additional_kwargs.reasoning_details =\n delta.reasoning_details;\n }\n return messageChunk;\n }\n\n async *_streamResponseChunks2(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const messagesMapped: OpenAICompletionParam[] =\n _convertMessagesToOpenAIParams(messages, this.model, {\n includeReasoningDetails: true,\n convertReasoningDetailsToContent: true,\n });\n\n const params = {\n ...this.invocationParams(options, {\n streaming: true,\n }),\n messages: messagesMapped,\n stream: true as const,\n };\n let defaultRole: OpenAIRoleEnum | undefined;\n\n const streamIterable = await this.completionWithRetry(params, options);\n let usage: OpenAIClient.Completions.CompletionUsage | undefined;\n\n // Store reasoning_details keyed by unique identifier to prevent incorrect merging\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningTextByIndex: Map<number, Record<string, any>> = new Map();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reasoningEncryptedById: Map<string, Record<string, any>> = new Map();\n\n for await (const data of streamIterable) {\n const choice = data.choices[0] as\n | Partial<OpenAIClient.Chat.Completions.ChatCompletionChunk.Choice>\n | undefined;\n if (data.usage) {\n usage = data.usage;\n }\n if (!choice) {\n continue;\n }\n\n const { delta } = choice;\n if (!delta) {\n continue;\n }\n\n // Accumulate reasoning_details from each delta\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const deltaAny = delta as Record<string, any>;\n // Extract current chunk's reasoning text for streaming (before accumulation)\n let currentChunkReasoningText = '';\n if (\n deltaAny.reasoning_details != null &&\n Array.isArray(deltaAny.reasoning_details)\n ) {\n for (const detail of deltaAny.reasoning_details) {\n // For encrypted reasoning (thought signatures), store by ID - MUST be separate\n if (detail.type === 'reasoning.encrypted' && detail.id) {\n reasoningEncryptedById.set(detail.id, {\n type: detail.type,\n id: detail.id,\n data: detail.data,\n format: detail.format,\n index: detail.index,\n });\n } else if (detail.type === 'reasoning.text') {\n // Extract current chunk's text for streaming\n currentChunkReasoningText += detail.text || '';\n // For text reasoning, accumulate text by index for final message\n const idx = detail.index ?? 0;\n const existing = reasoningTextByIndex.get(idx);\n if (existing) {\n // Only append text, keep other fields from first entry\n existing.text = (existing.text || '') + (detail.text || '');\n } else {\n reasoningTextByIndex.set(idx, {\n type: detail.type,\n text: detail.text || '',\n format: detail.format,\n index: idx,\n });\n }\n }\n }\n }\n\n const chunk = this._convertOpenAIDeltaToBaseMessageChunk(\n delta,\n data,\n defaultRole\n );\n\n // For models that send reasoning_details (Gemini style) instead of reasoning (DeepSeek style),\n // set the current chunk's reasoning text to additional_kwargs.reasoning for streaming\n if (currentChunkReasoningText && !chunk.additional_kwargs.reasoning) {\n chunk.additional_kwargs.reasoning = currentChunkReasoningText;\n }\n\n // IMPORTANT: Only set reasoning_details on the FINAL chunk to prevent\n // LangChain's chunk concatenation from corrupting the array\n // Check if this is the final chunk (has finish_reason)\n if (choice.finish_reason != null) {\n // Build properly structured reasoning_details array\n // Text entries first (but we only need the encrypted ones for thought signatures)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalReasoningDetails: Record<string, any>[] = [\n ...reasoningTextByIndex.values(),\n ...reasoningEncryptedById.values(),\n ];\n\n if (finalReasoningDetails.length > 0) {\n chunk.additional_kwargs.reasoning_details = finalReasoningDetails;\n }\n } else {\n // Clear reasoning_details from intermediate chunks to prevent concatenation issues\n delete chunk.additional_kwargs.reasoning_details;\n }\n\n defaultRole = delta.role ?? defaultRole;\n const newTokenIndices = {\n prompt: options.promptIndex ?? 0,\n completion: choice.index ?? 0,\n };\n if (typeof chunk.content !== 'string') {\n // eslint-disable-next-line no-console\n console.log(\n '[WARNING]: Received non-string content from OpenAI. This is currently not supported.'\n );\n continue;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const generationInfo: Record<string, any> = { ...newTokenIndices };\n if (choice.finish_reason != null) {\n generationInfo.finish_reason = choice.finish_reason;\n generationInfo.system_fingerprint = data.system_fingerprint;\n generationInfo.model_name = data.model;\n generationInfo.service_tier = data.service_tier;\n }\n if (this.logprobs == true) {\n generationInfo.logprobs = choice.logprobs;\n }\n const generationChunk = new ChatGenerationChunk({\n message: chunk,\n text: chunk.content,\n generationInfo,\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n await runManager?.handleLLMNewToken(\n generationChunk.text || '',\n newTokenIndices,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n if (usage) {\n const inputTokenDetails = {\n ...(usage.prompt_tokens_details?.audio_tokens != null && {\n audio: usage.prompt_tokens_details.audio_tokens,\n }),\n ...(usage.prompt_tokens_details?.cached_tokens != null && {\n cache_read: usage.prompt_tokens_details.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage.completion_tokens_details?.audio_tokens != null && {\n audio: usage.completion_tokens_details.audio_tokens,\n }),\n ...(usage.completion_tokens_details?.reasoning_tokens != null && {\n reasoning: usage.completion_tokens_details.reasoning_tokens,\n }),\n };\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunkClass({\n content: '',\n response_metadata: {\n usage: { ...usage },\n },\n usage_metadata: {\n input_tokens: usage.prompt_tokens,\n output_tokens: usage.completion_tokens,\n total_tokens: usage.total_tokens,\n ...(Object.keys(inputTokenDetails).length > 0 && {\n input_token_details: inputTokenDetails,\n }),\n ...(Object.keys(outputTokenDetails).length > 0 && {\n output_token_details: outputTokenDetails,\n }),\n },\n }),\n text: '',\n });\n yield generationChunk;\n if (this._lc_stream_delay != null) {\n await new Promise((resolve) =>\n setTimeout(resolve, this._lc_stream_delay)\n );\n }\n }\n if (options.signal?.aborted === true) {\n throw new Error('AbortError');\n }\n }\n}\n"],"names":["AIMessageChunkClass"],"mappings":";;;;;AAmCM,MAAO,cAAe,SAAQ,UAAU,CAAA;AAC5C,IAAA,WAAA,CAAY,OAA2C,EAAA;AACrD,QAAA,MAAM,EAAE,iBAAiB,EAAE,WAAW,GAAG,EAAE,EAAE,GAAG,MAAM,EAAE,GAAG,OAAO;AAClE,QAAA,KAAK,CAAC;AACJ,YAAA,GAAG,MAAM;AACT,YAAA,WAAW,EAAE;AACX,gBAAA,GAAG,WAAW;gBACd,iBAAiB;AAClB,aAAA;AACF,SAAA,CAAC;;AAEJ,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,qBAAqB;;IAEX,qCAAqC;;IAEtD,KAA0B,EAC1B,WAA6C,EAC7C,WAMU,EAAA;AAQV,QAAA,MAAM,YAAY,GAAG,KAAK,CAAC,qCAAqC,CAC9D,KAAK,EACL,WAAW,EACX,WAAW,CACZ;AACD,QAAA,IAAI,KAAK,CAAC,SAAS,IAAI,IAAI,EAAE;YAC3B,YAAY,CAAC,iBAAiB,CAAC,SAAS,GAAG,KAAK,CAAC,SAAS;;AAE5D,QAAA,IAAI,KAAK,CAAC,iBAAiB,IAAI,IAAI,EAAE;YACnC,YAAY,CAAC,iBAAiB,CAAC,iBAAiB;gBAC9C,KAAK,CAAC,iBAAiB;;AAE3B,QAAA,OAAO,YAAY;;IAGrB,OAAO,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BAAA;AACD,oBAAA,cAAc,EAAE;wBACd,YAAY,EAAE,KAAK,CAAC,aAAa;wBACjC,aAAa,EAAE,KAAK,CAAC,iBAAiB;wBACtC,YAAY,EAAE,KAAK,CAAC,YAAY;wBAChC,IAAI,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI;AAC/C,4BAAA,mBAAmB,EAAE,iBAAiB;yBACvC,CAAC;wBACF,IAAI,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI;AAChD,4BAAA,oBAAoB,EAAE,kBAAkB;yBACzC,CAAC;AACH,qBAAA;iBACF,CAAC;AACF,gBAAA,IAAI,EAAE,EAAE;AACT,aAAA,CAAC;AACF,YAAA,MAAM,eAAe;AACrB,YAAA,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,EAAE;AACjC,gBAAA,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,KACxB,UAAU,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAC3C;;;QAGL,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,EAAE;AACpC,YAAA,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC;;;AAGlC;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -57,19 +57,22 @@ function getChunkContent({ chunk, provider, reasoningKey, }) {
|
|
|
57
57
|
(chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
|
|
58
58
|
return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
|
|
59
59
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
60
|
+
/**
|
|
61
|
+
* For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).
|
|
62
|
+
* NOTE: We intentionally do NOT extract text from reasoning_details here.
|
|
63
|
+
* The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),
|
|
64
|
+
* but individual reasoning tokens are already streamed via additional_kwargs.reasoning.
|
|
65
|
+
* Extracting from reasoning_details would cause duplication.
|
|
66
|
+
* The reasoning_details is only used for:
|
|
67
|
+
* 1. Detecting reasoning mode in handleReasoning()
|
|
68
|
+
* 2. Final message storage (for thought signatures)
|
|
69
|
+
*/
|
|
70
|
+
if (provider === Providers.OPENROUTER) {
|
|
71
|
+
const reasoning = chunk?.additional_kwargs?.reasoning;
|
|
72
|
+
if (reasoning != null && reasoning !== '') {
|
|
73
|
+
return reasoning;
|
|
74
|
+
}
|
|
75
|
+
return chunk?.content;
|
|
73
76
|
}
|
|
74
77
|
return ((chunk?.additional_kwargs?.[reasoningKey] ?? '') ||
|
|
75
78
|
chunk?.content);
|
|
@@ -272,9 +275,12 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
272
275
|
reasoning_content = 'valid';
|
|
273
276
|
}
|
|
274
277
|
else if (agentContext.provider === Providers.OPENROUTER &&
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
+
// Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)
|
|
279
|
+
((chunk.additional_kwargs?.reasoning_details != null &&
|
|
280
|
+
Array.isArray(chunk.additional_kwargs.reasoning_details) &&
|
|
281
|
+
chunk.additional_kwargs.reasoning_details.length > 0) ||
|
|
282
|
+
(typeof chunk.additional_kwargs?.reasoning === 'string' &&
|
|
283
|
+
chunk.additional_kwargs.reasoning !== ''))) {
|
|
278
284
|
reasoning_content = 'valid';
|
|
279
285
|
}
|
|
280
286
|
if (reasoning_content != null &&
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n if (\n provider === Providers.OPENROUTER &&\n chunk?.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details)\n ) {\n // Extract text from reasoning_details array (for Gemini, DeepSeek, etc.)\n const textEntries = chunk.additional_kwargs.reasoning_details\n .filter(\n (detail) =>\n detail.type === 'reasoning.text' &&\n detail.text != null &&\n detail.text !== ''\n )\n .map((detail) => detail.text)\n .join('');\n if (textEntries) {\n return textEntries;\n }\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AAqBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAA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AAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport function getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n /**\n * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).\n * NOTE: We intentionally do NOT extract text from reasoning_details here.\n * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),\n * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.\n * Extracting from reasoning_details would cause duplication.\n * The reasoning_details is only used for:\n * 1. Detecting reasoning mode in handleReasoning()\n * 2. Final message storage (for thought signatures)\n */\n if (provider === Providers.OPENROUTER) {\n const reasoning = chunk?.additional_kwargs?.reasoning as string | undefined;\n if (reasoning != null && reasoning !== '') {\n return reasoning;\n }\n return chunk?.content;\n }\n return (\n ((chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ?? '') ||\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n async handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: StandardGraph\n ): Promise<void> {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const agentContext = graph.getAgentContext(metadata);\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: agentContext.reasoningKey,\n provider: agentContext.provider,\n });\n const skipHandling = await handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, agentContext);\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every(\n (tc) =>\n tc.id != null &&\n tc.id !== '' &&\n (tc as Partial<ToolCall>).name != null &&\n tc.name !== ''\n )\n ) {\n hasToolCalls = true;\n await handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n\n /** Set a preliminary message ID if found in empty chunk */\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n if (\n isEmptyChunk &&\n (chunk.id ?? '') !== '' &&\n !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')\n ) {\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n await handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n metadata,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (agentContext.currentTokenType === ContentTypes.TEXT) {\n await graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (agentContext.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n await graph.dispatchRunStep(\n newStepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n },\n metadata\n );\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n await graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n await graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n await graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n await graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n agentContext: AgentContext\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[\n agentContext.reasoningKey\n ] as string | Partial<ChatOpenAIReasoningSummary> | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (agentContext.provider === Providers.OPENAI ||\n agentContext.provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)\n ((chunk.additional_kwargs?.reasoning_details != null &&\n Array.isArray(chunk.additional_kwargs.reasoning_details) &&\n chunk.additional_kwargs.reasoning_details.length > 0) ||\n (typeof chunk.additional_kwargs?.reasoning === 'string' &&\n chunk.additional_kwargs.reasoning !== ''))\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n agentContext.tokenTypeSwitch === 'reasoning' &&\n agentContext.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.tool_call_chunks?.length ?? 0) > 0)\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n agentContext.currentTokenType = 'think_and_text';\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'content';\n } else if (\n agentContext.lastToken != null &&\n agentContext.lastToken.includes('</think>')\n ) {\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n agentContext.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart?: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n if (!contentPart) {\n console.warn('No content part found in \\'updateContent\\'');\n return;\n }\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const incomingName = contentPart.tool_call.name;\n const incomingId = contentPart.tool_call.id;\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n\n // When we receive a tool call with a name, it's the complete tool call\n // Consolidate with any previously accumulated args from chunks\n const hasValidName = incomingName != null && incomingName !== '';\n\n // Only process if incoming has a valid name (complete tool call)\n // or if we're doing a final update with complete data\n if (!hasValidName && !finalUpdate) {\n return;\n }\n\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n /** When args are a valid object, they are likely already invoked */\n let args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\n\n const id =\n getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??\n '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate | undefined;\n if (!contentPart) {\n return;\n }\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AAqBA;;;;AAIG;AACH,SAAS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