Sandbox SDK for Python and TypeScript
Updated
Install the Python SDK (pip install prized) or the TypeScript SDK (npm i @prized/sdk) to create sandboxes from your code, run commands, pause them with their memory, and fork a running or paused sandbox into live copies with its memory and processes, on the same account and balance as your Prized boxes.
On this page10
Each sandbox is a Firecracker microVM. A paused one keeps its memory and running processes, bills storage only, and the next command resumes it, usually in under a second (Pause and resume).
1. Install the SDK
python3 -m venv .venv && . .venv/bin/activate
pip install prizedThe first line makes a virtual environment, since Ubuntu, Debian and Homebrew refuse pip install into the system Python (if it says ensurepip is not available, run sudo apt install python3-venv first; on Windows, run py -m venv .venv, then .venv\Scripts\activate). It needs Python 3.10 or later: on 3.9, pip answers No matching distribution found for prized. On a Mac, whose own python3 is 3.9, uv gets you a newer one: uv venv -p 3.13 && uv pip install prized makes the environment and fetches Python 3.13 if you don't have it, then uv run hello.py runs the file.
The Python SDK needs Python 3.10 or later, and its one dependency is httpx. The TypeScript SDK runs on Node 18 or later, Bun, or Deno, with no dependencies. Both are Apache-2.0, and each README has every call and option: Python, TypeScript.
2. Export an API key
Open Sandboxes and choose Create API key (new to Prized, it signs you up with the free credit, no card), or make one at https://prized.dev/dashboard/workspace/api-keys with Full access, or Custom with Sandboxes: Write. The SDKs and the helpers below read it from PRIZED_API_KEY; never paste a key into code.
export PRIZED_API_KEY=dcp_…On Windows, in PowerShell: $env:PRIZED_API_KEY = "dcp_…".
On the free credit, sandboxes run within the free tier: up to 10 at once, each up to 2 vCPU and 4 GB and 60 minutes of running, then deleted. A top-up from $10 at https://prized.dev/dashboard/billing?lift=sandboxes#credit lifts it to the workspace quotas.
3. Run a sandbox
from prized import Sandbox
with Sandbox.create() as sb: # returns once it answers commands
print(sb.exec("python3 --version").stdout, end="")
# leaving the block deletes the sandboxThen run the file for your language:
python3 hello.pynode hello.mtsNode 22.18 or later runs the TypeScript file as it is; on Node 18 to 22.17, run npx tsx hello.mts instead. Each prints Python 3.12.3 and deletes the sandbox. The SDK waits for a new sandbox, retries what is safe to retry, and can stream a long command's output (on_stdout, onStdout) or run it in the background.
For a LangChain Deep Agent, pip install langchain-prized runs the agent's shell commands and file tools in a sandbox (LangChain).
For the OpenAI Agents SDK, pip install openai-agents-prized runs a SandboxAgent's commands and file edits in a sandbox (OpenAI Agents).
Pause, fork and long commands
These are the calls most people reach for next. The file makes a sandbox that is deleted after 30 minutes of running, writes a script into it and runs it in the background while streaming its output, pauses and resumes the sandbox, and forks it into two live copies.
from prized import Sandbox
with Sandbox.create(max_runtime_min=30) as sb: # deleted after 30 minutes of running
sb.files.write("count.py", "import time\nfor i in range(3):\n print(i, flush=True)\n time.sleep(1)\n")
job = sb.exec("python3 count.py", background=True) # returns at once
job.wait(on_stdout=lambda out: print(out, end="")) # 0, 1, 2 as they print
sb.pause() # memory and disk kept, no compute billed
sb.resume() # every process carries on
for copy in sb.fork(2): # two live copies, count.py included
print(copy.id, copy.exec("ls").stdout, end="")
copy.delete()It prints 0, 1 and 2 a second apart, then each copy's id and count.py. Each copy starts with the parent's disk, memory and running processes as they were at the fork (Fork). files.upload() copies a local file in. A write keeps the mode of a file it replaces, so a script you made executable stays executable; pass mode (0o755) to set one.
Run it with python3 next.py or node next.mts. A command run in the foreground stops after 60 seconds unless you pass timeout (seconds, Python) or timeoutMs (TypeScript), 0 for none; one in the background has no limit unless you give it one. A foreground command keeps the first 4 MiB of each output stream (truncated says when it cut one): for builds and test suites, pass full_output=True (Python) or fullOutput: true (TypeScript) to keep up to 100 MiB. A streamed or long command, a background command's start, and its wait() ride out a dropped connection for up to 2 minutes (the command still runs once): the SDK then stops a streamed or long command, while wait() leaves its command running (set poll_outage in seconds in Python or pollOutageMs in TypeScript, on the call or the client).
Preview a port
A server in the sandbox answers at its port's URL (Preview a port). The file starts one on port 3000, calls it with your key, then makes a 10-minute token: its browser URL opens the page in a browser tab, and its plain URL serves a client that cannot send a header, such as a WebSocket in a web page. The key works on every workspace; a token or a public port needs one that has paid in (on the free credit alone, the token line stops with 402 share_links_need_payment).
import time
import httpx
from prized import Sandbox
with Sandbox.create() as sb:
sb.exec("python3 -m http.server 3000 --bind 127.0.0.1", background=True)
time.sleep(1) # let the server start
page = httpx.get(sb.preview_url(3000), headers=sb.preview_headers()) # follows no redirect
print(page.status_code)
link = sb.preview_token(3000, expires_in=600)
print(link.browser_url, link.expires_at) # open in a browser for the next 10 minutesSend the key's headers only to the preview URL, and follow no redirect with them: fetch resends headers to whatever host a redirect names. set_port_public(3000, True) (Python) or setPortPublic(3000, true) (TypeScript) opens the port to anyone with its URL (its browser_url or browserUrl opens in a browser), for 7 days unless you pass expires_in or expiresIn, and False or false closes it again; only the workspace owner's key makes a port public.
No dependency: copy a helper
The Sandbox API is plain HTTPS with a bearer key, so one short file also works: the Python helper uses only the standard library, and the TypeScript one only fetch. Copy one into your project and replace the demo at its end with your own steps. From a shell, the CLI does the same.
Save a helper
import json, os, time, urllib.error, urllib.parse, urllib.request
API = "https://api.prized.dev/api/v1"
KEY = os.environ["PRIZED_API_KEY"] # never hardcode a key
FREE = "That is a free-tier limit: a top-up or a plan lifts it, at https://prized.dev/dashboard/billing?lift=sandboxes#credit"
# write() runs this to put an upload in place with the mode of the file it replaces
PUT = """trap 'rm -f -- "$SRC"' EXIT
if [ -L "$DST" ] || { [ -e "$DST" ] && [ ! -f "$DST" ]; }; then exit 47; fi
if [ -e "$DST" ]; then chmod --reference="$DST" -- "$SRC" && chmod a-st -- "$SRC" || exit; fi
mv -fT -- "$SRC" "$DST" || exit
sync -- "$(dirname -- "$DST")" 2> /dev/null || true"""
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args): # urllib would resend the key to wherever a redirect points
return None # so a 3xx raises HTTPError instead
OPEN = urllib.request.build_opener(NoRedirect).open
def call(method, url, body=None, data=None):
headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/octet-stream"}
if body is not None:
data, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
try:
with OPEN(urllib.request.Request(url, data, headers, method=method), timeout=3660) as r:
out = r.read()
return json.loads(out) if r.headers.get_content_type() == "application/json" else out
except urllib.error.HTTPError as e:
out = e.read()
err = json.loads(out) if out.startswith(b"{") else {"error": out[:200]}
hint = FREE if err.get("tier") == "free" else ""
e.msg = f"{err} {hint}" # str(e) is now "HTTP Error 429: {'error': ...} That is a free-tier limit ..."
raise
class Sandbox:
def __init__(self, id):
self.id = id
@classmethod
def create(cls, template="prized-base-v1"):
body = {"template": template, "resources": {"vcpu": 2, "memoryMb": 4096}, "maxRuntimeMin": 60}
return cls(call("POST", f"{API}/sandboxes", body)["sandbox"]["id"])
def wait(self): # until running, when it takes commands
while (sbx := call("GET", f"{API}/sandboxes/{self.id}")["sandbox"])["state"] == "starting":
time.sleep(1)
if sbx["state"] != "running":
raise RuntimeError(f"{self.id} is {sbx['state']}: {sbx['errorReason']}")
self.toolbox = sbx["toolboxBase"]
return self
def exec(self, command, retry=(409, 429), **opts): # opts: cwd, env, timeout
for i in range(6):
try:
return call("POST", f"{self.toolbox}/process/execute", {"command": command, **opts})
except urllib.error.HTTPError as e: # 409 and 429 come before the command runs
if e.code not in retry or i == 5:
raise
time.sleep(i + 1)
def write(self, path, data: bytes): # uploads beside path, then renames it over path
tmp = path[: path.rfind("/") + 1] + f".prized-write-{os.urandom(16).hex()}"
call("POST", f"{self.toolbox}/files/upload?path={urllib.parse.quote(tmp)}", data=data)
out = {"exitCode": -1}
try:
out = self.exec(PUT, env={"SRC": tmp, "DST": path}, cwd="/", timeout=60)
finally:
if out["exitCode"] < 0: # it never ran, or was stopped before it cleaned up
try:
self.exec('rm -f -- "$SRC"', env={"SRC": tmp}, cwd="/")
except Exception:
pass
if out["exitCode"] == 47: # a link, or not a file: the files API follows or refuses it
call("POST", f"{self.toolbox}/files/upload?path={urllib.parse.quote(path)}", data=data)
elif out["exitCode"] != 0:
raise RuntimeError(f"could not write {path} (exit {out['exitCode']}): {out['stderr']}")
def read(self, path) -> bytes:
return call("GET", f"{self.toolbox}/files/download?path={urllib.parse.quote(path)}")
def fork(self, count):
out = call("POST", f"{API}/sandboxes/{self.id}/fork", {"count": count})
return [Sandbox(s["id"]) for s in out["sandboxes"]]
def delete(self):
call("DELETE", f"{API}/sandboxes/{self.id}")
sbx, kids = Sandbox.create(), []
try:
print(sbx.wait().exec("python3 --version")["stdout"], end="")
sbx.write("/home/prized/work/hello.txt", b"hello from Python\n")
print(sbx.read("/home/prized/work/hello.txt").decode(), end="")
kids = sbx.fork(2) # two live copies, hello.txt included
for kid in kids:
print(kid.id, kid.wait().exec("cat hello.txt")["stdout"], end="")
finally:
for s in [sbx, *kids]:
try:
s.delete()
print("deleted", s.id)
except Exception as e: # try the rest; maxRuntimeMin removes this one anyway
print("could not delete", s.id, e)Run it
The demo creates a 2 vCPU, 4 GB sandbox that deletes itself after 60 minutes, runs a command, writes and reads a file, forks two copies that already have the file, and deletes all three. Python needs 3.8 or later:
python3 sandbox.pyNode 22.18 or later runs the TypeScript file as it is; on Node 18 to 22.17, run npx tsx sandbox.mts instead. Older Node has no global fetch, so upgrade it first.
node sandbox.mtsA run of the Python file prints:
Python 3.12.3
hello from Python
sbx_2f7f62ea3f77116f hello from Python
sbx_0426aba73aa4e2ff hello from Python
deleted sbx_723373199c11b589
deleted sbx_2f7f62ea3f77116f
deleted sbx_0426aba73aa4e2ffThe TypeScript file prints the same with v22.23.3 and hello from TypeScript.
What the helper handles
- Waiting. A create answers while the sandbox is
starting.wait()reads it untilrunning, and keeps itstoolboxBase(where its commands and files go). Arunningsandbox takes commands at once. - Retries.
exec()retries409 sandbox_not_runningand429 rate_limited, which come before a command runs, up to 5 times. It never retries502 sandbox_unreachable, since the command may have run; for one that is safe to run twice, passretry=(409, 429, 502)in Python or[409, 429, 502]as the third argument in TypeScript. - Cleanup.
finallydeletes the sandbox and each fork even when a step or another delete fails, andmaxRuntimeMin: 60deletes anything left behind. - Files.
write()keeps the mode of a file it replaces, so a script you made executable stays executable.read()returns bytes, so archives and images arrive intact; decode text yourself, as the demo does. - Long commands. A command runs for up to 300 seconds unless you pass
timeout(3,600 at most). Node'sfetchstops waiting for an answer after 300 seconds, so in TypeScript run a job that may take that long in the background, such asnohup ./job.sh > job.log 2>&1 &, and readjob.logwith later commands.
Errors
The SDKs raise PrizedError, and a helper's error carries the same API status and body: the error code, and fields such as reason or fits. When a free-tier limit refused the request, the body has "tier": "free", and the message names the limit and links the Billing section that lifts it (billing.url in the body). The ones you are most likely to see (every code):
| Error | Means | Do |
|---|---|---|
401 unauthorized or token_expired | The key was refused: mistyped, revoked or expired | Make a new one at https://prized.dev/dashboard/workspace/api-keys and export it again. No account yet? A coding agent can make one with your email address (Agent sign-in) |
404 not_found for a sandbox | It was deleted, by a delete or when its run time ended (60 minutes of running on the free tier) | Create a new one; more than 60 minutes of run time needs a top-up or a plan |
429 sandbox_quota_exceeded | A quota or free-tier limit, named in reason. Paused sandboxes keep their disk | Delete sandboxes you are done with (for sandbox_limit, pausing one also works if your disk quota has room). On the free tier, a top-up or a plan at https://prized.dev/dashboard/billing?lift=sandboxes#credit lifts the limits; past the workspace quotas, email to raise them |
422 invalid_resources | A shape outside the template's bounds (32 vCPU and 128 GB at most), or the free tier's 2 vCPU and 4 GB | Ask for less. On the free tier, a top-up or a plan at https://prized.dev/dashboard/billing?lift=sandboxes#credit lifts it to 32 vCPU and 128 GB |
409 fork_capacity | The parent's machine has room for only fits more copies | Fork fits or fewer; at fits: 0, fork a new sandbox instead, or wait |
A command run with full_output=True (Python) or fullOutput: true (TypeScript) whose output can't be read back afterwards raises output_read_failed, as OutputReadError. The command ran: the error has its exit code, reason says what stopped the read, and the output stays in the sandbox at stdout_path / stdoutPath for an hour, so read it from there rather than run the command again. If the sandbox was deleted before the read, the error is sandbox_deleted, still with the exit code, and the output went with the sandbox. If the sandbox couldn't save the output as it came, most often because its disk is full, the result is cut where the write failed, with truncated set and truncated_reason / truncatedReason write_failed.