E2B

repository·main·Indexed 12 days ago

https://github.com/e2b-dev/E2B

Open-source infrastructure providing secure, isolated cloud sandboxes for running AI-generated code. It includes SDKs for JavaScript/TypeScript and Python, a dedicated Code Interpreter SDK, and a CLI for managing sandbox templates and instances. E2B allows LLMs to interact with real computing environments safely and supports self-hosting via Terraform on AWS and GCP.

Tokens
47.1K
Snippets
159
Records
224
Agent score
95%

What's inside E2B

  1. E2B Practical Defaults and Best Practices

    main

    When working with E2B sandboxes, follow these recommended defaults:

    • Template: Use the base template unless a specific requirement dictates otherwise.
    • Shell Execution: Prefer bash -lc for executing multi-command strings via the CLI or SDK to ensure the environment is correctly loaded.
    • File Storage: Store temporary files in /tmp or the current working directory within the sandbox.
    • Code Execution: For workloads specifically requiring code execution (e.g., run_code or runCode), use the Code Interpreter SDK instead of standard sandbox commands.
  2. Execute code with the Code Interpreter SDK

    main

    For specialized code execution (e.g., running Python snippets and getting results), install the dedicated Code Interpreter SDK.

    Installation

    • JavaScript/TypeScript: npm i @e2b/code-interpreter
    • Python: pip install e2b-code-interpreter

    Usage (TypeScript) Use sandbox.runCode() to execute code strings. The result contains the output text.

    Usage (Python) Use sandbox.run_code() to execute code strings.

    import { Sandbox } from '@e2b/code-interpreter'
    
    const sandbox = await Sandbox.create()
    const execution = await sandbox.runCode('x = 1; x += 1; x')
    console.log(execution.text)  // outputs 2
  3. Provision E2B access via Stripe Projects

    main

    To use E2B sandboxes and APIs provisioned through Stripe Projects, you must first add E2B to your Stripe project and then pull the managed environment variables.

    Note: Do not use stripe projects env --json to extract keys for runtime use, as secret values like E2B_API_KEY may be redacted. Instead, use stripe projects env --pull --yes to download a .env file and extract the required variables manually.

    # Add E2B to the current Stripe project
    stripe projects add e2b/sandboxes
    
    # Pull provisioned credentials to a .env file
    stripe projects env --pull --yes
  4. Use the E2B CLI for sandbox management

    main

    The E2B CLI allows you to create, execute commands in, and resume sandboxes.

    Create a sandbox

    Use the --detach flag for non-interactive work. This returns a sandbox ID immediately instead of attaching an interactive terminal.

    e2b sandbox create base --detach

    Execute commands

    Use -- before your shell command to prevent the CLI from parsing your shell flags. For multi-command execution, it is recommended to use bash -lc.

    e2b sandbox exec <sandbox_id> -- bash -lc 'pwd && ls -la'

    Run long-running processes

    Run processes in the background and write a PID file within the sandbox to track them:

    e2b sandbox exec <sandbox_id> -- bash -lc 'nohup python server.py >server.log 2>&1 & echo $! >server.pid'

    Resume a sandbox

    e2b sandbox resume <sandbox_id>
  5. Install the E2B SDK

    main

    You can install the E2B SDK for either JavaScript/TypeScript or Python to start managing sandboxes.

    JavaScript / TypeScript

    npm i e2b

    Python

    pip install e2b
    npm i e2b
    # or
    pip install e2b
  6. Configure Sandbox Lifecycle and Timeout Behavior

    main

    The SandboxLifecycle configuration defines what happens when a sandbox reaches its timeout limit and how it handles auto-resumption.

    Timeout Actions

    • kill: Terminates the sandbox immediately. This is the default behavior.
    • pause: Pauses the sandbox. You can control the snapshot type using keep_memory:
      • keep_memory=True (Default): Saves a full memory snapshot. Resuming restores the running process state.
      • keep_memory=False: Saves only the filesystem. Resuming results in a "cold boot" (reboot), losing running processes and open connections.

    Auto-Resume

    • auto_resume: If set to True, activity (like inbound traffic) will automatically wake a paused sandbox.
    • Constraint: auto_resume can only be True if on_timeout is set to "pause" AND keep_memory is True. If keep_memory is False, the sandbox must be resumed explicitly via connect().
    # Example: Pause sandbox on timeout and keep memory for transparent auto-resume
    lifecycle = {
        "on_timeout": {
            "action": "pause",
            "keep_memory": True
        },
        "auto_resume": True
    }
  7. Watch filesystem changes with WatchDir

    main

    You can monitor filesystem activity using a watcher pattern.

    1. Create a watcher: Use CreateWatcherRequest specifying the path, whether to be recursive, and if include_entry (to get full EntryInfo with the event) should be enabled.
    2. Get events: Use GetWatcherEventsRequest with the watcher_id returned from the creation step to retrieve a list of FilesystemEvent objects.
    3. Cleanup: Use RemoveWatcherRequest to stop watching and clean up the watcher resource.

    WatchDirRequest Options:

    • path: The directory to watch.
    • recursive: Whether to watch subdirectories.
    • include_entry: If true, each FilesystemEvent includes the EntryInfo of the affected entry (if available).
    • allow_network_mounts: If true, allows watching paths on network filesystem mounts (NFS, CIFS, SMB, FUSE). Note that events on network mounts may be unreliable.
    # Conceptual workflow for watching files
    # 1. Create
    create_req = CreateWatcherRequest(path="/tmp", recursive=True, include_entry=True)
    # (Call service with create_req) -> returns watcher_id
    
    # 2. Get Events
    get_req = GetWatcherEventsRequest(watcher_id="your_id_here")
    # (Call service with get_req) -> returns list of FilesystemEvent
    
    # 3. Remove
    remove_req = RemoveWatcherRequest(watcher_id="your_id_here")
    # (Call service with remove_req)
  8. Configure Project and Team IDs

    main

    The E2B CLI resolves the projectId (or teamId) using the following precedence order:

    1. CLI Flag: The --project flag (note: --team is deprecated).
    2. Environment Variable: The E2B_PROJECT_ID environment variable (note: E2B_TEAM_ID is deprecated).
    3. User Config: The projectId defined in your local config file (~/.e2b/config.json).

    Important Note on Precedence: To prevent mismatches between an environment-provided API key and a local config file, the CLI will only fall back to the projectId in your local config file if the E2B_API_KEY environment variable is not set.

  9. Interact with running processes using CommandHandle

    main

    A CommandHandle is returned when you run a command with { background: true } or use Commands.connect(pid). It allows you to manage the lifecycle and I/O of a running process.

    Common methods on CommandHandle:

    • wait(): Returns a Promise<CommandResult> that resolves when the process exits.
    • sendStdin(data, opts): Sends data to the process's standard input.
    • closeStdin(opts): Signals EOF to the process (only if the command was started with stdin: true).
    • kill(): Terminates the process.
    • onStdout / onStderr: Listeners for process output streams.