@illuma-ai/agents 1.1.21 → 1.1.22

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.
Files changed (241) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/esm/graphs/Graph.mjs +12 -1
  8. package/dist/esm/graphs/Graph.mjs.map +1 -1
  9. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  11. package/dist/esm/run.mjs +20 -9
  12. package/dist/esm/run.mjs.map +1 -1
  13. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  14. package/package.json +1 -1
  15. package/src/graphs/Graph.ts +12 -1
  16. package/src/graphs/MultiAgentGraph.ts +105 -1
  17. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  18. package/src/run.ts +20 -11
  19. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  20. package/src/agents/AgentContext.js +0 -782
  21. package/src/agents/AgentContext.test.js +0 -421
  22. package/src/agents/__tests__/AgentContext.test.js +0 -678
  23. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  24. package/src/common/enum.js +0 -192
  25. package/src/common/index.js +0 -3
  26. package/src/events.js +0 -166
  27. package/src/graphs/Graph.js +0 -1857
  28. package/src/graphs/MultiAgentGraph.js +0 -1092
  29. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  30. package/src/graphs/__tests__/structured-output.test.js +0 -144
  31. package/src/graphs/contextManagement.e2e.test.js +0 -718
  32. package/src/graphs/contextManagement.test.js +0 -485
  33. package/src/graphs/handoffValidation.test.js +0 -276
  34. package/src/graphs/index.js +0 -3
  35. package/src/index.js +0 -28
  36. package/src/instrumentation.js +0 -21
  37. package/src/llm/anthropic/index.js +0 -319
  38. package/src/llm/anthropic/types.js +0 -46
  39. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  40. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  41. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  42. package/src/llm/anthropic/utils/tools.js +0 -25
  43. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  44. package/src/llm/bedrock/index.js +0 -303
  45. package/src/llm/bedrock/types.js +0 -2
  46. package/src/llm/bedrock/utils/index.js +0 -6
  47. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  48. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  49. package/src/llm/fake.js +0 -92
  50. package/src/llm/google/index.js +0 -215
  51. package/src/llm/google/types.js +0 -12
  52. package/src/llm/google/utils/common.js +0 -670
  53. package/src/llm/google/utils/tools.js +0 -111
  54. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  55. package/src/llm/openai/index.js +0 -1033
  56. package/src/llm/openai/types.js +0 -2
  57. package/src/llm/openai/utils/index.js +0 -756
  58. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  59. package/src/llm/openrouter/index.js +0 -261
  60. package/src/llm/openrouter/reasoning.test.js +0 -181
  61. package/src/llm/providers.js +0 -36
  62. package/src/llm/text.js +0 -65
  63. package/src/llm/vertexai/index.js +0 -402
  64. package/src/messages/__tests__/tools.test.js +0 -392
  65. package/src/messages/cache.js +0 -404
  66. package/src/messages/cache.test.js +0 -1167
  67. package/src/messages/content.js +0 -48
  68. package/src/messages/content.test.js +0 -314
  69. package/src/messages/core.js +0 -359
  70. package/src/messages/ensureThinkingBlock.test.js +0 -997
  71. package/src/messages/format.js +0 -973
  72. package/src/messages/formatAgentMessages.test.js +0 -2278
  73. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  74. package/src/messages/formatMessage.test.js +0 -608
  75. package/src/messages/ids.js +0 -18
  76. package/src/messages/index.js +0 -9
  77. package/src/messages/labelContentByAgent.test.js +0 -725
  78. package/src/messages/prune.js +0 -438
  79. package/src/messages/reducer.js +0 -60
  80. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  81. package/src/messages/summarize.js +0 -146
  82. package/src/messages/summarize.test.js +0 -332
  83. package/src/messages/tools.js +0 -90
  84. package/src/mockStream.js +0 -81
  85. package/src/prompts/collab.js +0 -7
  86. package/src/prompts/index.js +0 -3
  87. package/src/prompts/taskmanager.js +0 -58
  88. package/src/run.js +0 -427
  89. package/src/schemas/index.js +0 -3
  90. package/src/schemas/schema-preparation.test.js +0 -370
  91. package/src/schemas/validate.js +0 -314
  92. package/src/schemas/validate.test.js +0 -264
  93. package/src/scripts/abort.js +0 -127
  94. package/src/scripts/ant_web_search.js +0 -130
  95. package/src/scripts/ant_web_search_edge_case.js +0 -133
  96. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  97. package/src/scripts/args.js +0 -41
  98. package/src/scripts/bedrock-cache-debug.js +0 -186
  99. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  100. package/src/scripts/bedrock-merge-test.js +0 -80
  101. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  102. package/src/scripts/caching.js +0 -106
  103. package/src/scripts/cli.js +0 -152
  104. package/src/scripts/cli2.js +0 -119
  105. package/src/scripts/cli3.js +0 -163
  106. package/src/scripts/cli4.js +0 -165
  107. package/src/scripts/cli5.js +0 -165
  108. package/src/scripts/code_exec.js +0 -171
  109. package/src/scripts/code_exec_files.js +0 -180
  110. package/src/scripts/code_exec_multi_session.js +0 -185
  111. package/src/scripts/code_exec_ptc.js +0 -265
  112. package/src/scripts/code_exec_session.js +0 -217
  113. package/src/scripts/code_exec_simple.js +0 -120
  114. package/src/scripts/content.js +0 -111
  115. package/src/scripts/empty_input.js +0 -125
  116. package/src/scripts/handoff-test.js +0 -96
  117. package/src/scripts/image.js +0 -138
  118. package/src/scripts/memory.js +0 -83
  119. package/src/scripts/multi-agent-chain.js +0 -271
  120. package/src/scripts/multi-agent-conditional.js +0 -185
  121. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  122. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  123. package/src/scripts/multi-agent-parallel-start.js +0 -214
  124. package/src/scripts/multi-agent-parallel.js +0 -346
  125. package/src/scripts/multi-agent-sequence.js +0 -184
  126. package/src/scripts/multi-agent-supervisor.js +0 -324
  127. package/src/scripts/multi-agent-test.js +0 -147
  128. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  129. package/src/scripts/parallel-full-metadata-test.js +0 -176
  130. package/src/scripts/parallel-tools-test.js +0 -256
  131. package/src/scripts/programmatic_exec.js +0 -277
  132. package/src/scripts/programmatic_exec_agent.js +0 -168
  133. package/src/scripts/search.js +0 -118
  134. package/src/scripts/sequential-full-metadata-test.js +0 -143
  135. package/src/scripts/simple.js +0 -174
  136. package/src/scripts/single-agent-metadata-test.js +0 -152
  137. package/src/scripts/stream.js +0 -113
  138. package/src/scripts/test-custom-prompt-key.js +0 -132
  139. package/src/scripts/test-handoff-input.js +0 -143
  140. package/src/scripts/test-handoff-preamble.js +0 -227
  141. package/src/scripts/test-handoff-steering.js +0 -353
  142. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  143. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  144. package/src/scripts/test-parallel-handoffs.js +0 -229
  145. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  146. package/src/scripts/test-thinking-handoff.js +0 -132
  147. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  148. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  149. package/src/scripts/test-tools-before-handoff.js +0 -187
  150. package/src/scripts/test_code_api.js +0 -263
  151. package/src/scripts/thinking-bedrock.js +0 -128
  152. package/src/scripts/thinking-vertexai.js +0 -130
  153. package/src/scripts/thinking.js +0 -134
  154. package/src/scripts/tool_search.js +0 -114
  155. package/src/scripts/tools.js +0 -125
  156. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  157. package/src/specs/agent-handoffs.test.js +0 -924
  158. package/src/specs/anthropic.simple.test.js +0 -287
  159. package/src/specs/azure.simple.test.js +0 -381
  160. package/src/specs/cache.simple.test.js +0 -282
  161. package/src/specs/custom-event-await.test.js +0 -148
  162. package/src/specs/deepseek.simple.test.js +0 -189
  163. package/src/specs/emergency-prune.test.js +0 -308
  164. package/src/specs/moonshot.simple.test.js +0 -237
  165. package/src/specs/observability.integration.test.js +0 -1337
  166. package/src/specs/openai.simple.test.js +0 -233
  167. package/src/specs/openrouter.simple.test.js +0 -202
  168. package/src/specs/prune.test.js +0 -733
  169. package/src/specs/reasoning.test.js +0 -144
  170. package/src/specs/spec.utils.js +0 -4
  171. package/src/specs/thinking-handoff.test.js +0 -486
  172. package/src/specs/thinking-prune.test.js +0 -600
  173. package/src/specs/token-distribution-edge-case.test.js +0 -246
  174. package/src/specs/token-memoization.test.js +0 -32
  175. package/src/specs/tokens.test.js +0 -49
  176. package/src/specs/tool-error.test.js +0 -139
  177. package/src/splitStream.js +0 -204
  178. package/src/splitStream.test.js +0 -504
  179. package/src/stream.js +0 -650
  180. package/src/stream.test.js +0 -225
  181. package/src/test/mockTools.js +0 -340
  182. package/src/tools/BrowserTools.js +0 -245
  183. package/src/tools/Calculator.js +0 -38
  184. package/src/tools/Calculator.test.js +0 -225
  185. package/src/tools/CodeExecutor.js +0 -233
  186. package/src/tools/ProgrammaticToolCalling.js +0 -602
  187. package/src/tools/StreamingToolCallBuffer.js +0 -179
  188. package/src/tools/ToolNode.js +0 -930
  189. package/src/tools/ToolSearch.js +0 -904
  190. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  191. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  192. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  193. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  194. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  195. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  196. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  197. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  198. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  199. package/src/tools/__tests__/handlers.test.js +0 -799
  200. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  201. package/src/tools/handlers.js +0 -306
  202. package/src/tools/schema.js +0 -25
  203. package/src/tools/search/anthropic.js +0 -34
  204. package/src/tools/search/content.js +0 -116
  205. package/src/tools/search/content.test.js +0 -133
  206. package/src/tools/search/firecrawl.js +0 -173
  207. package/src/tools/search/format.js +0 -198
  208. package/src/tools/search/highlights.js +0 -241
  209. package/src/tools/search/index.js +0 -3
  210. package/src/tools/search/jina-reranker.test.js +0 -106
  211. package/src/tools/search/rerankers.js +0 -165
  212. package/src/tools/search/schema.js +0 -102
  213. package/src/tools/search/search.js +0 -561
  214. package/src/tools/search/serper-scraper.js +0 -126
  215. package/src/tools/search/test.js +0 -129
  216. package/src/tools/search/tool.js +0 -453
  217. package/src/tools/search/types.js +0 -2
  218. package/src/tools/search/utils.js +0 -59
  219. package/src/types/graph.js +0 -24
  220. package/src/types/graph.test.js +0 -192
  221. package/src/types/index.js +0 -7
  222. package/src/types/llm.js +0 -2
  223. package/src/types/messages.js +0 -2
  224. package/src/types/run.js +0 -2
  225. package/src/types/stream.js +0 -2
  226. package/src/types/tools.js +0 -2
  227. package/src/utils/contextAnalytics.js +0 -79
  228. package/src/utils/contextAnalytics.test.js +0 -166
  229. package/src/utils/events.js +0 -26
  230. package/src/utils/graph.js +0 -11
  231. package/src/utils/handlers.js +0 -65
  232. package/src/utils/index.js +0 -10
  233. package/src/utils/llm.js +0 -21
  234. package/src/utils/llmConfig.js +0 -205
  235. package/src/utils/logging.js +0 -37
  236. package/src/utils/misc.js +0 -51
  237. package/src/utils/run.js +0 -69
  238. package/src/utils/schema.js +0 -21
  239. package/src/utils/title.js +0 -119
  240. package/src/utils/tokens.js +0 -92
  241. package/src/utils/toonFormat.js +0 -379
@@ -1,180 +0,0 @@
1
- // src/scripts/code_exec_files.ts
2
- /**
3
- * Tests automatic session tracking for code execution file persistence.
4
- * Files created in one execution are automatically available in subsequent executions
5
- * without the LLM needing to track or pass session_id.
6
- *
7
- * Run with: npm run code_exec_files
8
- */
9
- import { config } from 'dotenv';
10
- config();
11
- import { HumanMessage } from '@langchain/core/messages';
12
- import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
13
- import { ToolEndHandler, ModelEndHandler, createMetadataAggregator, } from '@/events';
14
- import { getLLMConfig } from '@/utils/llmConfig';
15
- import { getArgs } from '@/scripts/args';
16
- import { Constants, GraphEvents } from '@/common';
17
- import { Run } from '@/run';
18
- import { createCodeExecutionTool } from '@/tools/CodeExecutor';
19
- const conversationHistory = [];
20
- /**
21
- * Prints session context from the graph for debugging
22
- */
23
- function printSessionContext(run) {
24
- const graph = run.Graph;
25
- if (!graph) {
26
- console.log('[Session] No graph available');
27
- return;
28
- }
29
- const session = graph.sessions.get(Constants.EXECUTE_CODE);
30
- if (!session) {
31
- console.log('[Session] No session context stored yet');
32
- return;
33
- }
34
- console.log('[Session] Current session context:');
35
- console.log(` - session_id: ${session.session_id}`);
36
- console.log(` - files: ${JSON.stringify(session.files, null, 2)}`);
37
- console.log(` - lastUpdated: ${new Date(session.lastUpdated).toISOString()}`);
38
- }
39
- async function testCodeExecution() {
40
- const { userName, location, provider, currentDate } = await getArgs();
41
- const { contentParts, aggregateContent } = createContentAggregator();
42
- const customHandlers = {
43
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
44
- [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
45
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
46
- [GraphEvents.ON_RUN_STEP_COMPLETED]: {
47
- handle: (event, data) => {
48
- console.log('====== ON_RUN_STEP_COMPLETED ======');
49
- console.dir(data, { depth: null });
50
- aggregateContent({
51
- event,
52
- data: data,
53
- });
54
- },
55
- },
56
- [GraphEvents.ON_RUN_STEP]: {
57
- handle: (event, data) => {
58
- console.log('====== ON_RUN_STEP ======');
59
- console.dir(data, { depth: null });
60
- aggregateContent({ event, data: data });
61
- },
62
- },
63
- [GraphEvents.ON_RUN_STEP_DELTA]: {
64
- handle: (event, data) => {
65
- console.log('====== ON_RUN_STEP_DELTA ======');
66
- console.dir(data, { depth: null });
67
- aggregateContent({ event, data: data });
68
- },
69
- },
70
- [GraphEvents.ON_MESSAGE_DELTA]: {
71
- handle: (event, data) => {
72
- console.log('====== ON_MESSAGE_DELTA ======');
73
- console.dir(data, { depth: null });
74
- aggregateContent({ event, data: data });
75
- },
76
- },
77
- [GraphEvents.TOOL_START]: {
78
- handle: (_event, data, _metadata) => {
79
- console.log('====== TOOL_START ======');
80
- console.dir(data, { depth: null });
81
- },
82
- },
83
- };
84
- const llmConfig = getLLMConfig(provider);
85
- const run = await Run.create({
86
- runId: 'message-num-1',
87
- graphConfig: {
88
- type: 'standard',
89
- llmConfig,
90
- tools: [createCodeExecutionTool()],
91
- instructions: 'You are a friendly AI assistant with coding capabilities. Always address the user by their name.',
92
- additional_instructions: `The user's name is ${userName} and they are located in ${location}. The current date is ${currentDate}.`,
93
- },
94
- returnContent: true,
95
- skipCleanup: true,
96
- customHandlers,
97
- });
98
- const streamConfig = {
99
- configurable: {
100
- provider,
101
- thread_id: 'conversation-num-1',
102
- },
103
- streamMode: 'values',
104
- version: 'v2',
105
- };
106
- console.log('\n========== Test 1: Create Project Plan ==========\n');
107
- console.log('Creating initial file - this establishes the session context.\n');
108
- const userMessage1 = `
109
- Hi ${userName} here. We are testing your file capabilities.
110
-
111
- 1. Create a text file named "project_plan.txt" that contains: "This is a project plan for a new software development project."
112
-
113
- Please generate this file so I can review it.
114
- `;
115
- conversationHistory.push(new HumanMessage(userMessage1));
116
- let inputs = {
117
- messages: conversationHistory,
118
- };
119
- await run.processStream(inputs, streamConfig);
120
- const finalMessages1 = run.getRunMessages();
121
- if (finalMessages1) {
122
- conversationHistory.push(...finalMessages1);
123
- }
124
- console.log('\n\n========== Session Context After Test 1 ==========\n');
125
- printSessionContext(run);
126
- console.dir(contentParts, { depth: null });
127
- console.log('\n========== Test 2: Edit Project Plan ==========\n');
128
- console.log('Editing the file from Test 1 - session_id is automatically injected.\n');
129
- const userMessage2 = `
130
- Thanks for creating the project plan. Now I'd like you to edit the same plan to:
131
-
132
- 1. Read the existing project_plan.txt file
133
- 2. Add a new section called "Technology Stack" that contains: "The technology stack for this project includes the following technologies" and nothing more.
134
- 3. Save this as a new file called "project_plan_v2.txt" (remember files are read-only)
135
- 4. Print the contents of both files to verify
136
- `;
137
- conversationHistory.push(new HumanMessage(userMessage2));
138
- inputs = {
139
- messages: conversationHistory,
140
- };
141
- await run.processStream(inputs, streamConfig);
142
- const finalMessages2 = run.getRunMessages();
143
- if (finalMessages2) {
144
- conversationHistory.push(...finalMessages2);
145
- }
146
- console.log('\n\n========== Session Context After Test 2 ==========\n');
147
- printSessionContext(run);
148
- console.dir(contentParts, { depth: null });
149
- const { handleLLMEnd, collected } = createMetadataAggregator();
150
- const titleResult = await run.generateTitle({
151
- provider,
152
- inputText: userMessage2,
153
- contentParts,
154
- chainOptions: {
155
- callbacks: [
156
- {
157
- handleLLMEnd,
158
- },
159
- ],
160
- },
161
- });
162
- console.log('Generated Title:', titleResult);
163
- console.log('Collected metadata:', collected);
164
- }
165
- process.on('unhandledRejection', (reason, promise) => {
166
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
167
- console.log('Conversation history:');
168
- console.dir(conversationHistory, { depth: null });
169
- process.exit(1);
170
- });
171
- process.on('uncaughtException', (err) => {
172
- console.error('Uncaught Exception:', err);
173
- });
174
- testCodeExecution().catch((err) => {
175
- console.error(err);
176
- console.log('Conversation history:');
177
- console.dir(conversationHistory, { depth: null });
178
- process.exit(1);
179
- });
180
- //# sourceMappingURL=code_exec_files.js.map
@@ -1,185 +0,0 @@
1
- // src/scripts/code_exec_multi_session.ts
2
- /**
3
- * Tests multi-session file tracking for code execution.
4
- * Verifies that:
5
- * 1. Files from multiple executions are accumulated
6
- * 2. Each file tracks its source session_id
7
- * 3. Edited/recreated files replace older versions (latest preferred)
8
- *
9
- * Run with: npm run code_exec_multi_session
10
- */
11
- import { config } from 'dotenv';
12
- config();
13
- import { HumanMessage } from '@langchain/core/messages';
14
- import { ChatModelStreamHandler } from '@/stream';
15
- import { ToolEndHandler, ModelEndHandler } from '@/events';
16
- import { getLLMConfig } from '@/utils/llmConfig';
17
- import { getArgs } from '@/scripts/args';
18
- import { Constants, GraphEvents } from '@/common';
19
- import { Run } from '@/run';
20
- import { createCodeExecutionTool } from '@/tools/CodeExecutor';
21
- const conversationHistory = [];
22
- /**
23
- * Prints session context from the graph
24
- */
25
- function printSessionContext(run, label) {
26
- const graph = run.Graph;
27
- if (!graph) {
28
- console.log(`\n[${label}] No graph available`);
29
- return;
30
- }
31
- const session = graph.sessions.get(Constants.EXECUTE_CODE);
32
- console.log(`\n========== ${label} ==========`);
33
- if (!session) {
34
- console.log(' No session context stored yet');
35
- return;
36
- }
37
- console.log(` Latest session_id: ${session.session_id}`);
38
- console.log(` Files tracked: ${session.files?.length ?? 0}`);
39
- for (const file of session.files ?? []) {
40
- console.log(` - ${file.name} (session: ${file.session_id})`);
41
- }
42
- }
43
- async function testMultiSessionFiles() {
44
- const { provider } = await getArgs();
45
- const customHandlers = {
46
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
47
- [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
48
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
49
- };
50
- const llmConfig = getLLMConfig(provider);
51
- const run = await Run.create({
52
- runId: 'multi-session-test',
53
- graphConfig: {
54
- type: 'standard',
55
- llmConfig,
56
- tools: [createCodeExecutionTool()],
57
- instructions: `You are a coding assistant. Execute code exactly as requested.
58
- When asked to create files, use Python and save to /mnt/data/.
59
- When reading files, print their contents.
60
- Be concise in responses.`,
61
- },
62
- returnContent: true,
63
- skipCleanup: true,
64
- customHandlers,
65
- });
66
- const streamConfig = {
67
- configurable: {
68
- provider,
69
- thread_id: 'multi-session-test',
70
- },
71
- streamMode: 'values',
72
- version: 'v2',
73
- };
74
- // ========== TEST 1: Create first file ==========
75
- console.log('\n\n' + '='.repeat(60));
76
- console.log('TEST 1: Create first file (file_a.txt)');
77
- console.log('='.repeat(60));
78
- conversationHistory.push(new HumanMessage(`
79
- Create a file called "file_a.txt" with the content:
80
- "This is file A, version 1"
81
- Print confirmation when done.
82
- `));
83
- await run.processStream({ messages: conversationHistory }, streamConfig);
84
- const messages1 = run.getRunMessages();
85
- if (messages1)
86
- conversationHistory.push(...messages1);
87
- printSessionContext(run, 'After Test 1');
88
- // ========== TEST 2: Create second file (different session) ==========
89
- console.log('\n\n' + '='.repeat(60));
90
- console.log('TEST 2: Create second file (file_b.txt)');
91
- console.log('Expecting: Both file_a.txt and file_b.txt tracked');
92
- console.log('='.repeat(60));
93
- conversationHistory.push(new HumanMessage(`
94
- Create a NEW file called "file_b.txt" with the content:
95
- "This is file B"
96
- Print confirmation when done.
97
- `));
98
- await run.processStream({ messages: conversationHistory }, streamConfig);
99
- const messages2 = run.getRunMessages();
100
- if (messages2)
101
- conversationHistory.push(...messages2);
102
- printSessionContext(run, 'After Test 2');
103
- // ========== TEST 3: Read BOTH files (verifies accumulation) ==========
104
- console.log('\n\n' + '='.repeat(60));
105
- console.log('TEST 3: Read BOTH files from previous executions');
106
- console.log('This verifies multi-session file accumulation works');
107
- console.log('='.repeat(60));
108
- conversationHistory.push(new HumanMessage(`
109
- Read and print the contents of BOTH files:
110
- 1. file_a.txt
111
- 2. file_b.txt
112
-
113
- Show me what's in each file.
114
- `));
115
- await run.processStream({ messages: conversationHistory }, streamConfig);
116
- const messages3 = run.getRunMessages();
117
- if (messages3)
118
- conversationHistory.push(...messages3);
119
- printSessionContext(run, 'After Test 3');
120
- // ========== TEST 4: Edit file_a.txt (verifies latest-wins) ==========
121
- console.log('\n\n' + '='.repeat(60));
122
- console.log('TEST 4: Edit file_a.txt (create new version)');
123
- console.log('Expecting: Old file_a.txt replaced with new version');
124
- console.log('='.repeat(60));
125
- conversationHistory.push(new HumanMessage(`
126
- Create an UPDATED version of "file_a.txt" with the content:
127
- "This is file A, version 2 - UPDATED"
128
- Print confirmation when done.
129
- `));
130
- await run.processStream({ messages: conversationHistory }, streamConfig);
131
- const messages4 = run.getRunMessages();
132
- if (messages4)
133
- conversationHistory.push(...messages4);
134
- printSessionContext(run, 'After Test 4');
135
- // ========== TEST 5: Read file_a.txt (verifies latest version) ==========
136
- console.log('\n\n' + '='.repeat(60));
137
- console.log('TEST 5: Read file_a.txt to verify it has the UPDATED content');
138
- console.log('Expected: "version 2 - UPDATED" NOT "version 1"');
139
- console.log('='.repeat(60));
140
- conversationHistory.push(new HumanMessage(`
141
- Read and print the contents of file_a.txt.
142
- Tell me what version it shows.
143
- `));
144
- await run.processStream({ messages: conversationHistory }, streamConfig);
145
- const messages5 = run.getRunMessages();
146
- if (messages5)
147
- conversationHistory.push(...messages5);
148
- printSessionContext(run, 'Final Session State');
149
- // ========== SUMMARY ==========
150
- console.log('\n\n' + '='.repeat(60));
151
- console.log('TEST SUMMARY');
152
- console.log('='.repeat(60));
153
- const finalSession = run.Graph?.sessions.get(Constants.EXECUTE_CODE);
154
- if (finalSession) {
155
- const files = finalSession.files ?? [];
156
- const uniqueSessionIds = new Set(files.map((f) => f.session_id));
157
- console.log(`\nTotal files tracked: ${files.length}`);
158
- console.log(`Unique session_ids: ${uniqueSessionIds.size}`);
159
- console.log('\nFiles:');
160
- for (const file of files) {
161
- console.log(` - ${file.name} (session: ${file.session_id?.slice(0, 20)}...)`);
162
- }
163
- // Verify expectations
164
- const fileACount = files.filter((f) => f.name === 'file_a.txt').length;
165
- const fileBCount = files.filter((f) => f.name === 'file_b.txt').length;
166
- console.log('\n✓ Checks:');
167
- console.log(` file_a.txt count: ${fileACount} (expected: 1, latest wins)`);
168
- console.log(` file_b.txt count: ${fileBCount} (expected: 1)`);
169
- if (fileACount === 1 && fileBCount === 1) {
170
- console.log('\n✅ All tests passed! Multi-session tracking works.');
171
- }
172
- else {
173
- console.log('\n❌ Test failed - unexpected file counts');
174
- }
175
- }
176
- }
177
- process.on('unhandledRejection', (reason, promise) => {
178
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
179
- process.exit(1);
180
- });
181
- testMultiSessionFiles().catch((err) => {
182
- console.error('Test failed:', err);
183
- process.exit(1);
184
- });
185
- //# sourceMappingURL=code_exec_multi_session.js.map
@@ -1,265 +0,0 @@
1
- // src/scripts/code_exec_ptc.ts
2
- /**
3
- * Live LLM test for Programmatic Tool Calling (PTC).
4
- * Run with: npm run code_exec_ptc
5
- *
6
- * Tests PTC with a real LLM in the loop, demonstrating:
7
- * 1. LLM decides when to use PTC
8
- * 2. LLM writes Python code that calls tools programmatically
9
- * 3. ToolNode automatically injects programmatic tools
10
- * 4. Tools filtered by allowed_callers
11
- */
12
- import { config } from 'dotenv';
13
- config();
14
- import { randomUUID } from 'crypto';
15
- import { HumanMessage } from '@langchain/core/messages';
16
- import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
17
- import {
18
- // createProgrammaticToolRegistry,
19
- createGetTeamMembersTool, createGetExpensesTool, createGetWeatherTool, } from '@/test/mockTools';
20
- import { createMetadataAggregator, ModelEndHandler, ToolEndHandler, } from '@/events';
21
- import { createProgrammaticToolCallingTool } from '@/tools/ProgrammaticToolCalling';
22
- import { createCodeExecutionTool } from '@/tools/CodeExecutor';
23
- import { getLLMConfig } from '@/utils/llmConfig';
24
- import { getArgs } from '@/scripts/args';
25
- import { GraphEvents } from '@/common';
26
- import { Run } from '@/run';
27
- const conversationHistory = [];
28
- /**
29
- * Creates a tool registry where ALL business tools are code_execution ONLY.
30
- * This forces the LLM to use PTC - it cannot call these tools directly.
31
- */
32
- function createPTCOnlyToolRegistry() {
33
- const toolDefs = [
34
- {
35
- name: 'get_team_members',
36
- description: 'Get list of team members. Returns array of objects with id, name, and department fields.',
37
- parameters: {
38
- type: 'object',
39
- properties: {},
40
- required: [],
41
- },
42
- allowed_callers: ['code_execution'], // PTC ONLY - not direct
43
- },
44
- {
45
- name: 'get_expenses',
46
- description: 'Get expense records for a user. Returns array of objects with amount and category fields.',
47
- parameters: {
48
- type: 'object',
49
- properties: {
50
- user_id: {
51
- type: 'string',
52
- description: 'The user ID to fetch expenses for',
53
- },
54
- },
55
- required: ['user_id'],
56
- },
57
- allowed_callers: ['code_execution'], // PTC ONLY - not direct
58
- },
59
- {
60
- name: 'get_weather',
61
- description: 'Get current weather for a city. Returns object with temperature (number) and condition (string) fields.',
62
- parameters: {
63
- type: 'object',
64
- properties: {
65
- city: {
66
- type: 'string',
67
- description: 'City name',
68
- },
69
- },
70
- required: ['city'],
71
- },
72
- allowed_callers: ['code_execution'], // PTC ONLY - not direct (changed from ['direct', 'code_execution'])
73
- },
74
- ];
75
- return new Map(toolDefs.map((def) => [def.name, def]));
76
- }
77
- async function testProgrammaticToolCalling() {
78
- const { userName, location, provider, currentDate } = await getArgs();
79
- const { contentParts, aggregateContent } = createContentAggregator();
80
- const customHandlers = {
81
- [GraphEvents.TOOL_END]: new ToolEndHandler(),
82
- [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
83
- [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
84
- [GraphEvents.ON_RUN_STEP_COMPLETED]: {
85
- handle: (event, data) => {
86
- console.log('====== ON_RUN_STEP_COMPLETED ======');
87
- console.dir(data, { depth: null });
88
- aggregateContent({
89
- event,
90
- data: data,
91
- });
92
- },
93
- },
94
- [GraphEvents.ON_RUN_STEP]: {
95
- handle: (event, data) => {
96
- console.log('====== ON_RUN_STEP ======');
97
- console.dir(data, { depth: null });
98
- aggregateContent({ event, data: data });
99
- },
100
- },
101
- [GraphEvents.ON_RUN_STEP_DELTA]: {
102
- handle: (event, data) => {
103
- aggregateContent({ event, data: data });
104
- },
105
- },
106
- [GraphEvents.ON_MESSAGE_DELTA]: {
107
- handle: (event, data) => {
108
- aggregateContent({ event, data: data });
109
- },
110
- },
111
- [GraphEvents.TOOL_START]: {
112
- handle: (_event, data, metadata) => {
113
- console.log('====== TOOL_START ======');
114
- console.dir(data, { depth: null });
115
- },
116
- },
117
- };
118
- const llmConfig = getLLMConfig(provider);
119
- // Create mock tool instances
120
- const teamTool = createGetTeamMembersTool();
121
- const expensesTool = createGetExpensesTool();
122
- const weatherTool = createGetWeatherTool();
123
- // Create special tools
124
- const codeExecTool = createCodeExecutionTool();
125
- const ptcTool = createProgrammaticToolCallingTool();
126
- // Build complete tool list and map
127
- const allTools = [teamTool, expensesTool, weatherTool, codeExecTool, ptcTool];
128
- const toolMap = new Map(allTools.map((t) => [t.name, t]));
129
- // Create tool registry where ALL business tools are PTC-only
130
- // This means the LLM CANNOT call get_team_members, get_expenses, get_weather directly
131
- // It MUST use run_tools_with_code to invoke them
132
- const toolRegistry = createPTCOnlyToolRegistry();
133
- console.log('\n' + '='.repeat(70));
134
- console.log('Tool Configuration Summary:');
135
- console.log('='.repeat(70));
136
- console.log('Total tools:', allTools.length);
137
- console.log('Programmatic-allowed:', Array.from(toolRegistry.values())
138
- .filter((t) => t.allowed_callers?.includes('code_execution'))
139
- .map((t) => t.name)
140
- .join(', '));
141
- console.log('Direct-callable:', Array.from(toolRegistry.values())
142
- .filter((t) => !t.allowed_callers || t.allowed_callers.includes('direct'))
143
- .map((t) => t.name)
144
- .join(', '));
145
- console.log('='.repeat(70) + '\n');
146
- const run = await Run.create({
147
- runId: randomUUID(),
148
- graphConfig: {
149
- type: 'standard',
150
- llmConfig,
151
- agents: [
152
- {
153
- agentId: 'default',
154
- provider: llmConfig.provider,
155
- clientOptions: llmConfig,
156
- tools: allTools,
157
- toolMap,
158
- toolRegistry,
159
- instructions: 'You are a friendly AI assistant with advanced coding capabilities.\n\n' +
160
- 'IMPORTANT: The tools get_team_members(), get_expenses(), and get_weather() are NOT available ' +
161
- 'for direct function calling. You MUST use the run_tools_with_code tool to invoke them.\n\n' +
162
- 'When you need to use these tools, write Python code using run_tools_with_code that calls:\n' +
163
- '- await get_team_members() - returns list of team members\n' +
164
- '- await get_expenses(user_id="...") - returns expenses for a user\n' +
165
- '- await get_weather(city="...") - returns weather data\n\n' +
166
- 'Use asyncio.gather() for parallel execution when calling multiple tools.',
167
- additional_instructions: `The user's name is ${userName} and they are located in ${location}. Today is ${currentDate}.`,
168
- },
169
- ],
170
- },
171
- returnContent: true,
172
- skipCleanup: true,
173
- customHandlers,
174
- });
175
- const config = {
176
- configurable: {
177
- provider,
178
- thread_id: 'ptc-conversation-1',
179
- },
180
- streamMode: 'values',
181
- version: 'v2',
182
- };
183
- console.log('Test 1: Team Expense Analysis with PTC');
184
- console.log('='.repeat(70) + '\n');
185
- const userMessage1 = `Hi ${userName}! I need you to analyze our team's expenses. Please:
186
-
187
- 1. Get the list of all team members
188
- 2. For each member, fetch their expense records
189
- 3. Calculate the total expenses per member
190
- 4. Identify anyone who spent more than $500
191
- 5. Show me a summary report
192
-
193
- IMPORTANT: Use the run_tools_with_code tool to do this efficiently.
194
- Don't call each tool separately - write Python code that orchestrates all the calls!`;
195
- conversationHistory.push(new HumanMessage(userMessage1));
196
- let inputs = {
197
- messages: conversationHistory,
198
- };
199
- const finalContentParts1 = await run.processStream(inputs, config);
200
- const finalMessages1 = run.getRunMessages();
201
- if (finalMessages1) {
202
- conversationHistory.push(...finalMessages1);
203
- }
204
- console.log('\n\n====================\n\n');
205
- console.log('Content Parts:');
206
- console.dir(contentParts, { depth: null });
207
- console.log('\n\n' + '='.repeat(70));
208
- console.log('Test 2: Conditional Logic and Parallel Execution');
209
- console.log('='.repeat(70) + '\n');
210
- const userMessage2 = `Great job! Now let's test some advanced patterns. Please:
211
-
212
- 1. Check the weather in both San Francisco and New York (in parallel!)
213
- 2. Based on which city has better weather (warmer), fetch the team members
214
- 3. For the Engineering team members only, calculate their travel expenses
215
- 4. Show me the results
216
-
217
- Again, use run_tools_with_code for maximum efficiency. Use asyncio.gather()
218
- to check both cities' weather at the same time!`;
219
- conversationHistory.push(new HumanMessage(userMessage2));
220
- inputs = {
221
- messages: conversationHistory,
222
- };
223
- const finalContentParts2 = await run.processStream(inputs, config);
224
- const finalMessages2 = run.getRunMessages();
225
- if (finalMessages2) {
226
- conversationHistory.push(...finalMessages2);
227
- }
228
- console.log('\n\n====================\n\n');
229
- console.log('Final Content Parts:');
230
- console.dir(finalContentParts2, { depth: null });
231
- console.log('\n\n' + '='.repeat(70));
232
- console.log('Generating conversation title...');
233
- console.log('='.repeat(70) + '\n');
234
- const { handleLLMEnd, collected } = createMetadataAggregator();
235
- const titleResult = await run.generateTitle({
236
- provider,
237
- inputText: userMessage1,
238
- contentParts,
239
- chainOptions: {
240
- callbacks: [
241
- {
242
- handleLLMEnd,
243
- },
244
- ],
245
- },
246
- });
247
- console.log('Generated Title:', titleResult);
248
- console.log('Collected metadata:', collected);
249
- }
250
- process.on('unhandledRejection', (reason, promise) => {
251
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
252
- console.log('Conversation history:');
253
- console.dir(conversationHistory, { depth: null });
254
- process.exit(1);
255
- });
256
- process.on('uncaughtException', (err) => {
257
- console.error('Uncaught Exception:', err);
258
- });
259
- testProgrammaticToolCalling().catch((err) => {
260
- console.error(err);
261
- console.log('Conversation history:');
262
- console.dir(conversationHistory, { depth: null });
263
- process.exit(1);
264
- });
265
- //# sourceMappingURL=code_exec_ptc.js.map