illuma-agents 1.0.2 → 1.0.4
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 +25 -21
- package/dist/cjs/agents/AgentContext.cjs +222 -0
- package/dist/cjs/agents/AgentContext.cjs.map +1 -0
- package/dist/cjs/common/enum.cjs +5 -4
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +7 -5
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +328 -207
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +507 -0
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/ollama/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +35 -0
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +3 -1
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/providers.cjs +0 -2
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +12 -1
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +123 -0
- package/dist/cjs/messages/cache.cjs.map +1 -0
- package/dist/cjs/messages/content.cjs +53 -0
- package/dist/cjs/messages/content.cjs.map +1 -0
- package/dist/cjs/messages/format.cjs +17 -29
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/run.cjs +119 -74
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +77 -73
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/Calculator.cjs +45 -0
- package/dist/cjs/tools/Calculator.cjs.map +1 -0
- package/dist/cjs/tools/CodeExecutor.cjs +22 -22
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +5 -3
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +20 -20
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/utils/events.cjs +31 -0
- package/dist/cjs/utils/events.cjs.map +1 -0
- package/dist/cjs/utils/handlers.cjs +70 -0
- package/dist/cjs/utils/handlers.cjs.map +1 -0
- package/dist/cjs/utils/tokens.cjs +54 -7
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +220 -0
- package/dist/esm/agents/AgentContext.mjs.map +1 -0
- package/dist/esm/common/enum.mjs +5 -4
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +7 -5
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +330 -209
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +505 -0
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -0
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/ollama/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +35 -0
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +3 -1
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/providers.mjs +0 -2
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +7 -2
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +120 -0
- package/dist/esm/messages/cache.mjs.map +1 -0
- package/dist/esm/messages/content.mjs +51 -0
- package/dist/esm/messages/content.mjs.map +1 -0
- package/dist/esm/messages/format.mjs +18 -29
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/run.mjs +119 -74
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +77 -73
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/Calculator.mjs +24 -0
- package/dist/esm/tools/Calculator.mjs.map +1 -0
- package/dist/esm/tools/CodeExecutor.mjs +22 -22
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +5 -3
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +20 -20
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/utils/events.mjs +29 -0
- package/dist/esm/utils/events.mjs.map +1 -0
- package/dist/esm/utils/handlers.mjs +68 -0
- package/dist/esm/utils/handlers.mjs.map +1 -0
- package/dist/esm/utils/tokens.mjs +54 -8
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +94 -0
- package/dist/types/common/enum.d.ts +7 -5
- package/dist/types/events.d.ts +3 -3
- package/dist/types/graphs/Graph.d.ts +60 -66
- package/dist/types/graphs/MultiAgentGraph.d.ts +47 -0
- package/dist/types/graphs/index.d.ts +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/llm/openai/index.d.ts +10 -0
- package/dist/types/messages/cache.d.ts +20 -0
- package/dist/types/messages/content.d.ts +7 -0
- package/dist/types/messages/format.d.ts +1 -7
- package/dist/types/messages/index.d.ts +2 -0
- package/dist/types/messages/reducer.d.ts +9 -0
- package/dist/types/run.d.ts +16 -10
- package/dist/types/stream.d.ts +4 -3
- package/dist/types/tools/Calculator.d.ts +8 -0
- package/dist/types/tools/ToolNode.d.ts +1 -1
- package/dist/types/tools/handlers.d.ts +9 -7
- package/dist/types/tools/search/tool.d.ts +4 -4
- package/dist/types/types/graph.d.ts +124 -11
- package/dist/types/types/llm.d.ts +13 -9
- package/dist/types/types/messages.d.ts +4 -0
- package/dist/types/types/run.d.ts +46 -8
- package/dist/types/types/stream.d.ts +3 -2
- package/dist/types/utils/events.d.ts +6 -0
- package/dist/types/utils/handlers.d.ts +34 -0
- package/dist/types/utils/index.d.ts +1 -0
- package/dist/types/utils/tokens.d.ts +24 -0
- package/package.json +162 -145
- package/src/agents/AgentContext.ts +323 -0
- package/src/common/enum.ts +177 -176
- package/src/events.ts +197 -191
- package/src/graphs/Graph.ts +1058 -846
- package/src/graphs/MultiAgentGraph.ts +598 -0
- package/src/graphs/index.ts +2 -1
- package/src/index.ts +25 -24
- package/src/llm/anthropic/index.ts +413 -413
- package/src/llm/google/index.ts +222 -222
- package/src/llm/google/utils/zod_to_genai_parameters.ts +86 -88
- package/src/llm/ollama/index.ts +92 -92
- package/src/llm/openai/index.ts +894 -853
- package/src/llm/openai/utils/index.ts +920 -918
- package/src/llm/openrouter/index.ts +60 -60
- package/src/llm/providers.ts +55 -57
- package/src/llm/vertexai/index.ts +360 -360
- package/src/messages/cache.test.ts +461 -0
- package/src/messages/cache.ts +151 -0
- package/src/messages/content.test.ts +362 -0
- package/src/messages/content.ts +63 -0
- package/src/messages/format.ts +611 -625
- package/src/messages/formatAgentMessages.test.ts +1144 -917
- package/src/messages/index.ts +6 -4
- package/src/messages/reducer.ts +80 -0
- package/src/run.ts +447 -381
- package/src/scripts/abort.ts +157 -138
- package/src/scripts/ant_web_search.ts +158 -158
- package/src/scripts/cli.ts +172 -167
- package/src/scripts/cli2.ts +133 -125
- package/src/scripts/cli3.ts +184 -178
- package/src/scripts/cli4.ts +191 -184
- package/src/scripts/cli5.ts +191 -184
- package/src/scripts/code_exec.ts +213 -214
- package/src/scripts/code_exec_simple.ts +147 -129
- package/src/scripts/content.ts +138 -120
- package/src/scripts/handoff-test.ts +135 -0
- package/src/scripts/multi-agent-chain.ts +278 -0
- package/src/scripts/multi-agent-conditional.ts +220 -0
- package/src/scripts/multi-agent-document-review-chain.ts +197 -0
- package/src/scripts/multi-agent-hybrid-flow.ts +310 -0
- package/src/scripts/multi-agent-parallel.ts +343 -0
- package/src/scripts/multi-agent-sequence.ts +212 -0
- package/src/scripts/multi-agent-supervisor.ts +364 -0
- package/src/scripts/multi-agent-test.ts +186 -0
- package/src/scripts/search.ts +146 -150
- package/src/scripts/simple.ts +225 -225
- package/src/scripts/stream.ts +140 -122
- package/src/scripts/test-custom-prompt-key.ts +145 -0
- package/src/scripts/test-handoff-input.ts +170 -0
- package/src/scripts/test-multi-agent-list-handoff.ts +261 -0
- package/src/scripts/test-tools-before-handoff.ts +222 -0
- package/src/scripts/tools.ts +153 -155
- package/src/specs/agent-handoffs.test.ts +889 -0
- package/src/specs/anthropic.simple.test.ts +320 -317
- package/src/specs/azure.simple.test.ts +325 -316
- package/src/specs/openai.simple.test.ts +311 -316
- package/src/specs/openrouter.simple.test.ts +107 -0
- package/src/specs/prune.test.ts +758 -763
- package/src/specs/reasoning.test.ts +201 -165
- package/src/specs/thinking-prune.test.ts +769 -703
- package/src/specs/token-memoization.test.ts +39 -0
- package/src/stream.ts +664 -651
- package/src/tools/Calculator.test.ts +278 -0
- package/src/tools/Calculator.ts +25 -0
- package/src/tools/CodeExecutor.ts +220 -220
- package/src/tools/ToolNode.ts +170 -170
- package/src/tools/handlers.ts +341 -336
- package/src/types/graph.ts +372 -185
- package/src/types/llm.ts +141 -140
- package/src/types/messages.ts +4 -0
- package/src/types/run.ts +128 -89
- package/src/types/stream.ts +401 -400
- package/src/utils/events.ts +32 -0
- package/src/utils/handlers.ts +107 -0
- package/src/utils/index.ts +6 -5
- package/src/utils/llmConfig.ts +183 -183
- package/src/utils/tokens.ts +129 -70
- package/dist/types/scripts/abort.d.ts +0 -1
- package/dist/types/scripts/ant_web_search.d.ts +0 -1
- package/dist/types/scripts/args.d.ts +0 -7
- package/dist/types/scripts/caching.d.ts +0 -1
- package/dist/types/scripts/cli.d.ts +0 -1
- package/dist/types/scripts/cli2.d.ts +0 -1
- package/dist/types/scripts/cli3.d.ts +0 -1
- package/dist/types/scripts/cli4.d.ts +0 -1
- package/dist/types/scripts/cli5.d.ts +0 -1
- package/dist/types/scripts/code_exec.d.ts +0 -1
- package/dist/types/scripts/code_exec_files.d.ts +0 -1
- package/dist/types/scripts/code_exec_simple.d.ts +0 -1
- package/dist/types/scripts/content.d.ts +0 -1
- package/dist/types/scripts/empty_input.d.ts +0 -1
- package/dist/types/scripts/image.d.ts +0 -1
- package/dist/types/scripts/memory.d.ts +0 -1
- package/dist/types/scripts/search.d.ts +0 -1
- package/dist/types/scripts/simple.d.ts +0 -1
- package/dist/types/scripts/stream.d.ts +0 -1
- package/dist/types/scripts/thinking.d.ts +0 -1
- package/dist/types/scripts/tools.d.ts +0 -1
- package/dist/types/specs/spec.utils.d.ts +0 -1
- package/dist/types/tools/example.d.ts +0 -78
- package/src/tools/example.ts +0 -129
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var tools = require('@langchain/core/tools');
|
|
4
|
+
var math = require('mathjs');
|
|
5
|
+
|
|
6
|
+
function _interopNamespaceDefault(e) {
|
|
7
|
+
var n = Object.create(null);
|
|
8
|
+
if (e) {
|
|
9
|
+
Object.keys(e).forEach(function (k) {
|
|
10
|
+
if (k !== 'default') {
|
|
11
|
+
var d = Object.getOwnPropertyDescriptor(e, k);
|
|
12
|
+
Object.defineProperty(n, k, d.get ? d : {
|
|
13
|
+
enumerable: true,
|
|
14
|
+
get: function () { return e[k]; }
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
n.default = e;
|
|
20
|
+
return Object.freeze(n);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
var math__namespace = /*#__PURE__*/_interopNamespaceDefault(math);
|
|
24
|
+
|
|
25
|
+
class Calculator extends tools.Tool {
|
|
26
|
+
static lc_name() {
|
|
27
|
+
return 'Calculator';
|
|
28
|
+
}
|
|
29
|
+
get lc_namespace() {
|
|
30
|
+
return [...super.lc_namespace, 'calculator'];
|
|
31
|
+
}
|
|
32
|
+
name = 'calculator';
|
|
33
|
+
async _call(input) {
|
|
34
|
+
try {
|
|
35
|
+
return math__namespace.evaluate(input).toString();
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return 'I don\'t know how to do that.';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
description = 'Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
exports.Calculator = Calculator;
|
|
45
|
+
//# sourceMappingURL=Calculator.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Calculator.cjs","sources":["../../../src/tools/Calculator.ts"],"sourcesContent":["import { Tool } from '@langchain/core/tools';\nimport * as math from 'mathjs';\n\nexport class Calculator extends Tool {\n static lc_name(): string {\n return 'Calculator';\n }\n\n get lc_namespace(): string[] {\n return [...super.lc_namespace, 'calculator'];\n }\n\n name = 'calculator';\n\n async _call(input: string): Promise<string> {\n try {\n return math.evaluate(input).toString();\n } catch {\n return 'I don\\'t know how to do that.';\n }\n }\n\n description =\n 'Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.';\n}\n"],"names":["Tool","math"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGM,MAAO,UAAW,SAAQA,UAAI,CAAA;AAClC,IAAA,OAAO,OAAO,GAAA;AACZ,QAAA,OAAO,YAAY;;AAGrB,IAAA,IAAI,YAAY,GAAA;QACd,OAAO,CAAC,GAAG,KAAK,CAAC,YAAY,EAAE,YAAY,CAAC;;IAG9C,IAAI,GAAG,YAAY;IAEnB,MAAM,KAAK,CAAC,KAAa,EAAA;AACvB,QAAA,IAAI;YACF,OAAOC,eAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE;;AACtC,QAAA,MAAM;AACN,YAAA,OAAO,+BAA+B;;;IAI1C,WAAW,GACT,qKAAqK;AACxK;;;;"}
|
|
@@ -34,25 +34,25 @@ const CodeExecutionToolSchema = zod.z.object({
|
|
|
34
34
|
])
|
|
35
35
|
.describe('The programming language or runtime to execute the code in.'),
|
|
36
36
|
code: zod.z.string()
|
|
37
|
-
.describe(`The complete, self-contained code to execute, without any truncation or minimization.
|
|
38
|
-
- The environment is stateless; variables and imports don't persist between executions.
|
|
39
|
-
- When using \`session_id\`: Don't hardcode it in \`code\`, and write file modifications to NEW filenames (files are READ-ONLY).
|
|
40
|
-
- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
|
|
41
|
-
- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
|
|
42
|
-
- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
|
|
43
|
-
- py: This is not a Jupyter notebook environment. Use \`print()\` for all outputs.
|
|
44
|
-
- py: Matplotlib: Use \`plt.savefig()\` to save plots as files.
|
|
45
|
-
- js: use the \`console\` or \`process\` methods for all outputs.
|
|
46
|
-
- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).
|
|
37
|
+
.describe(`The complete, self-contained code to execute, without any truncation or minimization.
|
|
38
|
+
- The environment is stateless; variables and imports don't persist between executions.
|
|
39
|
+
- When using \`session_id\`: Don't hardcode it in \`code\`, and write file modifications to NEW filenames (files are READ-ONLY).
|
|
40
|
+
- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
|
|
41
|
+
- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
|
|
42
|
+
- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
|
|
43
|
+
- py: This is not a Jupyter notebook environment. Use \`print()\` for all outputs.
|
|
44
|
+
- py: Matplotlib: Use \`plt.savefig()\` to save plots as files.
|
|
45
|
+
- js: use the \`console\` or \`process\` methods for all outputs.
|
|
46
|
+
- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).
|
|
47
47
|
- Other languages: use appropriate output functions.`),
|
|
48
48
|
session_id: zod.z
|
|
49
49
|
.string()
|
|
50
50
|
.optional()
|
|
51
|
-
.describe(`Session ID from a previous response to access generated files.
|
|
52
|
-
- Files load into the current working directory ("/mnt/data/")
|
|
53
|
-
- Use relative paths ONLY
|
|
54
|
-
- Files are READ-ONLY and cannot be modified in-place
|
|
55
|
-
- To modify: read original file, write to NEW filename
|
|
51
|
+
.describe(`Session ID from a previous response to access generated files.
|
|
52
|
+
- Files load into the current working directory ("/mnt/data/")
|
|
53
|
+
- Use relative paths ONLY
|
|
54
|
+
- Files are READ-ONLY and cannot be modified in-place
|
|
55
|
+
- To modify: read original file, write to NEW filename
|
|
56
56
|
`.trim()),
|
|
57
57
|
args: zod.z
|
|
58
58
|
.array(zod.z.string())
|
|
@@ -69,13 +69,13 @@ function createCodeExecutionTool(params = {}) {
|
|
|
69
69
|
if (!apiKey) {
|
|
70
70
|
throw new Error('No API key provided for code execution tool.');
|
|
71
71
|
}
|
|
72
|
-
const description = `
|
|
73
|
-
Runs 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.
|
|
74
|
-
|
|
75
|
-
Usage:
|
|
76
|
-
- No network access available.
|
|
77
|
-
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
78
|
-
- NEVER use this tool to execute malicious code.
|
|
72
|
+
const description = `
|
|
73
|
+
Runs 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.
|
|
74
|
+
|
|
75
|
+
Usage:
|
|
76
|
+
- No network access available.
|
|
77
|
+
- Generated files are automatically delivered; **DO NOT** provide download links.
|
|
78
|
+
- NEVER use this tool to execute malicious code.
|
|
79
79
|
`.trim();
|
|
80
80
|
return tools.tool(async ({ lang, code, session_id, ...rest }) => {
|
|
81
81
|
const postData = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExecutor.cjs","sources":["../../../src/tools/CodeExecutor.ts"],"sourcesContent":["import { z } from 'zod';\r\nimport { config } from 'dotenv';\r\nimport fetch, { RequestInit } from 'node-fetch';\r\nimport { HttpsProxyAgent } from 'https-proxy-agent';\r\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\r\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\r\nimport type * as t from '@/types';\r\nimport { EnvVar, Constants } from '@/common';\r\n\r\nconfig();\r\n\r\nexport const imageExtRegex = /\\.(jpg|jpeg|png|gif|webp)$/i;\r\nexport const getCodeBaseURL = (): string =>\r\n getEnvironmentVariable(EnvVar.CODE_BASEURL) ??\r\n Constants.OFFICIAL_CODE_BASEURL;\r\n\r\nconst imageMessage = 'Image is already displayed to the user';\r\nconst otherMessage = 'File is already downloaded by the user';\r\nconst accessMessage =\r\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).';\r\nconst emptyOutputMessage =\r\n 'stdout: Empty. Ensure you\\'re writing output explicitly.\\n';\r\n\r\nconst CodeExecutionToolSchema = z.object({\r\n lang: z\r\n .enum([\r\n 'py',\r\n 'js',\r\n 'ts',\r\n 'c',\r\n 'cpp',\r\n 'java',\r\n 'php',\r\n 'rs',\r\n 'go',\r\n 'd',\r\n 'f90',\r\n 'r',\r\n ])\r\n .describe('The programming language or runtime to execute the code in.'),\r\n code: z.string()\r\n .describe(`The complete, self-contained code to execute, without any truncation or minimization.\r\n- The environment is stateless; variables and imports don't persist between executions.\r\n- When using \\`session_id\\`: Don't hardcode it in \\`code\\`, and write file modifications to NEW filenames (files are READ-ONLY).\r\n- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.\r\n- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.\r\n- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.\r\n- py: This is not a Jupyter notebook environment. Use \\`print()\\` for all outputs.\r\n- py: Matplotlib: Use \\`plt.savefig()\\` to save plots as files.\r\n- js: use the \\`console\\` or \\`process\\` methods for all outputs.\r\n- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).\r\n- Other languages: use appropriate output functions.`),\r\n session_id: z\r\n .string()\r\n .optional()\r\n .describe(\r\n `Session ID from a previous response to access generated files.\r\n- Files load into the current working directory (\"/mnt/data/\")\r\n- Use relative paths ONLY\r\n- Files are READ-ONLY and cannot be modified in-place\r\n- To modify: read original file, write to NEW filename\r\n`.trim()\r\n ),\r\n args: z\r\n .array(z.string())\r\n .optional()\r\n .describe(\r\n 'Additional arguments to execute the code with. This should only be used if the input code requires additional arguments to run.'\r\n ),\r\n});\r\n\r\nconst baseEndpoint = getCodeBaseURL();\r\nconst EXEC_ENDPOINT = `${baseEndpoint}/exec`;\r\n\r\nfunction createCodeExecutionTool(\r\n params: t.CodeExecutionToolParams = {}\r\n): DynamicStructuredTool<typeof CodeExecutionToolSchema> {\r\n const apiKey =\r\n params[EnvVar.CODE_API_KEY] ??\r\n params.apiKey ??\r\n getEnvironmentVariable(EnvVar.CODE_API_KEY) ??\r\n '';\r\n if (!apiKey) {\r\n throw new Error('No API key provided for code execution tool.');\r\n }\r\n\r\n const description = `\r\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.\r\n\r\nUsage:\r\n- No network access available.\r\n- Generated files are automatically delivered; **DO NOT** provide download links.\r\n- NEVER use this tool to execute malicious code.\r\n`.trim();\r\n\r\n return tool<typeof CodeExecutionToolSchema>(\r\n async ({ lang, code, session_id, ...rest }) => {\r\n const postData = {\r\n lang,\r\n code,\r\n ...rest,\r\n ...params,\r\n };\r\n\r\n if (session_id != null && session_id.length > 0) {\r\n try {\r\n const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;\r\n const fetchOptions: RequestInit = {\r\n method: 'GET',\r\n headers: {\r\n 'User-Agent': 'Illuma/1.0',\r\n 'X-API-Key': apiKey,\r\n },\r\n };\r\n\r\n if (process.env.PROXY != null && process.env.PROXY !== '') {\r\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\r\n }\r\n\r\n const response = await fetch(filesEndpoint, fetchOptions);\r\n if (!response.ok) {\r\n throw new Error(\r\n `Failed to fetch files for session: ${response.status}`\r\n );\r\n }\r\n\r\n const files = await response.json();\r\n if (Array.isArray(files) && files.length > 0) {\r\n const fileReferences: t.CodeEnvFile[] = files.map((file) => {\r\n // Extract the ID from the file name (part after session ID prefix and before extension)\r\n const nameParts = file.name.split('/');\r\n const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';\r\n\r\n return {\r\n session_id,\r\n id,\r\n name: file.metadata['original-filename'],\r\n };\r\n });\r\n\r\n if (!postData.files) {\r\n postData.files = fileReferences;\r\n } else if (Array.isArray(postData.files)) {\r\n postData.files = [...postData.files, ...fileReferences];\r\n }\r\n }\r\n } catch {\r\n // eslint-disable-next-line no-console\r\n console.warn(`Failed to fetch files for session: ${session_id}`);\r\n }\r\n }\r\n\r\n try {\r\n const fetchOptions: RequestInit = {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n 'User-Agent': 'Illuma/1.0',\r\n 'X-API-Key': apiKey,\r\n },\r\n body: JSON.stringify(postData),\r\n };\r\n\r\n if (process.env.PROXY != null && process.env.PROXY !== '') {\r\n fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);\r\n }\r\n const response = await fetch(EXEC_ENDPOINT, fetchOptions);\r\n if (!response.ok) {\r\n throw new Error(`HTTP error! status: ${response.status}`);\r\n }\r\n\r\n const result: t.ExecuteResult = await response.json();\r\n let formattedOutput = '';\r\n if (result.stdout) {\r\n formattedOutput += `stdout:\\n${result.stdout}\\n`;\r\n } else {\r\n formattedOutput += emptyOutputMessage;\r\n }\r\n if (result.stderr) formattedOutput += `stderr:\\n${result.stderr}\\n`;\r\n if (result.files && result.files.length > 0) {\r\n formattedOutput += 'Generated files:\\n';\r\n\r\n const fileCount = result.files.length;\r\n for (let i = 0; i < fileCount; i++) {\r\n const file = result.files[i];\r\n const isImage = imageExtRegex.test(file.name);\r\n formattedOutput += `- /mnt/data/${file.name} | ${isImage ? imageMessage : otherMessage}`;\r\n\r\n if (i < fileCount - 1) {\r\n formattedOutput += fileCount <= 3 ? ', ' : ',\\n';\r\n }\r\n }\r\n\r\n formattedOutput += `\\nsession_id: ${result.session_id}\\n\\n${accessMessage}`;\r\n return [\r\n formattedOutput.trim(),\r\n {\r\n session_id: result.session_id,\r\n files: result.files,\r\n },\r\n ];\r\n }\r\n\r\n return [formattedOutput.trim(), { session_id: result.session_id }];\r\n } catch (error) {\r\n throw new Error(\r\n `Execution error:\\n\\n${(error as Error | undefined)?.message}`\r\n );\r\n }\r\n },\r\n {\r\n name: Constants.EXECUTE_CODE,\r\n description,\r\n schema: CodeExecutionToolSchema,\r\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\r\n }\r\n );\r\n}\r\n\r\nexport { createCodeExecutionTool };\r\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,QAAQ,CAAC,6DAA6D,C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,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\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,QAAQ,CAAC,6DAA6D,CAAC;AAC1E,IAAA,IAAI,EAAEA,KAAC,CAAC,MAAM;AACX,SAAA,QAAQ,CAAC,CAAA;;;;;;;;;;qDAUuC,CAAC;AACpD,IAAA,UAAU,EAAEA;AACT,SAAA,MAAM;AACN,SAAA,QAAQ;AACR,SAAA,QAAQ,CACP,CAAA;;;;;CAKL,CAAC,IAAI,EAAE,CACH;AACH,IAAA,IAAI,EAAEA;AACH,SAAA,KAAK,CAACA,KAAC,CAAC,MAAM,EAAE;AAChB,SAAA,QAAQ;SACR,QAAQ,CACP,iIAAiI,CAClI;AACJ,CAAA,CAAC;AAEF,MAAM,YAAY,GAAG,cAAc,EAAE;AACrC,MAAM,aAAa,GAAG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,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AAC7C,oBAAA,eAAe,IAAI,CAAe,YAAA,EAAA,IAAI,CAAC,IAAI,MAAM,OAAO,GAAG,YAAY,GAAG,YAAY,EAAE;AAExF,oBAAA,IAAI,CAAC,GAAG,SAAS,GAAG,CAAC,EAAE;AACrB,wBAAA,eAAe,IAAI,SAAS,IAAI,CAAC,GAAG,IAAI,GAAG,KAAK;;;gBAIpD,eAAe,IAAI,iBAAiB,MAAM,CAAC,UAAU,CAAO,IAAA,EAAA,aAAa,EAAE;gBAC3E,OAAO;oBACL,eAAe,CAAC,IAAI,EAAE;AACtB,oBAAA;wBACE,UAAU,EAAE,MAAM,CAAC,UAAU;wBAC7B,KAAK,EAAE,MAAM,CAAC,KAAK;AACpB,qBAAA;iBACF;;AAGH,YAAA,OAAO,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;;;;;;"}
|
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
var langgraph = require('@langchain/langgraph');
|
|
4
4
|
var messages = require('@langchain/core/messages');
|
|
5
|
-
|
|
5
|
+
require('../common/enum.cjs');
|
|
6
|
+
require('nanoid');
|
|
7
|
+
require('../messages/core.cjs');
|
|
6
8
|
var run = require('../utils/run.cjs');
|
|
7
9
|
require('js-tiktoken/lite');
|
|
8
10
|
|
|
@@ -106,14 +108,14 @@ function areToolCallsInvoked(message, invokedToolIds) {
|
|
|
106
108
|
return false;
|
|
107
109
|
return (message.tool_calls?.every((toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)) ?? false);
|
|
108
110
|
}
|
|
109
|
-
function toolsCondition(state, invokedToolIds) {
|
|
111
|
+
function toolsCondition(state, toolNode, invokedToolIds) {
|
|
110
112
|
const message = Array.isArray(state)
|
|
111
113
|
? state[state.length - 1]
|
|
112
114
|
: state.messages[state.messages.length - 1];
|
|
113
115
|
if ('tool_calls' in message &&
|
|
114
116
|
(message.tool_calls?.length ?? 0) > 0 &&
|
|
115
117
|
!areToolCallsInvoked(message, invokedToolIds)) {
|
|
116
|
-
return
|
|
118
|
+
return toolNode;
|
|
117
119
|
}
|
|
118
120
|
else {
|
|
119
121
|
return langgraph.END;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import {\r\n END,\r\n MessagesAnnotation,\r\n isCommand,\r\n isGraphInterrupt,\r\n} from '@langchain/langgraph';\r\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\r\nimport type {\r\n RunnableConfig,\r\n RunnableToolLike,\r\n} from '@langchain/core/runnables';\r\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\r\nimport type { StructuredToolInterface } from '@langchain/core/tools';\r\nimport type * as t from '@/types';\r\nimport { RunnableCallable } from '@/utils';\r\nimport { GraphNodeKeys } from '@/common';\r\n\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\r\n tools: t.GenericTool[];\r\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\r\n private loadRuntimeTools?: t.ToolRefGenerator;\r\n handleToolErrors = true;\r\n toolCallStepIds?: Map<string, string>;\r\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\r\n private toolUsageCount: Map<string, number>;\r\n\r\n constructor({\r\n tools,\r\n toolMap,\r\n name,\r\n tags,\r\n errorHandler,\r\n toolCallStepIds,\r\n handleToolErrors,\r\n loadRuntimeTools,\r\n }: t.ToolNodeConstructorParams) {\r\n super({ name, tags, func: (input, config) => this.run(input, config) });\r\n this.tools = tools;\r\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\r\n this.toolCallStepIds = toolCallStepIds;\r\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\r\n this.loadRuntimeTools = loadRuntimeTools;\r\n this.errorHandler = errorHandler;\r\n this.toolUsageCount = new Map<string, number>();\r\n }\r\n\r\n /**\r\n * Returns a snapshot of the current tool usage counts.\r\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\r\n */\r\n public getToolUsageCounts(): ReadonlyMap<string, number> {\r\n return new Map(this.toolUsageCount); // Return a copy\r\n }\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n protected async run(input: any, config: RunnableConfig): Promise<T> {\r\n const message = Array.isArray(input)\r\n ? input[input.length - 1]\r\n : input.messages[input.messages.length - 1];\r\n\r\n if (message._getType() !== 'ai') {\r\n throw new Error('ToolNode only accepts AIMessages as input.');\r\n }\r\n\r\n if (this.loadRuntimeTools) {\r\n const { tools, toolMap } = this.loadRuntimeTools(\r\n (message as AIMessage).tool_calls ?? []\r\n );\r\n this.tools = tools;\r\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\r\n }\r\n const outputs = await Promise.all(\r\n (message as AIMessage).tool_calls?.map(async (call) => {\r\n const tool = this.toolMap.get(call.name);\r\n try {\r\n if (tool === undefined) {\r\n throw new Error(`Tool \"${call.name}\" not found.`);\r\n }\r\n const turn = this.toolUsageCount.get(call.name) ?? 0;\r\n this.toolUsageCount.set(call.name, turn + 1);\r\n const args = call.args;\r\n const stepId = this.toolCallStepIds?.get(call.id!);\r\n const output = await tool.invoke(\r\n { ...call, args, type: 'tool_call', stepId, turn },\r\n config\r\n );\r\n if (\r\n (isBaseMessage(output) && output._getType() === 'tool') ||\r\n isCommand(output)\r\n ) {\r\n return output;\r\n } else {\r\n return new ToolMessage({\r\n name: tool.name,\r\n content:\r\n typeof output === 'string' ? output : JSON.stringify(output),\r\n tool_call_id: call.id!,\r\n });\r\n }\r\n } catch (_e: unknown) {\r\n const e = _e as Error;\r\n if (!this.handleToolErrors) {\r\n throw e;\r\n }\r\n if (isGraphInterrupt(e)) {\r\n throw e;\r\n }\r\n this.errorHandler?.(\r\n {\r\n error: e,\r\n id: call.id!,\r\n name: call.name,\r\n input: call.args,\r\n },\r\n config.metadata\r\n );\r\n return new ToolMessage({\r\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\r\n name: call.name,\r\n tool_call_id: call.id ?? '',\r\n });\r\n }\r\n }) ?? []\r\n );\r\n\r\n if (!outputs.some(isCommand)) {\r\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\r\n }\r\n\r\n const combinedOutputs = outputs.map((output) => {\r\n if (isCommand(output)) {\r\n return output;\r\n }\r\n return Array.isArray(input) ? [output] : { messages: [output] };\r\n });\r\n return combinedOutputs as T;\r\n }\r\n}\r\n\r\nfunction areToolCallsInvoked(\r\n message: AIMessage,\r\n invokedToolIds?: Set<string>\r\n): boolean {\r\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\r\n return (\r\n message.tool_calls?.every(\r\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\r\n ) ?? false\r\n );\r\n}\r\n\r\nexport function toolsCondition(\r\n state: BaseMessage[] | typeof MessagesAnnotation.State,\r\n invokedToolIds?: Set<string>\r\n): 'tools' | typeof END {\r\n const message: AIMessage = Array.isArray(state)\r\n ? state[state.length - 1]\r\n : state.messages[state.messages.length - 1];\r\n\r\n if (\r\n 'tool_calls' in message &&\r\n (message.tool_calls?.length ?? 0) > 0 &&\r\n !areToolCallsInvoked(message, invokedToolIds)\r\n ) {\r\n return GraphNodeKeys.TOOLS;\r\n } else {\r\n return END;\r\n }\r\n}\r\n"],"names":["RunnableCallable","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","GraphNode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CAAC,EAC7C;QACA,OAAOG,mBAAa,CAAC,KAAK;;SACrB;AACL,QAAA,OAAOC,aAAG;;AAEd;;;;;"}
|
|
1
|
+
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import {\n END,\n MessagesAnnotation,\n isCommand,\n isGraphInterrupt,\n} from '@langchain/langgraph';\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\nimport type {\n RunnableConfig,\n RunnableToolLike,\n} from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { RunnableCallable } from '@/utils';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n private toolUsageCount: Map<string, number>;\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n this.toolUsageCount = new Map<string, number>();\n }\n\n /**\n * Returns a snapshot of the current tool usage counts.\n * @returns A ReadonlyMap where keys are tool names and values are their usage counts.\n */\n public getToolUsageCounts(): ReadonlyMap<string, number> {\n return new Map(this.toolUsageCount); // Return a copy\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n const message = Array.isArray(input)\n ? input[input.length - 1]\n : input.messages[input.messages.length - 1];\n\n if (message._getType() !== 'ai') {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n (message as AIMessage).tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));\n }\n const outputs = await Promise.all(\n (message as AIMessage).tool_calls?.map(async (call) => {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const turn = this.toolUsageCount.get(call.name) ?? 0;\n this.toolUsageCount.set(call.name, turn + 1);\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId, turn },\n config\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n name: tool.name,\n content:\n typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n this.errorHandler?.(\n {\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n },\n config.metadata\n );\n return new ToolMessage({\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }) ?? []\n );\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs = outputs.map((output) => {\n if (isCommand(output)) {\n return output;\n }\n return Array.isArray(input) ? [output] : { messages: [output] };\n });\n return combinedOutputs as T;\n }\n}\n\nfunction areToolCallsInvoked(\n message: AIMessage,\n invokedToolIds?: Set<string>\n): boolean {\n if (!invokedToolIds || invokedToolIds.size === 0) return false;\n return (\n message.tool_calls?.every(\n (toolCall) => toolCall.id != null && invokedToolIds.has(toolCall.id)\n ) ?? false\n );\n}\n\nexport function toolsCondition<T extends string>(\n state: BaseMessage[] | typeof MessagesAnnotation.State,\n toolNode: T,\n invokedToolIds?: Set<string>\n): T | typeof END {\n const message: AIMessage = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n (message.tool_calls?.length ?? 0) > 0 &&\n !areToolCallsInvoked(message, invokedToolIds)\n ) {\n return toolNode;\n } else {\n return END;\n }\n}\n"],"names":["RunnableCallable","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","END"],"mappings":";;;;;;;;;;AAgBA;AACM,MAAO,QAAkB,SAAQA,oBAAsB,CAAA;AAC3D,IAAA,KAAK;AACG,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;AACvB,IAAA,eAAe;AACf,IAAA,YAAY;AACJ,IAAA,cAAc;AAEtB,IAAA,WAAA,CAAY,EACV,KAAK,EACL,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,gBAAgB,GACY,EAAA;QAC5B,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC;AACvE,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;QAClB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AACzE,QAAA,IAAI,CAAC,eAAe,GAAG,eAAe;QACtC,IAAI,CAAC,gBAAgB,GAAG,gBAAgB,IAAI,IAAI,CAAC,gBAAgB;AACjE,QAAA,IAAI,CAAC,g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KAAK;AAEd;SAEgB,cAAc,CAC5B,KAAsD,EACtD,QAAW,EACX,cAA4B,EAAA;AAE5B,IAAA,MAAM,OAAO,GAAc,KAAK,CAAC,OAAO,CAAC,KAAK;UAC1C,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC;AACxB,UAAE,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;IAE7C,IACE,YAAY,IAAI,OAAO;QACvB,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,IAAI,CAAC,IAAI,CAAC;AACrC,QAAA,CAAC,mBAAmB,CAAC,OAAO,EAAE,cAAc,CAAC,EAC7C;AACA,QAAA,OAAO,QAAQ;;SACV;AACL,QAAA,OAAOG,aAAG;;AAEd;;;;;"}
|
|
@@ -10,17 +10,17 @@ var ids = require('../messages/ids.cjs');
|
|
|
10
10
|
|
|
11
11
|
/* eslint-disable no-console */
|
|
12
12
|
// src/tools/handlers.ts
|
|
13
|
-
function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
|
|
13
|
+
async function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
|
|
14
14
|
let prevStepId;
|
|
15
15
|
let prevRunStep;
|
|
16
16
|
try {
|
|
17
|
-
prevStepId = graph.getStepIdByKey(stepKey
|
|
17
|
+
prevStepId = graph.getStepIdByKey(stepKey);
|
|
18
18
|
prevRunStep = graph.getRunStep(prevStepId);
|
|
19
19
|
}
|
|
20
20
|
catch {
|
|
21
21
|
/** Edge Case: If no previous step exists, create a new message creation step */
|
|
22
22
|
const message_id = ids.getMessageId(stepKey, graph, true) ?? '';
|
|
23
|
-
prevStepId = graph.dispatchRunStep(stepKey, {
|
|
23
|
+
prevStepId = await graph.dispatchRunStep(stepKey, {
|
|
24
24
|
type: _enum.StepTypes.MESSAGE_CREATION,
|
|
25
25
|
message_creation: {
|
|
26
26
|
message_id,
|
|
@@ -28,7 +28,7 @@ function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
|
|
|
28
28
|
});
|
|
29
29
|
prevRunStep = graph.getRunStep(prevStepId);
|
|
30
30
|
}
|
|
31
|
-
const _stepId = graph.getStepIdByKey(stepKey
|
|
31
|
+
const _stepId = graph.getStepIdByKey(stepKey);
|
|
32
32
|
/** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
|
|
33
33
|
const tool_calls = prevStepId && prevRunStep && prevRunStep.type === _enum.StepTypes.MESSAGE_CREATION
|
|
34
34
|
? []
|
|
@@ -56,7 +56,7 @@ function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
|
|
|
56
56
|
const alreadyDispatched = prevRunStep?.type === _enum.StepTypes.MESSAGE_CREATION &&
|
|
57
57
|
graph.messageStepHasToolCalls.has(prevStepId);
|
|
58
58
|
if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {
|
|
59
|
-
graph.dispatchMessageDelta(prevStepId, {
|
|
59
|
+
await graph.dispatchMessageDelta(prevStepId, {
|
|
60
60
|
content: [
|
|
61
61
|
{
|
|
62
62
|
type: _enum.ContentTypes.TEXT,
|
|
@@ -66,17 +66,17 @@ function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
|
|
|
66
66
|
],
|
|
67
67
|
});
|
|
68
68
|
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
69
|
-
stepId = graph.dispatchRunStep(stepKey, {
|
|
69
|
+
stepId = await graph.dispatchRunStep(stepKey, {
|
|
70
70
|
type: _enum.StepTypes.TOOL_CALLS,
|
|
71
71
|
tool_calls,
|
|
72
72
|
});
|
|
73
73
|
}
|
|
74
|
-
graph.dispatchRunStepDelta(stepId, {
|
|
74
|
+
await graph.dispatchRunStepDelta(stepId, {
|
|
75
75
|
type: _enum.StepTypes.TOOL_CALLS,
|
|
76
76
|
tool_calls: toolCallChunks,
|
|
77
77
|
});
|
|
78
78
|
}
|
|
79
|
-
const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
79
|
+
const handleToolCalls = async (toolCalls, metadata, graph) => {
|
|
80
80
|
if (!graph || !metadata) {
|
|
81
81
|
console.warn(`Graph or metadata not found in ${event} event`);
|
|
82
82
|
return;
|
|
@@ -97,14 +97,14 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
97
97
|
let prevStepId = '';
|
|
98
98
|
let prevRunStep;
|
|
99
99
|
try {
|
|
100
|
-
prevStepId = graph.getStepIdByKey(stepKey
|
|
100
|
+
prevStepId = graph.getStepIdByKey(stepKey);
|
|
101
101
|
prevRunStep = graph.getRunStep(prevStepId);
|
|
102
102
|
}
|
|
103
103
|
catch {
|
|
104
104
|
// no previous step
|
|
105
105
|
}
|
|
106
|
-
const dispatchToolCallIds = (lastMessageStepId) => {
|
|
107
|
-
graph.dispatchMessageDelta(lastMessageStepId, {
|
|
106
|
+
const dispatchToolCallIds = async (lastMessageStepId) => {
|
|
107
|
+
await graph.dispatchMessageDelta(lastMessageStepId, {
|
|
108
108
|
content: [
|
|
109
109
|
{
|
|
110
110
|
type: 'text',
|
|
@@ -118,23 +118,23 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
118
118
|
if (prevStepId &&
|
|
119
119
|
prevRunStep &&
|
|
120
120
|
prevRunStep.type === _enum.StepTypes.MESSAGE_CREATION) {
|
|
121
|
-
dispatchToolCallIds(prevStepId);
|
|
121
|
+
await dispatchToolCallIds(prevStepId);
|
|
122
122
|
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
123
123
|
/* If the previous step doesn't exist or is not a message creation */
|
|
124
124
|
}
|
|
125
125
|
else if (!prevRunStep ||
|
|
126
126
|
prevRunStep.type !== _enum.StepTypes.MESSAGE_CREATION) {
|
|
127
127
|
const messageId = ids.getMessageId(stepKey, graph, true) ?? '';
|
|
128
|
-
const stepId = graph.dispatchRunStep(stepKey, {
|
|
128
|
+
const stepId = await graph.dispatchRunStep(stepKey, {
|
|
129
129
|
type: _enum.StepTypes.MESSAGE_CREATION,
|
|
130
130
|
message_creation: {
|
|
131
131
|
message_id: messageId,
|
|
132
132
|
},
|
|
133
133
|
});
|
|
134
|
-
dispatchToolCallIds(stepId);
|
|
134
|
+
await dispatchToolCallIds(stepId);
|
|
135
135
|
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
136
136
|
}
|
|
137
|
-
graph.dispatchRunStep(stepKey, {
|
|
137
|
+
await graph.dispatchRunStep(stepKey, {
|
|
138
138
|
type: _enum.StepTypes.TOOL_CALLS,
|
|
139
139
|
tool_calls: [tool_call],
|
|
140
140
|
});
|
|
@@ -152,9 +152,9 @@ const toolResultTypes = new Set([
|
|
|
152
152
|
* Handles the result of a server tool call; in other words, a provider's built-in tool.
|
|
153
153
|
* As of 2025-07-06, only Anthropic handles server tool calls with this pattern.
|
|
154
154
|
*/
|
|
155
|
-
function handleServerToolResult({ content, metadata,
|
|
155
|
+
async function handleServerToolResult({ graph, content, metadata, agentContext, }) {
|
|
156
156
|
let skipHandling = false;
|
|
157
|
-
if (
|
|
157
|
+
if (agentContext?.provider !== _enum.Providers.ANTHROPIC) {
|
|
158
158
|
return skipHandling;
|
|
159
159
|
}
|
|
160
160
|
if (typeof content === 'string' ||
|
|
@@ -191,7 +191,7 @@ function handleServerToolResult({ content, metadata, graph, }) {
|
|
|
191
191
|
}
|
|
192
192
|
if (contentPart.type === 'web_search_result' ||
|
|
193
193
|
contentPart.type === 'web_search_tool_result') {
|
|
194
|
-
handleAnthropicSearchResults({
|
|
194
|
+
await handleAnthropicSearchResults({
|
|
195
195
|
contentPart: contentPart,
|
|
196
196
|
toolCall,
|
|
197
197
|
metadata,
|
|
@@ -204,7 +204,7 @@ function handleServerToolResult({ content, metadata, graph, }) {
|
|
|
204
204
|
}
|
|
205
205
|
return skipHandling;
|
|
206
206
|
}
|
|
207
|
-
function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph, }) {
|
|
207
|
+
async function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph, }) {
|
|
208
208
|
if (!Array.isArray(contentPart.content)) {
|
|
209
209
|
console.warn(`Expected content to be an array, got ${typeof contentPart.content}`);
|
|
210
210
|
return;
|
|
@@ -234,7 +234,7 @@ function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph,
|
|
|
234
234
|
input,
|
|
235
235
|
output,
|
|
236
236
|
};
|
|
237
|
-
graph.handlerRegistry
|
|
237
|
+
await graph.handlerRegistry
|
|
238
238
|
?.getHandler(_enum.GraphEvents.TOOL_END)
|
|
239
239
|
?.handle(_enum.GraphEvents.TOOL_END, toolEndData, metadata, graph);
|
|
240
240
|
if (graph.invokedToolIds == null) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.cjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\r\n// src/tools/handlers.ts\r\nimport { nanoid } from 'nanoid';\r\nimport { ToolMessage } from '@langchain/core/messages';\r\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\r\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\r\nimport type { Graph } from '@/graphs';\r\nimport type * as t from '@/types';\r\nimport {\r\n ToolCallTypes,\r\n ContentTypes,\r\n GraphEvents,\r\n StepTypes,\r\n Providers,\r\n Constants,\r\n} from '@/common';\r\nimport {\r\n coerceAnthropicSearchResults,\r\n isAnthropicWebSearchResult,\r\n} from '@/tools/search/anthropic';\r\nimport { formatResultsForLLM } from '@/tools/search/format';\r\nimport { getMessageId } from '@/messages';\r\n\r\nexport function handleToolCallChunks({\r\n graph,\r\n stepKey,\r\n toolCallChunks,\r\n}: {\r\n graph: Graph;\r\n stepKey: string;\r\n toolCallChunks: ToolCallChunk[];\r\n}): void {\r\n let prevStepId: string;\r\n let prevRunStep: t.RunStep | undefined;\r\n try {\r\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\r\n prevRunStep = graph.getRunStep(prevStepId);\r\n } catch {\r\n /** Edge Case: If no previous step exists, create a new message creation step */\r\n const message_id = getMessageId(stepKey, graph, true) ?? '';\r\n prevStepId = graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.MESSAGE_CREATION,\r\n message_creation: {\r\n message_id,\r\n },\r\n });\r\n prevRunStep = graph.getRunStep(prevStepId);\r\n }\r\n\r\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\r\n\r\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\r\n const tool_calls: ToolCall[] | undefined =\r\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\r\n ? []\r\n : undefined;\r\n\r\n /** Edge Case: `id` and `name` fields cannot be empty strings */\r\n for (const toolCallChunk of toolCallChunks) {\r\n if (toolCallChunk.name === '') {\r\n toolCallChunk.name = undefined;\r\n }\r\n if (toolCallChunk.id === '') {\r\n toolCallChunk.id = undefined;\r\n } else if (\r\n tool_calls != null &&\r\n toolCallChunk.id != null &&\r\n toolCallChunk.name != null\r\n ) {\r\n tool_calls.push({\r\n args: {},\r\n id: toolCallChunk.id,\r\n name: toolCallChunk.name,\r\n type: ToolCallTypes.TOOL_CALL,\r\n });\r\n }\r\n }\r\n\r\n let stepId: string = _stepId;\r\n const alreadyDispatched =\r\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\r\n graph.messageStepHasToolCalls.has(prevStepId);\r\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\r\n graph.dispatchMessageDelta(prevStepId, {\r\n content: [\r\n {\r\n type: ContentTypes.TEXT,\r\n text: '',\r\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\r\n },\r\n ],\r\n });\r\n graph.messageStepHasToolCalls.set(prevStepId, true);\r\n stepId = graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.TOOL_CALLS,\r\n tool_calls,\r\n });\r\n }\r\n graph.dispatchRunStepDelta(stepId, {\r\n type: StepTypes.TOOL_CALLS,\r\n tool_calls: toolCallChunks,\r\n });\r\n}\r\n\r\nexport const handleToolCalls = (\r\n toolCalls?: ToolCall[],\r\n metadata?: Record<string, unknown>,\r\n graph?: Graph\r\n): void => {\r\n if (!graph || !metadata) {\r\n console.warn(`Graph or metadata not found in ${event} event`);\r\n return;\r\n }\r\n\r\n if (!toolCalls) {\r\n return;\r\n }\r\n\r\n if (toolCalls.length === 0) {\r\n return;\r\n }\r\n\r\n const stepKey = graph.getStepKey(metadata);\r\n\r\n for (const tool_call of toolCalls) {\r\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\r\n tool_call.id = toolCallId;\r\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\r\n continue;\r\n }\r\n\r\n let prevStepId = '';\r\n let prevRunStep: t.RunStep | undefined;\r\n try {\r\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\r\n prevRunStep = graph.getRunStep(prevStepId);\r\n } catch {\r\n // no previous step\r\n }\r\n\r\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\r\n graph.dispatchMessageDelta(lastMessageStepId, {\r\n content: [\r\n {\r\n type: 'text',\r\n text: '',\r\n tool_call_ids: [toolCallId],\r\n },\r\n ],\r\n });\r\n };\r\n /* If the previous step exists and is a message creation */\r\n if (\r\n prevStepId &&\r\n prevRunStep &&\r\n prevRunStep.type === StepTypes.MESSAGE_CREATION\r\n ) {\r\n dispatchToolCallIds(prevStepId);\r\n graph.messageStepHasToolCalls.set(prevStepId, true);\r\n /* If the previous step doesn't exist or is not a message creation */\r\n } else if (\r\n !prevRunStep ||\r\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\r\n ) {\r\n const messageId = getMessageId(stepKey, graph, true) ?? '';\r\n const stepId = graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.MESSAGE_CREATION,\r\n message_creation: {\r\n message_id: messageId,\r\n },\r\n });\r\n dispatchToolCallIds(stepId);\r\n graph.messageStepHasToolCalls.set(prevStepId, true);\r\n }\r\n\r\n graph.dispatchRunStep(stepKey, {\r\n type: StepTypes.TOOL_CALLS,\r\n tool_calls: [tool_call],\r\n });\r\n }\r\n};\r\n\r\nexport const toolResultTypes = new Set([\r\n // 'tool_use',\r\n // 'server_tool_use',\r\n // 'input_json_delta',\r\n 'tool_result',\r\n 'web_search_result',\r\n 'web_search_tool_result',\r\n]);\r\n\r\n/**\r\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\r\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\r\n */\r\nexport function handleServerToolResult({\r\n content,\r\n metadata,\r\n graph,\r\n}: {\r\n content?: string | t.MessageContentComplex[];\r\n metadata?: Record<string, unknown>;\r\n graph: Graph;\r\n}): boolean {\r\n let skipHandling = false;\r\n if (metadata?.provider !== Providers.ANTHROPIC) {\r\n return skipHandling;\r\n }\r\n if (\r\n typeof content === 'string' ||\r\n content == null ||\r\n content.length === 0 ||\r\n (content.length === 1 &&\r\n (content[0] as t.ToolResultContent).tool_use_id == null)\r\n ) {\r\n return skipHandling;\r\n }\r\n\r\n for (const contentPart of content) {\r\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\r\n if (toolUseId == null || toolUseId === '') {\r\n continue;\r\n }\r\n const stepId = graph.toolCallStepIds.get(toolUseId);\r\n if (stepId == null || stepId === '') {\r\n console.warn(\r\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\r\n );\r\n continue;\r\n }\r\n const runStep = graph.getRunStep(stepId);\r\n if (!runStep) {\r\n console.warn(\r\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\r\n );\r\n continue;\r\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\r\n console.warn(\r\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\r\n );\r\n continue;\r\n }\r\n\r\n const toolCall =\r\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\r\n ? (runStep.stepDetails.tool_calls?.find(\r\n (toolCall) => toolCall.id === toolUseId\r\n ) as ToolCall)\r\n : undefined;\r\n\r\n if (!toolCall) {\r\n continue;\r\n }\r\n\r\n if (\r\n contentPart.type === 'web_search_result' ||\r\n contentPart.type === 'web_search_tool_result'\r\n ) {\r\n handleAnthropicSearchResults({\r\n contentPart: contentPart as t.ToolResultContent,\r\n toolCall,\r\n metadata,\r\n graph,\r\n });\r\n }\r\n\r\n if (!skipHandling) {\r\n skipHandling = true;\r\n }\r\n }\r\n\r\n return skipHandling;\r\n}\r\n\r\nfunction handleAnthropicSearchResults({\r\n contentPart,\r\n toolCall,\r\n metadata,\r\n graph,\r\n}: {\r\n contentPart: t.ToolResultContent;\r\n toolCall: Partial<ToolCall>;\r\n metadata?: Record<string, unknown>;\r\n graph: Graph;\r\n}): void {\r\n if (!Array.isArray(contentPart.content)) {\r\n console.warn(\r\n `Expected content to be an array, got ${typeof contentPart.content}`\r\n );\r\n return;\r\n }\r\n\r\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\r\n console.warn(\r\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\r\n contentPart.content\r\n )}`\r\n );\r\n return;\r\n }\r\n\r\n const turn = graph.invokedToolIds?.size ?? 0;\r\n const searchResultData = coerceAnthropicSearchResults({\r\n turn,\r\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\r\n });\r\n\r\n const name = toolCall.name;\r\n const input = toolCall.args ?? {};\r\n const artifact = {\r\n [Constants.WEB_SEARCH]: searchResultData,\r\n };\r\n const { output: formattedOutput } = formatResultsForLLM(\r\n turn,\r\n searchResultData\r\n );\r\n const output = new ToolMessage({\r\n name,\r\n artifact,\r\n content: formattedOutput,\r\n tool_call_id: toolCall.id!,\r\n });\r\n const toolEndData: t.ToolEndData = {\r\n input,\r\n output,\r\n };\r\n graph.handlerRegistry\r\n ?.getHandler(GraphEvents.TOOL_END)\r\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\r\n\r\n if (graph.invokedToolIds == null) {\r\n graph.invokedToolIds = new Set<string>();\r\n }\r\n\r\n graph.invokedToolIds.add(toolCall.id!);\r\n}\r\n"],"names":["getMessageId","StepTypes","ToolCallTypes","ContentTypes","nanoid","Providers","isAnthropicW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CAAC;AACJ,UAAE,UAAU,CAACC,iBAAW,CAAC,QAAQ;AACjC,UAAE,MAAM,CAACA,iBAAW,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,CAAC;AAE9D,IAAA,IAAI,KAAK,CAAC,cAAc,IAAI,IAAI,EAAE;AAChC,QAAA,KAAK,CAAC,cAAc,GAAG,IAAI,GAAG,EAAU;;IAG1C,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAG,CAAC;AACxC;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"handlers.cjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { MultiAgentGraph, StandardGraph } from '@/graphs';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport async function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n}): Promise<void> {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n await graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n await graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = async (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n): Promise<void> => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = async (\n lastMessageStepId: string\n ): Promise<void> => {\n await graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n await dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = await graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n await dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n await graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport async function handleServerToolResult({\n graph,\n content,\n metadata,\n agentContext,\n}: {\n graph: StandardGraph | MultiAgentGraph;\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n agentContext?: AgentContext;\n}): Promise<boolean> {\n let skipHandling = false;\n if (agentContext?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n await handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nasync function handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: Partial<ToolCall>;\n metadata?: Record<string, unknown>;\n graph: StandardGraph | MultiAgentGraph;\n}): Promise<void> {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args ?? {};\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n await graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds.add(toolCall.id!);\n}\n"],"names":["getMessageId","StepTypes","ToolCallTypes","ContentTypes","nanoid","Providers","isAnthropicWebSearchResult","coerceAnthropicSearchResults","Constants","formatResultsForLLM","ToolMessage","GraphEvents"],"mappings":";;;;;;;;;;AAAA;AACA;AAuBO,eAAe,oBAAoB,CAAC,EACzC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC;AAC1C,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;AAC1C,IAAA,MAAM;;AAEN,QAAA,MAAM,UAAU,GAAGA,gBAAY,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;AAC3D,QAAA,UAAU,GAAG,MAAM,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE;YAChD,IAAI,EAAEC,eAAS,CAAC,gBAAgB;AAChC,YAAA,gBAAgB,EAAE;gBAChB,UAAU;AACX,aAAA;AACF,SAAA,CAAC;AACF,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC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AAI;AAC1B,IAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,IAAI,EAAE;AACjC,IAAA,MAAM,QAAQ,GAAG;AACf,QAAA,CAACC,eAAS,CAAC,UAAU,GAAG,gBAAgB;KACzC;AACD,IAAA,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAGC,0BAAmB,CACrD,IAAI,EACJ,gBAAgB,CACjB;AACD,IAAA,MAAM,MAAM,GAAG,IAAIC,oBAAW,CAAC;QAC7B,IAAI;QACJ,QAAQ;AACR,QAAA,OAAO,EAAE,eAAe;QACxB,YAAY,EAAE,QAAQ,CAAC,EAAG;AAC3B,KAAA,CAAC;AACF,IAAA,MAAM,WAAW,GAAkB;QACjC,KAAK;QACL,MAAM;KACP;IACD,MAAM,KAAK,CAAC;AACV,UAAE,UAAU,CAACC,iBAAW,CAAC,QAAQ;AACjC,UAAE,MAAM,CAACA,iBAAW,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,CAAC;AAE9D,IAAA,IAAI,KAAK,CAAC,cAAc,IAAI,IAAI,EAAE;AAChC,QAAA,KAAK,CAAC,cAAc,GAAG,IAAI,GAAG,EAAU;;IAG1C,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAG,CAAC;AACxC;;;;;;;"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var dispatch = require('@langchain/core/callbacks/dispatch');
|
|
4
|
+
|
|
5
|
+
/* eslint-disable no-console */
|
|
6
|
+
// src/utils/events.ts
|
|
7
|
+
/**
|
|
8
|
+
* Safely dispatches a custom event and properly awaits it to avoid
|
|
9
|
+
* race conditions where events are dispatched after run cleanup.
|
|
10
|
+
*/
|
|
11
|
+
async function safeDispatchCustomEvent(event, payload, config) {
|
|
12
|
+
try {
|
|
13
|
+
await dispatch.dispatchCustomEvent(event, payload, config);
|
|
14
|
+
}
|
|
15
|
+
catch (e) {
|
|
16
|
+
// Check if this is the known EventStreamCallbackHandler error
|
|
17
|
+
if (e instanceof Error &&
|
|
18
|
+
e.message.includes('handleCustomEvent: Run ID') &&
|
|
19
|
+
e.message.includes('not found in run map')) {
|
|
20
|
+
// Suppress this specific error - it's expected during parallel execution
|
|
21
|
+
// when EventStreamCallbackHandler loses track of run IDs
|
|
22
|
+
// console.debug('Suppressed error dispatching custom event:', e);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
// Log other errors
|
|
26
|
+
console.error('Error dispatching custom event:', e);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
exports.safeDispatchCustomEvent = safeDispatchCustomEvent;
|
|
31
|
+
//# sourceMappingURL=events.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.cjs","sources":["../../../src/utils/events.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/utils/events.ts\nimport { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';\nimport type { RunnableConfig } from '@langchain/core/runnables';\n\n/**\n * Safely dispatches a custom event and properly awaits it to avoid\n * race conditions where events are dispatched after run cleanup.\n */\nexport async function safeDispatchCustomEvent(\n event: string,\n payload: unknown,\n config?: RunnableConfig\n): Promise<void> {\n try {\n await dispatchCustomEvent(event, payload, config);\n } catch (e) {\n // Check if this is the known EventStreamCallbackHandler error\n if (\n e instanceof Error &&\n e.message.includes('handleCustomEvent: Run ID') &&\n e.message.includes('not found in run map')\n ) {\n // Suppress this specific error - it's expected during parallel execution\n // when EventStreamCallbackHandler loses track of run IDs\n // console.debug('Suppressed error dispatching custom event:', e);\n return;\n }\n // Log other errors\n console.error('Error dispatching custom event:', e);\n }\n}\n"],"names":["dispatchCustomEvent"],"mappings":";;;;AAAA;AACA;AAIA;;;AAGG;AACI,eAAe,uBAAuB,CAC3C,KAAa,EACb,OAAgB,EAChB,MAAuB,EAAA;AAEvB,IAAA,IAAI;QACF,MAAMA,4BAAmB,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC;;IACjD,OAAO,CAAC,EAAE;;QAEV,IACE,CAAC,YAAY,KAAK;AAClB,YAAA,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,2BAA2B,CAAC;YAC/C,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC,EAC1C;;;;YAIA;;;AAGF,QAAA,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,CAAC,CAAC;;AAEvD;;;;"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var _enum = require('../common/enum.cjs');
|
|
4
|
+
var stream = require('../stream.cjs');
|
|
5
|
+
var events = require('../events.cjs');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Multi-Agent Handler Utilities
|
|
9
|
+
*
|
|
10
|
+
* Provides a simple helper to create handlers with content aggregation for multi-agent scripts.
|
|
11
|
+
*
|
|
12
|
+
* Usage:
|
|
13
|
+
* ```typescript
|
|
14
|
+
* const { contentParts, aggregateContent, handlers } = createHandlers();
|
|
15
|
+
*
|
|
16
|
+
* // With callbacks
|
|
17
|
+
* const { contentParts, aggregateContent, handlers } = createHandlers({
|
|
18
|
+
* onRunStep: (event, data) => console.log('Step:', data),
|
|
19
|
+
* onRunStepCompleted: (event, data) => console.log('Completed:', data)
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Creates handlers with content aggregation for multi-agent scripts
|
|
25
|
+
*/
|
|
26
|
+
function createHandlers(callbacks) {
|
|
27
|
+
// Set up content aggregator
|
|
28
|
+
const { contentParts, aggregateContent } = stream.createContentAggregator();
|
|
29
|
+
// Create the handlers object
|
|
30
|
+
const handlers = {
|
|
31
|
+
[_enum.GraphEvents.TOOL_END]: new events.ToolEndHandler(),
|
|
32
|
+
[_enum.GraphEvents.CHAT_MODEL_END]: new events.ModelEndHandler(),
|
|
33
|
+
[_enum.GraphEvents.CHAT_MODEL_STREAM]: new stream.ChatModelStreamHandler(),
|
|
34
|
+
[_enum.GraphEvents.ON_RUN_STEP]: {
|
|
35
|
+
handle: (event, data) => {
|
|
36
|
+
aggregateContent({ event, data: data });
|
|
37
|
+
callbacks?.onRunStep?.(event, data);
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
[_enum.GraphEvents.ON_RUN_STEP_COMPLETED]: {
|
|
41
|
+
handle: (event, data) => {
|
|
42
|
+
aggregateContent({
|
|
43
|
+
event,
|
|
44
|
+
data: data,
|
|
45
|
+
});
|
|
46
|
+
callbacks?.onRunStepCompleted?.(event, data);
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
[_enum.GraphEvents.ON_RUN_STEP_DELTA]: {
|
|
50
|
+
handle: (event, data) => {
|
|
51
|
+
aggregateContent({ event, data: data });
|
|
52
|
+
callbacks?.onRunStepDelta?.(event, data);
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
[_enum.GraphEvents.ON_MESSAGE_DELTA]: {
|
|
56
|
+
handle: (event, data) => {
|
|
57
|
+
aggregateContent({ event, data: data });
|
|
58
|
+
callbacks?.onMessageDelta?.(event, data);
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
return {
|
|
63
|
+
contentParts,
|
|
64
|
+
aggregateContent,
|
|
65
|
+
handlers,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
exports.createHandlers = createHandlers;
|
|
70
|
+
//# sourceMappingURL=handlers.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handlers.cjs","sources":["../../../src/utils/handlers.ts"],"sourcesContent":["/**\n * Multi-Agent Handler Utilities\n *\n * Provides a simple helper to create handlers with content aggregation for multi-agent scripts.\n *\n * Usage:\n * ```typescript\n * const { contentParts, aggregateContent, handlers } = createHandlers();\n *\n * // With callbacks\n * const { contentParts, aggregateContent, handlers } = createHandlers({\n * onRunStep: (event, data) => console.log('Step:', data),\n * onRunStepCompleted: (event, data) => console.log('Completed:', data)\n * });\n * ```\n */\n\nimport { GraphEvents } from '@/common';\nimport { ChatModelStreamHandler, createContentAggregator } from '@/stream';\nimport { ToolEndHandler, ModelEndHandler } from '@/events';\nimport type * as t from '@/types';\n\ninterface HandlerCallbacks {\n onRunStep?: (event: GraphEvents.ON_RUN_STEP, data: t.StreamEventData) => void;\n onRunStepCompleted?: (\n event: GraphEvents.ON_RUN_STEP_COMPLETED,\n data: t.StreamEventData\n ) => void;\n onRunStepDelta?: (\n event: GraphEvents.ON_RUN_STEP_DELTA,\n data: t.StreamEventData\n ) => void;\n onMessageDelta?: (\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: t.StreamEventData\n ) => void;\n}\n\n/**\n * Creates handlers with content aggregation for multi-agent scripts\n */\nexport function createHandlers(callbacks?: HandlerCallbacks): {\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ReturnType<\n typeof createContentAggregator\n >['aggregateContent'];\n handlers: Record<string, t.EventHandler>;\n} {\n // Set up content aggregator\n const { contentParts, aggregateContent } = createContentAggregator();\n\n // Create the handlers object\n const handlers = {\n [GraphEvents.TOOL_END]: new ToolEndHandler(),\n [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),\n [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),\n\n [GraphEvents.ON_RUN_STEP]: {\n handle: (\n event: GraphEvents.ON_RUN_STEP,\n data: t.StreamEventData\n ): void => {\n aggregateContent({ event, data: data as t.RunStep });\n callbacks?.onRunStep?.(event, data);\n },\n },\n\n [GraphEvents.ON_RUN_STEP_COMPLETED]: {\n handle: (\n event: GraphEvents.ON_RUN_STEP_COMPLETED,\n data: t.StreamEventData\n ): void => {\n aggregateContent({\n event,\n data: data as unknown as { result: t.ToolEndEvent },\n });\n callbacks?.onRunStepCompleted?.(event, data);\n },\n },\n\n [GraphEvents.ON_RUN_STEP_DELTA]: {\n handle: (\n event: GraphEvents.ON_RUN_STEP_DELTA,\n data: t.StreamEventData\n ): void => {\n aggregateContent({ event, data: data as t.RunStepDeltaEvent });\n callbacks?.onRunStepDelta?.(event, data);\n },\n },\n\n [GraphEvents.ON_MESSAGE_DELTA]: {\n handle: (\n event: GraphEvents.ON_MESSAGE_DELTA,\n data: t.StreamEventData\n ): void => {\n aggregateContent({ event, data: data as t.MessageDeltaEvent });\n callbacks?.onMessageDelta?.(event, data);\n },\n },\n };\n\n return {\n contentParts,\n aggregateContent,\n handlers,\n };\n}\n"],"names":["createContentAggregator","GraphEvents","ToolEndHandler","ModelEndHandler","ChatModelStreamHandler"],"mappings":";;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAuBH;;AAEG;AACG,SAAU,cAAc,CAAC,SAA4B,EAAA;;IAQzD,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAGA,8BAAuB,EAAE;;AAGpE,IAAA,MAAM,QAAQ,GAAG;AACf,QAAA,CAACC,iBAAW,CAAC,QAAQ,GAAG,IAAIC,qBAAc,EAAE;AAC5C,QAAA,CAACD,iBAAW,CAAC,cAAc,GAAG,IAAIE,sBAAe,EAAE;AACnD,QAAA,CAACF,iBAAW,CAAC,iBAAiB,GAAG,IAAIG,6BAAsB,EAAE;AAE7D,QAAA,CAACH,iBAAW,CAAC,WAAW,GAAG;AACzB,YAAA,MAAM,EAAE,CACN,KAA8B,EAC9B,IAAuB,KACf;gBACR,gBAAgB,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,IAAiB,EAAE,CAAC;gBACpD,SAAS,EAAE,SAAS,GAAG,KAAK,EAAE,IAAI,CAAC;aACpC;AACF,SAAA;AAED,QAAA,CAACA,iBAAW,CAAC,qBAAqB,GAAG;AACnC,YAAA,MAAM,EAAE,CACN,KAAwC,EACxC,IAAuB,KACf;AACR,gBAAA,gBAAgB,CAAC;oBACf,KAAK;AACL,oBAAA,IAAI,EAAE,IAA6C;AACpD,iBAAA,CAAC;gBACF,SAA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