aimyapi 1.0.6 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/README.md +195 -195
- package/dist/index.cjs +37 -5
- package/dist/index.d.cts +2 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +37 -5
- package/dist/index.mjs +37 -5
- package/example/example1.ts +30 -30
- package/example/example2.ts +58 -58
- package/example/example3.ts +69 -69
- package/example/ordering_api.md +94 -94
- package/example/ordering_api.ts +191 -191
- package/example/ordering_api_impl.ts +207 -207
- package/example/sales_api.md +4 -4
- package/example/sales_api.ts +29 -29
- package/example/sales_api_impl.ts +60 -60
- package/package.json +1 -1
- package/prompts/create-task-prompt.md +37 -30
- package/src/index.ts +495 -456
- package/src/sandbox-wrappers.ts +249 -249
- package/src/sandbox.ts +277 -277
- package/src/utils.ts +2 -2
- package/tsconfig.json +12 -12
package/src/index.ts
CHANGED
|
@@ -1,456 +1,495 @@
|
|
|
1
|
-
require('dotenv').config()
|
|
2
|
-
import fs from 'fs';
|
|
3
|
-
import { OpenAI } from "openai";
|
|
4
|
-
|
|
5
|
-
import createSandbox, { CodeRunResult } from "./sandbox";
|
|
6
|
-
import { rejectOpenPromises } from './sandbox-wrappers';
|
|
7
|
-
|
|
8
|
-
import { ChatCompletionMessageParam } from 'openai/resources/index.mjs';
|
|
9
|
-
import { QuickJSWASMModule, getQuickJS } from "quickjs-emscripten";
|
|
10
|
-
|
|
11
|
-
import { AutoParseableTool } from 'openai/lib/parser.js';
|
|
12
|
-
import { ZodSchema, z } from 'zod';
|
|
13
|
-
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
//console.
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
1
|
+
require('dotenv').config()
|
|
2
|
+
import fs from 'fs';
|
|
3
|
+
import { OpenAI } from "openai";
|
|
4
|
+
|
|
5
|
+
import createSandbox, { CodeRunResult } from "./sandbox";
|
|
6
|
+
import { rejectOpenPromises } from './sandbox-wrappers';
|
|
7
|
+
|
|
8
|
+
import { ChatCompletionMessageParam } from 'openai/resources/index.mjs';
|
|
9
|
+
import { QuickJSWASMModule, getQuickJS } from "quickjs-emscripten";
|
|
10
|
+
|
|
11
|
+
import { AutoParseableTool } from 'openai/lib/parser.js';
|
|
12
|
+
import { ZodSchema, z } from 'zod';
|
|
13
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
14
|
+
import { check } from 'zod/v4';
|
|
15
|
+
|
|
16
|
+
const openai = new OpenAI( { baseURL: process.env.OPENAI_API_BASE_URL || undefined, apiKey: process.env.OPENAI_API_KEY || undefined } );
|
|
17
|
+
|
|
18
|
+
let QuickJS:QuickJSWASMModule | null = null;
|
|
19
|
+
|
|
20
|
+
export interface AIMyAPIOptions {
|
|
21
|
+
apiObject: object;
|
|
22
|
+
apiExports?: object;
|
|
23
|
+
apiWhitelist?: string[]; // List of functions to expose to the user. Necessary to pass this yourself if you are extending your api from another class.
|
|
24
|
+
apiGlobals?: object;
|
|
25
|
+
apiDefFilePath: string; // Full path to the api definition file so that it can be loaded into the prompt
|
|
26
|
+
apiGlobalName?: string;
|
|
27
|
+
apiDocsPath?: string;
|
|
28
|
+
debug?: boolean;
|
|
29
|
+
model?: string;
|
|
30
|
+
additionalModelOptions?: object;
|
|
31
|
+
hideLogsFromAgent?: boolean; // If true, logs from code execution will not be included in the messages sent to the agent. This can be useful to prevent the agent from being overwhelmed with logs or to hide implementation details. Default is false (logs will be included in messages).
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export interface AIMyAPIInstance {
|
|
35
|
+
options:AIMyAPIOptions;
|
|
36
|
+
generateCode: (queryText:string, userChatHistory:ChatCompletionMessageParam[]) => Promise<GenerateCodeResult | null>;
|
|
37
|
+
runCode: (code:string) => Promise<CodeRunResult>;
|
|
38
|
+
checkCode: (code:string) => Promise<CodeRunResult>;
|
|
39
|
+
// run a single request with no history
|
|
40
|
+
processRequest: (userQuery:string, context?: object) => Promise<GenerateCodeResult | null>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface GenerateCodeResult {
|
|
44
|
+
success: boolean;
|
|
45
|
+
code?: string;
|
|
46
|
+
comments?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
const wrapCode = (apiGlobalName:string, apiFileDefPath:string, code:string) => `
|
|
51
|
+
(async () => {
|
|
52
|
+
try {
|
|
53
|
+
${code}
|
|
54
|
+
} catch(err) {
|
|
55
|
+
console.error(err);
|
|
56
|
+
}
|
|
57
|
+
})();
|
|
58
|
+
`;
|
|
59
|
+
|
|
60
|
+
const wrapCodeBlock = (code:string, codeType:string = "") => `
|
|
61
|
+
\`\`\`${codeType}
|
|
62
|
+
${code}
|
|
63
|
+
\`\`\`
|
|
64
|
+
`;
|
|
65
|
+
|
|
66
|
+
export function zodParseJSON<T>(schema: ZodSchema<T>) {
|
|
67
|
+
return (input: string): T => schema.parse(JSON.parse(input));
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function createBasePrompt(apiFilePath:string, apiGlobalName: string, documentationPath?: string, ): string {
|
|
71
|
+
const apiText: string = fs.readFileSync(apiFilePath, 'utf8');
|
|
72
|
+
const documentationText: string = documentationPath ? fs.readFileSync(documentationPath, 'utf8') : '';
|
|
73
|
+
|
|
74
|
+
//console.time("Loading templates");
|
|
75
|
+
const createTaskPrompt: string = fs.readFileSync( './prompts/create-task-prompt.md', 'utf8').replace("{{DOCUMENTATION}}", documentationText).replace("{{API}}", apiText).replace("{{API_GLOBAL_NAME}}", apiGlobalName || "");
|
|
76
|
+
//console.timeEnd("Loading templates")
|
|
77
|
+
|
|
78
|
+
return createTaskPrompt;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
const runCodeSchema = z.object({
|
|
83
|
+
code: z.string(),
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const checkCodeSchema = z.object({
|
|
87
|
+
code: z.string(),
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
const submitCodeSchema = z.object({
|
|
91
|
+
code: z.string(),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
// Basic harness for writing code for the sandbox.
|
|
95
|
+
export const generateCode = async function(instance:AIMyAPIInstance, queryText:string, userChatHistory:ChatCompletionMessageParam[], createTaskPrompt:string, debug:boolean = false, hideLogsFromAgent:boolean = false, model="gpt-5-mini", additionalModelOptions?: object, attempt:number = 0): Promise<GenerateCodeResult | null> {
|
|
96
|
+
let finalSubmittedCode = "";
|
|
97
|
+
|
|
98
|
+
if(debug) {
|
|
99
|
+
console.log("Generating code for query:", queryText);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const newHistoryItems = [];
|
|
103
|
+
// checkcode
|
|
104
|
+
const codingTools: AutoParseableTool<any, true>[] = [
|
|
105
|
+
{
|
|
106
|
+
type: "function",
|
|
107
|
+
function: {
|
|
108
|
+
name: "runCode",
|
|
109
|
+
// @ts-ignore
|
|
110
|
+
function: async ({code}: {code: string}) => {
|
|
111
|
+
if(debug) {
|
|
112
|
+
console.log("Running code...", code);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const res = await instance.runCode(code);
|
|
116
|
+
|
|
117
|
+
if(hideLogsFromAgent) {
|
|
118
|
+
res.logs = [];
|
|
119
|
+
}
|
|
120
|
+
return res;
|
|
121
|
+
},
|
|
122
|
+
description: "Run the provided code in a sandboxed environment. The code will have access to the API object. Returns the result of the code execution.",
|
|
123
|
+
parse: zodParseJSON(runCodeSchema),
|
|
124
|
+
parameters: zodToJsonSchema(runCodeSchema),
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
type: "function",
|
|
129
|
+
function: {
|
|
130
|
+
name: "checkCode",
|
|
131
|
+
// @ts-ignore
|
|
132
|
+
function: async ({code}: {code: string}) => {
|
|
133
|
+
if(debug) {
|
|
134
|
+
console.log("Checking code...", code);
|
|
135
|
+
}
|
|
136
|
+
const res = await instance.checkCode(code);
|
|
137
|
+
|
|
138
|
+
return res;
|
|
139
|
+
|
|
140
|
+
},
|
|
141
|
+
description: "Check the provided code for errors or issues without running it. Returns the result of the code check.",
|
|
142
|
+
parse: zodParseJSON(checkCodeSchema),
|
|
143
|
+
parameters: zodToJsonSchema(checkCodeSchema),
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
type: "function",
|
|
148
|
+
function: {
|
|
149
|
+
name: "submitCode",
|
|
150
|
+
// @ts-ignore
|
|
151
|
+
function: async ({code}: {code: string}) => {
|
|
152
|
+
const checkRes = await instance.checkCode(code);
|
|
153
|
+
if(!checkRes.success) {
|
|
154
|
+
return {
|
|
155
|
+
success: false,
|
|
156
|
+
reason: "Code check failed",
|
|
157
|
+
logs: checkRes.logs,
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
finalSubmittedCode = code;
|
|
162
|
+
return {
|
|
163
|
+
success: true,
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
description: "Submit the provided code as the final code to run. This will end the code generation process and the code will be run in the sandbox. Use this when you are confident in the code you have generated and want to run it.",
|
|
167
|
+
parse: zodParseJSON(submitCodeSchema),
|
|
168
|
+
parameters: zodToJsonSchema(submitCodeSchema),
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
];
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
|
|
175
|
+
const runner = openai.chat.completions
|
|
176
|
+
.runTools({
|
|
177
|
+
model,
|
|
178
|
+
messages: [
|
|
179
|
+
{
|
|
180
|
+
role: 'system',
|
|
181
|
+
content: "You will assist with writing or modifying code based on the user's request.",
|
|
182
|
+
},
|
|
183
|
+
...userChatHistory,
|
|
184
|
+
{
|
|
185
|
+
role: 'user',
|
|
186
|
+
content: attempt == 0 ? createTaskPrompt.replace("{{USER_QUERY}}", queryText) : queryText,
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
],
|
|
190
|
+
tools: codingTools,
|
|
191
|
+
...additionalModelOptions,
|
|
192
|
+
|
|
193
|
+
})
|
|
194
|
+
.on('message', async (message: ChatCompletionMessageParam) => {
|
|
195
|
+
if(debug) {
|
|
196
|
+
console.log("Message:", JSON.stringify(message, null, 2));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
newHistoryItems.push(message);
|
|
200
|
+
})
|
|
201
|
+
.on('functionToolCall', (functionCall: OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall.Function) => {
|
|
202
|
+
if(debug) {
|
|
203
|
+
console.log("Function Call:", JSON.stringify(functionCall, null, 2));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
})
|
|
208
|
+
.on('functionToolCallResult', (functionCall) => {
|
|
209
|
+
if(debug) {
|
|
210
|
+
console.log("Function Call Result:", JSON.stringify(functionCall, null, 2));
|
|
211
|
+
}
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
const finalContent = await runner.finalContent();
|
|
215
|
+
|
|
216
|
+
if(debug) {
|
|
217
|
+
console.log("Generate code final response:", finalContent);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if(!finalSubmittedCode) {
|
|
221
|
+
console.error("No code was submitted by the agent.");
|
|
222
|
+
if(attempt < 3) {
|
|
223
|
+
return generateCode(instance, `You must call submitCode with valid code before proceeding. Attempt ${attempt + 1} of 3.`, [
|
|
224
|
+
...userChatHistory,
|
|
225
|
+
{
|
|
226
|
+
role: 'user',
|
|
227
|
+
content: attempt == 0 ? createTaskPrompt.replace("{{USER_QUERY}}", queryText) : queryText,
|
|
228
|
+
},
|
|
229
|
+
...newHistoryItems
|
|
230
|
+
], createTaskPrompt, debug, hideLogsFromAgent, model, additionalModelOptions, attempt + 1);
|
|
231
|
+
} else {
|
|
232
|
+
return {
|
|
233
|
+
success: false,
|
|
234
|
+
comments: "No code was submitted by the agent after multiple attempts. Final comment: " + finalContent,
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
success: true,
|
|
242
|
+
code: finalSubmittedCode,
|
|
243
|
+
comments: finalContent || undefined,
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
} catch(err) {
|
|
247
|
+
console.error(err);
|
|
248
|
+
return {
|
|
249
|
+
success: false,
|
|
250
|
+
comments: `Error generating code: ${err}`,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
async function createWithAPI(options:AIMyAPIOptions): Promise<AIMyAPIInstance> {
|
|
256
|
+
// extend options with defaults
|
|
257
|
+
const localOptions = {
|
|
258
|
+
...{
|
|
259
|
+
apiGlobalName: "api",
|
|
260
|
+
apiGlobals: {},
|
|
261
|
+
apiWhitelist: Object.getOwnPropertyNames(Object.getPrototypeOf(options.apiObject)).filter((f) => f !== "constructor" && !f.startsWith("_")),
|
|
262
|
+
debug: false,
|
|
263
|
+
model: process.env.OPENAI_API_MODEL || "gpt-5.4-mini",
|
|
264
|
+
additionalModelOptions: {},
|
|
265
|
+
hideLogsFromAgent: false,
|
|
266
|
+
},
|
|
267
|
+
...options
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
if(!localOptions.apiObject || !localOptions.apiDefFilePath) {
|
|
271
|
+
throw new Error("apiObject and apiDefFilePath are required");
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const {apiObject, apiWhitelist, apiGlobalName, apiExports, apiDefFilePath, apiDocsPath, debug, model, additionalModelOptions, hideLogsFromAgent} = localOptions;
|
|
275
|
+
|
|
276
|
+
const createTaskPrompt = createBasePrompt( apiDefFilePath, apiGlobalName, apiDocsPath);
|
|
277
|
+
|
|
278
|
+
const instance = {
|
|
279
|
+
options: localOptions,
|
|
280
|
+
generateCode: async function(queryText:string, userChatHistory:ChatCompletionMessageParam[], currentContext:any = undefined) {
|
|
281
|
+
if(!queryText)
|
|
282
|
+
return null;
|
|
283
|
+
|
|
284
|
+
const formattedContext = wrapCodeBlock(JSON.stringify(currentContext, null, 2), "json");
|
|
285
|
+
|
|
286
|
+
return await generateCode(instance,
|
|
287
|
+
queryText,
|
|
288
|
+
userChatHistory,
|
|
289
|
+
createTaskPrompt.replace("{{CONTEXT}}", formattedContext),
|
|
290
|
+
debug,
|
|
291
|
+
hideLogsFromAgent,
|
|
292
|
+
model,
|
|
293
|
+
additionalModelOptions
|
|
294
|
+
);
|
|
295
|
+
},
|
|
296
|
+
checkCode: async function (generatedCode:string): Promise<CodeRunResult> {
|
|
297
|
+
if(!QuickJS) {
|
|
298
|
+
// Create QuickJS
|
|
299
|
+
if(debug)
|
|
300
|
+
console.log("Creating quick.js");
|
|
301
|
+
QuickJS = await getQuickJS();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
let apiGlobals: { [key: string]: { value: any } } = {}
|
|
305
|
+
|
|
306
|
+
if(options.apiGlobals) {
|
|
307
|
+
for(const key in options.apiGlobals) {
|
|
308
|
+
apiGlobals[key] = {
|
|
309
|
+
value: (options.apiGlobals as Record<string, any>)[key],
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Create sandbox
|
|
315
|
+
const {vm, checkCode} = await createSandbox(QuickJS, apiExports ? {
|
|
316
|
+
[apiDefFilePath]: apiExports,
|
|
317
|
+
} : undefined, {
|
|
318
|
+
...apiGlobals,
|
|
319
|
+
[apiGlobalName]: {
|
|
320
|
+
value: apiObject,
|
|
321
|
+
whitelist: apiWhitelist
|
|
322
|
+
}
|
|
323
|
+
}, options.debug);
|
|
324
|
+
|
|
325
|
+
try {
|
|
326
|
+
if(debug) {
|
|
327
|
+
console.log("checking Code:\n", generatedCode);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const res = await checkCode(wrapCode(apiGlobalName, apiDefFilePath, generatedCode));
|
|
331
|
+
|
|
332
|
+
if(!res) {
|
|
333
|
+
console.error("Unknown failure checking code");
|
|
334
|
+
return {
|
|
335
|
+
success: false,
|
|
336
|
+
logs: [],
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
if(debug) {
|
|
342
|
+
console.log(res.success ? "Code check passed" : "Code check failed");
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if(res.success) {
|
|
346
|
+
return {
|
|
347
|
+
success: true,
|
|
348
|
+
logs: [{ type: "log", args: ["✔️ Code check passed"], source: "compiler" }, ...res.logs],
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return {
|
|
353
|
+
success: false,
|
|
354
|
+
logs: [{ type: "error", args: ["❌ Code check failed"], source: "compiler" }, ...res.logs],
|
|
355
|
+
};
|
|
356
|
+
} catch(err) {
|
|
357
|
+
if(debug) {
|
|
358
|
+
console.error("Error checking code:", err);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
vm.dispose();
|
|
362
|
+
|
|
363
|
+
return {
|
|
364
|
+
success: false,
|
|
365
|
+
logs: [],
|
|
366
|
+
};
|
|
367
|
+
},
|
|
368
|
+
runCode: async function (code:string): Promise<CodeRunResult> {
|
|
369
|
+
// TODO: fix code duplication with checkCode, maybe combine into a single function that takes a parameter for whether to actually run the code or just check it?
|
|
370
|
+
if(!QuickJS) {
|
|
371
|
+
// Create QuickJS
|
|
372
|
+
if(debug)
|
|
373
|
+
console.log("Creating quick.js");
|
|
374
|
+
QuickJS = await getQuickJS();
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
let apiGlobals: { [key: string]: { value: any } } = {}
|
|
378
|
+
|
|
379
|
+
if(options.apiGlobals) {
|
|
380
|
+
for(const key in options.apiGlobals) {
|
|
381
|
+
apiGlobals[key] = {
|
|
382
|
+
value: (options.apiGlobals as Record<string, any>)[key],
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Create sandbox
|
|
388
|
+
// NOTE: not sure why I have to replace the backslash here
|
|
389
|
+
const {vm, runCode: runTask, isAsyncProcessRunning} = await createSandbox(QuickJS, apiExports ? {
|
|
390
|
+
[apiDefFilePath]: apiExports,
|
|
391
|
+
} : undefined, {
|
|
392
|
+
...apiGlobals,
|
|
393
|
+
[apiGlobalName]: {
|
|
394
|
+
value: apiObject,
|
|
395
|
+
whitelist: apiWhitelist
|
|
396
|
+
}
|
|
397
|
+
}, options.debug);
|
|
398
|
+
|
|
399
|
+
try {
|
|
400
|
+
if(debug) {
|
|
401
|
+
console.log("Running Code:\n", code);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const res = await runTask(wrapCode(apiGlobalName, apiDefFilePath, code));
|
|
405
|
+
|
|
406
|
+
if(!res) {
|
|
407
|
+
console.error("Unknown failure running task");
|
|
408
|
+
return {
|
|
409
|
+
success: false,
|
|
410
|
+
logs: [],
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
while(isAsyncProcessRunning()) {
|
|
415
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if(debug) {
|
|
419
|
+
console.log("Completed");
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
return res;
|
|
423
|
+
} catch(err) {
|
|
424
|
+
if(debug) {
|
|
425
|
+
console.error("Error running task:", err);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
430
|
+
|
|
431
|
+
rejectOpenPromises(vm);
|
|
432
|
+
vm.dispose();
|
|
433
|
+
|
|
434
|
+
return {
|
|
435
|
+
success: false,
|
|
436
|
+
logs: [],
|
|
437
|
+
};
|
|
438
|
+
},
|
|
439
|
+
// generates code and runs it in one step
|
|
440
|
+
processRequest: async function (userQuery: string, currentContext:any = undefined):Promise<GenerateCodeResult | null> {
|
|
441
|
+
// Create prompt
|
|
442
|
+
|
|
443
|
+
if(debug) {
|
|
444
|
+
console.log("Query:", userQuery);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Generate Code
|
|
448
|
+
console.time("Generate Task")
|
|
449
|
+
const generatedCode:GenerateCodeResult | null = await generateCode(instance,
|
|
450
|
+
userQuery,
|
|
451
|
+
[],
|
|
452
|
+
createTaskPrompt.replace("{{CONTEXT}}", currentContext ? JSON.stringify(currentContext, null, 2) : "" ),
|
|
453
|
+
debug,
|
|
454
|
+
hideLogsFromAgent,
|
|
455
|
+
model,
|
|
456
|
+
additionalModelOptions
|
|
457
|
+
);
|
|
458
|
+
console.timeEnd("Generate Task")
|
|
459
|
+
|
|
460
|
+
console.time("Run Code")
|
|
461
|
+
if(generatedCode?.code) {
|
|
462
|
+
await instance.runCode(generatedCode.code);
|
|
463
|
+
} else {
|
|
464
|
+
console.error("No code generated", generatedCode);
|
|
465
|
+
}
|
|
466
|
+
console.timeEnd("Run Code")
|
|
467
|
+
|
|
468
|
+
return generatedCode;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
return instance;
|
|
473
|
+
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
export interface AIMyAPIModuleExports {
|
|
477
|
+
createWithAPI: (options:AIMyAPIOptions) => Promise<AIMyAPIInstance>;
|
|
478
|
+
|
|
479
|
+
createBasePrompt: (apiFilePath:string, documentationPath: string) => string;
|
|
480
|
+
generateCode: (instance: AIMyAPIInstance, queryText:string, userChatHistory:ChatCompletionMessageParam[], createTaskPrompt:string, debug:boolean) => Promise<GenerateCodeResult | null>;
|
|
481
|
+
createSandbox: (QuickJS:QuickJSWASMModule, globals: any) => Promise<any>;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
export const AIMyAPI:AIMyAPIModuleExports = {
|
|
485
|
+
// Standard way of using the library
|
|
486
|
+
createWithAPI,
|
|
487
|
+
|
|
488
|
+
// functions for customized usage
|
|
489
|
+
createBasePrompt,
|
|
490
|
+
generateCode,
|
|
491
|
+
createSandbox,
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export * from "./sandbox";
|
|
495
|
+
|