# Sandboxes Run Python and shell commands in short-lived, isolated sandboxes. OpenAI-compatible, plus a direct exec API. A sandbox is a short-lived, isolated environment for running code your product did not ship with, such as code a model wrote, off your own machines. You create one, upload files, run Python or shell commands, read back their output and files, then delete it or let it expire. [The flow](https://docs.privatemind.com/containers.html#the-flow) shows the whole round trip in one script. The API calls a sandbox a container, as OpenAI's Containers API does. The paths are `/v1/containers`, ids start `cntr_`, and the object is a `container`. The sandbox and file endpoints match OpenAI's, so `client.containers.*` and `client.containers.files.*` in the official `openai` client work unchanged. **Execs**, which run code directly, are a PrivateMind addition with no OpenAI equivalent. For a long-lived environment a person works in from the app, use a [workspace](https://docs.privatemind.com/workspaces.html). > [!NOTE] > Sandboxes are switched on per organisation. If every call answers `403` with "Containers are not enabled for this organization", ask your account team. Keys created on the [API keys](https://docs.privatemind.com/api-keys.html) page can use sandboxes. Keys minted through the [key management API](https://docs.privatemind.com/key-management-api.html) are limited to inference, so their sandbox calls answer `403`. ## The flow 1. Create a sandbox with `POST /v1/containers`. 2. Upload input files to `/workspace/` with `POST /v1/containers/{id}/files`. 3. Run code with `POST /v1/containers/{id}/execs`. 4. List and download what the code wrote to `/outputs/` with `GET /v1/containers/{id}/files`. 5. Delete the sandbox with `DELETE /v1/containers/{id}`, or let it expire. ```python from openai import OpenAI client = OpenAI(base_url="https://api.privatemind.com/v1", api_key=PMIND_KEY) code = """ import pandas as pd df = pd.read_csv("/workspace/sales.csv") df.describe().to_csv("/outputs/summary.csv") print(len(df)) """ ct = client.containers.create(name="report") try: with open("sales.csv", "rb") as fh: client.containers.files.create(ct.id, file=("sales.csv", fh)) run = client.post(f"/containers/{ct.id}/execs", body={"code": code}, cast_to=object) if run["status"] != "completed": raise RuntimeError(run) print(run["stdout"]) for f in client.containers.files.list(ct.id): if f.path == "/outputs/summary.csv": content = client.containers.files.content.retrieve(f.id, container_id=ct.id) content.write_to_file("summary.csv") finally: client.containers.delete(ct.id) ``` The `openai` client has no exec methods, so the example calls its generic `client.post` with `cast_to=object`, which returns the parsed JSON. Any HTTP client works the same way. An exec still running after 30 seconds comes back `in_progress`. [Wait for a result](https://docs.privatemind.com/containers.html#wait-for-a-result) shows how to poll for it. ## Create a sandbox **cURL** ```bash curl -s "https://api.privatemind.com/v1/containers" \ -H "Authorization: Bearer $PMIND_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "report", "memory_limit": "1g", "expires_after": {"anchor": "last_active_at", "minutes": 20} }' ``` **Python** ```python ct = client.containers.create( name="report", memory_limit="1g", expires_after={"anchor": "last_active_at", "minutes": 20}, ) print(ct.id, ct.status) # cntr_... running ``` - **`name`** (required): up to 256 characters. Names need not be unique. `GET /v1/containers?name=` filters on it. - **`memory_limit`**: `512m` (1 CPU, a PrivateMind addition for light work), `1g` (1 CPU, the default) or `4g` (2 CPUs). Any other value answers `400`. The `openai` Python SDK's type hints leave out `512m`, but it sends it unchanged. - **`expires_after`**: `{"anchor": "last_active_at", "minutes": N}`, with `minutes` from 1 to 60. Default 20. - **`file_ids`**: up to 20 ids from the [Files API](https://docs.privatemind.com/files.html), copied into `/workspace/` at create. Each must be a file you [can see](https://docs.privatemind.com/files.html#who-can-see-a-file). In a shared sandbox, everyone who can use it sees the copy. - **`network_policy`**: only `{"type": "disabled"}`. Sandboxes have no network access. - **`skills`**: not supported. A non-empty list answers `400`. - **`visibility`**: who can use the sandbox, a PrivateMind addition. See [Who can use a sandbox](https://docs.privatemind.com/containers.html#who-can-use-a-sandbox). Create returns once the sandbox is running. ### Who can use a sandbox A sandbox is either `private` or shared with your org (`org`). A private sandbox belongs to the user who created it and works with any of their keys. To everyone else it doesn't exist: every call on it answers `404`, and lists leave it out. A shared one can be listed, used and deleted by anyone in your org. By default, a sandbox created with an org [application key](https://docs.privatemind.com/key-management-api.html#application-keys) is shared. One created with any other key, including a Notebook or OpenCode token, is private. To choose, pass `"visibility": "org"` or `"visibility": "private"`. From Python, that is `client.containers.create(name="report", extra_body={"visibility": "org"})`. You can't change it after create. ## The sandbox object ```json { "id": "cntr_6c1f0e5b2a9d4e7f8a3b1c2d4e5f6a7b", "object": "container", "name": "report", "created_at": 1781481050, "status": "running", "expires_after": { "anchor": "last_active_at", "minutes": 20 }, "last_active_at": 1781481050, "expires_at": 1781482250, "memory_limit": "1g", "network_policy": { "type": "disabled" }, "visibility": "private" } ``` `status` is one of: - `creating`: a create is in progress. You see this only in the list. - `running`: the sandbox is usable. - `expired`: it sat idle past its window, reached its 8-hour lifetime, or was stopped by a disk cap. - `failed`: it could not start. A sandbox ends as `expired` or `failed`. A deleted sandbox is gone: it answers `404` and leaves the list. `expires_at` and `visibility` are PrivateMind additions. `expires_at` is when the sandbox will expire if nothing touches it, and null once it has ended. ## Expiry A sandbox expires `minutes` after its last activity. These count as activity: - retrieving the sandbox - any call on its files - creating or retrieving an exec - an exec finishing Listing sandboxes or execs does not count. A sandbox never expires while an exec is queued or running. Whatever its activity, it stops 8 hours after it was created. An expired sandbox cannot be revived, so create a new one. `GET /v1/containers/{id}` still answers with `status: "expired"`. You can still list and retrieve its execs, with their code and output cleared. Its files and new execs answer `404`. ## List, retrieve and delete **cURL** ```bash curl -s "https://api.privatemind.com/v1/containers?limit=20" \ -H "Authorization: Bearer $PMIND_KEY" curl -s -X DELETE "https://api.privatemind.com/v1/containers/cntr_abc123" \ -H "Authorization: Bearer $PMIND_KEY" ``` **Python** ```python for c in client.containers.list(): print(c.id, c.name, c.status) ct = client.containers.retrieve(ct.id) client.containers.delete(ct.id) ``` `GET /v1/containers` lists the sandboxes you can use, newest first, with `limit` (1 to 100, default 20), `after`, `order` (`asc` or `desc`) and `name`. Pages carry `has_more`, and the client pages automatically. Delete stops the sandbox at once and answers `{"id": "cntr_...", "object": "container.deleted", "deleted": true}`. After that the sandbox answers `404`. ## Files Files live in two folders. **`/workspace/`** holds what you upload, and it is the working directory. **`/outputs/`** is where code should write results. The file list covers both. ### Upload `POST /v1/containers/{id}/files` takes a multipart `file` part, up to 100 MiB. The file lands at `/workspace/`. To put it elsewhere under `/workspace/`, send a `path`, either as a query parameter or as a form field before the `file` part. **cURL** ```bash curl -s "https://api.privatemind.com/v1/containers/cntr_abc123/files" \ -H "Authorization: Bearer $PMIND_KEY" \ -F path=/workspace/data/sales.csv \ -F file=@sales.csv ``` **Python** ```python f = client.containers.files.create(ct.id, file=("sales.csv", open("sales.csv", "rb"))) print(f.id, f.path) # cfile_... /workspace/sales.csv ``` To copy in a file already in the [Files API](https://docs.privatemind.com/files.html), send JSON instead: `{"file_id": "file-abc123", "path": "/workspace/input.jsonl"}` (`path` optional). The file must be one you can see. ### The file object ```json { "id": "cfile_0a1b2c3d4e5f60718293a4b5c6d7e8f9", "object": "container.file", "created_at": 1781481062, "bytes": 18234, "container_id": "cntr_6c1f0e5b2a9d4e7f8a3b1c2d4e5f6a7b", "path": "/workspace/sales.csv", "source": "user" } ``` `source` is `user` for uploads and `container` for files the code wrote. A file keeps its id for as long as its path exists. ### List, download and delete ```python for f in client.containers.files.list(ct.id): print(f.path, f.bytes, f.source) data = client.containers.files.content.retrieve(f.id, container_id=ct.id).read() client.containers.files.delete(f.id, container_id=ct.id) ``` The list reads the sandbox directly, so files your code wrote appear with no extra step. While an exec is queued or running, the list shows the files as of the last listing, and deleting a file answers `409`. Retry when the execs finish. Content downloads as `application/octet-stream`. Files never leave the sandbox on their own. Download what you want to keep before the sandbox ends. ## Run code An exec runs one piece of code in the sandbox. Call it over HTTP, or with the client's generic `post` as in [the flow](https://docs.privatemind.com/containers.html#the-flow). **cURL** ```bash curl -s "https://api.privatemind.com/v1/containers/cntr_abc123/execs" \ -H "Authorization: Bearer $PMIND_KEY" \ -H "Content-Type: application/json" \ -d '{"code": "x = 6 * 7\nprint(x)"}' ``` **Python** ```python run = client.post(f"/containers/{ct.id}/execs", body={"code": "x = 6 * 7\nprint(x)"}, cast_to=object) print(run["status"], run["stdout"]) # completed 42 ``` A shell command takes `command` instead of `code`: ```bash curl -s "https://api.privatemind.com/v1/containers/cntr_abc123/execs" \ -H "Authorization: Bearer $PMIND_KEY" \ -H "Content-Type: application/json" \ -d '{"type": "shell", "command": "wc -l *.csv", "cwd": "/workspace"}' ``` - **`type`**: `python` or `shell`. Defaults to `shell` when you send `command` and `python` otherwise. - **`code`** (Python): up to 1,000,000 bytes. All Python execs in a sandbox share one interpreter, so variables, imports and loaded data carry over from one exec to the next, as in a notebook. - **`command`** (shell): up to 128 KiB, run by `bash -c` as a fresh process each time. - **`cwd`** and **`env`** (shell only): the working directory (default `/workspace`) and up to 64 environment variables, 32 KiB in all. Environment values are never stored. - **`timeout_ms`**: 1 to 600,000. Default 120,000. - **`wait_ms`**: how long the request waits for the exec to finish, 0 to 60,000. Default 30,000. If the exec hasn't finished by then, you get the exec as it stands, `queued` or `in_progress`. [Poll for the rest](https://docs.privatemind.com/containers.html#wait-for-a-result). - **`stream`**: `true` answers with server-sent events. See [Streaming](https://docs.privatemind.com/containers.html#streaming). Execs in one sandbox run one at a time. A second exec waits as `queued` until the first finishes, so use more sandboxes for parallel work. Up to 16 can be queued or running per sandbox. More answer `429` with `too_many_execs`. ### The exec object ```json { "id": "cexec_9f8e7d6c5b4a39281706f5e4d3c2b1a0", "object": "container.exec", "container_id": "cntr_6c1f0e5b2a9d4e7f8a3b1c2d4e5f6a7b", "type": "python", "status": "completed", "code": "x = 6 * 7\nprint(x)", "command": null, "cwd": null, "created_at": 1781481070, "started_at": 1781481070, "completed_at": 1781481070, "exit_code": null, "stdout": "42\n", "stderr": "", "outputs": [], "error": null, "execution_time_ms": 12, "timeout_ms": 120000, "truncated": false } ``` `status` moves from `queued` to `in_progress`, then ends as one of: - **`completed`**: the code ran to the end. For a shell command this includes a non-zero exit, so read `exit_code`. - **`failed`**: Python raised an exception, the shell command could not start (for example, `cwd` does not exist), or the sandbox stopped under the exec. `error` holds `name` and `message`, plus `traceback` for a Python exception. If the platform loses an exec mid-run, for example during a restart, it ends `failed` with `error.name` `ExecLost`. Run it again. - **`timed_out`**: the exec ran past `timeout_ms`. A Python exec is interrupted and the interpreter stays usable. A shell command is killed and reports `exit_code` 124. - **`cancelled`**: you cancelled it, or its sandbox was deleted or stopped first. `outputs` carries rich Python results, such as the last expression's value or a chart, as `{"type", "mime", "data"}` items. Images are base64. Stored output is capped per exec at 1 MiB each for `stdout` and `stderr` and 4 MiB for `outputs`, and at 32 MiB across all execs in a sandbox. Past a cap, `truncated` is `true`. For larger results, write a file to `/outputs/` and download it. ### Wait for a result `GET /v1/containers/{id}/execs/{exec_id}` returns the exec. Add `?wait_ms=` (up to 60,000) to hold the request until the exec finishes or the wait runs out: ```python long_job = "import time\ntime.sleep(90)\nprint('done')" run = client.post(f"/containers/{ct.id}/execs", body={"code": long_job, "wait_ms": 0}, cast_to=object) while run["status"] in ("queued", "in_progress"): run = client.get( f"/containers/{ct.id}/execs/{run['id']}", options={"params": {"wait_ms": 30000}}, cast_to=object, ) print(run["status"]) ``` `GET /v1/containers/{id}/execs` lists a sandbox's execs, newest first, with `limit`, `after` and `order`. ### Streaming With `"stream": true` the exec answers `text/event-stream`, and output arrives as it is printed. Each event's data carries the event name in `type`. `exec.created` and `exec.completed` also carry the exec under `exec`. ```text event: exec.created data: {"type": "exec.created", "exec": {"id": "cexec_...", "status": "queued", ...}} event: exec.started data: {"type": "exec.started"} event: exec.stdout data: {"type": "exec.stdout", "text": "0\n"} event: exec.completed data: {"type": "exec.completed", "exec": {"id": "cexec_...", "status": "completed", "stdout": "0\n1\n2\n", ...}} ``` The other events are `exec.stderr` (`text`), `exec.output` (`output_type`, `mime`, `data`) and `exec.error` (`name`, `message`, `traceback`). Every stream ends with `exec.completed`, including when the exec was cancelled or its sandbox stopped. Lines starting with `:` are keepalives; skip them if you parse the stream yourself. **cURL** ```bash curl -sN "https://api.privatemind.com/v1/containers/cntr_abc123/execs" \ -H "Authorization: Bearer $PMIND_KEY" \ -H "Content-Type: application/json" \ -d '{"code": "for i in range(3):\n print(i)", "stream": true}' ``` **Python** ```python from openai import Stream events = client.post( f"/containers/{ct.id}/execs", body={"code": "for i in range(3):\n print(i)", "stream": True}, cast_to=object, stream=True, stream_cls=Stream[object], ) for event in events: if event["type"] == "exec.stdout": print(event["text"], end="") elif event["type"] == "exec.completed": run = event["exec"] ``` Read the stream as it arrives. A client that falls more than a few seconds behind is cut off. Its last `exec.completed` may then show the exec still running, so retrieve the exec for its result. ### Cancel an exec `POST /v1/containers/{id}/execs/{exec_id}/cancel` stops an exec and returns it. A queued exec is dropped before it runs. A running Python exec is interrupted with `KeyboardInterrupt` and the interpreter keeps its state. A running shell command is killed with everything it started. The next queued exec then runs. ## Limits and retention - **Sizes**: `512m` (1 CPU), `1g` (1 CPU) and `4g` (2 CPUs). A `512m` sandbox counts half as much as a `1g` one against the allowance below. - **Idle expiry**: 20 minutes by default, 60 at most. - **Lifetime**: 8 hours from creation, however busy the sandbox is. - **Disk**: 2 GiB in `/workspace`, 1 GiB in `/outputs` and 512 MiB in `/tmp`. Going over one stops the sandbox. - **Sandboxes per person**: 10 live at a time, across all of a person's keys. Another create answers `429` with `container_user_cap_exceeded`. Delete one or wait for one to expire. An org [application key](https://docs.privatemind.com/key-management-api.html#application-keys) has no per-person cap, only the org's memory allowance. - **Memory across the org**: your org's live sandboxes share a memory allowance. A create that would go over it answers `429` with `container_memory_cap_exceeded`. Delete a sandbox or wait for one to expire. - **Files**: up to 100 MiB per upload or download. - **Execs**: one at a time per sandbox, up to 16 queued or running, each up to 10 minutes. - **Network**: none. Code cannot reach the internet or any other service, so bring data in as files. - **Retention**: code, output and files exist only while the sandbox lives. When it ends, files go with it and the stored code, output and Python errors of its execs are cleared. Timings, exit codes and sizes are kept. Environment values are never stored. ## Errors Errors use the usual [error shape](https://docs.privatemind.com/errors.html), and the usual `401`, `402` and rate-limit `429` apply. The sandbox-specific ones: | Status | Code | Meaning | | --- | --- | --- | | `400` | `unsupported_memory_limit`, `invalid_minutes`, `invalid_path`, … | A parameter is missing, invalid or out of range; `param` names it | | `403` | `permission_error` | Sandboxes are not enabled for your org, or the key is limited to inference | | `404` | `not_found` | No such sandbox, file or exec in your org, or it's deleted or private to someone else. Files and new execs also answer `404` once the sandbox has ended | | `409` | `conflict` | The sandbox is still starting, or (file delete) an exec is queued or running; retry shortly | | `413` | `file_too_large` | An upload or download over 100 MiB | | `429` | `container_memory_cap_exceeded` | Your org's live sandboxes hold its whole memory allowance; delete one or wait for one to expire | | `429` | `container_user_cap_exceeded` | You already have 10 live sandboxes; delete one or wait for one to expire | | `429` | `too_many_execs` | 16 execs already queued or running in this sandbox | | `502` | `upstream_error` | The sandbox did not complete a file operation; try again | | `503` | `service_unavailable` | The sandbox could not be started; try again | ## Where next - [API explorer](https://docs.privatemind.com/api-explorer.html): every sandbox call, with a Try it console. - [Files](https://docs.privatemind.com/files.html): upload a file once and copy it into sandboxes by id. - [OpenAI SDK](https://docs.privatemind.com/openai-sdk.html): pointing the official client at PrivateMind. - [Errors](https://docs.privatemind.com/errors.html): status codes and the error shape.