illuma-agents 1.0.36 → 1.0.38

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 (128) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +69 -14
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +3 -1
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +50 -8
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +277 -11
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +128 -61
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/main.cjs +16 -7
  12. package/dist/cjs/main.cjs.map +1 -1
  13. package/dist/cjs/messages/cache.cjs +1 -0
  14. package/dist/cjs/messages/cache.cjs.map +1 -1
  15. package/dist/cjs/messages/core.cjs +1 -1
  16. package/dist/cjs/messages/core.cjs.map +1 -1
  17. package/dist/cjs/messages/tools.cjs +2 -2
  18. package/dist/cjs/messages/tools.cjs.map +1 -1
  19. package/dist/cjs/stream.cjs +4 -2
  20. package/dist/cjs/stream.cjs.map +1 -1
  21. package/dist/cjs/tools/BrowserTools.cjs +27 -3
  22. package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
  23. package/dist/cjs/tools/CodeExecutor.cjs +22 -21
  24. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  25. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
  26. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  27. package/dist/cjs/tools/ToolNode.cjs +101 -2
  28. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  29. package/dist/cjs/tools/ToolSearch.cjs +862 -0
  30. package/dist/cjs/tools/ToolSearch.cjs.map +1 -0
  31. package/dist/esm/agents/AgentContext.mjs +69 -14
  32. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  33. package/dist/esm/common/enum.mjs +3 -1
  34. package/dist/esm/common/enum.mjs.map +1 -1
  35. package/dist/esm/graphs/Graph.mjs +51 -9
  36. package/dist/esm/graphs/Graph.mjs.map +1 -1
  37. package/dist/esm/graphs/MultiAgentGraph.mjs +278 -12
  38. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  39. package/dist/esm/llm/bedrock/index.mjs +127 -60
  40. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  41. package/dist/esm/main.mjs +1 -1
  42. package/dist/esm/messages/cache.mjs +1 -0
  43. package/dist/esm/messages/cache.mjs.map +1 -1
  44. package/dist/esm/messages/core.mjs +1 -1
  45. package/dist/esm/messages/core.mjs.map +1 -1
  46. package/dist/esm/messages/tools.mjs +2 -2
  47. package/dist/esm/messages/tools.mjs.map +1 -1
  48. package/dist/esm/stream.mjs +4 -2
  49. package/dist/esm/stream.mjs.map +1 -1
  50. package/dist/esm/tools/BrowserTools.mjs +27 -3
  51. package/dist/esm/tools/BrowserTools.mjs.map +1 -1
  52. package/dist/esm/tools/CodeExecutor.mjs +22 -21
  53. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  54. package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
  55. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  56. package/dist/esm/tools/ToolNode.mjs +102 -3
  57. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  58. package/dist/esm/tools/ToolSearch.mjs +827 -0
  59. package/dist/esm/tools/ToolSearch.mjs.map +1 -0
  60. package/dist/types/agents/AgentContext.d.ts +33 -1
  61. package/dist/types/common/enum.d.ts +4 -2
  62. package/dist/types/graphs/Graph.d.ts +6 -0
  63. package/dist/types/graphs/MultiAgentGraph.d.ts +16 -0
  64. package/dist/types/index.d.ts +1 -1
  65. package/dist/types/llm/bedrock/index.d.ts +89 -11
  66. package/dist/types/llm/bedrock/types.d.ts +27 -0
  67. package/dist/types/llm/bedrock/utils/index.d.ts +5 -0
  68. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +31 -0
  69. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +33 -0
  70. package/dist/types/tools/BrowserTools.d.ts +2 -0
  71. package/dist/types/tools/CodeExecutor.d.ts +0 -3
  72. package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
  73. package/dist/types/tools/ToolNode.d.ts +3 -1
  74. package/dist/types/tools/ToolSearch.d.ts +148 -0
  75. package/dist/types/types/graph.d.ts +2 -0
  76. package/dist/types/types/llm.d.ts +3 -1
  77. package/dist/types/types/tools.d.ts +42 -2
  78. package/package.json +12 -5
  79. package/src/agents/AgentContext.ts +88 -16
  80. package/src/common/enum.ts +3 -1
  81. package/src/graphs/Graph.ts +64 -13
  82. package/src/graphs/MultiAgentGraph.ts +350 -13
  83. package/src/index.ts +1 -1
  84. package/src/llm/bedrock/index.ts +221 -99
  85. package/src/llm/bedrock/llm.spec.ts +616 -0
  86. package/src/llm/bedrock/types.ts +51 -0
  87. package/src/llm/bedrock/utils/index.ts +18 -0
  88. package/src/llm/bedrock/utils/message_inputs.ts +563 -0
  89. package/src/llm/bedrock/utils/message_outputs.ts +310 -0
  90. package/src/messages/__tests__/tools.test.ts +21 -21
  91. package/src/messages/cache.test.ts +259 -0
  92. package/src/messages/cache.ts +104 -1
  93. package/src/messages/core.ts +1 -1
  94. package/src/messages/tools.ts +2 -2
  95. package/src/scripts/caching.ts +27 -19
  96. package/src/scripts/code_exec_files.ts +58 -15
  97. package/src/scripts/code_exec_multi_session.ts +241 -0
  98. package/src/scripts/code_exec_session.ts +282 -0
  99. package/src/scripts/multi-agent-conditional.ts +1 -0
  100. package/src/scripts/multi-agent-supervisor.ts +1 -0
  101. package/src/scripts/programmatic_exec_agent.ts +4 -4
  102. package/src/scripts/test-handoff-preamble.ts +277 -0
  103. package/src/scripts/test-parallel-handoffs.ts +291 -0
  104. package/src/scripts/test-tools-before-handoff.ts +8 -4
  105. package/src/scripts/test_code_api.ts +361 -0
  106. package/src/scripts/thinking-bedrock.ts +159 -0
  107. package/src/scripts/thinking.ts +39 -18
  108. package/src/scripts/{tool_search_regex.ts → tool_search.ts} +5 -5
  109. package/src/scripts/tools.ts +7 -3
  110. package/src/stream.ts +4 -2
  111. package/src/tools/BrowserTools.ts +68 -14
  112. package/src/tools/CodeExecutor.ts +26 -23
  113. package/src/tools/ProgrammaticToolCalling.ts +18 -14
  114. package/src/tools/ToolNode.ts +114 -1
  115. package/src/tools/ToolSearch.ts +1041 -0
  116. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
  117. package/src/tools/__tests__/{ToolSearchRegex.integration.test.ts → ToolSearch.integration.test.ts} +6 -6
  118. package/src/tools/__tests__/ToolSearch.test.ts +1003 -0
  119. package/src/types/graph.ts +2 -0
  120. package/src/types/llm.ts +3 -1
  121. package/src/types/tools.ts +51 -2
  122. package/dist/cjs/tools/ToolSearchRegex.cjs +0 -455
  123. package/dist/cjs/tools/ToolSearchRegex.cjs.map +0 -1
  124. package/dist/esm/tools/ToolSearchRegex.mjs +0 -448
  125. package/dist/esm/tools/ToolSearchRegex.mjs.map +0 -1
  126. package/dist/types/tools/ToolSearchRegex.d.ts +0 -80
  127. package/src/tools/ToolSearchRegex.ts +0 -535
  128. package/src/tools/__tests__/ToolSearchRegex.test.ts +0 -232
@@ -0,0 +1,361 @@
1
+ // src/scripts/test_code_api.ts
2
+ /**
3
+ * Direct test of the Code API to verify session file persistence.
4
+ * This bypasses the LLM and tests the API directly.
5
+ *
6
+ * Run with: npx ts-node -r dotenv/config src/scripts/test_code_api.ts
7
+ */
8
+ import { config } from 'dotenv';
9
+ config();
10
+
11
+ import fetch, { RequestInit } from 'node-fetch';
12
+ import { HttpsProxyAgent } from 'https-proxy-agent';
13
+
14
+ const API_KEY = process.env.LIBRECHAT_CODE_API_KEY ?? '';
15
+ const BASE_URL =
16
+ process.env.LIBRECHAT_CODE_BASEURL ?? 'https://api.librechat.ai/v1';
17
+ const PROXY = process.env.PROXY;
18
+
19
+ if (!API_KEY) {
20
+ console.error('LIBRECHAT_CODE_API_KEY not set');
21
+ process.exit(1);
22
+ }
23
+
24
+ interface FileRef {
25
+ id: string;
26
+ name: string;
27
+ session_id?: string;
28
+ /** Lineage tracking - present if file was modified from previous session */
29
+ modified_from?: {
30
+ id: string;
31
+ session_id: string;
32
+ };
33
+ }
34
+
35
+ interface ExecResult {
36
+ session_id: string;
37
+ stdout: string;
38
+ stderr: string;
39
+ files?: FileRef[];
40
+ }
41
+
42
+ interface FileInfo {
43
+ name: string;
44
+ metadata: Record<string, string>;
45
+ }
46
+
47
+ async function makeRequest(
48
+ endpoint: string,
49
+ body?: Record<string, unknown>
50
+ ): Promise<unknown> {
51
+ const fetchOptions: RequestInit = {
52
+ method: body ? 'POST' : 'GET',
53
+ headers: {
54
+ 'Content-Type': 'application/json',
55
+ 'User-Agent': 'LibreChat/1.0',
56
+ 'X-API-Key': API_KEY,
57
+ },
58
+ };
59
+
60
+ if (body) {
61
+ fetchOptions.body = JSON.stringify(body);
62
+ }
63
+
64
+ if (PROXY) {
65
+ fetchOptions.agent = new HttpsProxyAgent(PROXY);
66
+ }
67
+
68
+ console.log(`\n>>> ${body ? 'POST' : 'GET'} ${endpoint}`);
69
+ if (body) {
70
+ console.log('Body:', JSON.stringify(body, null, 2));
71
+ }
72
+
73
+ const response = await fetch(endpoint, fetchOptions);
74
+ const result = await response.json();
75
+
76
+ console.log(`<<< Response (${response.status}):`);
77
+ console.log(JSON.stringify(result, null, 2));
78
+
79
+ if (!response.ok) {
80
+ throw new Error(`HTTP ${response.status}: ${JSON.stringify(result)}`);
81
+ }
82
+
83
+ return result;
84
+ }
85
+
86
+ async function testCodeAPI(): Promise<void> {
87
+ console.log('='.repeat(60));
88
+ console.log('TEST 1: Create a file');
89
+ console.log('='.repeat(60));
90
+
91
+ const createCode = `
92
+ import json
93
+
94
+ config = {
95
+ "app_name": "TestApp",
96
+ "version": "1.0.0",
97
+ "debug": True
98
+ }
99
+
100
+ with open("/mnt/data/test_config.json", "w") as f:
101
+ json.dump(config, f, indent=2)
102
+
103
+ with open("/mnt/data/test_config.json", "r") as f:
104
+ print(f.read())
105
+ `;
106
+
107
+ const result1 = (await makeRequest(`${BASE_URL}/exec`, {
108
+ lang: 'py',
109
+ code: createCode,
110
+ })) as ExecResult;
111
+
112
+ const sessionId = result1.session_id;
113
+ const files = result1.files ?? [];
114
+
115
+ console.log('\n--- Result Summary ---');
116
+ console.log('session_id:', sessionId);
117
+ console.log('files:', files);
118
+ console.log('stdout:', result1.stdout);
119
+ console.log('stderr:', result1.stderr);
120
+
121
+ if (!sessionId || files.length === 0) {
122
+ console.error('\n❌ No session_id or files returned!');
123
+ return;
124
+ }
125
+
126
+ // Check if files now include session_id (new API feature)
127
+ const hasSessionIdInFiles = files.some((f) => f.session_id != null);
128
+ console.log('\n✅ Files include session_id:', hasSessionIdInFiles);
129
+
130
+ console.log('\n' + '='.repeat(60));
131
+ console.log(
132
+ 'TEST 2: Fetch files IMMEDIATELY (no delay - testing race condition fix)'
133
+ );
134
+ console.log('='.repeat(60));
135
+
136
+ const filesResult = (await makeRequest(
137
+ `${BASE_URL}/files/${sessionId}?detail=full`
138
+ )) as FileInfo[];
139
+
140
+ console.log('\n--- Files in session (detail=full) ---');
141
+ for (const file of filesResult) {
142
+ console.log('File:', file.name);
143
+ console.log(' metadata:', file.metadata);
144
+ }
145
+
146
+ if (filesResult.length === 0) {
147
+ console.log(
148
+ '\n⚠️ Files endpoint returned empty - race condition may still exist'
149
+ );
150
+ } else {
151
+ console.log('\n✅ Files available immediately!');
152
+ }
153
+
154
+ // Test new normalized detail level
155
+ console.log('\n' + '='.repeat(60));
156
+ console.log('TEST 2b: Fetch files with detail=normalized');
157
+ console.log('='.repeat(60));
158
+
159
+ const normalizedResult = (await makeRequest(
160
+ `${BASE_URL}/files/${sessionId}?detail=normalized`
161
+ )) as FileRef[];
162
+
163
+ console.log('\n--- Files in session (detail=normalized) ---');
164
+ console.log(JSON.stringify(normalizedResult, null, 2));
165
+
166
+ console.log('\n' + '='.repeat(60));
167
+ console.log(
168
+ 'TEST 3: Read file IMMEDIATELY using files from original response'
169
+ );
170
+ console.log('='.repeat(60));
171
+
172
+ // Use files directly - if API returns session_id, use that; otherwise add it
173
+ const fileReferences: FileRef[] = files.map((file) => ({
174
+ session_id: file.session_id ?? sessionId,
175
+ id: file.id,
176
+ name: file.name,
177
+ }));
178
+
179
+ console.log(
180
+ '\nFile references we will send:',
181
+ JSON.stringify(fileReferences, null, 2)
182
+ );
183
+
184
+ const readCode = `
185
+ import json
186
+
187
+ with open("/mnt/data/test_config.json", "r") as f:
188
+ config = json.load(f)
189
+ print("Read config:")
190
+ print(json.dumps(config, indent=2))
191
+ print("Version:", config.get("version"))
192
+ `;
193
+
194
+ const result2 = (await makeRequest(`${BASE_URL}/exec`, {
195
+ lang: 'py',
196
+ code: readCode,
197
+ files: fileReferences,
198
+ })) as ExecResult;
199
+
200
+ console.log('\n--- Result Summary ---');
201
+ console.log('stdout:', result2.stdout);
202
+ console.log('stderr:', result2.stderr);
203
+
204
+ if (result2.stderr && result2.stderr.includes('FileNotFoundError')) {
205
+ console.log(
206
+ '\n❌ File not found! The file reference format might be wrong.'
207
+ );
208
+
209
+ // Try alternative format - just session_id
210
+ console.log('\n' + '='.repeat(60));
211
+ console.log('TEST 4: Try with just session_id in request');
212
+ console.log('='.repeat(60));
213
+
214
+ const result3 = (await makeRequest(`${BASE_URL}/exec`, {
215
+ lang: 'py',
216
+ code: readCode,
217
+ session_id: sessionId,
218
+ })) as ExecResult;
219
+
220
+ console.log('\n--- Result Summary ---');
221
+ console.log('stdout:', result3.stdout);
222
+ console.log('stderr:', result3.stderr);
223
+ } else {
224
+ console.log('\n✅ File read successfully!');
225
+ }
226
+
227
+ // ============================================================
228
+ // TEST 4: MODIFY the file (same filename) - tests editable files
229
+ // ============================================================
230
+ console.log('\n' + '='.repeat(60));
231
+ console.log('TEST 4: MODIFY file in-place (testing editable files feature)');
232
+ console.log('='.repeat(60));
233
+
234
+ const modifyCode = `
235
+ import json
236
+
237
+ # Read the existing file
238
+ with open("/mnt/data/test_config.json", "r") as f:
239
+ config = json.load(f)
240
+
241
+ print("Original config:")
242
+ print(json.dumps(config, indent=2))
243
+
244
+ # Modify the config
245
+ config["version"] = "2.0.0"
246
+ config["modified"] = True
247
+
248
+ # Write BACK to the SAME filename (should work now!)
249
+ with open("/mnt/data/test_config.json", "w") as f:
250
+ json.dump(config, f, indent=2)
251
+
252
+ # Verify the write
253
+ with open("/mnt/data/test_config.json", "r") as f:
254
+ updated = json.load(f)
255
+
256
+ print("\\nUpdated config:")
257
+ print(json.dumps(updated, indent=2))
258
+ `;
259
+
260
+ const result3 = (await makeRequest(`${BASE_URL}/exec`, {
261
+ lang: 'py',
262
+ code: modifyCode,
263
+ files: fileReferences,
264
+ })) as ExecResult;
265
+
266
+ console.log('\n--- Result Summary ---');
267
+ console.log('stdout:', result3.stdout);
268
+ console.log('stderr:', result3.stderr);
269
+ console.log('files:', JSON.stringify(result3.files, null, 2));
270
+
271
+ if (result3.stderr && result3.stderr.includes('Permission denied')) {
272
+ console.log('\n❌ Permission denied - files are still read-only!');
273
+ } else if (result3.stderr && result3.stderr.includes('Error')) {
274
+ console.log('\n❌ Error modifying file:', result3.stderr);
275
+ } else {
276
+ console.log('\n✅ File modified successfully!');
277
+
278
+ // Check for modified_from lineage
279
+ const modifiedFile = result3.files?.find(
280
+ (f) => f.name === 'test_config.json'
281
+ );
282
+ if (modifiedFile) {
283
+ console.log('\n--- Modified File Details ---');
284
+ console.log(' id:', modifiedFile.id);
285
+ console.log(' name:', modifiedFile.name);
286
+ console.log(' session_id:', modifiedFile.session_id);
287
+ if (modifiedFile.modified_from) {
288
+ console.log(
289
+ ' modified_from:',
290
+ JSON.stringify(modifiedFile.modified_from)
291
+ );
292
+ console.log(
293
+ '\n✅ Lineage tracking working! File shows it was modified from previous session.'
294
+ );
295
+ } else {
296
+ console.log(
297
+ '\n⚠️ No modified_from field - lineage tracking not present'
298
+ );
299
+ }
300
+ } else {
301
+ console.log('\n⚠️ Modified file not found in response files array');
302
+ }
303
+ }
304
+
305
+ // ============================================================
306
+ // TEST 5: Verify modification persists in next execution
307
+ // ============================================================
308
+ console.log('\n' + '='.repeat(60));
309
+ console.log(
310
+ 'TEST 5: Verify modified file can be read in subsequent execution'
311
+ );
312
+ console.log('='.repeat(60));
313
+
314
+ // Use the new file references from the modify response
315
+ const newFileRefs: FileRef[] = (result3.files ?? []).map((file) => ({
316
+ session_id: file.session_id ?? result3.session_id,
317
+ id: file.id,
318
+ name: file.name,
319
+ }));
320
+
321
+ if (newFileRefs.length === 0) {
322
+ console.log(
323
+ '\n⚠️ No files returned from modification, skipping verification'
324
+ );
325
+ } else {
326
+ console.log(
327
+ '\nUsing new file references:',
328
+ JSON.stringify(newFileRefs, null, 2)
329
+ );
330
+
331
+ const verifyCode = `
332
+ import json
333
+
334
+ with open("/mnt/data/test_config.json", "r") as f:
335
+ config = json.load(f)
336
+
337
+ print("Verified config:")
338
+ print(json.dumps(config, indent=2))
339
+
340
+ if config.get("version") == "2.0.0" and config.get("modified") == True:
341
+ print("\\n✅ Modification persisted correctly!")
342
+ else:
343
+ print("\\n❌ Modification did NOT persist!")
344
+ `;
345
+
346
+ const result4 = (await makeRequest(`${BASE_URL}/exec`, {
347
+ lang: 'py',
348
+ code: verifyCode,
349
+ files: newFileRefs,
350
+ })) as ExecResult;
351
+
352
+ console.log('\n--- Result Summary ---');
353
+ console.log('stdout:', result4.stdout);
354
+ console.log('stderr:', result4.stderr);
355
+ }
356
+ }
357
+
358
+ testCodeAPI().catch((err) => {
359
+ console.error('Error:', err);
360
+ process.exit(1);
361
+ });
@@ -0,0 +1,159 @@
1
+ // src/scripts/thinking-bedrock.ts
2
+ import { config } from 'dotenv';
3
+ config();
4
+ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
5
+ import type { UsageMetadata } from '@langchain/core/messages';
6
+ import * as t from '@/types';
7
+ import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
8
+ import { createCodeExecutionTool } from '@/tools/CodeExecutor';
9
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
10
+ import { GraphEvents, Providers } from '@/common';
11
+ import { getLLMConfig } from '@/utils/llmConfig';
12
+ import { getArgs } from '@/scripts/args';
13
+ import { Run } from '@/run';
14
+
15
+ const conversationHistory: BaseMessage[] = [];
16
+ let _contentParts: t.MessageContentComplex[] = [];
17
+ const collectedUsage: UsageMetadata[] = [];
18
+
19
+ async function testBedrockThinking(): Promise<void> {
20
+ const { userName } = await getArgs();
21
+ const instructions = `You are a helpful AI assistant for ${userName}. When answering questions, be thorough in your reasoning.`;
22
+ const { contentParts, aggregateContent } = createContentAggregator();
23
+ _contentParts = contentParts as t.MessageContentComplex[];
24
+
25
+ // Set up event handlers
26
+ const customHandlers = {
27
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
28
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(collectedUsage),
29
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
30
+ [GraphEvents.ON_RUN_STEP_COMPLETED]: {
31
+ handle: (
32
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
33
+ data: t.StreamEventData
34
+ ): void => {
35
+ console.log('====== ON_RUN_STEP_COMPLETED ======');
36
+ aggregateContent({
37
+ event,
38
+ data: data as unknown as { result: t.ToolEndEvent },
39
+ });
40
+ },
41
+ },
42
+ [GraphEvents.ON_RUN_STEP]: {
43
+ handle: (event: GraphEvents.ON_RUN_STEP, data: t.RunStep) => {
44
+ aggregateContent({ event, data });
45
+ },
46
+ },
47
+ [GraphEvents.ON_RUN_STEP_DELTA]: {
48
+ handle: (
49
+ event: GraphEvents.ON_RUN_STEP_DELTA,
50
+ data: t.RunStepDeltaEvent
51
+ ) => {
52
+ aggregateContent({ event, data });
53
+ },
54
+ },
55
+ [GraphEvents.ON_MESSAGE_DELTA]: {
56
+ handle: (
57
+ event: GraphEvents.ON_MESSAGE_DELTA,
58
+ data: t.MessageDeltaEvent
59
+ ) => {
60
+ aggregateContent({ event, data });
61
+ },
62
+ },
63
+ [GraphEvents.ON_REASONING_DELTA]: {
64
+ handle: (
65
+ event: GraphEvents.ON_REASONING_DELTA,
66
+ data: t.ReasoningDeltaEvent
67
+ ) => {
68
+ aggregateContent({ event, data });
69
+ },
70
+ },
71
+ };
72
+
73
+ const baseLlmConfig = getLLMConfig(Providers.BEDROCK);
74
+
75
+ // Enable thinking with token budget for Bedrock
76
+ const llmConfig = {
77
+ ...baseLlmConfig,
78
+ model: 'us.anthropic.claude-3-7-sonnet-20250219-v1:0',
79
+ maxTokens: 5000,
80
+ additionalModelRequestFields: {
81
+ thinking: { type: 'enabled', budget_tokens: 2000 },
82
+ },
83
+ };
84
+
85
+ const run = await Run.create<t.IState>({
86
+ runId: 'test-bedrock-thinking-id',
87
+ graphConfig: {
88
+ instructions,
89
+ type: 'standard',
90
+ tools: [createCodeExecutionTool()],
91
+ llmConfig,
92
+ },
93
+ returnContent: true,
94
+ customHandlers: customHandlers as t.RunConfig['customHandlers'],
95
+ });
96
+
97
+ const config = {
98
+ configurable: {
99
+ thread_id: 'bedrock-thinking-test-thread',
100
+ },
101
+ streamMode: 'values',
102
+ version: 'v2' as const,
103
+ };
104
+
105
+ // Test 1: Regular thinking mode
106
+ console.log('\n\nTest 1: Bedrock Regular thinking mode');
107
+ const userMessage1 = `Please print 'hello world' in python`;
108
+ conversationHistory.push(new HumanMessage(userMessage1));
109
+
110
+ console.log('Running first query with Bedrock thinking enabled...');
111
+ const firstInputs = { messages: [...conversationHistory] };
112
+ await run.processStream(firstInputs, config);
113
+
114
+ // Extract and display thinking blocks
115
+ const finalMessages = run.getRunMessages();
116
+ console.log('\n\nFinal messages after Test 1:');
117
+ console.dir(finalMessages, { depth: null });
118
+
119
+ // Test 2: Try multi-turn conversation
120
+ console.log(
121
+ '\n\nTest 2: Multi-turn conversation with Bedrock thinking enabled'
122
+ );
123
+ const userMessage2 = `Given your previous analysis, what would be the most significant technical challenges in making this transition?`;
124
+ conversationHistory.push(new HumanMessage(userMessage2));
125
+
126
+ console.log('Running second query with Bedrock thinking enabled...');
127
+ const secondInputs = { messages: [...conversationHistory] };
128
+ await run.processStream(secondInputs, config);
129
+
130
+ // Display thinking blocks for second response
131
+ const finalMessages2 = run.getRunMessages();
132
+ console.log('\n\nBedrock thinking feature test completed!');
133
+ console.dir(finalMessages2, { depth: null });
134
+
135
+ console.log('\n\nContent parts:');
136
+ console.dir(_contentParts, { depth: null });
137
+ }
138
+
139
+ process.on('unhandledRejection', (reason, promise) => {
140
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
141
+ console.log('Conversation history:');
142
+ console.dir(conversationHistory, { depth: null });
143
+ console.log('Content parts:');
144
+ console.dir(_contentParts, { depth: null });
145
+ process.exit(1);
146
+ });
147
+
148
+ process.on('uncaughtException', (err) => {
149
+ console.error('Uncaught Exception:', err);
150
+ });
151
+
152
+ testBedrockThinking().catch((err) => {
153
+ console.error(err);
154
+ console.log('Conversation history:');
155
+ console.dir(conversationHistory, { depth: null });
156
+ console.log('Content parts:');
157
+ console.dir(_contentParts, { depth: null });
158
+ process.exit(1);
159
+ });
@@ -1,7 +1,11 @@
1
1
  // src/scripts/test-thinking.ts
2
2
  import { config } from 'dotenv';
3
3
  config();
4
- import { HumanMessage, SystemMessage, BaseMessage } from '@langchain/core/messages';
4
+ import {
5
+ HumanMessage,
6
+ SystemMessage,
7
+ BaseMessage,
8
+ } from '@langchain/core/messages';
5
9
  import type { UsageMetadata } from '@langchain/core/messages';
6
10
  import * as t from '@/types';
7
11
  import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
@@ -21,17 +25,23 @@ async function testThinking(): Promise<void> {
21
25
  const instructions = `You are a helpful AI assistant for ${userName}. When answering questions, be thorough in your reasoning.`;
22
26
  const { contentParts, aggregateContent } = createContentAggregator();
23
27
  _contentParts = contentParts as t.MessageContentComplex[];
24
-
28
+
25
29
  // Set up event handlers
26
30
  const customHandlers = {
27
31
  [GraphEvents.TOOL_END]: new ToolEndHandler(),
28
32
  [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(collectedUsage),
29
33
  [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
30
34
  [GraphEvents.ON_RUN_STEP_COMPLETED]: {
31
- handle: (event: GraphEvents.ON_RUN_STEP_COMPLETED, data: t.StreamEventData): void => {
35
+ handle: (
36
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
37
+ data: t.StreamEventData
38
+ ): void => {
32
39
  console.log('====== ON_RUN_STEP_COMPLETED ======');
33
- aggregateContent({ event, data: data as unknown as { result: t.ToolEndEvent } });
34
- }
40
+ aggregateContent({
41
+ event,
42
+ data: data as unknown as { result: t.ToolEndEvent },
43
+ });
44
+ },
35
45
  },
36
46
  [GraphEvents.ON_RUN_STEP]: {
37
47
  handle: (event: GraphEvents.ON_RUN_STEP, data: t.RunStep) => {
@@ -39,29 +49,38 @@ async function testThinking(): Promise<void> {
39
49
  },
40
50
  },
41
51
  [GraphEvents.ON_RUN_STEP_DELTA]: {
42
- handle: (event: GraphEvents.ON_RUN_STEP_DELTA, data: t.RunStepDeltaEvent) => {
52
+ handle: (
53
+ event: GraphEvents.ON_RUN_STEP_DELTA,
54
+ data: t.RunStepDeltaEvent
55
+ ) => {
43
56
  aggregateContent({ event, data });
44
57
  },
45
58
  },
46
59
  [GraphEvents.ON_MESSAGE_DELTA]: {
47
- handle: (event: GraphEvents.ON_MESSAGE_DELTA, data: t.MessageDeltaEvent) => {
60
+ handle: (
61
+ event: GraphEvents.ON_MESSAGE_DELTA,
62
+ data: t.MessageDeltaEvent
63
+ ) => {
48
64
  aggregateContent({ event, data });
49
65
  },
50
66
  },
51
67
  [GraphEvents.ON_REASONING_DELTA]: {
52
- handle: (event: GraphEvents.ON_REASONING_DELTA, data: t.ReasoningDeltaEvent) => {
68
+ handle: (
69
+ event: GraphEvents.ON_REASONING_DELTA,
70
+ data: t.ReasoningDeltaEvent
71
+ ) => {
53
72
  aggregateContent({ event, data });
54
73
  },
55
74
  },
56
75
  };
57
76
 
58
77
  const baseLlmConfig: t.LLMConfig = getLLMConfig(Providers.ANTHROPIC);
59
-
78
+
60
79
  // Enable thinking with token budget
61
80
  const llmConfig = {
62
81
  ...baseLlmConfig,
63
82
  model: 'claude-3-7-sonnet-latest',
64
- thinking: { type: "enabled", budget_tokens: 2000 }
83
+ thinking: { type: 'enabled', budget_tokens: 2000 },
65
84
  };
66
85
 
67
86
  const run = await Run.create<t.IState>({
@@ -93,7 +112,7 @@ async function testThinking(): Promise<void> {
93
112
  console.log('Running first query with thinking enabled...');
94
113
  const firstInputs = { messages: [...conversationHistory] };
95
114
  await run.processStream(firstInputs, config);
96
-
115
+
97
116
  // Extract and display thinking blocks
98
117
  const finalMessages = run.getRunMessages();
99
118
 
@@ -101,30 +120,32 @@ async function testThinking(): Promise<void> {
101
120
  console.log('\n\nTest 2: Multi-turn conversation with thinking enabled');
102
121
  const userMessage2 = `Given your previous analysis, what would be the most significant technical challenges in making this transition?`;
103
122
  conversationHistory.push(new HumanMessage(userMessage2));
104
-
123
+
105
124
  console.log('Running second query with thinking enabled...');
106
125
  const secondInputs = { messages: [...conversationHistory] };
107
126
  await run.processStream(secondInputs, config);
108
-
127
+
109
128
  // Display thinking blocks for second response
110
129
  const finalMessages2 = run.getRunMessages();
111
130
 
112
131
  // Test 3: Redacted thinking mode
113
132
  console.log('\n\nTest 3: Redacted thinking mode');
114
- const magicString = "ANTHROPIC_MAGIC_STRING_TRIGGER_REDACTED_THINKING_46C9A13E193C177646C7398A98432ECCCE4C1253D5E2D82641AC0E52CC2876CB";
133
+ const magicString =
134
+ 'ANTHROPIC_MAGIC_STRING_TRIGGER_REDACTED_THINKING_46C9A13E193C177646C7398A98432ECCCE4C1253D5E2D82641AC0E52CC2876CB';
115
135
  const userMessage3 = `${magicString}\n\nExplain how quantum computing works in simple terms.`;
116
-
136
+
117
137
  // Reset conversation for clean test
118
138
  conversationHistory.length = 0;
119
139
  conversationHistory.push(new HumanMessage(userMessage3));
120
-
140
+
121
141
  console.log('Running query with redacted thinking...');
122
142
  const thirdInputs = { messages: [...conversationHistory] };
123
143
  await run.processStream(thirdInputs, config);
124
-
144
+
125
145
  // Display redacted thinking blocks
126
146
  const finalMessages3 = run.getRunMessages();
127
147
  console.log('\n\nThinking feature test completed!');
148
+ console.dir(finalMessages3, { depth: null });
128
149
  }
129
150
 
130
151
  process.on('unhandledRejection', (reason, promise) => {
@@ -147,4 +168,4 @@ testThinking().catch((err) => {
147
168
  console.log('Content parts:');
148
169
  console.dir(_contentParts, { depth: null });
149
170
  process.exit(1);
150
- });
171
+ });
@@ -1,7 +1,7 @@
1
- // src/scripts/tool_search_regex.ts
1
+ // src/scripts/tool_search.ts
2
2
  /**
3
3
  * Test script for the Tool Search Regex tool.
4
- * Run with: npm run tool_search_regex
4
+ * Run with: npm run tool_search
5
5
  *
6
6
  * Demonstrates runtime registry injection - the tool registry is passed
7
7
  * at invocation time, not at initialization time.
@@ -9,7 +9,7 @@
9
9
  import { config } from 'dotenv';
10
10
  config();
11
11
 
12
- import { createToolSearchRegexTool } from '@/tools/ToolSearchRegex';
12
+ import { createToolSearch } from '@/tools/ToolSearch';
13
13
  import type { LCToolRegistry } from '@/types';
14
14
  import { createToolSearchToolRegistry } from '@/test/mockTools';
15
15
 
@@ -22,7 +22,7 @@ interface RunTestOptions {
22
22
  }
23
23
 
24
24
  async function runTest(
25
- searchTool: ReturnType<typeof createToolSearchRegexTool>,
25
+ searchTool: ReturnType<typeof createToolSearch>,
26
26
  testName: string,
27
27
  query: string,
28
28
  options: RunTestOptions
@@ -82,7 +82,7 @@ async function main(): Promise<void> {
82
82
  );
83
83
 
84
84
  console.log('\nCreating Tool Search Regex tool WITH registry for testing...');
85
- const searchTool = createToolSearchRegexTool({ apiKey, toolRegistry });
85
+ const searchTool = createToolSearch({ apiKey, toolRegistry });
86
86
  console.log('Tool created successfully!');
87
87
  console.log(
88
88
  'Note: In production, ToolNode injects toolRegistry via params when invoked through the graph.\n'