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