aimyapi 1.0.8 → 1.0.10

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 WhiteNoise
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2023 WhiteNoise
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,195 +1,221 @@
1
- # AI My API
2
-
3
- AIMyAPI is a typescript code sandbox for your LLM using [QuickJS](https://github.com/justjake/quickjs-emscripten). It allows you to expose a global API object and allows your agent to write functions against it without giving it access to the internet or your filesystem except through the methods you define.
4
-
5
- Requires an OpenAI compatible API
6
-
7
- AIMyAPI will handle async operations and timers in your API object.
8
-
9
- ## About version 1.0 update and motivation
10
-
11
- AIMyAPI was originally written at a time (circa ChatGPT 3.5 / GPT-4) before tool calling existed, before Claude code and codex and just before OpenAI released their code interpreter. LLM models have also gotten drastically better since. Some of the problems it originally aimed to solve are better solved today with simple tool calling. However, there is still a need to safely run small programs in a sandboxed way, reliable way. Tools are good if you have a set interface but there may be times that an agent needs to do some sorting or filtering, or an algorithm or analysis, or some repeatable workflow which isn't implemented by the available tool functions. Writing code allows the agent to do things it might not otherwise be able to do with tools alone. All the AI models are thoroughly trained to write code do solve all kinds of problems. Having the ability to write code allows the tools API surface to be smaller; it could simply be a set of CRUD operations.
12
-
13
- The other advantage of writing code is privacy and security. When an agent executes code in a sandbox, it doesn't see any of the results*, API keys or other things you may want to keep hidden. When an agent uses tools, it sees all the parameters and results of the tool calls. Code can be audited for security and correctness before running it. Finally, code can encompass a series of operations, whereas tool calls need to be approved one at a time or just trusted, often without knowing what will come next.
14
-
15
- Version 1.0 updates AIMyAPI code generation to use the tool calling process for writing code. This allows the agent to check the code and run some tests or API calls before committing to a final version. This should result in better code since the previous model relied on the agent always being able to one-shot the code, which depended on it having a complete view of the problem before writing the code which wasn't always realistic. We could also update this process a bit to add "Plan" / "Build" / "Test" phases instead of just one code generation prompt.
16
-
17
- *You'll have the option to hide logs and errors from the agent - logging can allow the agent to fix it's own coding mistakes and test the code, but it also allows information to leave the sandbox which you may want to limit depending on the sensitivity the data your api is handling. Another approach would be to implement a mocked version of your API that the agent can use to write code and debug against while keeping your real data hidden and safe from potentially destructive operations.
18
-
19
- ## Quickstart
20
-
21
- Install the package
22
-
23
- ```bash
24
- npm i aimyapi --save
25
- ```
26
-
27
- **Setup:** create a .env file in the root of your project and add your OpenAI api key:
28
- ```bash
29
- OPENAI_API_KEY=XXXX
30
- OPENAI_API_BASE_URL=XXXX // If using your own server, otherwise omit to use the default
31
- OPENAI_API_MODEL=XXXX // defaults to "gpt-5-mini"
32
- ```
33
-
34
-
35
- Simply define your strongly-typed typescript API:
36
-
37
- `sales_api.ts`
38
- ```typescript
39
- // Sales data for each month, per business unit
40
- export interface SalesData {
41
- sales: number;
42
- month: number; // 1...12
43
- year: number;
44
- businessUnit: "Advertising" | "Hardware" | "Software";
45
- }
46
-
47
- export interface APIInterface {
48
- getSalesData(): SalesData[];
49
- // Returns an array of sales data.
50
-
51
- print(text: string): void;
52
- // Prints the specified text to the user.
53
- };
54
-
55
- // Global object you will use for accessing the APIInterface. Any other globals can go here too if you declare them in the `apiGlobals` parameter.
56
- declare global {
57
- const api: APIInterface;
58
- }
59
-
60
- ```
61
-
62
- Implement it (`sales_api_impl.ts`):
63
- ```typescript
64
- export class API implements APIInterface {
65
-
66
- getSalesData() {
67
- ...
68
- ```
69
-
70
- Document it (`sales_api.md`):
71
-
72
- ```
73
- Examples of how you should respond:
74
-
75
- user: How are you today?
76
-
77
- assistant:
78
-
79
- api.print("I'm great, thanks for asking!");
80
- ```
81
-
82
- Instantiate your api and AIMyAPI. AIMyAPI will wrap your API so that it can be called from within the QuickJS sandbox.
83
-
84
- ```typescript
85
- import { AIMyAPI } from "aimyapi"
86
-
87
- const api = new API();
88
-
89
- const aimyapi = await AIMyAPI.createWithAPI({
90
- apiObject: api,
91
- apiExports: APIExports,
92
- apiDefFilePath: "./sales_api.ts",
93
- apiDocsPath: "./sales_api.md",
94
- })
95
- ```
96
-
97
- And now you can make requests against the API in natural language.
98
- Any code generated by the LLM will be run within the sandbox. The LLM will ONLY have access to functions provided within your API and cannot use javascript to make http requests etc.
99
-
100
- ```typescript
101
- await aimyapi.processRequest("Which business unit had the highest sales in 2020?");
102
- ```
103
-
104
- This would produce the following code generated by the LLM prompt, which is run in the sandbox and makes calls on your API object:
105
-
106
- ```typescript
107
-
108
- let salesData = api.getSalesData();
109
- let maxSales = 0;
110
- let businessUnitWithMaxSales = "";
111
- for (let i = 0; i < salesData.length; i++) {
112
- if (salesData[i].year === 2020 && salesData[i].sales > maxSales) {
113
- maxSales = salesData[i].sales;
114
- businessUnitWithMaxSales = salesData[i].businessUnit;
115
- }
116
- }
117
- api.print(\`The business unit with the highest sales in 2020 was ${businessUnitWithMaxSales}.\`);
118
-
119
- ```
120
-
121
- This example does not take advantage of the chat history and treats every request as a fresh chat. See `example2` for a more complex example that uses the chat history.
122
-
123
- APIs should be kept simple and understandable. If you have a complicated API you may want to write a simpler facade for it.
124
-
125
-
126
- ## API Reference for AIMyAPI
127
-
128
- ### createWithAPI(options: AIMyAPIOptions): Promise<CreateWithAPIExports>
129
-
130
- Primary function you will use to create a module for working your API API. For a simple example with no chat history, see example1. For an example with chat history see example2.
131
-
132
- #### Options:
133
-
134
- ```typescript
135
- export interface AIMyAPIOptions {
136
- apiObject: object;
137
- apiExports: object;
138
- apiWhitelist?: string[];
139
- apiGlobals?: object;
140
- apiDefFilePath: string;
141
- apiGlobalName?: string;
142
- apiDocsPath?: string;
143
- debug?: boolean;
144
- model?: string;
145
- additionalModelOptions?: object;
146
- hideLogsFromAgent?: boolean;
147
- };
148
- ```
149
-
150
- - `apiObject`: An object representing the API to be used.
151
- - `apiExports`: An object representing the exported functions and variables from the API.
152
- - `apiGlobals` (optional): An object representing global variables for the API.
153
- - `apiDefFilePath`: A string representing the full path to the API definition file.
154
- - `apiGlobalName` (optional): A string representing the name of the global variable for the API.
155
- - `apiDocsPath` (optional): A string representing the path to the documentation for the API.
156
- - `debug` (optional): A boolean indicating whether to output debugging information.
157
-
158
- ### The AIMyAPI module (type: CreateWithAPIExports)
159
-
160
- The module created by the `createWithAPI` function:
161
-
162
- #### Methods
163
-
164
- ```typescript
165
- export interface AIMyAPIInstance {
166
- options:AIMyAPIOptions;
167
- generateCode: (queryText:string, userChatHistory:ChatCompletionMessageParam[]) => Promise<GenerateCodeResult | null>;
168
- runCode: (code:string) => Promise<CodeRunResult>;
169
- checkCode: (code:string) => Promise<CodeRunResult>;
170
- // run a single request with no history
171
- processRequest: (userQuery:string, context?: object) => Promise<GenerateCodeResult | null>;
172
- }
173
- ```
174
-
175
- - `generateCode()`: A function that generates code to be run in the sandbox for the given query text and user chat history.
176
- - `runCode()`: A function that runs the generated code in the sandbox.
177
- - `checkCode()`: Typecheck / compile the code
178
- - `processRequest()`: A single function that generates and runs code assuming no chat history.
179
-
180
-
181
- ## Safety notes:
182
-
183
- - If the user is giving sensitive information in a query, that information isn't private. Refer to the OpenAI policies and plan accordingly.
184
- - The LLM will do stupid things with your API. You should idiot proof your functions, make sure you sanity check any inputs, etc.
185
- - Even though we are running the code in sandbox, you should still treat anything coming back from the LLM as untrusted code.
186
- - You should never give the LLM access to anything mission critical through your API such as live production data or services.
187
- - Give as few permissions as is necessary - read only access would be preferred.
188
- - Users can trick the LLM to do things that you may not want or intend. Again, access controls are critical. You shouldn't let users access anything they wouldn't normally be able to access via your API.
189
- - Any 'dangerous' operations should involve some kind of human oversight and approval.
190
- - A way to audit and rollback anything the LLM does would be wise. The LLM can misunderstand requests due to false assumptions or incomplete information (or trickery). If you allow it to modify your data it could mess things up.
191
- - By using this library you acknowledge that you take full responsibility for anything that happens as a result of it's use. We cannot gaurantee what will happen based on your instructions to the LLM or how the LLM interprets them etc.
192
-
193
-
194
-
195
-
1
+ # AI My API
2
+
3
+ AIMyAPI is a typescript code sandbox for your LLM using [QuickJS](https://github.com/justjake/quickjs-emscripten). It allows you to expose a global API object and allows your agent to write functions against it without giving it access to the internet or your filesystem except through the methods you define.
4
+
5
+ Requires an OpenAI compatible API
6
+
7
+ AIMyAPI will handle async operations and timers in your API object.
8
+
9
+ ## About version 1.0 update and motivation
10
+
11
+ AIMyAPI was originally written at a time (circa ChatGPT 3.5 / GPT-4) before tool calling existed, before Claude code and codex and just before OpenAI released their code interpreter. LLM models have also gotten drastically better since. Some of the problems it originally aimed to solve are better solved today with simple tool calling. However, there is still a need to safely run small programs in a sandboxed way, reliable way. Tools are good if you have a set interface but there may be times that an agent needs to do some sorting or filtering, or an algorithm or analysis, or some repeatable workflow which isn't implemented by the available tool functions. Writing code allows the agent to do things it might not otherwise be able to do with tools alone. All the AI models are thoroughly trained to write code do solve all kinds of problems. Having the ability to write code allows the tools API surface to be smaller; it could simply be a set of CRUD operations.
12
+
13
+ The other advantage of writing code is privacy and security. When an agent executes code in a sandbox, it doesn't see any of the results*, API keys or other things you may want to keep hidden. When an agent uses tools, it sees all the parameters and results of the tool calls. Code can be audited for security and correctness before running it. Finally, code can encompass a series of operations, whereas tool calls need to be approved one at a time or just trusted, often without knowing what will come next.
14
+
15
+ Version 1.0 updates AIMyAPI code generation to use the tool calling process for writing code. This allows the agent to check the code and run some tests or API calls before committing to a final version. This should result in better code since the previous model relied on the agent always being able to one-shot the code, which depended on it having a complete view of the problem before writing the code which wasn't always realistic. We could also update this process a bit to add "Plan" / "Build" / "Test" phases instead of just one code generation prompt.
16
+
17
+ *You'll have the option to hide logs and errors from the agent - logging can allow the agent to fix it's own coding mistakes and test the code, but it also allows information to leave the sandbox which you may want to limit depending on the sensitivity the data your api is handling. Another approach would be to implement a mocked version of your API that the agent can use to write code and debug against while keeping your real data hidden and safe from potentially destructive operations.
18
+
19
+ ## Quickstart
20
+
21
+ Install the package
22
+
23
+ ```bash
24
+ npm i aimyapi --save
25
+ ```
26
+
27
+ **Setup:** create a .env file in the root of your project and add your OpenAI api key:
28
+ ```bash
29
+ OPENAI_API_KEY=XXXX
30
+ OPENAI_API_BASE_URL=XXXX // If using your own server, otherwise omit to use the default
31
+ OPENAI_API_MODEL=XXXX // defaults to "gpt-5-mini"
32
+ ```
33
+
34
+
35
+ Simply define your strongly-typed typescript API:
36
+
37
+ `sales_api.ts`
38
+ ```typescript
39
+ // Sales data for each month, per business unit
40
+ export interface SalesData {
41
+ sales: number;
42
+ month: number; // 1...12
43
+ year: number;
44
+ businessUnit: "Advertising" | "Hardware" | "Software";
45
+ }
46
+
47
+ export interface APIInterface {
48
+ getSalesData(): SalesData[];
49
+ // Returns an array of sales data.
50
+
51
+ print(text: string): void;
52
+ // Prints the specified text to the user.
53
+ };
54
+
55
+ // Global object you will use for accessing the APIInterface. Any other globals can go here too if you declare them in the `apiGlobals` parameter.
56
+ declare global {
57
+ const api: APIInterface;
58
+ }
59
+
60
+ ```
61
+
62
+ Implement it (`sales_api_impl.ts`):
63
+ ```typescript
64
+ export class API implements APIInterface {
65
+
66
+ getSalesData() {
67
+ ...
68
+ ```
69
+
70
+ Document it (`sales_api.md`):
71
+
72
+ ```
73
+ Examples of how you should respond:
74
+
75
+ user: How are you today?
76
+
77
+ assistant:
78
+
79
+ api.print("I'm great, thanks for asking!");
80
+ ```
81
+
82
+ Instantiate your api and AIMyAPI. AIMyAPI will wrap your API so that it can be called from within the QuickJS sandbox.
83
+
84
+ ```typescript
85
+ import { AIMyAPI } from "aimyapi"
86
+
87
+ const api = new API();
88
+
89
+ const aimyapi = await AIMyAPI.createWithAPI({
90
+ apiObject: api,
91
+ apiExports: APIExports,
92
+ apiDefFilePath: "./sales_api.ts",
93
+ apiDocsPath: "./sales_api.md",
94
+ })
95
+ ```
96
+
97
+ And now you can make requests against the API in natural language.
98
+ Any code generated by the LLM will be run within the sandbox. The LLM will ONLY have access to functions provided within your API and cannot use javascript to make http requests etc.
99
+
100
+ ```typescript
101
+ await aimyapi.processRequest("Which business unit had the highest sales in 2020?");
102
+ ```
103
+
104
+ This would produce the following code generated by the LLM prompt, which is run in the sandbox and makes calls on your API object:
105
+
106
+ ```typescript
107
+
108
+ let salesData = api.getSalesData();
109
+ let maxSales = 0;
110
+ let businessUnitWithMaxSales = "";
111
+ for (let i = 0; i < salesData.length; i++) {
112
+ if (salesData[i].year === 2020 && salesData[i].sales > maxSales) {
113
+ maxSales = salesData[i].sales;
114
+ businessUnitWithMaxSales = salesData[i].businessUnit;
115
+ }
116
+ }
117
+ api.display(\`The business unit with the highest sales in 2020 was ${businessUnitWithMaxSales}.\`);
118
+
119
+ ```
120
+
121
+ This example does not take advantage of the chat history and treats every request as a fresh chat. See `example2` for a more complex example that uses the chat history.
122
+
123
+ APIs should be kept simple and understandable. If you have a complicated API you may want to write a simpler facade for it.
124
+
125
+ ### Limitations
126
+
127
+ The sandbox implementation supports basic types and the built in objects Promise and Date. It doesn't currently support Map, Set, Regex, etc. So you cannot return those types from your API functions. Some Date functionality differs from current javascript specs.
128
+
129
+ ### Recommendations
130
+
131
+ Create a separate sandbox with a mocked API for generating code. This way the agent doesn't modify anything while troubleshooting or running test scripts. Additionally it prevents the agent from ever seeing real data if you want to maintain privacy. Use the real API only when you want to run code.
132
+
133
+ Implement schema validation for your API functions. Follow the convention by defining `_params_[FUNCTIONNAME]` as a Zod object:
134
+
135
+ ```ts
136
+ // Schema validation for function parameters. Will throw if parameters are invalid to prevent silent failures and surface info to the agent.
137
+ // fields should be defined in the same order that they occur in the function
138
+ public _params_sendEmail = z.object({
139
+ to: z.string(),
140
+ subject: z.string(),
141
+ body: z.string().min(5)
142
+ })
143
+
144
+ // Mock implementation, doesn't actually send an email
145
+ async sendEmail(to: string, subject: string, body: string): Promise<void> {
146
+ ...
147
+ }
148
+ ```
149
+
150
+
151
+ ## API Reference for AIMyAPI
152
+
153
+ ### createWithAPI(options: AIMyAPIOptions): Promise<CreateWithAPIExports>
154
+
155
+ Primary function you will use to create a module for working your API API. For a simple example with no chat history, see example1. For an example with chat history see example2.
156
+
157
+ #### Options:
158
+
159
+ ```typescript
160
+ export interface AIMyAPIOptions {
161
+ apiObject: object;
162
+ apiExports: object;
163
+ apiWhitelist?: string[];
164
+ apiGlobals?: object;
165
+ apiDefFilePath: string;
166
+ apiGlobalName?: string;
167
+ apiDocsPath?: string;
168
+ debug?: boolean;
169
+ model?: string;
170
+ additionalModelOptions?: object;
171
+ hideLogsFromAgent?: boolean;
172
+ };
173
+ ```
174
+
175
+ - `apiObject`: An object representing the API to be used.
176
+ - `apiExports`: An object representing the exported functions and variables from the API.
177
+ - `apiGlobals` (optional): An object representing global variables for the API.
178
+ - `apiDefFilePath`: A string representing the full path to the API definition file.
179
+ - `apiGlobalName` (optional): A string representing the name of the global variable for the API.
180
+ - `apiDocsPath` (optional): A string representing the path to the documentation for the API.
181
+ - `debug` (optional): A boolean indicating whether to output debugging information.
182
+
183
+ ### The AIMyAPI module (type: CreateWithAPIExports)
184
+
185
+ The module created by the `createWithAPI` function:
186
+
187
+ #### Methods
188
+
189
+ ```typescript
190
+ export interface AIMyAPIInstance {
191
+ options:AIMyAPIOptions;
192
+ generateCode: (queryText:string, userChatHistory:ChatCompletionMessageParam[]) => Promise<GenerateCodeResult | null>;
193
+ runCode: (code:string) => Promise<CodeRunResult>;
194
+ checkCode: (code:string) => Promise<CodeRunResult>;
195
+ // run a single request with no history
196
+ processRequest: (userQuery:string, context?: object) => Promise<GenerateCodeResult | null>;
197
+ }
198
+ ```
199
+
200
+ - `generateCode()`: A function that generates code to be run in the sandbox for the given query text and user chat history.
201
+ - `runCode()`: A function that runs the generated code in the sandbox.
202
+ - `checkCode()`: Typecheck / compile the code
203
+ - `processRequest()`: A single function that generates and runs code assuming no chat history. This is more of a convenience function for the examples, since code gen and runn
204
+
205
+
206
+ ## Safety notes:
207
+
208
+ - When generating code, you should use a mocked version of your API. You can create separate sandboxes for writing code vs. running code.
209
+ - If the user is giving sensitive information in a query, that information isn't private. Refer to the OpenAI policies and plan accordingly.
210
+ - The LLM will do stupid things with your API. You should idiot proof your functions, make sure you sanity check any inputs, etc.
211
+ - Even though we are running the code in sandbox, you should still treat anything coming back from the LLM as untrusted code.
212
+ - You should never give the LLM access to anything mission critical through your API such as live production data or services.
213
+ - Give as few permissions as is necessary - read only access would be preferred.
214
+ - Users can trick the LLM to do things that you may not want or intend. Again, access controls are critical. You shouldn't let users access anything they wouldn't normally be able to access via your API.
215
+ - Any 'dangerous' operations should involve some kind of human oversight and approval.
216
+ - A way to audit and rollback anything the LLM does would be wise. The LLM can misunderstand requests due to false assumptions or incomplete information (or trickery). If you allow it to modify your data it could mess things up.
217
+ - By using this library you acknowledge that you take full responsibility for anything that happens as a result of it's use. We cannot gaurantee what will happen based on your instructions to the LLM or how the LLM interprets them etc.
218
+
219
+
220
+
221
+