@librechat/agents 3.0.75 → 3.0.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/graphs/Graph.cjs +34 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +22 -21
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +14 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +28 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +35 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +22 -21
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +14 -11
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +28 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +6 -0
- package/dist/types/tools/CodeExecutor.d.ts +0 -3
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +0 -3
- package/dist/types/tools/ToolNode.d.ts +3 -1
- package/dist/types/types/tools.d.ts +32 -0
- package/package.json +3 -2
- package/src/graphs/Graph.ts +44 -0
- package/src/scripts/code_exec_files.ts +58 -15
- package/src/scripts/code_exec_session.ts +282 -0
- package/src/scripts/test_code_api.ts +361 -0
- package/src/tools/CodeExecutor.ts +26 -23
- package/src/tools/ProgrammaticToolCalling.ts +18 -14
- package/src/tools/ToolNode.ts +33 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -2
- package/src/types/tools.ts +40 -0
|
@@ -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
|
+
});
|
|
@@ -17,7 +17,7 @@ export const getCodeBaseURL = (): string =>
|
|
|
17
17
|
const imageMessage = 'Image is already displayed to the user';
|
|
18
18
|
const otherMessage = 'File is already downloaded by the user';
|
|
19
19
|
const accessMessage =
|
|
20
|
-
'Note: Files
|
|
20
|
+
'Note: Files from previous executions are automatically available and can be modified.';
|
|
21
21
|
const emptyOutputMessage =
|
|
22
22
|
'stdout: Empty. Ensure you\'re writing output explicitly.\n';
|
|
23
23
|
|
|
@@ -41,7 +41,8 @@ const CodeExecutionToolSchema = z.object({
|
|
|
41
41
|
code: z.string()
|
|
42
42
|
.describe(`The complete, self-contained code to execute, without any truncation or minimization.
|
|
43
43
|
- The environment is stateless; variables and imports don't persist between executions.
|
|
44
|
-
-
|
|
44
|
+
- Generated files from previous executions are automatically available in "/mnt/data/".
|
|
45
|
+
- Files from previous executions are automatically available and can be modified in place.
|
|
45
46
|
- Input code **IS ALREADY** displayed to the user, so **DO NOT** repeat it in your response unless asked.
|
|
46
47
|
- Output code **IS NOT** displayed to the user, so **DO** write all desired output explicitly.
|
|
47
48
|
- IMPORTANT: You MUST explicitly print/output ALL results you want the user to see.
|
|
@@ -50,17 +51,6 @@ const CodeExecutionToolSchema = z.object({
|
|
|
50
51
|
- js: use the \`console\` or \`process\` methods for all outputs.
|
|
51
52
|
- r: IMPORTANT: No X11 display available. ALL graphics MUST use Cairo library (library(Cairo)).
|
|
52
53
|
- Other languages: use appropriate output functions.`),
|
|
53
|
-
session_id: z
|
|
54
|
-
.string()
|
|
55
|
-
.optional()
|
|
56
|
-
.describe(
|
|
57
|
-
`Session ID from a previous response to access generated files.
|
|
58
|
-
- Files load into the current working directory ("/mnt/data/")
|
|
59
|
-
- Use relative paths ONLY
|
|
60
|
-
- Files are READ-ONLY and cannot be modified in-place
|
|
61
|
-
- To modify: read original file, write to NEW filename
|
|
62
|
-
`.trim()
|
|
63
|
-
),
|
|
64
54
|
args: z
|
|
65
55
|
.array(z.string())
|
|
66
56
|
.optional()
|
|
@@ -94,15 +84,33 @@ Usage:
|
|
|
94
84
|
`.trim();
|
|
95
85
|
|
|
96
86
|
return tool<typeof CodeExecutionToolSchema>(
|
|
97
|
-
async ({ lang, code,
|
|
98
|
-
|
|
87
|
+
async ({ lang, code, ...rest }, config) => {
|
|
88
|
+
/**
|
|
89
|
+
* Extract session context from config.toolCall (injected by ToolNode).
|
|
90
|
+
* - session_id: For API to associate with previous session
|
|
91
|
+
* - _injected_files: File refs to pass directly (avoids /files endpoint race condition)
|
|
92
|
+
*/
|
|
93
|
+
const { session_id, _injected_files } = (config.toolCall ?? {}) as {
|
|
94
|
+
session_id?: string;
|
|
95
|
+
_injected_files?: t.CodeEnvFile[];
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const postData: Record<string, unknown> = {
|
|
99
99
|
lang,
|
|
100
100
|
code,
|
|
101
101
|
...rest,
|
|
102
102
|
...params,
|
|
103
103
|
};
|
|
104
104
|
|
|
105
|
-
|
|
105
|
+
/**
|
|
106
|
+
* File injection priority:
|
|
107
|
+
* 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)
|
|
108
|
+
* 2. Fall back to fetching from /files endpoint if session_id provided but no injected files
|
|
109
|
+
*/
|
|
110
|
+
if (_injected_files && _injected_files.length > 0) {
|
|
111
|
+
postData.files = _injected_files;
|
|
112
|
+
} else if (session_id != null && session_id.length > 0) {
|
|
113
|
+
/** Fallback: fetch from /files endpoint (may have race condition issues) */
|
|
106
114
|
try {
|
|
107
115
|
const filesEndpoint = `${baseEndpoint}/files/${session_id}?detail=full`;
|
|
108
116
|
const fetchOptions: RequestInit = {
|
|
@@ -127,7 +135,6 @@ Usage:
|
|
|
127
135
|
const files = await response.json();
|
|
128
136
|
if (Array.isArray(files) && files.length > 0) {
|
|
129
137
|
const fileReferences: t.CodeEnvFile[] = files.map((file) => {
|
|
130
|
-
// Extract the ID from the file name (part after session ID prefix and before extension)
|
|
131
138
|
const nameParts = file.name.split('/');
|
|
132
139
|
const id = nameParts.length > 1 ? nameParts[1].split('.')[0] : '';
|
|
133
140
|
|
|
@@ -138,11 +145,7 @@ Usage:
|
|
|
138
145
|
};
|
|
139
146
|
});
|
|
140
147
|
|
|
141
|
-
|
|
142
|
-
postData.files = fileReferences;
|
|
143
|
-
} else if (Array.isArray(postData.files)) {
|
|
144
|
-
postData.files = [...postData.files, ...fileReferences];
|
|
145
|
-
}
|
|
148
|
+
postData.files = fileReferences;
|
|
146
149
|
}
|
|
147
150
|
} catch {
|
|
148
151
|
// eslint-disable-next-line no-console
|
|
@@ -191,7 +194,7 @@ Usage:
|
|
|
191
194
|
}
|
|
192
195
|
}
|
|
193
196
|
|
|
194
|
-
formattedOutput += `\
|
|
197
|
+
formattedOutput += `\n\n${accessMessage}`;
|
|
195
198
|
return [
|
|
196
199
|
formattedOutput.trim(),
|
|
197
200
|
{
|
|
@@ -19,7 +19,7 @@ config();
|
|
|
19
19
|
const imageMessage = 'Image is already displayed to the user';
|
|
20
20
|
const otherMessage = 'File is already downloaded by the user';
|
|
21
21
|
const accessMessage =
|
|
22
|
-
'Note: Files
|
|
22
|
+
'Note: Files from previous executions are automatically available and can be modified.';
|
|
23
23
|
const emptyOutputMessage =
|
|
24
24
|
'stdout: Empty. Ensure you\'re writing output explicitly.\n';
|
|
25
25
|
|
|
@@ -68,12 +68,6 @@ Rules:
|
|
|
68
68
|
- Tools are pre-defined—DO NOT write function definitions
|
|
69
69
|
- Only print() output returns to the model`
|
|
70
70
|
),
|
|
71
|
-
session_id: z
|
|
72
|
-
.string()
|
|
73
|
-
.optional()
|
|
74
|
-
.describe(
|
|
75
|
-
'Session ID for file access (same as regular code execution). Files load into /mnt/data/ and are READ-ONLY.'
|
|
76
|
-
),
|
|
77
71
|
timeout: z
|
|
78
72
|
.number()
|
|
79
73
|
.int()
|
|
@@ -542,7 +536,7 @@ export function formatCompletedResponse(
|
|
|
542
536
|
}
|
|
543
537
|
}
|
|
544
538
|
|
|
545
|
-
formatted += `\
|
|
539
|
+
formatted += `\n\n${accessMessage}`;
|
|
546
540
|
}
|
|
547
541
|
|
|
548
542
|
return [
|
|
@@ -613,7 +607,7 @@ Rules:
|
|
|
613
607
|
- Do NOT define \`async def main()\` or call \`asyncio.run()\`—just write code with await
|
|
614
608
|
- Tools are pre-defined—DO NOT write function definitions
|
|
615
609
|
- Only \`print()\` output returns; tool results are raw dicts/lists/strings
|
|
616
|
-
-
|
|
610
|
+
- Generated files are automatically available in /mnt/data/ for subsequent executions
|
|
617
611
|
- Tool names normalized: hyphens→underscores, keywords get \`_tool\` suffix
|
|
618
612
|
|
|
619
613
|
When to use: loops, conditionals, parallel (\`asyncio.gather\`), multi-step pipelines.
|
|
@@ -624,11 +618,15 @@ Example (complete pipeline):
|
|
|
624
618
|
|
|
625
619
|
return tool<typeof ProgrammaticToolCallingSchema>(
|
|
626
620
|
async (params, config) => {
|
|
627
|
-
const { code,
|
|
621
|
+
const { code, timeout = DEFAULT_TIMEOUT } = params;
|
|
628
622
|
|
|
629
623
|
// Extra params injected by ToolNode (follows web_search pattern)
|
|
630
|
-
const { toolMap, toolDefs
|
|
631
|
-
|
|
624
|
+
const { toolMap, toolDefs, session_id, _injected_files } =
|
|
625
|
+
(config.toolCall ?? {}) as ToolCall &
|
|
626
|
+
Partial<t.ProgrammaticCache> & {
|
|
627
|
+
session_id?: string;
|
|
628
|
+
_injected_files?: t.CodeEnvFile[];
|
|
629
|
+
};
|
|
632
630
|
|
|
633
631
|
if (toolMap == null || toolMap.size === 0) {
|
|
634
632
|
throw new Error(
|
|
@@ -661,9 +659,15 @@ Example (complete pipeline):
|
|
|
661
659
|
);
|
|
662
660
|
}
|
|
663
661
|
|
|
664
|
-
|
|
662
|
+
/**
|
|
663
|
+
* File injection priority:
|
|
664
|
+
* 1. Use _injected_files from ToolNode (avoids /files endpoint race condition)
|
|
665
|
+
* 2. Fall back to fetching from /files endpoint if session_id provided but no injected files
|
|
666
|
+
*/
|
|
665
667
|
let files: t.CodeEnvFile[] | undefined;
|
|
666
|
-
if (
|
|
668
|
+
if (_injected_files && _injected_files.length > 0) {
|
|
669
|
+
files = _injected_files;
|
|
670
|
+
} else if (session_id != null && session_id.length > 0) {
|
|
667
671
|
files = await fetchSessionFiles(baseUrl, apiKey, session_id, proxy);
|
|
668
672
|
}
|
|
669
673
|
|
package/src/tools/ToolNode.ts
CHANGED
|
@@ -42,6 +42,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
42
42
|
private toolRegistry?: t.LCToolRegistry;
|
|
43
43
|
/** Cached programmatic tools (computed once on first PTC call) */
|
|
44
44
|
private programmaticCache?: t.ProgrammaticCache;
|
|
45
|
+
/** Reference to Graph's sessions map for automatic session injection */
|
|
46
|
+
private sessions?: t.ToolSessionMap;
|
|
45
47
|
|
|
46
48
|
constructor({
|
|
47
49
|
tools,
|
|
@@ -53,6 +55,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
53
55
|
handleToolErrors,
|
|
54
56
|
loadRuntimeTools,
|
|
55
57
|
toolRegistry,
|
|
58
|
+
sessions,
|
|
56
59
|
}: t.ToolNodeConstructorParams) {
|
|
57
60
|
super({ name, tags, func: (input, config) => this.run(input, config) });
|
|
58
61
|
this.toolMap = toolMap ?? new Map(tools.map((tool) => [tool.name, tool]));
|
|
@@ -62,6 +65,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
62
65
|
this.errorHandler = errorHandler;
|
|
63
66
|
this.toolUsageCount = new Map<string, number>();
|
|
64
67
|
this.toolRegistry = toolRegistry;
|
|
68
|
+
this.sessions = sessions;
|
|
65
69
|
}
|
|
66
70
|
|
|
67
71
|
/**
|
|
@@ -139,6 +143,35 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
|
|
|
139
143
|
};
|
|
140
144
|
}
|
|
141
145
|
|
|
146
|
+
/**
|
|
147
|
+
* Inject session context for code execution tools when available.
|
|
148
|
+
* Both session_id and _injected_files are injected directly to invokeParams
|
|
149
|
+
* (not inside args) so they bypass Zod schema validation and reach config.toolCall.
|
|
150
|
+
* This avoids /files endpoint race conditions.
|
|
151
|
+
*/
|
|
152
|
+
if (
|
|
153
|
+
call.name === Constants.EXECUTE_CODE ||
|
|
154
|
+
call.name === Constants.PROGRAMMATIC_TOOL_CALLING
|
|
155
|
+
) {
|
|
156
|
+
const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as
|
|
157
|
+
| t.CodeSessionContext
|
|
158
|
+
| undefined;
|
|
159
|
+
if (codeSession?.session_id != null && codeSession.files.length > 0) {
|
|
160
|
+
/** Convert tracked files to CodeEnvFile format for the API */
|
|
161
|
+
const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({
|
|
162
|
+
session_id: codeSession.session_id,
|
|
163
|
+
id: file.id,
|
|
164
|
+
name: file.name,
|
|
165
|
+
}));
|
|
166
|
+
/** Inject session_id and files directly - bypasses Zod, reaches config.toolCall */
|
|
167
|
+
invokeParams = {
|
|
168
|
+
...invokeParams,
|
|
169
|
+
session_id: codeSession.session_id,
|
|
170
|
+
_injected_files: fileRefs,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
142
175
|
const output = await tool.invoke(invokeParams, config);
|
|
143
176
|
if (
|
|
144
177
|
(isBaseMessage(output) && output._getType() === 'tool') ||
|
|
@@ -643,7 +643,6 @@ for member in team:
|
|
|
643
643
|
expect(output).toContain('Generated files:');
|
|
644
644
|
expect(output).toContain('report.pdf');
|
|
645
645
|
expect(output).toContain('data.csv');
|
|
646
|
-
expect(output).toContain('session_id: sess_abc123');
|
|
647
646
|
expect(artifact.files).toHaveLength(2);
|
|
648
647
|
expect(artifact.files).toEqual(response.files);
|
|
649
648
|
});
|
|
@@ -881,7 +880,6 @@ for member in team:
|
|
|
881
880
|
expect(output).toContain('Generated files:');
|
|
882
881
|
expect(output).toContain('report.csv');
|
|
883
882
|
expect(output).toContain('chart.png');
|
|
884
|
-
expect(output).toContain('session_id: sess_xyz');
|
|
885
883
|
expect(output).toContain('File is already downloaded');
|
|
886
884
|
expect(output).toContain('Image is already displayed');
|
|
887
885
|
expect(artifact.files).toHaveLength(2);
|
package/src/types/tools.ts
CHANGED
|
@@ -39,6 +39,8 @@ export type ToolNodeOptions = {
|
|
|
39
39
|
) => Promise<void>;
|
|
40
40
|
/** Tool registry for lazy computation of programmatic tools and tool search */
|
|
41
41
|
toolRegistry?: LCToolRegistry;
|
|
42
|
+
/** Reference to Graph's sessions map for automatic session injection */
|
|
43
|
+
sessions?: ToolSessionMap;
|
|
42
44
|
};
|
|
43
45
|
|
|
44
46
|
export type ToolNodeConstructorParams = ToolRefs & ToolNodeOptions;
|
|
@@ -253,3 +255,41 @@ export type ProgrammaticToolCallingParams = {
|
|
|
253
255
|
/** Environment variable key for API key */
|
|
254
256
|
[key: string]: unknown;
|
|
255
257
|
};
|
|
258
|
+
|
|
259
|
+
// ============================================================================
|
|
260
|
+
// Tool Session Context Types
|
|
261
|
+
// ============================================================================
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Tracks code execution session state for automatic file persistence.
|
|
265
|
+
* Stored in Graph.sessions and injected into subsequent tool invocations.
|
|
266
|
+
*/
|
|
267
|
+
export type CodeSessionContext = {
|
|
268
|
+
/** Session ID from the code execution environment */
|
|
269
|
+
session_id: string;
|
|
270
|
+
/** Files generated in this session (for context/tracking) */
|
|
271
|
+
files: FileRefs;
|
|
272
|
+
/** Timestamp of last update */
|
|
273
|
+
lastUpdated: number;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Artifact structure returned by code execution tools (CodeExecutor, PTC).
|
|
278
|
+
* Used to extract session context after tool completion.
|
|
279
|
+
*/
|
|
280
|
+
export type CodeExecutionArtifact = {
|
|
281
|
+
session_id?: string;
|
|
282
|
+
files?: FileRefs;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Generic session context union type for different tool types.
|
|
287
|
+
* Extend this as new tool session types are added.
|
|
288
|
+
*/
|
|
289
|
+
export type ToolSessionContext = CodeSessionContext;
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Map of tool names to their session contexts.
|
|
293
|
+
* Keys are tool constants (e.g., Constants.EXECUTE_CODE, Constants.PROGRAMMATIC_TOOL_CALLING).
|
|
294
|
+
*/
|
|
295
|
+
export type ToolSessionMap = Map<string, ToolSessionContext>;
|