Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
js guide
Vasek Mlejnskyd7a3197fe94a
diff --git a/apps/docs/src/app/llm-platforms/openai/page.mdx b/apps/docs/src/app/llm-platforms/openai/page.mdxindex e7c45f8a7..3197fd8ae 100644--- a/apps/docs/src/app/llm-platforms/openai/page.mdx+++ b/apps/docs/src/app/llm-platforms/openai/page.mdx@@ -10,6 +10,10 @@ You can use E2B's sandbox as an environment for the tool execution for your AI aThis way you can let the AI assistant use the E2B sandbox to download files, use custom cloud browser, use terminal, write, run, and debug code, and more.+Follow the SDK guides:+- [Python](#python)+- [JavaScript](#java-script)+## Python<Note title="Source Code">[TODO: Fix link] See the full Python code in our [cookbook]().@@ -28,13 +32,13 @@ import openaifrom e2b import Sandbox # $HighlightLineclient = openai.Client()-sbx = Sandbox() # $HighlightLine+sandbox = Sandbox() # $HighlightLine```</CodeGroup>### 2. Define assistant's actions-We're using the `sandbox.action()` decorator to mark our function as an assistant action. An assistant action is a function that the AI assistant can use to complete its task.-It can be pretty much anything you want - running code, downloading files, analyzing data, for example running a terminal command.+An assistant action is a regular Python function that takes the sandbox object as the first argument and a dictionary with arguments as second. The assistant will be able to call this function to complete its task when it runs.+The action can do be pretty much anything you want - running code, downloading files, analyzing data, for example running a terminal command.We define three actions:- `save_code_to_file`@@ -84,21 +88,21 @@ def read_file(sandbox: Sandbox, args: Dict[str, Any]) -> str:</CodeGroup>### 3. Add action to sandbox-Now we need to make sure the sandbox knows about our `write_to_file` action. We'll use the `add_action` method.+Now we need to make sure the sandbox knows about our actions we defined above. We'll use the `add_action` method.<CodeGroup isFileName title="main.py" isRunnable={false}>```py# Import our action-from .actions import write_to_file+from .actions import read_file, save_code_to_file, list_files# Add action to the sandbox we created in the previous steps-sbx.add_action(write_to_file)+sandbox.add_action(read_file).add_action(save_code_to_file).add_action(list_files)```</CodeGroup>### 4. Create AI Assistant-We'll use the OpenAI API to create a new AI Assistant. You can read the full code [TODO: FIX LINK here]().+We'll use the OpenAI API to create a new AI Assistant. You can read the full code [[TODO: FIX LINK] here]().-Keep a close attention to the `functions` definition inside the `[TODO: FIX LINK assistant.py]()` file. We're using the [Function calling](https://platform.openai.com/docs/assistants/tools/function-calling) feature to give our assistant an ability to call the sandbox actions we defined.+Keep a close attention to the `functions` definition inside the `[[TODO: FIX LINK] assistant.py]()` file. We're using the [Function calling](https://platform.openai.com/docs/assistants/tools/function-calling) feature to give our assistant an ability to call the sandbox actions we defined.<CodeGroup isFileName title="assistant.py" isRunnable={false}>```pythonfrom typing import List@@ -143,8 +147,10 @@ Read the official [OpenAI's assistants documentation](https://platform.openai.coOnce the assistant is created, we use the OpenAI API to retrieve it, create a thread, send messages to the thread, and finally run the thread.-When the thread is running, we get a `run` object. The `run.status` field tells us if our assistant requires to run an action.-When+When the thread is running, we get a `run` object. The `run.status` field tells us if our assistant requires to run any action.++If the `run.status` indicates that the assistant wants to call actions, we just pass the `run` object to the `sandbox.openai.actions.run()` function.+The E2B sandbox will automatically call the correct actions and returns correctly formatted output object (called `outputs` in the code below) that you can submit back to the assistant.<CodeGroup isFileName title="main.py" isRunnable={false}>```python@@ -156,8 +162,8 @@ run = client.beta.threads.runs.create(thread_id=thread.id, assistant_id=assistan# Start polling the run objectwhile True:if run.status == "requires_action": # $HighlightLine- outputs = sandbox.openai.assistant.run(run) # $HighlightLine- if len(outputs) > 0:+ outputs = sandbox.openai.actions.run(run) # $HighlightLine+ if len(outputs) > 0: # $HighlightLineclient.beta.threads.runs.submit_tool_outputs( # $HighlightLinethread_id=thread.id, run_id=run.id, tool_outputs=outputs # $HighlightLine) # $HighlightLine@@ -175,10 +181,194 @@ sandbox.close()See the full code [[TODO: Fix link] here]().----## JavaScript<Note title="Source Code">-[TODO: Fix link] See the full JS code in our [cookbook]().-</Note>\ No newline at end of file+[TODO: Fix link] See the full Python code in our [cookbook]().+</Note>++### `sandbox.addAction()`+Use the `addAction()` method to register a JavaScript function as an runnable action for the AI assistant and the LLM.++The JavaScript function you register will always receive the `sandbox` instance as the first argument.+This allows you to define your actions in separate files.++### 1. Import E2B and create sandbox+<CodeGroup isFileName title="index.ts" isRunnable={false}>+```js+import OpenAI from 'openai'+import { Sandbox } from '@e2b/sdk' // $HighlightLine++const openai = new OpenAI()+const sandbox = await Sandbox.create({ // $HighlightLine+ onStdout: console.log, // $HighlightLine+ onStderr: console.error, // $HighlightLine+}) // $HighlightLine+```+</CodeGroup>++### 2. Define assistant's actions+An assistant action is a regular JavaScript function that takes the sandbox object as the first argument and an object with arguments as the second. The assistant will be able to call this function to complete its task when it runs.+The action can do be pretty much anything you want - running code, downloading files, analyzing data, for example running a terminal command.++We define three actions:+- `saveCodeToFile`+ - Takes `code` and `filename` as arguments and saves the code to a file inside sandbox.+- `listFiles`+ - Returns a list of files on a given `path`.+- `readFile`+ - Reads a file on the `path` and returns the content of this file.+<CodeGroup isFileName title="actions.ts" isRunnable={false}>+```js+import { Sandbox } from '@e2b/sdk'+import path from 'path'++export async function saveCodeToFile(+ sandbox: Sandbox,+ { code, filename }: { code: string; filename: string },+): Promise<string> {+ try {+ const dir = path.dirname(filename)++ await sandbox.filesystem.makeDir(dir)+ await sandbox.filesystem.write(filename, code)++ return 'success'+ } catch (e) {+ return `Error: ${e.message}}`+ }+}++export async function listFiles(sandbox: Sandbox, { path }: { path: string }): Promise<string> {+ try {+ const files = await sandbox.filesystem.list(path)+ const response = files.map(file => (file.isDir ? `dir: ${file.name}` : file.name)).join('\n')+ return response+ } catch (e) {+ return `Error: ${e.message}}`+ }+}++export async function readFile(sandbox: Sandbox, { path }: { path: string }): Promise<string> {+ try {+ return await sandbox.filesystem.read(path)+ } catch (e) {+ return `Error: ${e.message}}`+ }+}+```+</CodeGroup>++### 3. Add action to sandbox+Now we need to make sure the sandbox knows about our actions we defined above. We'll use the `addAction` method.+<CodeGroup isFileName title="index.ts" isRunnable={false}>+```js+// Import our action+import { listFiles, readFile, saveCodeToFile } from './actions'++// Add action to the sandbox we created in the previous steps+sandbox+ .addAction(readFile)+ .addAction(saveCodeToFile)+ .addAction(listFiles)+```+</CodeGroup>++### 4. Create AI Assistant+We'll use the OpenAI API to create a new AI Assistant. You can read the full code [[TODO: FIX LINK] here]().++Keep a close attention to the `functions` definition inside the `[[TODO: FIX LINK] assistant.py]()` file. We're using the [Function calling](https://platform.openai.com/docs/assistants/tools/function-calling) feature to give our assistant an ability to call the sandbox actions we defined.+<CodeGroup isFileName title="assistant.ts" isRunnable={false}>+```js+import { AssistantCreateParams } from 'openai/src/resources/beta/assistants/assistants'++export const functions: Array<+ | AssistantCreateParams.AssistantToolsCode+ | AssistantCreateParams.AssistantToolsRetrieval+ | AssistantCreateParams.AssistantToolsFunction+> = [+ // Save code to file+ {+ type: 'function',+ function: {+ name: 'saveCodeToFile', // $HighlightLine+ description: 'Save code to file',+ parameters: {+ type: 'object',+ properties: {+ code: { // $HighlightLine+ type: 'string',+ description: 'The code to save',+ },+ filename: { // $HighlightLine+ type: 'string',+ description: 'The filename including the path and extension',+ },+ },+ },+ },+ },+ // ... rest of the functions+ ]++// ... rest of the file+```+</CodeGroup>++- **The `name` field is the same name as the name of the sandbox action we created in the previous step.**+- **The parameters `code` and `filename` are the parameters passed to the sandbox action as a part of the `args` dictionary.**+++### 5. Let assistant run our actions+<Note title="How Assistants Work">+Read the official [OpenAI's assistants documentation](https://platform.openai.com/docs/assistants/how-it-works).+</Note>++Once the assistant is created, we use the OpenAI API to retrieve it, create a thread, send messages to the thread, and finally run the thread.++When the thread is running, we get a `run` object. The `run.status` field tells us if our assistant requires to run any action.++If the `run.status` indicates that the assistant wants to call actions, we just pass the `run` object to the `sandbox.openai.actions.run()` function.+The E2B sandbox will automatically call the correct actions and returns correctly formatted output object (called `outputs` in the code below) that you can submit back to the assistant.++<CodeGroup isFileName title="main.py" isRunnable={false}>+```js+// ... rest of the logic++const assistant = await openai.beta.assistants.retrieve(AI_ASSISTANT_ID)+let run = await openai.beta.threads.runs.create(thread.id, { assistant_id: assistant.id })++// Start polling the run object+assistantLoop: while (true) {+ await sleep(1000)++ switch (run.status) {+ case 'requires_action': { // $HighlightLine+ const outputs = await sandbox.openai.actions.run(run) // $HighlightLine++ if (outputs.length > 0) { // $HighlightLine+ await openai.beta.threads.runs.submitToolOutputs(thread.id, run.id, { // $HighlightLine+ tool_outputs: outputs, // $HighlightLine+ }) // $HighlightLine+ } // $HighlightLine++ break+ }+ // ... handle rest of the `run` states+ default:+ console.error(`Unknown status: ${run.status}`)+ break assistantLoop+ }++ run = await openai.beta.threads.runs.retrieve(thread.id, run.id)+}++// Close the sandbox once everything is done+await sandbox.close()+```+</CodeGroup>++++See the full code [[TODO: Fix link] here]().\ No newline at end of file