illuma-agents 1.0.37 → 1.0.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +112 -14
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +5 -1
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +148 -8
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +277 -11
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +128 -61
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +22 -7
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +140 -46
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +1 -1
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +2 -2
- package/dist/cjs/messages/tools.cjs.map +1 -1
- package/dist/cjs/schemas/validate.cjs +173 -0
- package/dist/cjs/schemas/validate.cjs.map +1 -0
- package/dist/cjs/stream.cjs +4 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +22 -21
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +101 -2
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +862 -0
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +112 -14
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +5 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +149 -9
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +278 -12
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +127 -60
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +140 -46
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +1 -1
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +2 -2
- package/dist/esm/messages/tools.mjs.map +1 -1
- package/dist/esm/schemas/validate.mjs +167 -0
- package/dist/esm/schemas/validate.mjs.map +1 -0
- package/dist/esm/stream.mjs +4 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/BrowserTools.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +22 -21
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +102 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +827 -0
- package/dist/esm/tools/ToolSearch.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +51 -1
- package/dist/types/common/enum.d.ts +6 -2
- package/dist/types/graphs/Graph.d.ts +12 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +16 -0
- package/dist/types/index.d.ts +2 -1
- package/dist/types/llm/bedrock/index.d.ts +89 -11
- package/dist/types/llm/bedrock/types.d.ts +27 -0
- package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
- package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
- package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
- package/dist/types/messages/cache.d.ts +4 -1
- package/dist/types/schemas/index.d.ts +1 -0
- package/dist/types/schemas/validate.d.ts +36 -0
- package/dist/types/tools/CodeExecutor.d.ts +0 -3
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
- package/dist/types/tools/ToolNode.d.ts +3 -1
- package/dist/types/tools/ToolSearch.d.ts +148 -0
- package/dist/types/types/graph.d.ts +71 -0
- package/dist/types/types/llm.d.ts +3 -1
- package/dist/types/types/tools.d.ts +42 -2
- package/package.json +13 -6
- package/src/agents/AgentContext.test.ts +312 -0
- package/src/agents/AgentContext.ts +144 -16
- package/src/common/enum.ts +5 -1
- package/src/graphs/Graph.ts +214 -13
- package/src/graphs/MultiAgentGraph.ts +350 -13
- package/src/index.ts +4 -1
- package/src/llm/bedrock/index.ts +221 -99
- package/src/llm/bedrock/llm.spec.ts +616 -0
- package/src/llm/bedrock/types.ts +51 -0
- package/src/llm/bedrock/utils/index.ts +18 -0
- package/src/llm/bedrock/utils/message_inputs.ts +563 -0
- package/src/llm/bedrock/utils/message_outputs.ts +310 -0
- package/src/messages/__tests__/tools.test.ts +21 -21
- package/src/messages/cache.test.ts +304 -0
- package/src/messages/cache.ts +183 -53
- package/src/messages/core.ts +1 -1
- package/src/messages/tools.ts +2 -2
- package/src/schemas/index.ts +2 -0
- package/src/schemas/validate.test.ts +358 -0
- package/src/schemas/validate.ts +238 -0
- package/src/scripts/caching.ts +27 -19
- package/src/scripts/code_exec_files.ts +58 -15
- package/src/scripts/code_exec_multi_session.ts +241 -0
- package/src/scripts/code_exec_session.ts +282 -0
- package/src/scripts/multi-agent-conditional.ts +1 -0
- package/src/scripts/multi-agent-supervisor.ts +1 -0
- package/src/scripts/programmatic_exec_agent.ts +4 -4
- package/src/scripts/test-handoff-preamble.ts +277 -0
- package/src/scripts/test-parallel-handoffs.ts +291 -0
- package/src/scripts/test-tools-before-handoff.ts +8 -4
- package/src/scripts/test_code_api.ts +361 -0
- package/src/scripts/thinking-bedrock.ts +159 -0
- package/src/scripts/thinking.ts +39 -18
- package/src/scripts/{tool_search_regex.ts → tool_search.ts} +5 -5
- package/src/scripts/tools.ts +7 -3
- package/src/specs/cache.simple.test.ts +396 -0
- package/src/stream.ts +4 -2
- package/src/tools/BrowserTools.ts +39 -17
- package/src/tools/CodeExecutor.ts +26 -23
- package/src/tools/ProgrammaticToolCalling.ts +18 -14
- package/src/tools/ToolNode.ts +114 -1
- package/src/tools/ToolSearch.ts +1041 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
- package/src/tools/__tests__/{ToolSearchRegex.integration.test.ts → ToolSearch.integration.test.ts} +6 -6
- package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
- package/src/types/graph.test.ts +183 -0
- package/src/types/graph.ts +73 -0
- package/src/types/llm.ts +3 -1
- package/src/types/tools.ts +51 -2
- package/dist/cjs/tools/ToolSearchRegex.cjs +0 -455
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +0 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +0 -448
- package/dist/esm/tools/ToolSearchRegex.mjs.map +0 -1
- package/dist/types/tools/ToolSearchRegex.d.ts +0 -80
- package/src/tools/ToolSearchRegex.ts +0 -535
- package/src/tools/__tests__/ToolSearchRegex.test.ts +0 -232
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ToolSearch.mjs","sources":["../../../src/tools/ToolSearch.ts"],"sourcesContent":["// src/tools/ToolSearch.ts\nimport { z } from 'zod';\nimport * as okapibm25Module from 'okapibm25';\nimport { config } from 'dotenv';\n\ntype BM25Fn = (\n documents: string[],\n keywords: string[],\n constants?: { k1?: number; b?: number }\n) => number[];\n\nfunction getBM25Function(): BM25Fn {\n const mod = okapibm25Module as unknown as {\n default: BM25Fn | { default: BM25Fn } | undefined;\n };\n if (typeof mod === 'function') return mod;\n if (typeof mod.default === 'function') return mod.default;\n if (mod.default != null && typeof mod.default.default === 'function')\n return mod.default.default;\n throw new Error('Could not resolve BM25 function from okapibm25 module');\n}\n\nconst BM25 = getBM25Function();\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 * as t from '@/types';\nimport { getCodeBaseURL } from './CodeExecutor';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\n/** Maximum allowed regex pattern length */\nconst MAX_PATTERN_LENGTH = 200;\n\n/** Maximum allowed regex nesting depth */\nconst MAX_REGEX_COMPLEXITY = 5;\n\n/** Default search timeout in milliseconds */\nconst SEARCH_TIMEOUT = 5000;\n\n/** Zod schema type for tool search parameters */\ntype ToolSearchSchema = z.ZodObject<{\n query: z.ZodDefault<z.ZodOptional<z.ZodString>>;\n fields: z.ZodDefault<\n z.ZodOptional<z.ZodArray<z.ZodEnum<['name', 'description', 'parameters']>>>\n >;\n max_results: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;\n mcp_server: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>>;\n}>;\n\n/**\n * Creates the Zod schema with dynamic query description based on mode.\n * @param mode - The search mode determining query interpretation\n * @returns Zod schema for tool search parameters\n */\nfunction createToolSearchSchema(mode: t.ToolSearchMode): ToolSearchSchema {\n const queryDescription =\n mode === 'local'\n ? 'Search term to find in tool names and descriptions. Case-insensitive substring matching. Optional if mcp_server is provided.'\n : 'Regex pattern to search tool names and descriptions. Optional if mcp_server is provided.';\n\n return z.object({\n query: z\n .string()\n .max(MAX_PATTERN_LENGTH)\n .optional()\n .default('')\n .describe(queryDescription),\n fields: z\n .array(z.enum(['name', 'description', 'parameters']))\n .optional()\n .default(['name', 'description'])\n .describe('Which fields to search. Default: name and description'),\n max_results: z\n .number()\n .int()\n .min(1)\n .max(50)\n .optional()\n .default(10)\n .describe('Maximum number of matching tools to return'),\n mcp_server: z\n .union([z.string(), z.array(z.string())])\n .optional()\n .describe(\n 'Filter to tools from specific MCP server(s). Can be a single server name or array of names. If provided without a query, lists all tools from those servers.'\n ),\n });\n}\n\n/**\n * Extracts the MCP server name from a tool name.\n * MCP tools follow the pattern: toolName_mcp_serverName\n * @param toolName - The full tool name\n * @returns The server name if it's an MCP tool, undefined otherwise\n */\nfunction extractMcpServerName(toolName: string): string | undefined {\n const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);\n if (delimiterIndex === -1) {\n return undefined;\n }\n return toolName.substring(delimiterIndex + Constants.MCP_DELIMITER.length);\n}\n\n/**\n * Checks if a tool belongs to a specific MCP server.\n * @param toolName - The full tool name\n * @param serverName - The server name to match\n * @returns True if the tool belongs to the specified server\n */\nfunction isFromMcpServer(toolName: string, serverName: string): boolean {\n const toolServer = extractMcpServerName(toolName);\n return toolServer === serverName;\n}\n\n/**\n * Checks if a tool belongs to any of the specified MCP servers.\n * @param toolName - The full tool name\n * @param serverNames - Array of server names to match\n * @returns True if the tool belongs to any of the specified servers\n */\nfunction isFromAnyMcpServer(toolName: string, serverNames: string[]): boolean {\n const toolServer = extractMcpServerName(toolName);\n if (toolServer === undefined) {\n return false;\n }\n return serverNames.includes(toolServer);\n}\n\n/**\n * Normalizes server filter input to always be an array.\n * @param serverFilter - String, array of strings, or undefined\n * @returns Array of server names (empty if none specified)\n */\nfunction normalizeServerFilter(\n serverFilter: string | string[] | undefined\n): string[] {\n if (serverFilter === undefined) {\n return [];\n }\n if (typeof serverFilter === 'string') {\n return serverFilter === '' ? [] : [serverFilter];\n }\n return serverFilter.filter((s) => s !== '');\n}\n\n/**\n * Extracts all unique MCP server names from a tool registry.\n * @param toolRegistry - The tool registry to scan\n * @param onlyDeferred - If true, only considers deferred tools\n * @returns Array of unique server names, sorted alphabetically\n */\nfunction getAvailableMcpServers(\n toolRegistry: t.LCToolRegistry | undefined,\n onlyDeferred: boolean = true\n): string[] {\n if (!toolRegistry) {\n return [];\n }\n\n const servers = new Set<string>();\n for (const [, toolDef] of toolRegistry) {\n if (onlyDeferred && toolDef.defer_loading !== true) {\n continue;\n }\n const server = extractMcpServerName(toolDef.name);\n if (server !== undefined && server !== '') {\n servers.add(server);\n }\n }\n\n return Array.from(servers).sort();\n}\n\n/**\n * Escapes special regex characters in a string to use as a literal pattern.\n * @param pattern - The string to escape\n * @returns The escaped string safe for use in a RegExp\n */\nfunction escapeRegexSpecialChars(pattern: string): string {\n return pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Counts the maximum nesting depth of groups in a regex pattern.\n * @param pattern - The regex pattern to analyze\n * @returns The maximum nesting depth\n */\nfunction countNestedGroups(pattern: string): number {\n let maxDepth = 0;\n let currentDepth = 0;\n\n for (let i = 0; i < pattern.length; i++) {\n if (pattern[i] === '(' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth++;\n maxDepth = Math.max(maxDepth, currentDepth);\n } else if (pattern[i] === ')' && (i === 0 || pattern[i - 1] !== '\\\\')) {\n currentDepth = Math.max(0, currentDepth - 1);\n }\n }\n\n return maxDepth;\n}\n\n/**\n * Detects nested quantifiers that can cause catastrophic backtracking.\n * Patterns like (a+)+, (a*)*, (a+)*, etc.\n * @param pattern - The regex pattern to check\n * @returns True if nested quantifiers are detected\n */\nfunction hasNestedQuantifiers(pattern: string): boolean {\n const nestedQuantifierPattern = /\\([^)]*[+*][^)]*\\)[+*?]/;\n return nestedQuantifierPattern.test(pattern);\n}\n\n/**\n * Checks if a regex pattern contains potentially dangerous constructs.\n * @param pattern - The regex pattern to validate\n * @returns True if the pattern is dangerous\n */\nfunction isDangerousPattern(pattern: string): boolean {\n if (hasNestedQuantifiers(pattern)) {\n return true;\n }\n\n if (countNestedGroups(pattern) > MAX_REGEX_COMPLEXITY) {\n return true;\n }\n\n const dangerousPatterns = [\n /\\.\\{1000,\\}/, // Excessive wildcards\n /\\(\\?=\\.\\{100,\\}\\)/, // Runaway lookaheads\n /\\([^)]*\\|\\s*\\){20,}/, // Excessive alternation (rough check)\n /\\(\\.\\*\\)\\+/, // (.*)+\n /\\(\\.\\+\\)\\+/, // (.+)+\n /\\(\\.\\*\\)\\*/, // (.*)*\n /\\(\\.\\+\\)\\*/, // (.+)*\n ];\n\n for (const dangerous of dangerousPatterns) {\n if (dangerous.test(pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Sanitizes a regex pattern for safe execution.\n * If the pattern is dangerous, it will be escaped to a literal string search.\n * @param pattern - The regex pattern to sanitize\n * @returns Object containing the safe pattern and whether it was escaped\n */\nfunction sanitizeRegex(pattern: string): { safe: string; wasEscaped: boolean } {\n if (isDangerousPattern(pattern)) {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n\n try {\n new RegExp(pattern);\n return { safe: pattern, wasEscaped: false };\n } catch {\n return {\n safe: escapeRegexSpecialChars(pattern),\n wasEscaped: true,\n };\n }\n}\n\n/**\n * Simplifies tool parameters for search purposes.\n * Extracts only the essential structure needed for parameter name searching.\n * @param parameters - The tool's JSON schema parameters\n * @returns Simplified parameters object\n */\nfunction simplifyParametersForSearch(\n parameters?: t.JsonSchemaType\n): t.JsonSchemaType | undefined {\n if (!parameters) {\n return undefined;\n }\n\n if (parameters.properties) {\n return {\n type: parameters.type,\n properties: Object.fromEntries(\n Object.entries(parameters.properties).map(([key, value]) => [\n key,\n { type: (value as t.JsonSchemaType).type },\n ])\n ),\n } as t.JsonSchemaType;\n }\n\n return { type: parameters.type };\n}\n\n/**\n * Tokenizes a string into lowercase words for BM25.\n * Splits on underscores and non-alphanumeric characters for consistent matching.\n * @param text - The text to tokenize\n * @returns Array of lowercase tokens\n */\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]/g, ' ')\n .split(/\\s+/)\n .filter((token) => token.length > 0);\n}\n\n/**\n * Creates a searchable document string from tool metadata.\n * @param tool - The tool metadata\n * @param fields - Which fields to include\n * @returns Combined document string for BM25\n */\nfunction createToolDocument(tool: t.ToolMetadata, fields: string[]): string {\n const parts: string[] = [];\n\n if (fields.includes('name')) {\n const baseName = tool.name.replace(/_/g, ' ');\n parts.push(baseName, baseName);\n }\n\n if (fields.includes('description') && tool.description) {\n parts.push(tool.description);\n }\n\n if (fields.includes('parameters') && tool.parameters?.properties) {\n const paramNames = Object.keys(tool.parameters.properties).join(' ');\n parts.push(paramNames);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Determines which field had the best match for a query.\n * @param tool - The tool to check\n * @param queryTokens - Tokenized query\n * @param fields - Fields to check\n * @returns The matched field and a snippet\n */\nfunction findMatchedField(\n tool: t.ToolMetadata,\n queryTokens: string[],\n fields: string[]\n): { field: string; snippet: string } {\n if (fields.includes('name')) {\n const nameLower = tool.name.toLowerCase();\n for (const token of queryTokens) {\n if (nameLower.includes(token)) {\n return { field: 'name', snippet: tool.name };\n }\n }\n }\n\n if (fields.includes('description') && tool.description) {\n const descLower = tool.description.toLowerCase();\n for (const token of queryTokens) {\n if (descLower.includes(token)) {\n return {\n field: 'description',\n snippet: tool.description.substring(0, 100),\n };\n }\n }\n }\n\n if (fields.includes('parameters') && tool.parameters?.properties) {\n const paramNames = Object.keys(tool.parameters.properties);\n const paramLower = paramNames.join(' ').toLowerCase();\n for (const token of queryTokens) {\n if (paramLower.includes(token)) {\n return { field: 'parameters', snippet: paramNames.join(', ') };\n }\n }\n }\n\n const fallbackSnippet = tool.description\n ? tool.description.substring(0, 100)\n : tool.name;\n return { field: 'unknown', snippet: fallbackSnippet };\n}\n\n/**\n * Performs BM25-based search for better relevance ranking.\n * Uses Okapi BM25 algorithm for term frequency and document length normalization.\n * @param tools - Array of tool metadata to search\n * @param query - The search query\n * @param fields - Which fields to search\n * @param maxResults - Maximum results to return\n * @returns Search response with matching tools ranked by BM25 score\n */\nfunction performLocalSearch(\n tools: t.ToolMetadata[],\n query: string,\n fields: string[],\n maxResults: number\n): t.ToolSearchResponse {\n if (tools.length === 0 || !query.trim()) {\n return {\n tool_references: [],\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n }\n\n const documents = tools.map((tool) => createToolDocument(tool, fields));\n const queryTokens = tokenize(query);\n\n if (queryTokens.length === 0) {\n return {\n tool_references: [],\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n }\n\n const scores = BM25(documents, queryTokens, { k1: 1.5, b: 0.75 }) as number[];\n\n const maxScore = Math.max(...scores.filter((s) => s > 0), 1);\n const queryLower = query.toLowerCase().trim();\n\n const results: t.ToolSearchResult[] = [];\n for (let i = 0; i < tools.length; i++) {\n if (scores[i] > 0) {\n const { field, snippet } = findMatchedField(\n tools[i],\n queryTokens,\n fields\n );\n let normalizedScore = Math.min(scores[i] / maxScore, 1.0);\n\n // Boost score for exact base name match\n const baseName = getBaseToolName(tools[i].name).toLowerCase();\n if (baseName === queryLower) {\n normalizedScore = 1.0;\n } else if (baseName.startsWith(queryLower)) {\n normalizedScore = Math.max(normalizedScore, 0.95);\n }\n\n results.push({\n tool_name: tools[i].name,\n match_score: normalizedScore,\n matched_field: field,\n snippet,\n });\n }\n }\n\n results.sort((a, b) => b.match_score - a.match_score);\n const topResults = results.slice(0, maxResults);\n\n return {\n tool_references: topResults,\n total_tools_searched: tools.length,\n pattern_used: query,\n };\n}\n\n/**\n * Generates the JavaScript search script to be executed in the sandbox.\n * Uses plain JavaScript for maximum compatibility with the Code API.\n * @param deferredTools - Array of tool metadata to search through\n * @param fields - Which fields to search\n * @param maxResults - Maximum number of results to return\n * @param sanitizedPattern - The sanitized regex pattern\n * @returns The JavaScript code string\n */\nfunction generateSearchScript(\n deferredTools: t.ToolMetadata[],\n fields: string[],\n maxResults: number,\n sanitizedPattern: string\n): string {\n const lines = [\n '// Tool definitions (injected)',\n 'var tools = ' + JSON.stringify(deferredTools) + ';',\n 'var searchFields = ' + JSON.stringify(fields) + ';',\n 'var maxResults = ' + maxResults + ';',\n 'var pattern = ' + JSON.stringify(sanitizedPattern) + ';',\n '',\n '// Compile regex (pattern is sanitized client-side)',\n 'var regex;',\n 'try {',\n ' regex = new RegExp(pattern, \\'i\\');',\n '} catch (e) {',\n ' regex = new RegExp(pattern.replace(/[.*+?^${}()[\\\\]\\\\\\\\|]/g, \"\\\\\\\\$&\"), \"i\");',\n '}',\n '',\n '// Search logic',\n 'var results = [];',\n '',\n 'for (var j = 0; j < tools.length; j++) {',\n ' var tool = tools[j];',\n ' var bestScore = 0;',\n ' var matchedField = \\'\\';',\n ' var snippet = \\'\\';',\n '',\n ' // Search name (highest priority)',\n ' if (searchFields.indexOf(\\'name\\') >= 0 && regex.test(tool.name)) {',\n ' bestScore = 0.95;',\n ' matchedField = \\'name\\';',\n ' snippet = tool.name;',\n ' }',\n '',\n ' // Search description (medium priority)',\n ' if (searchFields.indexOf(\\'description\\') >= 0 && tool.description && regex.test(tool.description)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.75;',\n ' matchedField = \\'description\\';',\n ' snippet = tool.description.substring(0, 100);',\n ' }',\n ' }',\n '',\n ' // Search parameter names (lower priority)',\n ' if (searchFields.indexOf(\\'parameters\\') >= 0 && tool.parameters && tool.parameters.properties) {',\n ' var paramNames = Object.keys(tool.parameters.properties).join(\\' \\');',\n ' if (regex.test(paramNames)) {',\n ' if (bestScore === 0) {',\n ' bestScore = 0.60;',\n ' matchedField = \\'parameters\\';',\n ' snippet = paramNames;',\n ' }',\n ' }',\n ' }',\n '',\n ' if (bestScore > 0) {',\n ' results.push({',\n ' tool_name: tool.name,',\n ' match_score: bestScore,',\n ' matched_field: matchedField,',\n ' snippet: snippet',\n ' });',\n ' }',\n '}',\n '',\n '// Sort by score (descending) and limit results',\n 'results.sort(function(a, b) { return b.match_score - a.match_score; });',\n 'var topResults = results.slice(0, maxResults);',\n '',\n '// Output as JSON',\n 'console.log(JSON.stringify({',\n ' tool_references: topResults.map(function(r) {',\n ' return {',\n ' tool_name: r.tool_name,',\n ' match_score: r.match_score,',\n ' matched_field: r.matched_field,',\n ' snippet: r.snippet',\n ' };',\n ' }),',\n ' total_tools_searched: tools.length,',\n ' pattern_used: pattern',\n '}));',\n ];\n return lines.join('\\n');\n}\n\n/**\n * Parses the search results from stdout JSON.\n * @param stdout - The stdout string containing JSON results\n * @returns Parsed search response\n */\nfunction parseSearchResults(stdout: string): t.ToolSearchResponse {\n const jsonMatch = stdout.trim();\n const parsed = JSON.parse(jsonMatch) as t.ToolSearchResponse;\n return parsed;\n}\n\n/**\n * Formats search results as structured JSON for efficient parsing.\n * @param searchResponse - The parsed search response\n * @returns JSON string with search results\n */\nfunction formatSearchResults(searchResponse: t.ToolSearchResponse): string {\n const { tool_references, total_tools_searched, pattern_used } =\n searchResponse;\n\n const output = {\n found: tool_references.length,\n tools: tool_references.map((ref) => ({\n name: ref.tool_name,\n score: Number(ref.match_score.toFixed(2)),\n matched_in: ref.matched_field,\n snippet: ref.snippet,\n })),\n total_searched: total_tools_searched,\n query: pattern_used,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Extracts the base tool name (without MCP server suffix) from a full tool name.\n * @param toolName - The full tool name\n * @returns The base tool name without server suffix\n */\nfunction getBaseToolName(toolName: string): string {\n const delimiterIndex = toolName.indexOf(Constants.MCP_DELIMITER);\n if (delimiterIndex === -1) {\n return toolName;\n }\n return toolName.substring(0, delimiterIndex);\n}\n\n/**\n * Generates a compact listing of deferred tools grouped by server.\n * Format: \"server: tool1, tool2, tool3\"\n * Non-MCP tools are grouped under \"other\".\n * @param toolRegistry - The tool registry\n * @param onlyDeferred - Whether to only include deferred tools\n * @returns Formatted string with tools grouped by server\n */\nfunction getDeferredToolsListing(\n toolRegistry: t.LCToolRegistry | undefined,\n onlyDeferred: boolean\n): string {\n if (!toolRegistry) {\n return '';\n }\n\n const toolsByServer: Record<string, string[]> = {};\n\n for (const lcTool of toolRegistry.values()) {\n if (onlyDeferred && lcTool.defer_loading !== true) {\n continue;\n }\n\n const toolName = lcTool.name;\n const serverName = extractMcpServerName(toolName) ?? 'other';\n const baseName = getBaseToolName(toolName);\n\n if (!(serverName in toolsByServer)) {\n toolsByServer[serverName] = [];\n }\n toolsByServer[serverName].push(baseName);\n }\n\n const serverNames = Object.keys(toolsByServer).sort((a, b) => {\n if (a === 'other') return 1;\n if (b === 'other') return -1;\n return a.localeCompare(b);\n });\n\n if (serverNames.length === 0) {\n return '';\n }\n\n const lines = serverNames.map(\n (server) => `${server}: ${toolsByServer[server].join(', ')}`\n );\n\n return lines.join('\\n');\n}\n\n/**\n * Formats a server listing response as structured JSON.\n * NOTE: This is a PREVIEW only - tools are NOT discovered/loaded.\n * @param tools - Array of tool metadata from the server(s)\n * @param serverNames - The MCP server name(s)\n * @returns JSON string showing all tools grouped by server\n */\nfunction formatServerListing(\n tools: t.ToolMetadata[],\n serverNames: string | string[]\n): string {\n const servers = Array.isArray(serverNames) ? serverNames : [serverNames];\n\n if (tools.length === 0) {\n return JSON.stringify(\n {\n listing_mode: true,\n servers,\n total_tools: 0,\n tools_by_server: {},\n hint: 'No tools found from the specified MCP server(s).',\n },\n null,\n 2\n );\n }\n\n const toolsByServer: Record<\n string,\n Array<{ name: string; description: string }>\n > = {};\n for (const tool of tools) {\n const server = extractMcpServerName(tool.name) ?? 'unknown';\n if (!(server in toolsByServer)) {\n toolsByServer[server] = [];\n }\n toolsByServer[server].push({\n name: getBaseToolName(tool.name),\n description:\n tool.description.length > 100\n ? tool.description.substring(0, 97) + '...'\n : tool.description,\n });\n }\n\n const output = {\n listing_mode: true,\n servers,\n total_tools: tools.length,\n tools_by_server: toolsByServer,\n hint: `To use a tool, search for it by name (e.g., query: \"${getBaseToolName(tools[0]?.name ?? 'tool_name')}\") to load it.`,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\n/**\n * Creates a Tool Search tool for discovering tools from a large registry.\n *\n * This tool enables AI agents to dynamically discover tools from a large library\n * without loading all tool definitions into the LLM context window. The agent\n * can search for relevant tools on-demand.\n *\n * **Modes:**\n * - `code_interpreter` (default): Uses external sandbox for regex search. Safer for complex patterns.\n * - `local`: Uses safe substring matching locally. No network call, faster, completely safe from ReDoS.\n *\n * The tool registry can be provided either:\n * 1. At initialization time via params.toolRegistry\n * 2. At runtime via config.configurable.toolRegistry when invoking\n *\n * @param params - Configuration parameters for the tool (toolRegistry is optional)\n * @returns A LangChain DynamicStructuredTool for tool searching\n *\n * @example\n * // Option 1: Code interpreter mode (regex via sandbox)\n * const tool = createToolSearch({ apiKey, toolRegistry });\n * await tool.invoke({ query: 'expense.*report' });\n *\n * @example\n * // Option 2: Local mode (safe substring search, no API key needed)\n * const tool = createToolSearch({ mode: 'local', toolRegistry });\n * await tool.invoke({ query: 'expense' });\n */\nfunction createToolSearch(\n initParams: t.ToolSearchParams = {}\n): DynamicStructuredTool<ReturnType<typeof createToolSearchSchema>> {\n const mode: t.ToolSearchMode = initParams.mode ?? 'code_interpreter';\n const defaultOnlyDeferred = initParams.onlyDeferred ?? true;\n const schema = createToolSearchSchema(mode);\n\n const apiKey: string =\n mode === 'code_interpreter'\n ? ((initParams[EnvVar.CODE_API_KEY] as string | undefined) ??\n initParams.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '')\n : '';\n\n if (mode === 'code_interpreter' && !apiKey) {\n throw new Error(\n 'No API key provided for tool search in code_interpreter mode. Use mode: \"local\" to search without an API key.'\n );\n }\n\n const baseEndpoint = initParams.baseUrl ?? getCodeBaseURL();\n const EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\n const deferredToolsListing = getDeferredToolsListing(\n initParams.toolRegistry,\n defaultOnlyDeferred\n );\n\n const toolsListSection =\n deferredToolsListing.length > 0\n ? `\n\nDeferred tools (search to load):\n${deferredToolsListing}`\n : '';\n\n const mcpNote =\n deferredToolsListing.includes(Constants.MCP_DELIMITER) ||\n deferredToolsListing.split('\\n').some((line) => !line.startsWith('other:'))\n ? `\n- MCP tools use format: toolName${Constants.MCP_DELIMITER}serverName\n- Use mcp_server param to filter by server`\n : '';\n\n const description =\n mode === 'local'\n ? `\nSearches deferred tools using BM25 ranking. Multi-word queries supported.\n${mcpNote}${toolsListSection}\n`.trim()\n : `\nSearches deferred tools by regex pattern.\n${mcpNote}${toolsListSection}\n`.trim();\n\n return tool<typeof schema>(\n async (params, config) => {\n const {\n query,\n fields = ['name', 'description'],\n max_results = 10,\n mcp_server,\n } = params;\n\n const {\n toolRegistry: paramToolRegistry,\n onlyDeferred: paramOnlyDeferred,\n mcpServer: paramMcpServer,\n } = config.toolCall ?? {};\n\n const toolRegistry = paramToolRegistry ?? initParams.toolRegistry;\n const onlyDeferred =\n paramOnlyDeferred !== undefined\n ? paramOnlyDeferred\n : defaultOnlyDeferred;\n const rawServerFilter =\n mcp_server ?? paramMcpServer ?? initParams.mcpServer;\n const serverFilters = normalizeServerFilter(rawServerFilter);\n const hasServerFilter = serverFilters.length > 0;\n\n if (toolRegistry == null) {\n return [\n 'Error: No tool registry provided. Configure toolRegistry at agent level or initialization.',\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: query,\n error: 'No tool registry provided',\n },\n },\n ];\n }\n\n const toolsArray: t.LCTool[] = Array.from(toolRegistry.values());\n const deferredTools: t.ToolMetadata[] = toolsArray\n .filter((lcTool) => {\n if (onlyDeferred === true && lcTool.defer_loading !== true) {\n return false;\n }\n if (\n hasServerFilter &&\n !isFromAnyMcpServer(lcTool.name, serverFilters)\n ) {\n return false;\n }\n return true;\n })\n .map((lcTool) => ({\n name: lcTool.name,\n description: lcTool.description ?? '',\n parameters: simplifyParametersForSearch(lcTool.parameters),\n }));\n\n if (deferredTools.length === 0) {\n const serverMsg = hasServerFilter\n ? ` from MCP server(s): ${serverFilters.join(', ')}`\n : '';\n return [\n `No tools available to search${serverMsg}. The tool registry is empty or no matching deferred tools are registered.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: query,\n mcp_server: serverFilters,\n },\n },\n ];\n }\n\n const isServerListing = hasServerFilter && query === '';\n\n if (isServerListing) {\n const formattedOutput = formatServerListing(\n deferredTools,\n serverFilters\n );\n\n return [\n formattedOutput,\n {\n tool_references: [],\n metadata: {\n total_available: deferredTools.length,\n mcp_server: serverFilters,\n listing_mode: true,\n },\n },\n ];\n }\n\n if (mode === 'local') {\n const searchResponse = performLocalSearch(\n deferredTools,\n query,\n fields,\n max_results\n );\n const formattedOutput = formatSearchResults(searchResponse);\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n mcp_server: serverFilters.length > 0 ? serverFilters : undefined,\n },\n },\n ];\n }\n\n const { safe: sanitizedPattern, wasEscaped } = sanitizeRegex(query);\n let warningMessage = '';\n if (wasEscaped) {\n warningMessage =\n 'Note: The provided pattern was converted to a literal search for safety.\\n\\n';\n }\n\n const searchScript = generateSearchScript(\n deferredTools,\n fields,\n max_results,\n sanitizedPattern\n );\n\n const postData = {\n lang: 'js',\n code: searchScript,\n timeout: SEARCH_TIMEOUT,\n };\n\n try {\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(postData),\n };\n\n if (process.env.PROXY != null && process.env.PROXY !== '') {\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\n }\n\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n const result: t.ExecuteResult = await response.json();\n\n if (result.stderr && result.stderr.trim()) {\n // eslint-disable-next-line no-console\n console.warn('[ToolSearch] stderr:', result.stderr);\n }\n\n if (!result.stdout || !result.stdout.trim()) {\n return [\n `${warningMessage}No tools matched the pattern \"${sanitizedPattern}\".\\nTotal tools searched: ${deferredTools.length}`,\n {\n tool_references: [],\n metadata: {\n total_searched: deferredTools.length,\n pattern: sanitizedPattern,\n },\n },\n ];\n }\n\n const searchResponse = parseSearchResults(result.stdout);\n const formattedOutput = `${warningMessage}${formatSearchResults(searchResponse)}`;\n\n return [\n formattedOutput,\n {\n tool_references: searchResponse.tool_references,\n metadata: {\n total_searched: searchResponse.total_tools_searched,\n pattern: searchResponse.pattern_used,\n },\n },\n ];\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('[ToolSearch] Error:', error);\n\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n return [\n `Tool search failed: ${errorMessage}\\n\\nSuggestion: Try a simpler search pattern or search for specific tool names.`,\n {\n tool_references: [],\n metadata: {\n total_searched: 0,\n pattern: sanitizedPattern,\n error: errorMessage,\n },\n },\n ];\n }\n },\n {\n name: Constants.TOOL_SEARCH,\n description,\n schema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport {\n createToolSearch,\n performLocalSearch,\n extractMcpServerName,\n isFromMcpServer,\n isFromAnyMcpServer,\n normalizeServerFilter,\n getAvailableMcpServers,\n getDeferredToolsListing,\n getBaseToolName,\n formatServerListing,\n sanitizeRegex,\n escapeRegexSpecialChars,\n isDangerousPattern,\n countNestedGroups,\n hasNestedQuantifiers,\n};\n"],"names":[],"mappings":";;;;;;;;;;AAAA;AAWA,SAAS,eAAe,GAAA;IACtB,MAAM,GAAG,GAAG,eAEX;IACD,IAAI,OAAO,GAAG,KAAK,UAAU;AAAE,QAAA,OAAO,GAAG;AACzC,IAAA,IAAI,OAAO,GAAG,CAAC,OAAO,KAAK,UAAU;QAAE,OAAO,GAAG,CAAC,OAAO;AACzD,IAAA,IAAI,GAAG,CAAC,OAAO,IAAI,IAAI,IAAI,OAAO,GAAG,CAAC,OAAO,CAAC,OAAO,KAAK,UAAU;AAClE,QAAA,OAAO,GAAG,CAAC,OAAO,CAAC,OAAO;AAC5B,IAAA,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC;AAC1E;AAEA,MAAM,IAAI,GAAG,eAAe,EAAE;AAS9B,MAAM,EAAE;AAER;AACA,MAAM,kBAAkB,GAAG,GAAG;AAE9B;AACA,MAAM,oBAAoB,GA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AAC,eAAe;AAC/C,oBAAA,QAAQ,EAAE;wBACR,cAAc,EAAE,cAAc,CAAC,oBAAoB;wBACnD,OAAO,EAAE,cAAc,CAAC,YAAY;AACrC,qBAAA;AACF,iBAAA;aACF;;QACD,OAAO,KAAK,EAAE;;AAEd,YAAA,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC;AAE3C,YAAA,MAAM,YAAY,GAChB,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;YACxD,OAAO;AACL,gBAAA,CAAA,oBAAA,EAAuB,YAAY,CAAiF,+EAAA,CAAA;AACpH,gBAAA;AACE,oBAAA,eAAe,EAAE,EAAE;AACnB,oBAAA,QAAQ,EAAE;AACR,wBAAA,cAAc,EAAE,CAAC;AACjB,wBAAA,OAAO,EAAE,gBAAgB;AACzB,wBAAA,KAAK,EAAE,YAAY;AACpB,qBAAA;AACF,iBAAA;aACF;;AAEL,KAAC,EACD;QACE,IAAI,EAAE,SAAS,CAAC,WAAW;QAC3B,WAAW;QACX,MAAM;QACN,cAAc,EAAE,SAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;"}
|
|
@@ -14,6 +14,8 @@ export declare class AgentContext {
|
|
|
14
14
|
static fromConfig(agentConfig: t.AgentInputs, tokenCounter?: t.TokenCounter, indexTokenCountMap?: Record<string, number>): AgentContext;
|
|
15
15
|
/** Agent identifier */
|
|
16
16
|
agentId: string;
|
|
17
|
+
/** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */
|
|
18
|
+
name?: string;
|
|
17
19
|
/** Provider for this specific agent */
|
|
18
20
|
provider: Providers;
|
|
19
21
|
/** Client options for this agent */
|
|
@@ -81,8 +83,25 @@ export declare class AgentContext {
|
|
|
81
83
|
private toolTokensTotal;
|
|
82
84
|
/** Per-prompt token breakdown for detailed admin reporting */
|
|
83
85
|
private promptBreakdown;
|
|
84
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Handoff context when this agent receives control via handoff.
|
|
88
|
+
* Contains source and parallel execution info for system message context.
|
|
89
|
+
*/
|
|
90
|
+
handoffContext?: {
|
|
91
|
+
/** Source agent that transferred control */
|
|
92
|
+
sourceAgentName: string;
|
|
93
|
+
/** Names of sibling agents executing in parallel (empty if sequential) */
|
|
94
|
+
parallelSiblings: string[];
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Structured output configuration.
|
|
98
|
+
* When set, the agent will return a validated JSON response
|
|
99
|
+
* instead of streaming text.
|
|
100
|
+
*/
|
|
101
|
+
structuredOutput?: t.StructuredOutputConfig;
|
|
102
|
+
constructor({ agentId, name, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, }: {
|
|
85
103
|
agentId: string;
|
|
104
|
+
name?: string;
|
|
86
105
|
provider: Providers;
|
|
87
106
|
clientOptions?: t.ClientOptions;
|
|
88
107
|
maxContextTokens?: number;
|
|
@@ -98,7 +117,19 @@ export declare class AgentContext {
|
|
|
98
117
|
toolEnd?: boolean;
|
|
99
118
|
instructionTokens?: number;
|
|
100
119
|
useLegacyContent?: boolean;
|
|
120
|
+
structuredOutput?: t.StructuredOutputConfig;
|
|
101
121
|
});
|
|
122
|
+
/**
|
|
123
|
+
* Checks if structured output mode is enabled for this agent.
|
|
124
|
+
* When enabled, the agent will use model.invoke() instead of streaming
|
|
125
|
+
* and return a validated JSON response.
|
|
126
|
+
*/
|
|
127
|
+
get isStructuredOutputMode(): boolean;
|
|
128
|
+
/**
|
|
129
|
+
* Gets the structured output schema with normalized defaults.
|
|
130
|
+
* Returns undefined if structured output is not configured.
|
|
131
|
+
*/
|
|
132
|
+
getStructuredOutputSchema(): Record<string, unknown> | undefined;
|
|
102
133
|
/**
|
|
103
134
|
* Builds instructions text for tools that are ONLY callable via programmatic code execution.
|
|
104
135
|
* These tools cannot be called directly by the LLM but are available through the
|
|
@@ -122,8 +153,14 @@ export declare class AgentContext {
|
|
|
122
153
|
initializeSystemRunnable(): void;
|
|
123
154
|
/**
|
|
124
155
|
* Builds the raw instructions string (without creating SystemMessage).
|
|
156
|
+
* Includes agent identity preamble and handoff context when available.
|
|
125
157
|
*/
|
|
126
158
|
private buildInstructionsString;
|
|
159
|
+
/**
|
|
160
|
+
* Builds the agent identity preamble including handoff context if present.
|
|
161
|
+
* This helps the agent understand its role in the multi-agent workflow.
|
|
162
|
+
*/
|
|
163
|
+
private buildIdentityPreamble;
|
|
127
164
|
/**
|
|
128
165
|
* Build system runnable from pre-built instructions string.
|
|
129
166
|
* Only called when content has actually changed.
|
|
@@ -191,6 +228,19 @@ export declare class AgentContext {
|
|
|
191
228
|
* @returns LCToolRegistry with tool definitions
|
|
192
229
|
*/
|
|
193
230
|
getDeferredToolRegistry(onlyDeferred?: boolean): t.LCToolRegistry;
|
|
231
|
+
/**
|
|
232
|
+
* Sets the handoff context for this agent.
|
|
233
|
+
* Call this when the agent receives control via handoff from another agent.
|
|
234
|
+
* Marks system runnable as stale to include handoff context in system message.
|
|
235
|
+
* @param sourceAgentName - Name of the agent that transferred control
|
|
236
|
+
* @param parallelSiblings - Names of other agents executing in parallel with this one
|
|
237
|
+
*/
|
|
238
|
+
setHandoffContext(sourceAgentName: string, parallelSiblings: string[]): void;
|
|
239
|
+
/**
|
|
240
|
+
* Clears any handoff context.
|
|
241
|
+
* Call this when resetting the agent or when handoff context is no longer relevant.
|
|
242
|
+
*/
|
|
243
|
+
clearHandoffContext(): void;
|
|
194
244
|
/**
|
|
195
245
|
* Marks tools as discovered via tool search.
|
|
196
246
|
* Discovered tools will be included in the next model binding.
|
|
@@ -19,6 +19,8 @@ export declare enum GraphEvents {
|
|
|
19
19
|
ON_REASONING_DELTA = "on_reasoning_delta",
|
|
20
20
|
/** [Custom] Context analytics event for traces */
|
|
21
21
|
ON_CONTEXT_ANALYTICS = "on_context_analytics",
|
|
22
|
+
/** [Custom] Structured output event - emitted when agent returns structured JSON */
|
|
23
|
+
ON_STRUCTURED_OUTPUT = "on_structured_output",
|
|
22
24
|
/** Custom event, emitted by system */
|
|
23
25
|
ON_CUSTOM_EVENT = "on_custom_event",
|
|
24
26
|
/** Emitted when a chat model starts processing. */
|
|
@@ -116,11 +118,13 @@ export declare enum Callback {
|
|
|
116
118
|
export declare enum Constants {
|
|
117
119
|
OFFICIAL_CODE_BASEURL = "https://api.illuma.ai/v1",
|
|
118
120
|
EXECUTE_CODE = "execute_code",
|
|
119
|
-
|
|
121
|
+
TOOL_SEARCH = "tool_search",
|
|
120
122
|
PROGRAMMATIC_TOOL_CALLING = "run_tools_with_code",
|
|
121
123
|
WEB_SEARCH = "web_search",
|
|
122
124
|
CONTENT_AND_ARTIFACT = "content_and_artifact",
|
|
123
|
-
LC_TRANSFER_TO_ = "lc_transfer_to_"
|
|
125
|
+
LC_TRANSFER_TO_ = "lc_transfer_to_",
|
|
126
|
+
/** Delimiter for MCP tools: toolName_mcp_serverName */
|
|
127
|
+
MCP_DELIMITER = "_mcp_"
|
|
124
128
|
}
|
|
125
129
|
export declare enum TitleMethod {
|
|
126
130
|
STRUCTURED = "structured",
|
|
@@ -45,6 +45,12 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
45
45
|
/** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
|
|
46
46
|
invokedToolIds?: Set<string>;
|
|
47
47
|
handlerRegistry: HandlerRegistry | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Tool session contexts for automatic state persistence across tool invocations.
|
|
50
|
+
* Keyed by tool name (e.g., Constants.EXECUTE_CODE).
|
|
51
|
+
* Currently supports code execution session tracking (session_id, files).
|
|
52
|
+
*/
|
|
53
|
+
sessions: t.ToolSessionMap;
|
|
48
54
|
}
|
|
49
55
|
export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
|
|
50
56
|
overrideModel?: t.ChatModel;
|
|
@@ -145,6 +151,12 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
|
|
|
145
151
|
getUsageMetadata(finalMessage?: BaseMessage): Partial<UsageMetadata> | undefined;
|
|
146
152
|
/** Execute model invocation with streaming support */
|
|
147
153
|
private attemptInvoke;
|
|
154
|
+
/**
|
|
155
|
+
* Execute model invocation with structured output.
|
|
156
|
+
* Uses withStructuredOutput to force the model to return JSON conforming to the schema.
|
|
157
|
+
* Disables streaming and returns a validated JSON response.
|
|
158
|
+
*/
|
|
159
|
+
private attemptStructuredInvoke;
|
|
148
160
|
cleanupSignalListener(currentModel?: t.ChatModel): void;
|
|
149
161
|
createCallModel(agentId?: string): (state: t.BaseGraphState, config?: RunnableConfig) => Promise<Partial<t.BaseGraphState>>;
|
|
150
162
|
createAgentNode(agentId: string): t.CompiledAgentWorfklow;
|
|
@@ -75,12 +75,28 @@ export declare class MultiAgentGraph extends StandardGraph {
|
|
|
75
75
|
private createHandoffTools;
|
|
76
76
|
/**
|
|
77
77
|
* Create handoff tools for an edge (handles multiple destinations)
|
|
78
|
+
* @param edge - The graph edge defining the handoff
|
|
79
|
+
* @param sourceAgentId - The ID of the agent that will perform the handoff
|
|
80
|
+
* @param sourceAgentName - The human-readable name of the source agent
|
|
78
81
|
*/
|
|
79
82
|
private createHandoffToolsForEdge;
|
|
80
83
|
/**
|
|
81
84
|
* Create a complete agent subgraph (similar to createReactAgent)
|
|
82
85
|
*/
|
|
83
86
|
private createAgentSubgraph;
|
|
87
|
+
/**
|
|
88
|
+
* Detects if the current agent is receiving a handoff and processes the messages accordingly.
|
|
89
|
+
* Returns filtered messages with the transfer tool call/message removed, plus any instructions,
|
|
90
|
+
* source agent, and parallel sibling information extracted from the transfer.
|
|
91
|
+
*
|
|
92
|
+
* Supports both single handoffs (last message is the transfer) and parallel handoffs
|
|
93
|
+
* (multiple transfer ToolMessages, need to find the one targeting this agent).
|
|
94
|
+
*
|
|
95
|
+
* @param messages - Current state messages
|
|
96
|
+
* @param agentId - The agent ID to check for handoff reception
|
|
97
|
+
* @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings
|
|
98
|
+
*/
|
|
99
|
+
private processHandoffReception;
|
|
84
100
|
/**
|
|
85
101
|
* Create the multi-agent workflow with dynamic handoffs
|
|
86
102
|
*/
|
package/dist/types/index.d.ts
CHANGED
|
@@ -8,9 +8,10 @@ export * from './tools/Calculator';
|
|
|
8
8
|
export * from './tools/CodeExecutor';
|
|
9
9
|
export * from './tools/BrowserTools';
|
|
10
10
|
export * from './tools/ProgrammaticToolCalling';
|
|
11
|
-
export * from './tools/
|
|
11
|
+
export * from './tools/ToolSearch';
|
|
12
12
|
export * from './tools/handlers';
|
|
13
13
|
export * from './tools/search';
|
|
14
|
+
export * from './schemas';
|
|
14
15
|
export * from './common';
|
|
15
16
|
export * from './utils';
|
|
16
17
|
export type * from './types';
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Optimized ChatBedrockConverse wrapper that fixes contentBlockIndex conflicts
|
|
3
|
-
* and adds
|
|
3
|
+
* and adds support for:
|
|
4
|
+
*
|
|
5
|
+
* - Prompt caching support for Bedrock Converse API (Illuma feature)
|
|
6
|
+
* - Application Inference Profiles (PR #9129)
|
|
7
|
+
* - Service Tiers (Priority/Standard/Flex) (PR #9785) - requires AWS SDK 3.966.0+
|
|
4
8
|
*
|
|
5
9
|
* Bedrock sends the same contentBlockIndex for both text and tool_use content blocks,
|
|
6
10
|
* causing LangChain's merge logic to fail with "field[contentBlockIndex] already exists"
|
|
@@ -21,36 +25,110 @@
|
|
|
21
25
|
* response. This wrapper adds input_token_details to usage_metadata with cache information.
|
|
22
26
|
*/
|
|
23
27
|
import { ChatBedrockConverse } from '@langchain/aws';
|
|
24
|
-
import type { ChatBedrockConverseInput } from '@langchain/aws';
|
|
25
28
|
import type { BaseMessage } from '@langchain/core/messages';
|
|
26
|
-
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
29
|
+
import { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs';
|
|
27
30
|
import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
28
|
-
|
|
31
|
+
import type { ChatBedrockConverseInput } from '@langchain/aws';
|
|
32
|
+
/**
|
|
33
|
+
* Service tier type for Bedrock invocations.
|
|
34
|
+
* Requires AWS SDK >= 3.966.0 to actually work.
|
|
35
|
+
* @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html
|
|
36
|
+
*/
|
|
37
|
+
export type ServiceTierType = 'priority' | 'default' | 'flex' | 'reserved';
|
|
38
|
+
/**
|
|
39
|
+
* Extended input interface with additional features:
|
|
40
|
+
* - promptCache: Enable Bedrock prompt caching for tool definitions
|
|
41
|
+
* - applicationInferenceProfile: Use an inference profile ARN instead of model ID
|
|
42
|
+
* - serviceTier: Specify service tier (Priority, Standard, Flex, Reserved)
|
|
43
|
+
*/
|
|
29
44
|
export interface CustomChatBedrockConverseInput extends ChatBedrockConverseInput {
|
|
45
|
+
/**
|
|
46
|
+
* Enable Bedrock prompt caching for tool definitions.
|
|
47
|
+
* When true, adds cachePoint markers to tools array.
|
|
48
|
+
*/
|
|
30
49
|
promptCache?: boolean;
|
|
50
|
+
/**
|
|
51
|
+
* Application Inference Profile ARN to use for the model.
|
|
52
|
+
* For example, "arn:aws:bedrock:eu-west-1:123456789102:application-inference-profile/fm16bt65tzgx"
|
|
53
|
+
* When provided, this ARN will be used for the actual inference calls instead of the model ID.
|
|
54
|
+
* Must still provide `model` as normal modelId to benefit from all the metadata.
|
|
55
|
+
* @see https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-create.html
|
|
56
|
+
*/
|
|
57
|
+
applicationInferenceProfile?: string;
|
|
58
|
+
/**
|
|
59
|
+
* Service tier for model invocation.
|
|
60
|
+
* Specifies the processing tier type used for serving the request.
|
|
61
|
+
* Supported values are 'priority', 'default', 'flex', and 'reserved'.
|
|
62
|
+
*
|
|
63
|
+
* - 'priority': Prioritized processing for lower latency
|
|
64
|
+
* - 'default': Standard processing tier
|
|
65
|
+
* - 'flex': Flexible processing tier with lower cost
|
|
66
|
+
* - 'reserved': Reserved capacity for consistent performance
|
|
67
|
+
*
|
|
68
|
+
* If not provided, AWS uses the default tier.
|
|
69
|
+
* Note: Requires AWS SDK >= 3.966.0 to work.
|
|
70
|
+
* @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html
|
|
71
|
+
*/
|
|
72
|
+
serviceTier?: ServiceTierType;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Extended call options with serviceTier override support.
|
|
76
|
+
*/
|
|
77
|
+
export interface CustomChatBedrockConverseCallOptions {
|
|
78
|
+
serviceTier?: ServiceTierType;
|
|
31
79
|
}
|
|
32
80
|
export declare class CustomChatBedrockConverse extends ChatBedrockConverse {
|
|
81
|
+
/** Enable Bedrock prompt caching for tool definitions */
|
|
33
82
|
promptCache: boolean;
|
|
83
|
+
/** Application Inference Profile ARN to use instead of model ID */
|
|
84
|
+
applicationInferenceProfile?: string;
|
|
85
|
+
/** Service tier for model invocation */
|
|
86
|
+
serviceTier?: ServiceTierType;
|
|
34
87
|
constructor(fields?: CustomChatBedrockConverseInput);
|
|
35
88
|
static lc_name(): string;
|
|
36
89
|
/**
|
|
37
|
-
*
|
|
38
|
-
*
|
|
90
|
+
* Get the model ID to use for API calls.
|
|
91
|
+
* Returns applicationInferenceProfile if set, otherwise returns this.model.
|
|
92
|
+
*/
|
|
93
|
+
protected getModelId(): string;
|
|
94
|
+
/**
|
|
95
|
+
* Override invocationParams to:
|
|
96
|
+
* 1. Add cachePoint to tools when promptCache is enabled
|
|
97
|
+
* 2. Add serviceTier support
|
|
39
98
|
*
|
|
40
|
-
* STRATEGY: Separate cachePoints for core tools and MCP tools
|
|
99
|
+
* CACHING STRATEGY: Separate cachePoints for core tools and MCP tools
|
|
41
100
|
* - Core tools (web_search, execute_code, etc.) are stable → cache first
|
|
42
101
|
* - MCP tools (have '_mcp_' in name) are dynamic → cache separately after
|
|
43
102
|
* - This allows core tools to stay cached when MCP selection changes
|
|
44
103
|
*
|
|
45
104
|
* NOTE: Only Claude models support cachePoint - Nova and other models will reject it.
|
|
46
105
|
*/
|
|
47
|
-
invocationParams(options?: this['ParsedCallOptions']): ReturnType<ChatBedrockConverse['invocationParams']
|
|
106
|
+
invocationParams(options?: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions): ReturnType<ChatBedrockConverse['invocationParams']> & {
|
|
107
|
+
serviceTier?: {
|
|
108
|
+
type: ServiceTierType;
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Override _generateNonStreaming to use applicationInferenceProfile as modelId.
|
|
113
|
+
* Uses the same model-swapping pattern as streaming for consistency.
|
|
114
|
+
*/
|
|
115
|
+
_generateNonStreaming(messages: BaseMessage[], options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions, runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
|
|
48
116
|
/**
|
|
49
117
|
* Override _streamResponseChunks to:
|
|
50
|
-
* 1.
|
|
51
|
-
* 2.
|
|
118
|
+
* 1. Use applicationInferenceProfile as modelId (by temporarily swapping this.model)
|
|
119
|
+
* 2. Strip contentBlockIndex from response_metadata to prevent merge conflicts
|
|
120
|
+
* 3. Extract cacheReadInputTokens/cacheWriteInputTokens and add to usage_metadata
|
|
121
|
+
*
|
|
122
|
+
* Note: We delegate to super._streamResponseChunks() to preserve @langchain/aws's
|
|
123
|
+
* internal chunk handling which correctly preserves array content for reasoning blocks.
|
|
124
|
+
*/
|
|
125
|
+
_streamResponseChunks(messages: BaseMessage[], options: this['ParsedCallOptions'] & CustomChatBedrockConverseCallOptions, runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
|
|
126
|
+
/**
|
|
127
|
+
* Process a chunk by:
|
|
128
|
+
* 1. Removing contentBlockIndex from response_metadata
|
|
129
|
+
* 2. Extracting cache token information from Bedrock's usage data
|
|
52
130
|
*/
|
|
53
|
-
|
|
131
|
+
private processChunk;
|
|
54
132
|
/**
|
|
55
133
|
* Check if contentBlockIndex exists at any level in the object
|
|
56
134
|
*/
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for Bedrock Converse utilities.
|
|
3
|
+
*/
|
|
4
|
+
import type { Message as BedrockMessage, SystemContentBlock as BedrockSystemContentBlock, ContentBlock as BedrockContentBlock, ConverseResponse, ContentBlockDeltaEvent, ConverseStreamMetadataEvent, ContentBlockStartEvent, ReasoningContentBlock, ReasoningContentBlockDelta } from '@aws-sdk/client-bedrock-runtime';
|
|
5
|
+
/**
|
|
6
|
+
* Reasoning content block type for LangChain messages.
|
|
7
|
+
*/
|
|
8
|
+
export interface MessageContentReasoningBlock {
|
|
9
|
+
type: 'reasoning_content';
|
|
10
|
+
reasoningText?: {
|
|
11
|
+
text?: string;
|
|
12
|
+
signature?: string;
|
|
13
|
+
};
|
|
14
|
+
redactedContent?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface MessageContentReasoningBlockReasoningTextPartial {
|
|
17
|
+
type: 'reasoning_content';
|
|
18
|
+
reasoningText: {
|
|
19
|
+
text?: string;
|
|
20
|
+
signature?: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export interface MessageContentReasoningBlockRedacted {
|
|
24
|
+
type: 'reasoning_content';
|
|
25
|
+
redactedContent: string;
|
|
26
|
+
}
|
|
27
|
+
export type { BedrockMessage, BedrockSystemContentBlock, BedrockContentBlock, ConverseResponse, ContentBlockDeltaEvent, ConverseStreamMetadataEvent, ContentBlockStartEvent, ReasoningContentBlock, ReasoningContentBlockDelta, };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bedrock Converse utility exports.
|
|
3
|
+
*/
|
|
4
|
+
export { convertToConverseMessages, extractImageInfo, langchainReasoningBlockToBedrockReasoningBlock, concatenateLangchainReasoningBlocks, } from './message_inputs';
|
|
5
|
+
export { convertConverseMessageToLangChainMessage, handleConverseStreamContentBlockStart, handleConverseStreamContentBlockDelta, handleConverseStreamMetadata, bedrockReasoningBlockToLangchainReasoningBlock, bedrockReasoningDeltaToLangchainPartialReasoningBlock, } from './message_outputs';
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Utility functions for converting LangChain messages to Bedrock Converse messages.
|
|
3
|
+
* Ported from @langchain/aws common.js
|
|
4
|
+
*/
|
|
5
|
+
import { type BaseMessage, MessageContentComplex } from '@langchain/core/messages';
|
|
6
|
+
import type { BedrockMessage, BedrockSystemContentBlock, BedrockContentBlock, MessageContentReasoningBlock } from '../types';
|
|
7
|
+
/**
|
|
8
|
+
* Convert a LangChain reasoning block to a Bedrock reasoning block.
|
|
9
|
+
*/
|
|
10
|
+
export declare function langchainReasoningBlockToBedrockReasoningBlock(content: MessageContentReasoningBlock): {
|
|
11
|
+
reasoningText?: {
|
|
12
|
+
text?: string;
|
|
13
|
+
signature?: string;
|
|
14
|
+
};
|
|
15
|
+
redactedContent?: Uint8Array;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Concatenate consecutive reasoning blocks in content array.
|
|
19
|
+
*/
|
|
20
|
+
export declare function concatenateLangchainReasoningBlocks(content: Array<MessageContentComplex | MessageContentReasoningBlock>): Array<MessageContentComplex | MessageContentReasoningBlock>;
|
|
21
|
+
/**
|
|
22
|
+
* Extract image info from a base64 string or URL.
|
|
23
|
+
*/
|
|
24
|
+
export declare function extractImageInfo(base64: string): BedrockContentBlock;
|
|
25
|
+
/**
|
|
26
|
+
* Convert LangChain messages to Bedrock Converse messages.
|
|
27
|
+
*/
|
|
28
|
+
export declare function convertToConverseMessages(messages: BaseMessage[]): {
|
|
29
|
+
converseMessages: BedrockMessage[];
|
|
30
|
+
converseSystem: BedrockSystemContentBlock[];
|
|
31
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Utility functions for converting Bedrock Converse responses to LangChain messages.
|
|
3
|
+
* Ported from @langchain/aws common.js
|
|
4
|
+
*/
|
|
5
|
+
import { AIMessage } from '@langchain/core/messages';
|
|
6
|
+
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
7
|
+
import type { BedrockMessage, ConverseResponse, ContentBlockDeltaEvent, ConverseStreamMetadataEvent, ContentBlockStartEvent, ReasoningContentBlock, ReasoningContentBlockDelta, MessageContentReasoningBlock, MessageContentReasoningBlockReasoningTextPartial, MessageContentReasoningBlockRedacted } from '../types';
|
|
8
|
+
/**
|
|
9
|
+
* Convert a Bedrock reasoning block delta to a LangChain partial reasoning block.
|
|
10
|
+
*/
|
|
11
|
+
export declare function bedrockReasoningDeltaToLangchainPartialReasoningBlock(reasoningContent: ReasoningContentBlockDelta): MessageContentReasoningBlockReasoningTextPartial | MessageContentReasoningBlockRedacted;
|
|
12
|
+
/**
|
|
13
|
+
* Convert a Bedrock reasoning block to a LangChain reasoning block.
|
|
14
|
+
*/
|
|
15
|
+
export declare function bedrockReasoningBlockToLangchainReasoningBlock(reasoningContent: ReasoningContentBlock): MessageContentReasoningBlock;
|
|
16
|
+
/**
|
|
17
|
+
* Convert a Bedrock Converse message to a LangChain message.
|
|
18
|
+
*/
|
|
19
|
+
export declare function convertConverseMessageToLangChainMessage(message: BedrockMessage, responseMetadata: Omit<ConverseResponse, 'output'>): AIMessage;
|
|
20
|
+
/**
|
|
21
|
+
* Handle a content block delta event from Bedrock Converse stream.
|
|
22
|
+
*/
|
|
23
|
+
export declare function handleConverseStreamContentBlockDelta(contentBlockDelta: ContentBlockDeltaEvent): ChatGenerationChunk;
|
|
24
|
+
/**
|
|
25
|
+
* Handle a content block start event from Bedrock Converse stream.
|
|
26
|
+
*/
|
|
27
|
+
export declare function handleConverseStreamContentBlockStart(contentBlockStart: ContentBlockStartEvent): ChatGenerationChunk | null;
|
|
28
|
+
/**
|
|
29
|
+
* Handle a metadata event from Bedrock Converse stream.
|
|
30
|
+
*/
|
|
31
|
+
export declare function handleConverseStreamMetadata(metadata: ConverseStreamMetadataEvent, extra: {
|
|
32
|
+
streamUsage: boolean;
|
|
33
|
+
}): ChatGenerationChunk;
|
|
@@ -8,18 +8,21 @@ type MessageWithContent = {
|
|
|
8
8
|
* Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,
|
|
9
9
|
* then adds fresh cache control to the last 2 user messages in a single backward pass.
|
|
10
10
|
* This ensures we don't accumulate stale cache points across multiple turns.
|
|
11
|
+
* Returns a new array - only clones messages that require modification.
|
|
11
12
|
* @param messages - The array of message objects.
|
|
12
|
-
* @returns -
|
|
13
|
+
* @returns - A new array of message objects with cache control added.
|
|
13
14
|
*/
|
|
14
15
|
export declare function addCacheControl<T extends AnthropicMessage | BaseMessage>(messages: T[]): T[];
|
|
15
16
|
/**
|
|
16
17
|
* Removes all Anthropic cache_control fields from messages
|
|
17
18
|
* Used when switching from Anthropic to Bedrock provider
|
|
19
|
+
* Returns a new array - only clones messages that require modification.
|
|
18
20
|
*/
|
|
19
21
|
export declare function stripAnthropicCacheControl<T extends MessageWithContent>(messages: T[]): T[];
|
|
20
22
|
/**
|
|
21
23
|
* Removes all Bedrock cachePoint blocks from messages
|
|
22
24
|
* Used when switching from Bedrock to Anthropic provider
|
|
25
|
+
* Returns a new array - only clones messages that require modification.
|
|
23
26
|
*/
|
|
24
27
|
export declare function stripBedrockCacheControl<T extends MessageWithContent>(messages: T[]): T[];
|
|
25
28
|
/**
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './validate';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type * as t from '@/types';
|
|
3
|
+
/**
|
|
4
|
+
* Validation result from structured output
|
|
5
|
+
*/
|
|
6
|
+
export interface ValidationResult<T = Record<string, unknown>> {
|
|
7
|
+
success: boolean;
|
|
8
|
+
data?: T;
|
|
9
|
+
error?: string;
|
|
10
|
+
raw?: unknown;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Validates structured output against a JSON Schema.
|
|
14
|
+
*
|
|
15
|
+
* @param output - The output to validate
|
|
16
|
+
* @param schema - JSON Schema to validate against
|
|
17
|
+
* @returns Validation result with success flag and data or error
|
|
18
|
+
*/
|
|
19
|
+
export declare function validateStructuredOutput(output: unknown, schema: Record<string, unknown>): ValidationResult;
|
|
20
|
+
/**
|
|
21
|
+
* Converts a Zod schema to JSON Schema format.
|
|
22
|
+
* This is a simplified converter for common types.
|
|
23
|
+
*/
|
|
24
|
+
export declare function zodToJsonSchema(zodSchema: z.ZodType): Record<string, unknown>;
|
|
25
|
+
/**
|
|
26
|
+
* Creates a structured output error message for retry.
|
|
27
|
+
*/
|
|
28
|
+
export declare function createValidationErrorMessage(result: ValidationResult, customMessage?: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* Checks if a value is a valid JSON Schema object.
|
|
31
|
+
*/
|
|
32
|
+
export declare function isValidJsonSchema(value: unknown): value is Record<string, unknown>;
|
|
33
|
+
/**
|
|
34
|
+
* Normalizes a JSON Schema by adding defaults and cleaning up.
|
|
35
|
+
*/
|
|
36
|
+
export declare function normalizeJsonSchema(schema: Record<string, unknown>, config?: t.StructuredOutputConfig): Record<string, unknown>;
|
|
@@ -6,18 +6,15 @@ export declare const getCodeBaseURL: () => string;
|
|
|
6
6
|
declare const CodeExecutionToolSchema: z.ZodObject<{
|
|
7
7
|
lang: z.ZodEnum<["py", "js", "ts", "c", "cpp", "java", "php", "rs", "go", "d", "f90", "r"]>;
|
|
8
8
|
code: z.ZodString;
|
|
9
|
-
session_id: z.ZodOptional<z.ZodString>;
|
|
10
9
|
args: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
11
10
|
}, "strip", z.ZodTypeAny, {
|
|
12
11
|
code: string;
|
|
13
12
|
lang: "r" | "d" | "py" | "js" | "ts" | "c" | "cpp" | "java" | "php" | "rs" | "go" | "f90";
|
|
14
13
|
args?: string[] | undefined;
|
|
15
|
-
session_id?: string | undefined;
|
|
16
14
|
}, {
|
|
17
15
|
code: string;
|
|
18
16
|
lang: "r" | "d" | "py" | "js" | "ts" | "c" | "cpp" | "java" | "php" | "rs" | "go" | "f90";
|
|
19
17
|
args?: string[] | undefined;
|
|
20
|
-
session_id?: string | undefined;
|
|
21
18
|
}>;
|
|
22
19
|
declare function createCodeExecutionTool(params?: t.CodeExecutionToolParams): DynamicStructuredTool<typeof CodeExecutionToolSchema>;
|
|
23
20
|
export { createCodeExecutionTool };
|