Python SDK

The sandboxer-sdk package — sync and async clients for Python 3.10+, with typed models and a low-level method for every API operation.

.md

Install#

pip install sandboxer-sdk
# or: uv add sandboxer-sdk · poetry add sandboxer-sdk
# the package installs as sandboxer-sdk and imports as sandboxer

Note Install sandboxer-sdk, not sandboxer. The PyPI package named sandboxer is an unrelated project that uses the same import name.

Note On an older version, API responses carry a Sandboxer-Client-Warning header (for example, "sandboxer-sdk 0.1.2 for Python is out of date; run pip install -U sandboxer-sdk (0.1.3)") and Sandboxer-Client-Latest with the newest version. Run pip install -U sandboxer-sdk to update.

Configure#

import os
from sandboxer import Sandboxer

client = Sandboxer(
    api_key=os.environ["SANDBOXER_API_KEY"],   # default: SANDBOXER_API_KEY, then SANDBOXER_TOKEN
    base_url="https://sandboxer.com/api/v1",   # default: SANDBOXER_API_URL, then this URL
    org="team_acme",                           # bill an organization wallet (X-Sandboxer-Org)
    timeout=60,                                # seconds; None disables it
    max_retries=3,
)

Every argument is optional, so Sandboxer() reads its settings from the environment. Inside a sandbox, SANDBOXER_TOKEN and SANDBOXER_API_URL are already set. Use with Sandboxer() as client: in scripts so connections are closed.

Create, use, stop#

from sandboxer import Sandboxer

with Sandboxer() as client:
    sandbox = client.create(type="default", ttl_seconds=1800, name="pr-1842")   # waits until ready
    # region="us-east" or "eu-central"; without it, the region nearest you (/docs/regions)
    try:
        run = sandbox.exec("python3 --version", timeout_seconds=60)
        print(run.exit_code, run.stdout)
    finally:
        sandbox.stop()   # archive; sandbox.resume() brings it back

exec takes a shell string or an argv list (quoted for you), plus cwd, env and timeout_seconds (1–600, default 30). Pass check=True to raise CommandError on a non-zero exit. ttl_seconds=None disables auto-stop; from_="web-stack" starts from a named snapshot.

Common calls#

Task Method
List / get client.list(state=["ready", "idle", "running"]) (a generator that fetches pages as you iterate; wrap it in list(...) for a list), client.get(sandbox_id)
Lifecycle stop, resume, fork, snapshot(name), delete, recover, share
Fields sb.id, sb.state and sb.name; everything else (type, vcpu, memory_gb, url, archive_after, …) is on sb.info, refreshed with sb.refresh()
Auto-stop and names extend(ttl_seconds), update(name=…, subdomain=…)
Commands exec, exec_stream, start, command_status, attach, kill, history, processes
Files files.read, files.read_bytes, files.write, files.download
Hosting / SSH / desktop host(port), ssh_key(public_key), desktop()
Agents prompt, events, conversations, steer, interrupt
Usage usage(), snapshots(), latest_snapshot()

Everything else is on client.api: one method per operationId in the API reference, in snake_case. Body fields go in as keyword arguments (or a model from sandboxer.models); responses are pydantic models with snake_case attributes.

api = client.api
api.me()
api.update(sandbox.id, ttl_seconds=7200)
api.request("GET", "/provider-models")   # escape hatch for anything else

Stream a command#

stream = sandbox.exec_stream("npm install")
for frame in stream:                     # started, stdout/stderr chunks, then exit or error
    if frame.type in ("stdout", "stderr"):
        print(frame.data, end="")
result = stream.wait()                   # CommandResult with the collected output

Detached commands#

build = sandbox.start("make -j8", cwd="project")
for frame in build.attach():             # live output; reconnects transparently
    print(frame.type, frame.data)
status = build.status()                  # or sandbox.command_status(build.process_id)
build.kill()                             # SIGTERM, then SIGKILL after 5 s

result = sandbox.start("./ci.sh").wait()   # follow to the end
print(result.exit_code, result.stdout[-2000:])

Prompt an agent#

run = sandbox.prompt("Add type hints to utils.py and run mypy", provider="codex")
for event in run.events():               # this run's events, until it is done
    if event.type == "response" and event.data.get("content"):
        print(event.data["content"])
run.wait()                               # finished, failed or interrupted
print(run.text())                        # the final response text

run.steer("...") adds an instruction to the running turn; run.interrupt() stops it.

Files#

sandbox.files.write("data/input.json", '{"n": 3}')               # text
sandbox.files.write("chart.png", open("chart.png", "rb").read())   # bytes (sent base64)
text = sandbox.files.read("data/input.json")                      # str, up to 5 MiB
png = sandbox.files.read_bytes("chart.png")                       # bytes, up to 5 MiB
archive = sandbox.files.download("build/app.tar.gz")              # bytes, up to 50 MiB

Paths are relative to /home/user; absolute paths under /home/user or /tmp work too.

Errors#

Every failure raises SandboxerError with the error envelope already parsed. Subclasses include BadRequestError, AuthenticationError, PaymentRequiredError, PermissionDeniedError, NotFoundError, ConflictError, RateLimitError, APIConnectionError and APITimeoutError.

from sandboxer import SandboxerError

try:
    client.create(type="xlarge")
except SandboxerError as e:
    print(e.status, e.code, e.message, e.details, e.request_id, e.retryable)

Async#

AsyncSandboxer and AsyncSandbox mirror the same API with async/await:

import asyncio
from sandboxer import AsyncSandboxer

async def main() -> None:
    async with AsyncSandboxer() as client:
        async with await client.create(type="small", on_exit="delete") as sandbox:
            print((await sandbox.exec("uname -a")).stdout)

asyncio.run(main())

on_exit="stop" or "delete" cleans up when the block exits, in sync with blocks too. Async versions of the helper functions are in sandboxer.aio.