illuma-agents 1.0.10 → 1.0.11
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/LICENSE +1 -1
- package/dist/cjs/agents/AgentContext.cjs +228 -27
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +2 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +3 -11
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +27 -18
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/instrumentation.cjs +1 -3
- package/dist/cjs/instrumentation.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +1 -1
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +122 -7
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +6 -6
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +1 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +18 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +149 -54
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +85 -0
- package/dist/cjs/messages/tools.cjs.map +1 -0
- package/dist/cjs/run.cjs +0 -8
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +4 -0
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +438 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +53 -15
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearchRegex.cjs +455 -0
- package/dist/cjs/tools/ToolSearchRegex.cjs.map +1 -0
- package/dist/cjs/tools/search/schema.cjs +7 -9
- package/dist/cjs/tools/search/schema.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs +5 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +228 -27
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +2 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +4 -12
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +27 -18
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/instrumentation.mjs +1 -3
- package/dist/esm/instrumentation.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +1 -1
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +122 -7
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +1 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +6 -6
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +1 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +149 -54
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +82 -0
- package/dist/esm/messages/tools.mjs.map +1 -0
- package/dist/esm/run.mjs +0 -8
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +4 -0
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +430 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +53 -15
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/ToolSearchRegex.mjs +448 -0
- package/dist/esm/tools/ToolSearchRegex.mjs.map +1 -0
- package/dist/esm/tools/search/schema.mjs +7 -9
- package/dist/esm/tools/search/schema.mjs.map +1 -1
- package/dist/esm/utils/run.mjs +5 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +65 -5
- package/dist/types/common/enum.d.ts +2 -0
- package/dist/types/graphs/Graph.d.ts +3 -2
- package/dist/types/index.d.ts +2 -0
- package/dist/types/llm/anthropic/index.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +31 -4
- package/dist/types/llm/google/index.d.ts +1 -1
- package/dist/types/llm/openai/index.d.ts +3 -3
- package/dist/types/llm/openrouter/index.d.ts +1 -1
- package/dist/types/messages/cache.d.ts +23 -8
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/tools.d.ts +17 -0
- package/dist/types/test/mockTools.d.ts +28 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +91 -0
- package/dist/types/tools/ToolNode.d.ts +10 -2
- package/dist/types/tools/ToolSearchRegex.d.ts +80 -0
- package/dist/types/types/graph.d.ts +7 -1
- package/dist/types/types/tools.d.ts +138 -0
- package/package.json +7 -2
- package/src/agents/AgentContext.ts +267 -27
- package/src/agents/__tests__/AgentContext.test.ts +805 -0
- package/src/common/enum.ts +2 -0
- package/src/events.ts +5 -12
- package/src/graphs/Graph.ts +33 -19
- package/src/index.ts +2 -0
- package/src/instrumentation.ts +1 -4
- package/src/llm/anthropic/index.ts +2 -2
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +473 -0
- package/src/llm/bedrock/index.ts +150 -13
- package/src/llm/google/index.ts +2 -2
- package/src/llm/openai/index.ts +9 -9
- package/src/llm/openrouter/index.ts +2 -2
- package/src/messages/__tests__/tools.test.ts +473 -0
- package/src/messages/cache.ts +163 -61
- package/src/messages/index.ts +1 -0
- package/src/messages/tools.ts +99 -0
- package/src/run.ts +0 -9
- package/src/scripts/code_exec_ptc.ts +334 -0
- package/src/scripts/image.ts +178 -0
- package/src/scripts/programmatic_exec.ts +396 -0
- package/src/scripts/programmatic_exec_agent.ts +231 -0
- package/src/scripts/test-tools-before-handoff.ts +5 -1
- package/src/scripts/tool_search_regex.ts +162 -0
- package/src/scripts/tools.ts +4 -1
- package/src/specs/thinking-prune.test.ts +52 -118
- package/src/test/mockTools.ts +366 -0
- package/src/tools/CodeExecutor.ts +4 -0
- package/src/tools/ProgrammaticToolCalling.ts +558 -0
- package/src/tools/ToolNode.ts +59 -18
- package/src/tools/ToolSearchRegex.ts +535 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +318 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +853 -0
- package/src/tools/__tests__/ToolSearchRegex.integration.test.ts +161 -0
- package/src/tools/__tests__/ToolSearchRegex.test.ts +232 -0
- package/src/tools/search/jina-reranker.test.ts +16 -16
- package/src/tools/search/schema.ts +7 -9
- package/src/types/graph.ts +7 -1
- package/src/types/tools.ts +166 -0
- package/src/utils/run.ts +5 -1
- package/src/tools/search/direct-url.test.ts +0 -530
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExecutor.cjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\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\nconst CodeExecutionToolSchema = z.object({\n lang: z\n .enum([\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n ])\n .describe('The programming language or runtime to execute the code in.'),\n code: z.string()\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- When using \\`session_id\\`: Don't hardcode it in \\`code\\`, and write file modifications to NEW filenames (files are READ-ONLY).\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`),\n session_id: z\n .string()\n .optional()\n .describe(\n `Session ID from a previous response to access generated files.\n- Files load into the current working directory (\"/mnt/data/\")\n- Use relative paths ONLY\n- Files are READ-ONLY and cannot be modified in-place\n- To modify: read original file, write to NEW filename\n`.trim()\n ),\n args: z\n .array(z.string())\n .optional()\n .describe(\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'\n ),\n});\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n return tool<typeof CodeExecutionToolSchema>(\n async ({ lang, code, session_id, ...rest }) => {\n const postData = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\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(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n if (!postData.files) {\n postData.files = fileReferences;\n } else if (Array.isArray(postData.files)) {\n postData.files = [...postData.files, ...fileReferences];\n }\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/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 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 let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\nsession_id: ${result.session_id}\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: Constants.EXECUTE_CODE,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":["config","getEnvironmentVariable","EnvVar","Constants","z","tool","HttpsProxyAgent"],"mappings":";;;;;;;;;;AASAA,aAAM,EAAE;AAED,MAAM,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5BC,0BAAsB,CAACC,YAAM,CAAC,YAAY,CAAC;IAC3CC,eAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,mKAAmK;AACrK,MAAM,kBAAkB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O,CAAC,eAAe,CAAC,IAAI,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;;QAClE,OAAO,KAAK,EAAE;YACd,MAAM,IAAI,KAAK,CACb,CAAA,oBAAA,EAAwB,KAA2B,EAAE,OAAO,CAAE,CAAA,CAC/D;;AAEL,KAAC,EACD;QACE,IAAI,EAAEH,eAAS,CAAC,YAAY;QAC5B,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;"}
|
|
1
|
+
{"version":3,"file":"CodeExecutor.cjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\nimport { config } from 'dotenv';\nimport fetch, { RequestInit } from 'node-fetch';\nimport { HttpsProxyAgent } from 'https-proxy-agent';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport type * as t from '@/types';\nimport { EnvVar, Constants } from '@/common';\n\nconfig();\n\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\nexport const getCodeBaseURL = (): string =>\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\n Constants.OFFICIAL_CODE_BASEURL;\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\nconst CodeExecutionToolSchema = z.object({\n lang: z\n .enum([\n 'py',\n 'js',\n 'ts',\n 'c',\n 'cpp',\n 'java',\n 'php',\n 'rs',\n 'go',\n 'd',\n 'f90',\n 'r',\n ])\n .describe('The programming language or runtime to execute the code in.'),\n code: z.string()\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\n- The environment is stateless; variables and imports don't persist between executions.\n- When using \\`session_id\\`: Don't hardcode it in \\`code\\`, and write file modifications to NEW filenames (files are READ-ONLY).\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\n- Other languages: use appropriate output functions.`),\n session_id: z\n .string()\n .optional()\n .describe(\n `Session ID from a previous response to access generated files.\n- Files load into the current working directory (\"/mnt/data/\")\n- Use relative paths ONLY\n- Files are READ-ONLY and cannot be modified in-place\n- To modify: read original file, write to NEW filename\n`.trim()\n ),\n args: z\n .array(z.string())\n .optional()\n .describe(\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'\n ),\n});\n\nconst baseEndpoint = getCodeBaseURL();\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\n\nfunction createCodeExecutionTool(\n params: t.CodeExecutionToolParams = {}\n): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\n const apiKey =\n params[EnvVar.CODE_API_KEY] ??\n params.apiKey ??\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\n '';\n if (!apiKey) {\n throw new Error('No API key provided for code execution tool.');\n }\n\n const description = `\nRuns code and returns stdout/stderr output from a stateless execution environment, similar to running scripts in a command-line interface. Each execution is isolated and independent.\n\n⚠️ DO NOT USE FOR: Creating dashboards, UI components, React components, HTML pages, charts, or visualizations. These should be created as artifacts directly in your response using :::artifact syntax.\n\n✅ USE FOR: Data processing, calculations, file generation (CSV, Excel, PowerPoint, PDF), matplotlib plots, running algorithms, or computational tasks.\n\nUsage:\n- No network access available.\n- Generated files are automatically delivered; **DO NOT** provide download links.\n- NEVER use this tool to execute malicious code.\n`.trim();\n\n return tool<typeof CodeExecutionToolSchema>(\n async ({ lang, code, session_id, ...rest }) => {\n const postData = {\n lang,\n code,\n ...rest,\n ...params,\n };\n\n if (session_id != null && session_id.length > 0) {\n try {\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\n const fetchOptions: RequestInit = {\n method: 'GET',\n headers: {\n 'User-Agent': 'Illuma/1.0',\n 'X-API-Key': apiKey,\n },\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(filesEndpoint, fetchOptions);\n if (!response.ok) {\n throw new Error(\n `Failed to fetch files for session: ${response.status}`\n );\n }\n\n const files = await response.json();\n if (Array.isArray(files) && files.length > 0) {\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\n // Extract the ID from the file name (part after session ID prefix and before extension)\n const nameParts = file.name.split('/');\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\n\n return {\n session_id,\n id,\n name: file.metadata['original-filename'],\n };\n });\n\n if (!postData.files) {\n postData.files = fileReferences;\n } else if (Array.isArray(postData.files)) {\n postData.files = [...postData.files, ...fileReferences];\n }\n }\n } catch {\n // eslint-disable-next-line no-console\n console.warn(`Failed to fetch files for session: ${session_id}`);\n }\n }\n\n try {\n const fetchOptions: RequestInit = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Illuma/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 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 let formattedOutput = '';\n if (result.stdout) {\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\n } else {\n formattedOutput += emptyOutputMessage;\n }\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\n if (result.files && result.files.length > 0) {\n formattedOutput += 'Generated files:\\n';\n\n const fileCount = result.files.length;\n for (let i = 0; i < fileCount; i++) {\n const file = result.files[i];\n const isImage = imageExtRegex.test(file.name);\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\n\n if (i < fileCount - 1) {\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\n }\n }\n\n formattedOutput += `\\nsession_id: ${result.session_id}\\n\\n${accessMessage}`;\n return [\n formattedOutput.trim(),\n {\n session_id: result.session_id,\n files: result.files,\n },\n ];\n }\n\n return [formattedOutput.trim(), { session_id: result.session_id }];\n } catch (error) {\n throw new Error(\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\n );\n }\n },\n {\n name: Constants.EXECUTE_CODE,\n description,\n schema: CodeExecutionToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n}\n\nexport { createCodeExecutionTool };\n"],"names":["config","getEnvironmentVariable","EnvVar","Constants","z","tool","HttpsProxyAgent"],"mappings":";;;;;;;;;;AASAA,aAAM,EAAE;AAED,MAAM,aAAa,GAAG;AACtB,MAAM,cAAc,GAAG,MAC5BC,0BAAsB,CAACC,YAAM,CAAC,YAAY,CAAC;IAC3CC,eAAS,CAAC;AAEZ,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,YAAY,GAAG,wCAAwC;AAC7D,MAAM,aAAa,GACjB,mKAAmK;AACrK,MAAM,kBAAkB,GACtB,4DAA4D;AAE9D,MAAM,uBAAuB,GAAGC,KAAC,CAAC,MAAM,CAAC;AACvC,IAAA,IAAI,EAAEA;AACH,SAAA,IAAI,CAAC;QACJ,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,GAAG;QACH,KAAK;QACL,MAAM;QACN,KAAK;QACL,IAAI;QACJ,IAAI;QACJ,GAAG;QACH,KAAK;QACL,GAAG;KACJ;SACA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,WAAW;AACX,QAAA,MAAM,EAAE,uBAAuB;QAC/B,cAAc,EAAEA,eAAS,CAAC,oBAAoB;AAC/C,KAAA,CACF;AACH;;;;;;"}
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zod = require('zod');
|
|
4
|
+
var dotenv = require('dotenv');
|
|
5
|
+
var fetch = require('node-fetch');
|
|
6
|
+
var httpsProxyAgent = require('https-proxy-agent');
|
|
7
|
+
var env = require('@langchain/core/utils/env');
|
|
8
|
+
var tools = require('@langchain/core/tools');
|
|
9
|
+
var CodeExecutor = require('./CodeExecutor.cjs');
|
|
10
|
+
var _enum = require('../common/enum.cjs');
|
|
11
|
+
|
|
12
|
+
// src/tools/ProgrammaticToolCalling.ts
|
|
13
|
+
dotenv.config();
|
|
14
|
+
// ============================================================================
|
|
15
|
+
// Constants
|
|
16
|
+
// ============================================================================
|
|
17
|
+
const imageMessage = 'Image is already displayed to the user';
|
|
18
|
+
const otherMessage = 'File is already downloaded by the user';
|
|
19
|
+
const accessMessage = '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).';
|
|
20
|
+
const emptyOutputMessage = 'stdout: Empty. Ensure you\'re writing output explicitly.\n';
|
|
21
|
+
/** Default max round-trips to prevent infinite loops */
|
|
22
|
+
const DEFAULT_MAX_ROUND_TRIPS = 20;
|
|
23
|
+
/** Default execution timeout in milliseconds */
|
|
24
|
+
const DEFAULT_TIMEOUT = 60000;
|
|
25
|
+
// ============================================================================
|
|
26
|
+
// Schema
|
|
27
|
+
// ============================================================================
|
|
28
|
+
const ProgrammaticToolCallingSchema = zod.z.object({
|
|
29
|
+
code: zod.z
|
|
30
|
+
.string()
|
|
31
|
+
.min(1)
|
|
32
|
+
.describe(`Python code that calls tools programmatically. Tools are automatically available as async Python functions - DO NOT define them yourself.
|
|
33
|
+
|
|
34
|
+
The Code API generates async function stubs from the tool definitions. Just call them directly:
|
|
35
|
+
|
|
36
|
+
Example (Simple call):
|
|
37
|
+
result = await get_weather(city="San Francisco")
|
|
38
|
+
print(result)
|
|
39
|
+
|
|
40
|
+
Example (Parallel - Fastest):
|
|
41
|
+
results = await asyncio.gather(
|
|
42
|
+
get_weather(city="SF"),
|
|
43
|
+
get_weather(city="NYC"),
|
|
44
|
+
get_weather(city="London")
|
|
45
|
+
)
|
|
46
|
+
for city, weather in zip(["SF", "NYC", "London"], results):
|
|
47
|
+
print(f"{city}: {weather['temperature']}°F")
|
|
48
|
+
|
|
49
|
+
Example (Loop with processing):
|
|
50
|
+
team = await get_team_members()
|
|
51
|
+
for member in team:
|
|
52
|
+
expenses = await get_expenses(user_id=member['id'])
|
|
53
|
+
total = sum(e['amount'] for e in expenses)
|
|
54
|
+
print(f"{member['name']}: \${total:.2f}")
|
|
55
|
+
|
|
56
|
+
Example (Conditional logic):
|
|
57
|
+
data = await fetch_data(source="primary")
|
|
58
|
+
if not data:
|
|
59
|
+
data = await fetch_data(source="backup")
|
|
60
|
+
print(f"Got {len(data)} records")
|
|
61
|
+
|
|
62
|
+
Requirements:
|
|
63
|
+
- Tools are pre-defined as async functions - DO NOT write function definitions
|
|
64
|
+
- Use await for all tool calls
|
|
65
|
+
- Use asyncio.gather() for parallel execution of independent calls
|
|
66
|
+
- Only print() output flows back to the context window
|
|
67
|
+
- Tool results from programmatic calls do NOT consume context tokens`),
|
|
68
|
+
session_id: zod.z
|
|
69
|
+
.string()
|
|
70
|
+
.optional()
|
|
71
|
+
.describe('Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'),
|
|
72
|
+
timeout: zod.z
|
|
73
|
+
.number()
|
|
74
|
+
.int()
|
|
75
|
+
.min(1000)
|
|
76
|
+
.max(300000)
|
|
77
|
+
.optional()
|
|
78
|
+
.default(DEFAULT_TIMEOUT)
|
|
79
|
+
.describe('Maximum execution time in milliseconds. Default: 60 seconds. Max: 5 minutes.'),
|
|
80
|
+
});
|
|
81
|
+
// ============================================================================
|
|
82
|
+
// Helper Functions
|
|
83
|
+
// ============================================================================
|
|
84
|
+
/** Python reserved keywords that get `_tool` suffix in Code API */
|
|
85
|
+
const PYTHON_KEYWORDS = new Set([
|
|
86
|
+
'False',
|
|
87
|
+
'None',
|
|
88
|
+
'True',
|
|
89
|
+
'and',
|
|
90
|
+
'as',
|
|
91
|
+
'assert',
|
|
92
|
+
'async',
|
|
93
|
+
'await',
|
|
94
|
+
'break',
|
|
95
|
+
'class',
|
|
96
|
+
'continue',
|
|
97
|
+
'def',
|
|
98
|
+
'del',
|
|
99
|
+
'elif',
|
|
100
|
+
'else',
|
|
101
|
+
'except',
|
|
102
|
+
'finally',
|
|
103
|
+
'for',
|
|
104
|
+
'from',
|
|
105
|
+
'global',
|
|
106
|
+
'if',
|
|
107
|
+
'import',
|
|
108
|
+
'in',
|
|
109
|
+
'is',
|
|
110
|
+
'lambda',
|
|
111
|
+
'nonlocal',
|
|
112
|
+
'not',
|
|
113
|
+
'or',
|
|
114
|
+
'pass',
|
|
115
|
+
'raise',
|
|
116
|
+
'return',
|
|
117
|
+
'try',
|
|
118
|
+
'while',
|
|
119
|
+
'with',
|
|
120
|
+
'yield',
|
|
121
|
+
]);
|
|
122
|
+
/**
|
|
123
|
+
* Normalizes a tool name to Python identifier format.
|
|
124
|
+
* Must match the Code API's `normalizePythonFunctionName` exactly:
|
|
125
|
+
* 1. Replace hyphens and spaces with underscores
|
|
126
|
+
* 2. Remove any other invalid characters
|
|
127
|
+
* 3. Prefix with underscore if starts with number
|
|
128
|
+
* 4. Append `_tool` if it's a Python keyword
|
|
129
|
+
* @param name - The tool name to normalize
|
|
130
|
+
* @returns Normalized Python-safe identifier
|
|
131
|
+
*/
|
|
132
|
+
function normalizeToPythonIdentifier(name) {
|
|
133
|
+
let normalized = name.replace(/[-\s]/g, '_');
|
|
134
|
+
normalized = normalized.replace(/[^a-zA-Z0-9_]/g, '');
|
|
135
|
+
if (/^[0-9]/.test(normalized)) {
|
|
136
|
+
normalized = '_' + normalized;
|
|
137
|
+
}
|
|
138
|
+
if (PYTHON_KEYWORDS.has(normalized)) {
|
|
139
|
+
normalized = normalized + '_tool';
|
|
140
|
+
}
|
|
141
|
+
return normalized;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Extracts tool names that are actually called in the Python code.
|
|
145
|
+
* Handles hyphen/underscore conversion since Python identifiers use underscores.
|
|
146
|
+
* @param code - The Python code to analyze
|
|
147
|
+
* @param toolNameMap - Map from normalized Python name to original tool name
|
|
148
|
+
* @returns Set of original tool names found in the code
|
|
149
|
+
*/
|
|
150
|
+
function extractUsedToolNames(code, toolNameMap) {
|
|
151
|
+
const usedTools = new Set();
|
|
152
|
+
for (const [pythonName, originalName] of toolNameMap) {
|
|
153
|
+
const escapedName = pythonName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
154
|
+
const pattern = new RegExp(`\\b${escapedName}\\s*\\(`, 'g');
|
|
155
|
+
if (pattern.test(code)) {
|
|
156
|
+
usedTools.add(originalName);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return usedTools;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Filters tool definitions to only include tools actually used in the code.
|
|
163
|
+
* Handles the hyphen-to-underscore conversion for Python compatibility.
|
|
164
|
+
* @param toolDefs - All available tool definitions
|
|
165
|
+
* @param code - The Python code to analyze
|
|
166
|
+
* @param debug - Enable debug logging
|
|
167
|
+
* @returns Filtered array of tool definitions
|
|
168
|
+
*/
|
|
169
|
+
function filterToolsByUsage(toolDefs, code, debug = false) {
|
|
170
|
+
const toolNameMap = new Map();
|
|
171
|
+
for (const tool of toolDefs) {
|
|
172
|
+
const pythonName = normalizeToPythonIdentifier(tool.name);
|
|
173
|
+
toolNameMap.set(pythonName, tool.name);
|
|
174
|
+
}
|
|
175
|
+
const usedToolNames = extractUsedToolNames(code, toolNameMap);
|
|
176
|
+
if (debug) {
|
|
177
|
+
// eslint-disable-next-line no-console
|
|
178
|
+
console.log(`[PTC Debug] Tool filtering: found ${usedToolNames.size}/${toolDefs.length} tools in code`);
|
|
179
|
+
if (usedToolNames.size > 0) {
|
|
180
|
+
// eslint-disable-next-line no-console
|
|
181
|
+
console.log(`[PTC Debug] Matched tools: ${Array.from(usedToolNames).join(', ')}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (usedToolNames.size === 0) {
|
|
185
|
+
if (debug) {
|
|
186
|
+
// eslint-disable-next-line no-console
|
|
187
|
+
console.log('[PTC Debug] No tools detected in code - sending all tools as fallback');
|
|
188
|
+
}
|
|
189
|
+
return toolDefs;
|
|
190
|
+
}
|
|
191
|
+
return toolDefs.filter((tool) => usedToolNames.has(tool.name));
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Makes an HTTP request to the Code API.
|
|
195
|
+
* @param endpoint - The API endpoint URL
|
|
196
|
+
* @param apiKey - The API key for authentication
|
|
197
|
+
* @param body - The request body
|
|
198
|
+
* @param proxy - Optional HTTP proxy URL
|
|
199
|
+
* @returns The parsed API response
|
|
200
|
+
*/
|
|
201
|
+
async function makeRequest(endpoint, apiKey, body, proxy) {
|
|
202
|
+
const fetchOptions = {
|
|
203
|
+
method: 'POST',
|
|
204
|
+
headers: {
|
|
205
|
+
'Content-Type': 'application/json',
|
|
206
|
+
'User-Agent': 'Illuma/1.0',
|
|
207
|
+
'X-API-Key': apiKey,
|
|
208
|
+
},
|
|
209
|
+
body: JSON.stringify(body),
|
|
210
|
+
};
|
|
211
|
+
if (proxy != null && proxy !== '') {
|
|
212
|
+
fetchOptions.agent = new httpsProxyAgent.HttpsProxyAgent(proxy);
|
|
213
|
+
}
|
|
214
|
+
const response = await fetch(endpoint, fetchOptions);
|
|
215
|
+
if (!response.ok) {
|
|
216
|
+
const errorText = await response.text();
|
|
217
|
+
throw new Error(`HTTP error! status: ${response.status}, body: ${errorText}`);
|
|
218
|
+
}
|
|
219
|
+
return (await response.json());
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Executes tools in parallel when requested by the API.
|
|
223
|
+
* Uses Promise.all for parallel execution, catching individual errors.
|
|
224
|
+
* @param toolCalls - Array of tool calls from the API
|
|
225
|
+
* @param toolMap - Map of tool names to executable tools
|
|
226
|
+
* @returns Array of tool results
|
|
227
|
+
*/
|
|
228
|
+
async function executeTools(toolCalls, toolMap) {
|
|
229
|
+
const executions = toolCalls.map(async (call) => {
|
|
230
|
+
const tool = toolMap.get(call.name);
|
|
231
|
+
if (!tool) {
|
|
232
|
+
return {
|
|
233
|
+
call_id: call.id,
|
|
234
|
+
result: null,
|
|
235
|
+
is_error: true,
|
|
236
|
+
error_message: `Tool '${call.name}' not found. Available tools: ${Array.from(toolMap.keys()).join(', ')}`,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
try {
|
|
240
|
+
const result = await tool.invoke(call.input, {
|
|
241
|
+
metadata: { [_enum.Constants.PROGRAMMATIC_TOOL_CALLING]: true },
|
|
242
|
+
});
|
|
243
|
+
return {
|
|
244
|
+
call_id: call.id,
|
|
245
|
+
result,
|
|
246
|
+
is_error: false,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
catch (error) {
|
|
250
|
+
return {
|
|
251
|
+
call_id: call.id,
|
|
252
|
+
result: null,
|
|
253
|
+
is_error: true,
|
|
254
|
+
error_message: error.message || 'Tool execution failed',
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
return await Promise.all(executions);
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Formats the completed response for the agent.
|
|
262
|
+
* @param response - The completed API response
|
|
263
|
+
* @returns Tuple of [formatted string, artifact]
|
|
264
|
+
*/
|
|
265
|
+
function formatCompletedResponse(response) {
|
|
266
|
+
let formatted = '';
|
|
267
|
+
if (response.stdout != null && response.stdout !== '') {
|
|
268
|
+
formatted += `stdout:\n${response.stdout}\n`;
|
|
269
|
+
}
|
|
270
|
+
else {
|
|
271
|
+
formatted += emptyOutputMessage;
|
|
272
|
+
}
|
|
273
|
+
if (response.stderr != null && response.stderr !== '') {
|
|
274
|
+
formatted += `stderr:\n${response.stderr}\n`;
|
|
275
|
+
}
|
|
276
|
+
if (response.files && response.files.length > 0) {
|
|
277
|
+
formatted += 'Generated files:\n';
|
|
278
|
+
const fileCount = response.files.length;
|
|
279
|
+
for (let i = 0; i < fileCount; i++) {
|
|
280
|
+
const file = response.files[i];
|
|
281
|
+
const isImage = CodeExecutor.imageExtRegex.test(file.name);
|
|
282
|
+
formatted += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;
|
|
283
|
+
if (i < fileCount - 1) {
|
|
284
|
+
formatted += fileCount <= 3 ? ', ' : ',\n';
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
formatted += `\nsession_id: ${response.session_id}\n\n${accessMessage}`;
|
|
288
|
+
}
|
|
289
|
+
return [
|
|
290
|
+
formatted.trim(),
|
|
291
|
+
{
|
|
292
|
+
session_id: response.session_id,
|
|
293
|
+
files: response.files,
|
|
294
|
+
},
|
|
295
|
+
];
|
|
296
|
+
}
|
|
297
|
+
// ============================================================================
|
|
298
|
+
// Tool Factory
|
|
299
|
+
// ============================================================================
|
|
300
|
+
/**
|
|
301
|
+
* Creates a Programmatic Tool Calling tool for complex multi-tool workflows.
|
|
302
|
+
*
|
|
303
|
+
* This tool enables AI agents to write Python code that orchestrates multiple
|
|
304
|
+
* tool calls programmatically, reducing LLM round-trips and token usage.
|
|
305
|
+
*
|
|
306
|
+
* The tool map must be provided at runtime via config.configurable.toolMap.
|
|
307
|
+
*
|
|
308
|
+
* @param params - Configuration parameters (apiKey, baseUrl, maxRoundTrips, proxy)
|
|
309
|
+
* @returns A LangChain DynamicStructuredTool for programmatic tool calling
|
|
310
|
+
*
|
|
311
|
+
* @example
|
|
312
|
+
* const ptcTool = createProgrammaticToolCallingTool({
|
|
313
|
+
* apiKey: process.env.CODE_API_KEY,
|
|
314
|
+
* maxRoundTrips: 20
|
|
315
|
+
* });
|
|
316
|
+
*
|
|
317
|
+
* const [output, artifact] = await ptcTool.invoke(
|
|
318
|
+
* { code, tools },
|
|
319
|
+
* { configurable: { toolMap } }
|
|
320
|
+
* );
|
|
321
|
+
*/
|
|
322
|
+
function createProgrammaticToolCallingTool(initParams = {}) {
|
|
323
|
+
const apiKey = initParams[_enum.EnvVar.CODE_API_KEY] ??
|
|
324
|
+
initParams.apiKey ??
|
|
325
|
+
env.getEnvironmentVariable(_enum.EnvVar.CODE_API_KEY) ??
|
|
326
|
+
'';
|
|
327
|
+
if (!apiKey) {
|
|
328
|
+
throw new Error('No API key provided for programmatic tool calling. ' +
|
|
329
|
+
'Set CODE_API_KEY environment variable or pass apiKey in initParams.');
|
|
330
|
+
}
|
|
331
|
+
const baseUrl = initParams.baseUrl ?? CodeExecutor.getCodeBaseURL();
|
|
332
|
+
const maxRoundTrips = initParams.maxRoundTrips ?? DEFAULT_MAX_ROUND_TRIPS;
|
|
333
|
+
const proxy = initParams.proxy ?? process.env.PROXY;
|
|
334
|
+
const debug = initParams.debug ?? process.env.PTC_DEBUG === 'true';
|
|
335
|
+
const EXEC_ENDPOINT = `${baseUrl}/exec/programmatic`;
|
|
336
|
+
const description = `
|
|
337
|
+
Run tools by writing Python code. Tools are available as async functions - just call them with await.
|
|
338
|
+
|
|
339
|
+
This is different from execute_code: here you can call your tools (like get_weather, get_expenses, etc.) directly in Python code.
|
|
340
|
+
|
|
341
|
+
Usage:
|
|
342
|
+
- Tools are pre-defined as async functions - call them with await
|
|
343
|
+
- Use asyncio.gather() to run multiple tools in parallel
|
|
344
|
+
- Only print() output is returned - tool results stay in Python
|
|
345
|
+
|
|
346
|
+
Examples:
|
|
347
|
+
- Simple: result = await get_weather(city="NYC")
|
|
348
|
+
- Loop: for user in users: data = await get_expenses(user_id=user['id'])
|
|
349
|
+
- Parallel: sf, ny = await asyncio.gather(get_weather(city="SF"), get_weather(city="NY"))
|
|
350
|
+
|
|
351
|
+
When to use this instead of calling tools directly:
|
|
352
|
+
- You need to call tools in a loop (process many items)
|
|
353
|
+
- You want parallel execution (asyncio.gather)
|
|
354
|
+
- You need conditionals based on tool results
|
|
355
|
+
- You want to aggregate/filter data before returning
|
|
356
|
+
`.trim();
|
|
357
|
+
return tools.tool(async (params, config) => {
|
|
358
|
+
const { code, session_id, timeout = DEFAULT_TIMEOUT } = params;
|
|
359
|
+
// Extra params injected by ToolNode (follows web_search pattern)
|
|
360
|
+
const { toolMap, toolDefs } = (config.toolCall ?? {});
|
|
361
|
+
if (toolMap == null || toolMap.size === 0) {
|
|
362
|
+
throw new Error('No toolMap provided. ' +
|
|
363
|
+
'ToolNode should inject this from AgentContext when invoked through the graph.');
|
|
364
|
+
}
|
|
365
|
+
if (toolDefs == null || toolDefs.length === 0) {
|
|
366
|
+
throw new Error('No tool definitions provided. ' +
|
|
367
|
+
'Either pass tools in the input or ensure ToolNode injects toolDefs.');
|
|
368
|
+
}
|
|
369
|
+
let roundTrip = 0;
|
|
370
|
+
try {
|
|
371
|
+
// ====================================================================
|
|
372
|
+
// Phase 1: Filter tools and make initial request
|
|
373
|
+
// ====================================================================
|
|
374
|
+
const effectiveTools = filterToolsByUsage(toolDefs, code, debug);
|
|
375
|
+
if (debug) {
|
|
376
|
+
// eslint-disable-next-line no-console
|
|
377
|
+
console.log(`[PTC Debug] Sending ${effectiveTools.length} tools to API ` +
|
|
378
|
+
`(filtered from ${toolDefs.length})`);
|
|
379
|
+
}
|
|
380
|
+
let response = await makeRequest(EXEC_ENDPOINT, apiKey, {
|
|
381
|
+
code,
|
|
382
|
+
tools: effectiveTools,
|
|
383
|
+
session_id,
|
|
384
|
+
timeout,
|
|
385
|
+
}, proxy);
|
|
386
|
+
// ====================================================================
|
|
387
|
+
// Phase 2: Handle response loop
|
|
388
|
+
// ====================================================================
|
|
389
|
+
while (response.status === 'tool_call_required') {
|
|
390
|
+
roundTrip++;
|
|
391
|
+
if (roundTrip > maxRoundTrips) {
|
|
392
|
+
throw new Error(`Exceeded maximum round trips (${maxRoundTrips}). ` +
|
|
393
|
+
'This may indicate an infinite loop, excessive tool calls, ' +
|
|
394
|
+
'or a logic error in your code.');
|
|
395
|
+
}
|
|
396
|
+
if (debug) {
|
|
397
|
+
// eslint-disable-next-line no-console
|
|
398
|
+
console.log(`[PTC Debug] Round trip ${roundTrip}: ${response.tool_calls?.length ?? 0} tool(s) to execute`);
|
|
399
|
+
}
|
|
400
|
+
const toolResults = await executeTools(response.tool_calls ?? [], toolMap);
|
|
401
|
+
response = await makeRequest(EXEC_ENDPOINT, apiKey, {
|
|
402
|
+
continuation_token: response.continuation_token,
|
|
403
|
+
tool_results: toolResults,
|
|
404
|
+
}, proxy);
|
|
405
|
+
}
|
|
406
|
+
// ====================================================================
|
|
407
|
+
// Phase 3: Handle final state
|
|
408
|
+
// ====================================================================
|
|
409
|
+
if (response.status === 'completed') {
|
|
410
|
+
return formatCompletedResponse(response);
|
|
411
|
+
}
|
|
412
|
+
if (response.status === 'error') {
|
|
413
|
+
throw new Error(`Execution error: ${response.error}` +
|
|
414
|
+
(response.stderr != null && response.stderr !== ''
|
|
415
|
+
? `\n\nStderr:\n${response.stderr}`
|
|
416
|
+
: ''));
|
|
417
|
+
}
|
|
418
|
+
throw new Error(`Unexpected response status: ${response.status}`);
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
throw new Error(`Programmatic execution failed: ${error.message}`);
|
|
422
|
+
}
|
|
423
|
+
}, {
|
|
424
|
+
name: _enum.Constants.PROGRAMMATIC_TOOL_CALLING,
|
|
425
|
+
description,
|
|
426
|
+
schema: ProgrammaticToolCallingSchema,
|
|
427
|
+
responseFormat: _enum.Constants.CONTENT_AND_ARTIFACT,
|
|
428
|
+
});
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
exports.createProgrammaticToolCallingTool = createProgrammaticToolCallingTool;
|
|
432
|
+
exports.executeTools = executeTools;
|
|
433
|
+
exports.extractUsedToolNames = extractUsedToolNames;
|
|
434
|
+
exports.filterToolsByUsage = filterToolsByUsage;
|
|
435
|
+
exports.formatCompletedResponse = formatCompletedResponse;
|
|
436
|
+
exports.makeRequest = makeRequest;
|
|
437
|
+
exports.normalizeToPythonIdentifier = normalizeToPythonIdentifier;
|
|
438
|
+
//# sourceMappingURL=ProgrammaticToolCalling.cjs.map
|
|
@@ -0,0 +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 automatically available as async Python functions - DO NOT define them yourself.\n\nThe Code API generates async function stubs from the tool definitions. Just call them directly:\n\nExample (Simple call):\n result = await get_weather(city=\"San Francisco\")\n print(result)\n\nExample (Parallel - Fastest):\n results = await asyncio.gather(\n get_weather(city=\"SF\"),\n get_weather(city=\"NYC\"),\n get_weather(city=\"London\")\n )\n for city, weather in zip([\"SF\", \"NYC\", \"London\"], results):\n print(f\"{city}: {weather['temperature']}°F\")\n\nExample (Loop with processing):\n team = await get_team_members()\n for member in team:\n expenses = await get_expenses(user_id=member['id'])\n total = sum(e['amount'] for e in expenses)\n print(f\"{member['name']}: \\${total:.2f}\")\n\nExample (Conditional logic):\n data = await fetch_data(source=\"primary\")\n if not data:\n data = await fetch_data(source=\"backup\")\n print(f\"Got {len(data)} records\")\n\nRequirements:\n- Tools are pre-defined as async functions - DO NOT write function definitions\n- Use await for all tool calls\n- Use asyncio.gather() for parallel execution of independent calls\n- Only print() output flows back to the context window\n- Tool results from programmatic calls do NOT consume context tokens`\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 * 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': 'Illuma/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 * Executes tools in parallel when requested by the API.\n * Uses Promise.all for parallel execution, catching individual errors.\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 return {\n call_id: call.id,\n result,\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 by writing Python code. Tools are available as async functions - just call them with await.\n\nThis is different from execute_code: here you can call your tools (like get_weather, get_expenses, etc.) directly in Python code.\n\nUsage:\n- Tools are pre-defined as async functions - call them with await\n- Use asyncio.gather() to run multiple tools in parallel\n- Only print() output is returned - tool results stay in Python\n\nExamples:\n- Simple: result = await get_weather(city=\"NYC\")\n- Loop: for user in users: data = await get_expenses(user_id=user['id'])\n- Parallel: sf, ny = await asyncio.gather(get_weather(city=\"SF\"), get_weather(city=\"NY\"))\n\nWhen to use this instead of calling tools directly:\n- You need to call tools in a loop (process many items)\n- You want parallel execution (asyncio.gather)\n- You need conditionals based on tool results\n- You want to aggregate/filter data before returning\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 let response = await makeRequest(\n EXEC_ENDPOINT,\n apiKey,\n {\n code,\n tools: effectiveTools,\n session_id,\n timeout,\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","Env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