Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
Merge remote-tracking branch 'origin/main' into openai-integration
Jakub Novak64ac53d4b611
diff --cc apps/docs/src/components/Navigation/routes.tsxindex b6900cb7f,27f83bcd0..a7691a3fe--- a/apps/docs/src/components/Navigation/routes.tsx+++ b/apps/docs/src/components/Navigation/routes.tsx@@@ -16,12 -16,9 +16,12 @@@ importTimer,Variable,PencilRuler,- File, TerminalSquare,+ File, TerminalSquare, RefreshCw,} from 'lucide-react'+import logoOpenAI from '@/images/logos/openai.svg'+import Image from 'next/image'+export const routes = [{title: 'Overview',diff --cc packages/js-sdk/src/sandbox/index.tsindex 9ccec662b,fac0d7ac2..1e0c79f3b--- a/packages/js-sdk/src/sandbox/index.ts+++ b/packages/js-sdk/src/sandbox/index.ts@@@ -10,7 -10,7 +10,8 @@@ import { Process, ProcessManager, Proceimport { CallOpts, SandboxConnection, SandboxConnectionOpts } from './sandboxConnection'import { Terminal, TerminalManager, TerminalOpts, TerminalOutput, terminalService } from './terminal'import { resolvePath } from '../utils/filesystem'+import { Actions } from '../templates/openai'+ import { CurrentWorkingDirectoryDoesntExistError } from '../error'export type DownloadFileFormat =| 'base64'@@@ -432,26 -433,6 +440,26 @@@ export class Sandbox extends SandboxConreturn `${protocol}://${hostname}${FILE_ROUTE}`}+ /**+ * Returns a map of added actions.- *++ *+ * @returns Map of added actions+ */+ get actions() {+ return new Map(this._actions)+ }++ /**+ * OpenAI integration that can be used to get output for the actions added in the sandbox.- *++ *+ * @returns OpenAI integration+ */+ get openai() {+ return {+ actions: new Actions(this),+ } as const+ }+/*** Creates a new Sandbox.* @param optsOrID Sandbox options or Sandbox ID@@@ -475,75 -456,59 +483,113 @@@})}+ /**+ * Reconnects to an existing Sandbox.+ * @param sandboxIDorOpts Sandbox ID or Sandbox options+ * @returns Existing Sandbox+ *+ * @example+ * ```ts+ * const sandbox = await Sandbox.reconnect(sandboxID)+ * ```+ */+ static async reconnect(+ sandboxIDorOpts: string | Omit<SandboxOpts, 'id'> & { sandboxID: string }+ ) {+ let sandboxID: string+ let opts: SandboxOpts+ if (typeof sandboxIDorOpts === 'string'){+ sandboxID = sandboxIDorOpts+ opts = {}+ } else {+ sandboxID = sandboxIDorOpts.sandboxID+ opts = sandboxIDorOpts+ }++ const instanceIDAndClientID = sandboxID.split("-")+ const instanceID = instanceIDAndClientID[0]+ const clientID = instanceIDAndClientID[1]+ opts.__sandbox = { instanceID, clientID, envID: 'unknown' }+ return new Sandbox(opts)+ ._open({ timeout: opts?.timeout })+ .then(async (sandbox) => {+ if (opts?.cwd) {+ console.log(`Custom cwd for Sandbox set: "${opts.cwd}"`)+ await sandbox.filesystem.makeDir(opts.cwd)+ }+ return sandbox+ })+ }+- protected override async _open(opts: CallOpts) {- await super._open(opts)+ /**+ * Add a new action. The name of the action is automatically extracted from the function name.- *++ *+ * You can use this action with specific integrations like OpenAI to interact with the sandbox and get output for the action.- *++ *+ * @param action Action handler+ * @returns Sandbox+ *+ * @example+ * ```ts+ * const sandbox = await Sandbox.create()+ * sandbox.addAction('readFile', (sandbox, args) => sandbox.filesystem.read(args.path))+ * ```+ */+ addAction<T = { [name: string]: any }>(action: Action<T>): this;+ /**+ * Add a new action with a specified name.- *++ *+ * You can use this action with specific integrations like OpenAI to interact with the sandbox and get output for the action.- *++ *+ * @param name Action name+ * @param action Action handler+ * @returns Sandbox+ *+ * @example+ * ```ts+ * async function readFile(sandbox: Sandbox, args: any) {+ * return sandbox.filesystem.read(args.path)+ * }- *++ *+ * const sandbox = await Sandbox.create()+ * sandbox.addAction(readFile)+ * ```+ */+ addAction<T = { [name: string]: any }>(name: string, action: Action<T>): this;+ addAction<T = { [name: string]: any }>(actionOrName: string | Action<T>, action?: Action<T>): this {+ if (typeof actionOrName === 'string') {+ if (!action) throw new Error('Action is required')+ this._actions.set(actionOrName, action)+ return this+ } else if (typeof actionOrName === 'function') {+ action = actionOrName++ if (!action.name) {+ throw new Error('Action name is required')+ }- const portsHandler = this.onScanPorts- ? (ports: { State: string; Ip: string; Port: number }[]) =>- this.onScanPorts?.(- ports.map((p) => ({ ip: p.Ip, port: p.Port, state: p.State })),- )- : undefined+ this._actions.set(action.name, action)+ } else {+ throw new Error('Action or action name and action is required')+ }- await this._handleSubscriptions(- portsHandler- ? this._subscribe(codeSnippetService, portsHandler, 'scanOpenedPorts')- : undefined,- )+ return this+ }++ /**+ * Remove an action.+ * @param name Action name+ * @returns Sandbox- *++ *+ * @example+ * ```ts+ * const sandbox = await Sandbox.create()+ * sandbox.addAction('hello', (sandbox, args) => 'Hello World')+ * sandbox.removeAction('hello')+ * ```+ */+ removeAction(name: string) {+ this._actions.delete(name)return this}@@@ -582,18 -547,6 +628,18 @@@return `/home/user/${filename}`}+ /**+ * Downloads a file from the sandbox.+ * @param remotePath Path to a file on the sandbox+ * @param format Format of the downloaded file+ * @returns File content- *++ *+ * @example+ * ```ts+ * const sandbox = await Sandbox.create()+ * const content = await sandbox.downloadFile('/home/user/file.txt')+ * ```+ */async downloadFile(remotePath: string, format?: DownloadFileFormat) {remotePath = encodeURIComponent(remotePath)diff --cc packages/python-sdk/e2b/sandbox/main.pyindex 203d15b96,46471c529..75ef79486--- a/packages/python-sdk/e2b/sandbox/main.py+++ b/packages/python-sdk/e2b/sandbox/main.py@@@ -3,8 -3,9 +3,9 @@@ import urllib.parsimport requestsfrom os import path-from typing import Any, Callable, List, Literal, Optional, IO+from typing import Any, Callable, Dict, List, Literal, Optional, IO, Tuple, Union+ from e2b.api.v2.client import modelsfrom e2b.constants import TIMEOUT, ENVD_PORT, FILE_ROUTEfrom e2b.sandbox.code_snippet import CodeSnippetManager, OpenPortfrom e2b.sandbox.env_vars import EnvVars@@@ -107,88 -111,9 +111,88 @@@ class Sandbox(SandboxConnection)_debug_hostname=_debug_hostname,_debug_port=_debug_port,_debug_dev_env=_debug_dev_env,- on_close=self._close_services,timeout=timeout,)+ self._on_close_child = self._close_services+ self._actions: Dict[str, Action] = {}++ def add_action(self, action: "Action", name: Optional[str] = None) -> "Sandbox":+ """+ Add a new action. If the name is not specified, it is automatically extracted from the function name.+ An action is a function that takes a sandbox and a dictionary of arguments and returns a string.++ You can use this action with specific integrations like OpenAI to interact with the sandbox and get output for the action.+ :param action: The action to add+ :param name: The name of the action, if not provided, the name of the function will be used++ Example:++ ```python+ from e2b import Sandbox++ def read_file(sandbox, args):+ with open(args["path"], "r") as f:+ return sandbox.filesystem.read(args.path)++ s = Sandbox()+ s.add_action(read_file)+ s.add_action(name="hello", action=lambda s, args: f"Hello {args['name']}!")+ ```+ """+ self._actions[name] = action++ return self++ def remove_action(self, name: str) -> "Sandbox":+ """+ Remove an action.++ :param name: The name of the action+ """+ del self._actions[name]++ return self++ @property+ def actions(self) -> Dict[str, "Action"]:+ """+ Return a dict of added actions.+ """++ return self._actions.copy()++ def action(self, name: Optional[str] = None):+ """+ Decorator to add an action.++ :param name: The name of the action, if not provided, the name of the function will be used+ """++ def _action(action: Action):+ self.add_action(action=action, name=name or action.__name__)++ return action++ return _action++ @property+ def openai(self):+ """+ OpenAI integration that can be used to get output for the actions added in the sandbox.++ Example:++ ```python+ from e2b import Sandbox++ s = Sandbox()+ s.openai.actions.run(run)+ ```+ """++ from e2b.templates.openai import OpenAI, Actions++ return OpenAI(Actions(self))def _open(self, timeout: Optional[float] = TIMEOUT) -> None:"""