Python SDK

Integrate sandboxes into your Python web applications.

Python SDK

Create a sandbox, execute code, download results, and stop compute from your application. Python 3.10 or later is required.

Install and authenticate

bash
python3 -m pip install stateset-sandbox==2.8.0
export STATESET_API_KEY='your-api-key'

Create an API key in your verified workspace. The key identifies your workspace automatically. Keep it in a server-side environment variable.

Add a card on the Billing page before your first sandbox. It is not charged while your trial credits last. Without one, creating a sandbox raises PaymentMethodRequiredError (402 PAYMENT_METHOD_REQUIRED), whose billing_url links to that page.

First program

Save this as agent.py, then run python3 agent.py:

python
from pathlib import Path
from stateset_sandbox import Sandbox

with Sandbox.create(
    timeout_seconds=300,
    resource_class="dedicated",
    budget={"max_cost_cents": 100, "max_runtime_seconds": 300, "on_exhausted": "stop"},
) as sandbox:
    print("Run:", sandbox.id)
    sandbox.wait_for_status("running", timeout_seconds=120)
    sandbox.write_file("/workspace/main.py", 'print("Hello from StateSet")')
    result = sandbox.exec(["python3", "/workspace/main.py"], timeout=30_000)
    if result.exit_code != 0:
        raise RuntimeError(result.stderr or "Command failed")
    print(result.stdout, end="")
    Path("main.py").write_bytes(sandbox.read_file_bytes("/workspace/main.py"))

The context manager stops compute on success or failure. Download the files you need before leaving it. If stopping raises, retry sandbox.close() or inspect the run in the dashboard. Cleanup failure remains visible and retryable; the configured lifetime still applies.

For useful workflows, open Templates. The code, browser, and data samples each include a complete downloadable Python program that runs the same source and downloads the same results as the console.

Files and browser screenshots

write_file(path, text) and read_file(path) handle UTF-8 text. Use write_file_bytes(path, data) and read_file_bytes(path) for PNGs, PDFs, archives, or other binary content. Paths inside the sandbox must be under /workspace.

Choose template="browser" for the Playwright and Chromium runtime. A local file downloaded to your application survives sandbox cleanup. Files left only in a temporary sandbox do not.

Async applications

Use AsyncSandbox in an async application. Its create, execute, file and cleanup operations are awaitable:

python
import asyncio
from stateset_sandbox import AsyncSandbox

async def main():
    async with await AsyncSandbox.create(timeout_seconds=300) as sandbox:
        result = await sandbox.exec(["python3", "-c", "print(42)"], timeout=30_000)
        if result.exit_code != 0:
            raise RuntimeError(result.stderr or "Command failed")
        print(result.stdout)

asyncio.run(main())

Limits and cost

timeout_seconds sets the sandbox lifetime in seconds. The timeout argument to exec is a command deadline in **milliseconds**.

Creation accepts cpus, memory, resource_class, budget, template, image, and durable. A template preserves your budget and resource choices. Shared capacity requires at least one vCPU and can be preempted. Availability depends on the deployment.

Run budgets are checked periodically. In-flight work may exceed the limit; review Usage and the run's cost breakdown. See pricing for rates, allowances and the workload calculator.

Reconnect and recovery

Save sandbox.id to reconnect to an existing sandbox with Sandbox.connect(saved_id). Reconnecting does not rerun a command. Inspect an execution receipt after a lost connection before deciding whether another execution is safe.

durable=True requests persistent workspace storage when supported. Workspace persistence does not preserve process memory. Pause, resume, snapshots and forks depend on deployment capabilities; check service status before relying on them. Compute billing stops on a supported pause only after compute suspension is confirmed.

Advanced client

The low-level client exposes execution receipts, artifacts, snapshots and governance APIs. It also derives the workspace from your API key:

python
import os
from stateset_sandbox import StateSetSandbox, CreateSandboxOptions

with StateSetSandbox(
    base_url="https://api.sandbox.stateset.app",
    auth_token=os.environ["STATESET_API_KEY"],
) as client:
    run = client.create(CreateSandboxOptions(timeout_seconds=300))
    try:
        result = client.execute(run.sandbox_id, command=["echo", "Hello"])
        if result.exit_code != 0:
            raise RuntimeError(result.stderr or "Command failed")
        print(result.stdout)
    finally:
        client.stop(run.sandbox_id)

Troubleshooting

  • **401:** Check that the key is valid and belongs to the intended workspace.
  • **403:** Verify your email and the API key's allowed scopes.
  • **402 PAYMENT_METHOD_REQUIRED:** Add a card on the Billing page; it is not charged while your trial credits last.
  • **402 (other):** Check trial credits, billing and run budgets.
  • **429:** Reduce concurrency or wait for the server's retry interval.
  • **Unknown execution outcome:** Inspect the execution receipt and any external effects before retrying a command.
  • **Missing files:** Download or retain artifacts while the sandbox is still available.

Open the dashboard or contact support.