Metadata-Version: 2.4
Name: sandboxplease
Version: 0.2.0
Summary: One API key, every agent sandbox provider: create sandboxes on E2B, Daytona, Modal, Vercel and more, with routing and fallbacks. Python client for SandboxPlease.
Keywords: sandbox,sandboxes,ai-agents,agents,code-execution,code-interpreter,e2b,daytona,modal,microvm,llm,mcp
Author: SandboxPlease
Author-email: SandboxPlease <support@sandboxplease.com>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.27
Requires-Python: >=3.10
Project-URL: Homepage, https://sandboxplease.com
Project-URL: Documentation, https://sandboxplease.com/docs
Project-URL: Repository, https://github.com/minitap-ai/sandboxplease-sdks
Project-URL: Issues, https://github.com/minitap-ai/sandboxplease-sdks/issues
Project-URL: Changelog, https://github.com/minitap-ai/sandboxplease-sdks/blob/main/CHANGELOG.md
Description-Content-Type: text/markdown

[![SandboxPlease: one API for every agent sandbox](https://raw.githubusercontent.com/minitap-ai/sandboxplease-sdks/main/.github/assets/banner.webp)](https://sandboxplease.com)

# sandboxplease (Python)

One API key, every agent sandbox provider: E2B, Daytona, Modal, Vercel Sandbox and more, with routing and
fallbacks, at exactly the provider's list price. Sync and async, fully typed, Python 3.10+.

[Docs](https://sandboxplease.com/docs) · [API reference](https://sandboxplease.com/docs/api-reference) · [Providers](https://sandboxplease.com/sandboxes) · [Examples](https://github.com/minitap-ai/sandboxplease-sdks/tree/main/examples) · [Changelog](https://github.com/minitap-ai/sandboxplease-sdks/blob/main/CHANGELOG.md)

Install the released SDK from PyPI. To build from a checkout, follow the [source setup instructions](https://github.com/minitap-ai/sandboxplease-sdks/blob/main/CONTRIBUTING.md).

```bash
pip install sandboxplease
export SANDBOXPLEASE_API_KEY=sp-v1-...   # https://sandboxplease.com/settings/keys
```

```python
from sandboxplease import SandboxPlease

with SandboxPlease() as sp, sp.sandboxes.create() as sbx:
    out = sbx.exec("python3 -c 'print(1 + 1)'", check=True)
    print(f"{sbx.provider} says {out.stdout}")
```

The sandbox is killed when the `with` block exits.

The quickstart requires SandboxPlease API access and an enabled provider.

## Pick by capability

`require` keeps only the providers that have every capability, by name or by value
([every capability](https://sandboxplease.com/docs/capabilities)):

```python
with sp.sandboxes.create(provider={"require": {"gpu": "any", "vcpu": 8, "pause": True}}) as gpu_box:
    gpu_box.exec("nvidia-smi")
```

## More

```python
sbx = sp.sandboxes.create(
    "e2b/standard",
    provider={"order": ["e2b", "daytona"], "require": ["ports"], "region": "eu"},
    timeout=600,
    idle_timeout=300,  # killed after 5 minutes without a call
    network={"allow": ["pypi.org", "*.github.com"]},
)
sbx.provider  # "e2b"
sbx.region  # "eu"
sbx.size  # {"name": "standard", "cpu": 2, "memory_gb": 4}
sbx.price_per_hour  # 0.1656, USD per hour: the provider's list price, billed per second, no markup
sbx.cold_start_ms  # 412
sbx.fallback  # None, or {"from": "e2b", "reason": "plan_limit", "message": "..."} when another provider took over
if sbx.fallback:
    print(f"{sbx.fallback['message']} Running on {sbx.provider}.")
sbx.exec("npm test", on_stdout=print, on_stderr=print)  # streamed as it runs
sbx.files.write("/app/main.py", "print(1)")
sbx.files.read("/app/main.py")
sbx.files.list("/app")
sbx.ports.url(3000)
sbx.pause()
sbx.resume()
sbx.kill()

sp.sandboxes.list()
sp.sandboxes.kill_all()  # every sandbox this key reaches, when your agent lost track
sp.sandboxes.kill_all(older_than_hours=6)  # only the ones started 6+ hours ago
sp.sandboxes.get(sbx.id)
sp.catalog()
sp.base_image()  # sandboxplease/base, the default image, on every provider
sp.key()  # {"balance_usd": ..., "credit_limit_usd": ..., "limit_remaining_usd": ...}: check before a long job
sp.quote(gpu={"type": "A100"}, duration=3600)  # what create would run and cost, nothing started
```

`quote` takes the arguments of `sandboxes.create()` and returns the providers create would try, in order, each with the
vCPUs and memory it really serves and its price per hour (`compute`, `gpu`, `devices`, `total`), plus the providers
left out and why. Quote before an expensive sandbox and tell the person the price.

Async: `AsyncSandboxPlease` has the same surface with `await` and `async with`.

`exec` returns an `ExecResult` (`stdout`, `stderr`, `exit_code`); a non-zero exit is returned unless you pass
`check=True`, which raises `CommandError` with the tail of stderr.

## Provider options

Pass a provider's own create fields; only the picked provider's entry is sent, so one call can carry options for every fallback. `provider_sandbox_id` is the id to hand to the vendor's SDK.

```python
sbx = sp.sandboxes.create(
    provider={"order": ["e2b", "modal"]},
    provider_options={
        "e2b": {"template": "my-python-template", "metadata": {"team": "ml"}},
        "modal": {"encryptedPorts": [8080]},
    },
)
print(sbx.provider, sbx.provider_sandbox_id, sbx.provider_metadata)
```

Every provider's fields: https://sandboxplease.com/docs/provider-options

## Snapshots and parallel copies

Set a sandbox up once, snapshot it, then start copies of it to run work in parallel. Needs a provider with the `fork`
(memory and running processes kept) or `snapshot` (filesystem only) feature.

```python
from concurrent.futures import ThreadPoolExecutor

base = sp.sandboxes.create(provider={"require": ["snapshot"]})
base.exec("pip install pytest", check=True)
snap = base.snapshot()
copies = sp.sandboxes.create(from_snapshot=snap["id"], count=5)
with ThreadPoolExecutor() as pool:
    results = list(pool.map(lambda i: copies[i].exec(f"pytest tests/shard_{i}"), range(len(copies))))
for sbx in [base, *copies]:
    sbx.kill()
sp.snapshots.delete(snap["id"])
```

Copies run on the snapshot's provider, size and region, with no fallback. `sp.snapshots.list()` and
`sp.snapshots.get(snapshot_id)` read them back; a snapshot expires after 7 days. With `AsyncSandboxPlease`, run the
copies with `asyncio.gather`.

## Mobile devices

Attach cloud devices to a miniSandbox sandbox (the only provider that takes them). Your agent drives them from inside
the sandbox with miniSandbox's device tool, documented by miniSandbox. Kinds: `android_phone`, `android_tablet`, `ios_simulator` (an iPhone), `ipad`, `apple_watch` and
`iphone_duo` (a foldable iPhone). Coming soon: `android_physical`, `android_tv` and `iphone_physical`; asking for one
raises `FeatureNotLiveError` and records your interest.

```python
with sp.sandboxes.create(devices=[{"kind": "android_phone", "os_version": "15"}]) as sbx:
    print(sbx.provider, sbx.devices)  # minisandbox [{'id': ..., 'kind': 'android_phone', 'os_version': '15'}]
```

Asking for a coming-soon kind raises `FeatureNotLiveError` and records your interest. Pausing
the sandbox releases its devices and stops their billing; resuming boots new devices of the same kinds, so reinstall
the app after a resume. Guide: https://sandboxplease.com/docs/mobile-devices

Limits: at most 3 devices per sandbox (more raises `InvalidRequestError` with code `too_many_devices`) and 10 attached
at once per workspace, across its running sandboxes (a create or resume past it raises `DeviceLimitError`, with
`in_use`). Need more? Contact support at support@sandboxplease.com.

Each device bills per started minute while attached, on credits even when the sandbox runs on your own provider key,
and a create holds its first 10 minutes. `catalog()` lists every kind with its `price_per_minute` (`None` while a
kind is coming soon); `sbx.device_price_per_minute` is what its devices cost per minute together.

```python
phone = next(d for d in sp.catalog()["devices"] if d["kind"] == "android_phone")
print(f"{phone['label']}: ${phone['price_per_minute']}/min")
```

## Errors

Every error subclasses `SandboxPleaseError` and prints what to do next:

```text
sandboxplease.InsufficientCreditsError: [insufficient_credits] Balance $0.00 is too low to start this sandbox
  hint: Add credits at https://sandboxplease.com/settings/credits or use your own provider key (BYOK) at https://sandboxplease.com/settings/byok.
  docs: https://sandboxplease.com/docs/errors#insufficient_credits
  request: req_6aa641ea3ed59a24cb563a01
```

Branch on `err.code` or the class: `InsufficientCreditsError` (`.balance`), `KeyLimitError` (the key's credit limit or
daily cap, `.rule`), `NoEligibleProviderError` (`.skipped`), `ProviderError` (`.attempts`), `KeyPolicyError` (`.rule`,
the key policy rule that refused the call), `PermissionDeniedError` (a new account's limits, a suspended account),
`InvalidRequestError`, `NotFoundError`, `SandboxEndedError`, `SandboxPausedError`, `AuthenticationError`,
`RateLimitError` (`.rule` when a key policy limit refused it), `DeviceLimitError`, `APIConnectionError`, `CommandError`,
`FeatureNotLiveError` (`.feature`). `err.hint`, `err.docs_url` and `err.request_id` are there too.

## Configuration

```python
SandboxPlease(
    api_key="sp-v1-...",  # default: SANDBOXPLEASE_API_KEY
    base_url="https://api.sandboxplease.com",  # default: SANDBOXPLEASE_BASE_URL, then this
    timeout=60.0,  # seconds per request
    max_retries=2,  # on 429, 5xx and network errors, with exponential backoff
)
```

Reads, kills, file writes and `sandboxes.create` are retried; `create` sends an `Idempotency-Key`, so a retry never
starts a second sandbox. `exec`, `pause`, `resume` and `snapshot` are not retried.

## Development

```bash
uv sync
uv run ruff format --check . && uv run ruff check . && uv run pyright && uv run pytest
```

End-to-end tests and the rest: [CONTRIBUTING.md](https://github.com/minitap-ai/sandboxplease-sdks/blob/main/CONTRIBUTING.md).

## License

MIT
