Skip to main content

Bespoke Labs Logo

Universal Sandbox Interface

One Python API for code and agents across sandbox providers, and observability.

Animation: the inside-sandbox agent example runs Codex on 10 backends by changing only the backend string, and each run's create, setup, exec, and destroy events appear in a telemetry view


Create a sandbox, run code or shell commands, move files in and out, and clean up through a common Python API. Run locally or choose Docker, Daytona, E2B, Modal, and other providers. Add the optional self-hosted control plane when your team needs a shared dashboard, usage tracking, and provisioning policies.

Quickstart · Run an agent · Providers · Documentation

Install

Use Python 3.10+ for the SDK. Install only the provider extras you need; the core package requires only Pydantic.

pip install bespokelabs-sandbox

See installation options for provider extras, the server (Python 3.11+), and using Sandbox alongside other Bespoke packages.

Quickstart

Run your first snippet locally, with no provider account or Docker daemon:

from bespokelabs.sandbox import Sandbox

with Sandbox("local") as sb:
    result = sb.execute_code('print("Ready to run")')
    if result.exit_code != 0:
        raise RuntimeError(result.stderr)
    print(result.stdout)  # Ready to run

local executes on your host and does not provide an isolation boundary. The context manager requests cleanup when the block exits, including on errors. The Docker workflow below runs code in a container.

Process a file in a sandbox

With Docker installed and running, install the Docker extra:

pip install 'bespokelabs-sandbox[docker]'

This complete workflow seeds a JSON file, processes it in a container, downloads the output to your machine, and cleans up the container on exit:

import json
from pathlib import Path

from bespokelabs.sandbox import Sandbox

with Sandbox(
    "docker",
    image="python:3.12-slim",
    files={"/tmp/numbers.json": json.dumps([10, 20, 30])},
) as sb:
    result = sb.execute_code("""
import json
from pathlib import Path

numbers = json.loads(Path("/tmp/numbers.json").read_text())
summary = {"count": len(numbers), "total": sum(numbers)}
Path("/tmp/summary.json").write_text(json.dumps(summary))
""")
    if result.exit_code != 0:
        raise RuntimeError(result.stderr)
    sb.download_file("/tmp/summary.json", "sandbox-result.json")

# The downloaded result remains after the sandbox is destroyed.
print(json.loads(Path("sandbox-result.json").read_text()))
# {'count': 3, 'total': 60}

Docker pulls the image on the first run if it is not already available. For shell commands, use sb.execute_command("python", ["/path/to/script.py"]). Code and command results expose stdout, stderr, and exit_code; inspect the exit code for command failures. Provider or transport failures can raise SandboxError.

The same API works with configured cloud providers, subject to their feature support. See the reference for repository and directory setup, file operations, and async execution.

Run your first agent

Use the same Docker installation to run a CLI agent inside a sandbox. This example uses the codex preset, which installs the CLI at startup on the backend's base image. Provide your model API key in the environment before running the Python example:

export CODEX_API_KEY='your-api-key'
import os

from bespokelabs.sandbox import Sandbox

with Sandbox(
    "docker",
    preset="codex",
    env_vars={"CODEX_API_KEY": os.environ["CODEX_API_KEY"]},
    files={"/tmp/example.py": "def average(xs):\n    return sum(xs) / len(xs)\n"},
) as sb:
    result = sb.run_agent(
        "Read /tmp/example.py. Explain what happens for an empty list and "
        "suggest a fix. Do not modify files.",
        harness="codex",
        extra_args=["--skip-git-repo-check"],
    )
    if result.exit_code != 0:
        raise RuntimeError(result.stderr or result.stdout)
    print(result.text)
    print("Tokens:", result.usage.total_tokens)

This makes a model API call using your account. --skip-git-repo-check allows this file-only example to run without a Git repository. Startup installation needs network access and adds setup time. The preset installs tools; it does not supply credentials. preset= selects the environment and harness= selects the CLI that run_agent() invokes.

Use run_agent() for supported CLI agents and normalized output and usage. Use agent(AgentSpec.inside(...)) when you need a custom command, working directory, or prompt delivery mode. For an agent running in your own process, use agent_tools() or AgentSpec.outside(...) to drive the sandbox.

The agent guide covers Claude Code, Codex, OpenCode, Grok, custom runners, presets, and resuming conversations. Direct SDK runs are not uploaded to the dashboard; use the hosted agent workflow to persist usage in the control plane.

Supported Backends

Local

Local execution needs no provider account. Docker, Ray, and Safehouse have the runtime requirements listed below.

Backend Extra Requires
Local subprocess (none) Python installed
Monty [monty] Bundled Monty worker binary
Agent Safehouse (none) macOS + safehouse CLI
Docker [docker] Docker daemon running
Ray [ray] Ray installed (local or remote cluster)

Cloud

Backend Extra Auth
Daytona [daytona] DAYTONA_API_KEY
Tensorlake [tensorlake] TENSORLAKE_API_KEY or tl login
Modal [modal] MODAL_TOKEN_ID + MODAL_TOKEN_SECRET
RunPod (none) RUNPOD_API_KEY + registered SSH key
E2B [e2b] E2B_API_KEY
Novita [novita] NOVITA_API_KEY
boxd [boxd] BOXD_API_KEY
Google Cloud Batch (jobs only) [gcp-batch] Application Default Credentials

You only need to install the backend you use. The others are lazily imported.

Local and Ray execute subprocesses on the host or Ray worker and inherit its environment. Their workspace path rewriting is a convenience, not an OS security boundary. Safehouse wraps subprocesses with its macOS policy, while its file helpers still access the host directly. Use the isolation properties of your selected backend when deciding which workloads to run.

See the feature matrix, credential setup, and Monty guide and Novita guide for adapter details (including Novita's native connect lifecycle and protected-service authentication).

Hosted control plane

Add the self-hosted control plane when a team needs shared visibility and policies. Provider credentials stay on your server; applications connect with organization-scoped product keys through RemoteSandboxClient or HTTP. The direct SDK works independently, and its runs are not automatically uploaded.

The dashboard shows resource usage, compute spend, hosted agent token and model cost records, execution history, and cleanup state. Provisioning policies cover concurrency, compute spend, allowed providers and GPUs, and requested lifetimes.

Docker, Monty, and Daytona usage overview with illustrative workload totals and measured resource peaks

Illustrative Docker + Monty + Daytona workload, with measured resource peaks from small live smoke tests shown separately. Monty resource telemetry is unavailable and excluded from idle totals. Cost estimates exclude local host compute.

See the current per-sandbox dashboard

Per-sandbox CPU, RAM, GPU utilization, and GPU memory charts

Actual dashboard with fixture data. Resource charts refresh every 15 seconds; available metrics depend on the provider and sandbox image.

Follow the control plane setup guide to install the server, configure a provider, issue a product key, run a client job, and open the dashboard.

This is a service you operate. Run one API process per SQLite database; execution handles do not survive a server restart. Resource metrics require a compatible image, and restart reconciliation and cleanup require deployment-supplied adapters. Compute budget checks apply at creation and exclude model spend. See the operations runbook before deploying.

Documentation

Guide Contents
Installation Python versions, provider extras, server installation, package compatibility
Backends and feature support Provider requirements, Monty, feature matrix, environment variables
Python SDK reference Creation options, execution, files, workspaces, networking, GPUs, jobs, snapshots, lifecycle, async, errors, telemetry
Running agents Agent placement, CLI harnesses, presets, token usage, cost reporting, Envy
Control plane setup Server setup, product keys, remote execution, dashboard, policies
Control plane operations Deployment, supervision, recovery, and operating limits
HTTP API contract Endpoints, authentication, request semantics, and exports

Examples

Run examples from a source checkout after installing the package. Each script lists its own provider and agent prerequisites.

Example Demonstrates
move_files_into_sandbox.py Generated local directory, file-map seeding, and live transfers
find_cheapest.py Cold-start/execution benchmarks and bundled compute estimates
sandbox_repo.py Claude Code or Codex inside Daytona/Tensorlake, with a clone or web input
claude_code_outside.py Host-side agent driving sandbox commands through a local bridge
claude_code_persona.py Declarative workspace and agent persona files
github_stats.py Parsing agent output into a Pydantic model

A local transfer demo needs no cloud credentials or agent CLI:

python examples/move_files_into_sandbox.py --backend local

Development

See the development setup guide for environment setup, tests, linting, and the codebase map. DEVELOPMENT.md describes design direction and compatibility rules.

License

Apache License 2.0.

Metadata

Release files for bespokelabs-sandbox 0.4.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for bespokelabs-sandbox 0.4.1
File Size Uploaded Provenance Actions
bespokelabs_sandbox-0.4.1.tar.gz 298.3 kB Without provenance Details for bespokelabs_sandbox-0.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for bespokelabs-sandbox 0.4.1
File Interpreter ABI Platform Actions
bespokelabs_sandbox-0.4.1-py3-none-any.whl Python 3 none any Details for bespokelabs_sandbox-0.4.1-py3-none-any.whl

Total release size: 508.9 kB

Release files / bespokelabs_sandbox-0.4.1.tar.gz

Download URL bespokelabs_sandbox-0.4.1.tar.gz
Size 298.3 kB
Tags Source
SHA-256 checksum
How to use checksums
de65431607cda0ac029803f7b68a4211e1ac003944e29618a8d3df405ce92464
BLAKE2b-256 checksum
How to use checksums
6437dfaffddec416ad4e2fe20af064b374d60e5530b9e691b75724106b509bb4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Release files / bespokelabs_sandbox-0.4.1-py3-none-any.whl

Download URL bespokelabs_sandbox-0.4.1-py3-none-any.whl
Size 210.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d24f39fbe9ddaa570ee93e4f182d4a5579714af97751bb25522e3f6dd794b534
BLAKE2b-256 checksum
How to use checksums
3991da33e0e04ee5c78047804bd242a43476cf0a7b85576baaef0edb279d8a2f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.6

Security for bespokelabs-sandbox 0.4.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page