Quickstarts
Your first code sandbox
Create an isolated, short-lived sandbox, run Python, JavaScript and shell code in it, stream a run’s output, move files in and out, and end it so billing stops.
A code sandbox is a small, isolated machine for running code you did not write yourself, such as code an AI agent generates. You send it code, it runs the code and answers with the output. Every sandbox is its own container under gVisor, an extra kernel boundary between the code and the host, and it is short-lived by design: it ends by itself, and nothing in it survives its end.
Lifetime and billing
A sandbox is billed per second from the moment it starts, at its size's price, until it ends. GET /v1/sandboxes/sizes lists the sizes with their per-hour and per-second prices; the default is cpu-2c-4gb. Sandboxes never get GPUs.
A sandbox ends in one of three ways:
- At its deadline.
lifetime_seconds(default 3600) sets how long it lives.POST /v1/sandboxes/{sandbox_id}/extendmoves the deadline later, but never more than 24 hours after the sandbox was created;lifetime.max_expires_atsays how far it can go. - When it is idle. With no run and no file operation for
idle_timeout_seconds(default 900), it ends. A run in progress counts as activity, andlifetime.idle_expires_atshows when the idle timeout falls due. - When you end it.
POST /v1/sandboxes/{sandbox_id}/endcuts off any run in progress, deletes the sandbox's files and stops billing.
end_reason records which of these happened (requested, expired, idle, or billing when the organization runs out of credit). Nothing is kept after a sandbox ends except its run records, which stay readable for 7 days. Anything you want to keep, download first.
What a sandbox costs
A sandbox costs its size's per-second price for every second from start to end, whether code is running or not. The usage field of a sandbox shows the seconds billed so far and their cost. Short lifetimes and idle timeouts keep a forgotten sandbox from costing more than a few minutes. See How compute is billed.
Before you start
| Variable | Value |
|---|---|
API_KEY | sk_… (your project API key) |
API_BASE_URL | https://api.hayonix.ai/v1 |
INFERENCE_BASE_URL | https://api.hayonix.ai/v1 |
The samples read REGION. A project can hold up to 5 live sandboxes, and the organization's sandboxes quota applies as well (see Quotas and limits).
Create a sandbox
The call answers at once with the sandbox in starting. It is placed on a machine and started in the background.
SANDBOX_ID=$(
jq -n --arg region "$REGION" '{
name: "quickstart",
region: $region,
size: "cpu-2c-4gb",
lifetime_seconds: 1800
}' |
curl -sS --fail-with-body "$API_BASE_URL/sandboxes" \
-H "$AUTH" -H "Content-Type: application/json" -d @- |
jq -r .id
)
echo "created $SANDBOX_ID"Wait until it is ready
A sandbox moves from starting to ready (waiting for code) and is busy while code runs. You do not have to wait for ready: a run sent while the sandbox starts waits for it. The samples wait explicitly so that the first run answers within the client's usual timeout.
while STATE=$(curl -sS --fail-with-body "$API_BASE_URL/sandboxes/$SANDBOX_ID" -H "$AUTH" |
jq -r .status.state)
[ "$STATE" = starting ]; do sleep 2; done
[ "$STATE" = ready ] || { echo "sandbox is $STATE"; exit 1; }
echo "state: $STATE"Run code
POST /v1/sandboxes/{sandbox_id}/runs takes a language and the code, and by default answers when the run has finished, with its whole output.
run() { # run LANGUAGE CODE [QUERY]: prints the run record
jq -n --arg language "$1" --arg code "$2" '{language: $language, code: $code}' |
curl -sS --fail-with-body "$API_BASE_URL/sandboxes/$SANDBOX_ID/runs${3:-}" \
-H "$AUTH" -H "Content-Type: application/json" -d @-
}
run python 'x = 21 * 2' >/dev/null
# One Python interpreter per sandbox: `x` is still defined in the next run.
OUT=$(run python 'print(x)')
echo "$OUT" | jq -r '"outcome: \(.outcome) exit code: \(.exit_code)", "stdout: \(.stdout | rtrimstr("\n"))"'
[ "$(echo "$OUT" | jq -r '.stdout | rtrimstr("\n")')" = 42 ] || { echo "expected 42"; exit 1; }The language decides what carries over from one run to the next:
| Language | How it runs | What carries over |
|---|---|---|
python | One interpreter per sandbox; runs queue for it | Variables, imports and functions, and files |
javascript | A fresh Node process per run | Files |
shell | A fresh bash process per run | Files |
Every run starts in /workspace, and files there persist for the sandbox's life whatever the language. Python comes with numpy, pandas, matplotlib, pillow and requests installed. Code is at most 256 KiB, and stdin (given to the code on standard input) at most 1 MiB. Up to 4 runs can be in progress in one sandbox at a time.
The run record
A run is queued, then running, then completed (it ran) or error (it could not run; error says why). A completed run has exit_code, stdout and stderr, and outcome sums it up in one word: succeeded, failed (a non-zero exit code), or the reason it was stopped.
Each run has two limits you can set:
timeout_seconds: default 60, at most 900.max_output_bytes: stdout and stderr together, default 1 MiB, at most 4 MiB.
When a run is stopped before it finishes, cut_off says why:
cut_off | Meaning |
|---|---|
time_limit | It ran past timeout_seconds |
output_limit | It printed more than max_output_bytes |
out_of_memory | It ran out of memory |
cancelled | It was cancelled (POST …/runs/{run_id}/cancel) |
sandbox_ended | The sandbox ended while it ran |
When a Python run ends with the interpreter gone (it crashed, ran out of memory, or had to be killed to stop at its limit), that run has state_reset: true: the next run starts a fresh interpreter, so variables from earlier runs are gone. Files are still there.
The response to the run carries all of its output, up to its cap. The record kept afterwards (GET …/runs/{run_id}, GET …/runs) holds the first 64 KiB of each stream, and output.truncated says when that copy is shorter than what the run printed.
Retries never run code twice
Running code is a creating call, so it takes an Idempotency-Key (the SDKs send one for you). A retry with the same key attaches to the first run instead of starting another. See Idempotency.
Stream a run's output
For a long run, ask for the run back at once with wait=false and follow its output as it is produced from GET /v1/sandboxes/{sandbox_id}/runs/{run_id}/events, a server-sent event stream. (stream=true on the run request answers with the same stream directly.)
# ?wait=false answers at once with the queued run; its events carry the output live.
RUN_ID=$(run shell 'for i in 1 2 3; do echo "tick $i"; sleep 1; done' '?wait=false' | jq -r .id)
# The stream ends after its `end` event; `output` events carry {stream, text}.
EVENT=""
curl -sS -N --fail-with-body "$API_BASE_URL/sandboxes/$SANDBOX_ID/runs/$RUN_ID/events" -H "$AUTH" |
while IFS= read -r line; do
case "$line" in
"event: "*) EVENT="${line#event: }" ;;
"data: "*) if [ "$EVENT" = output ]; then printf '%s' "${line#data: }" | jq -j .text; fi ;;
esac
done
curl -sS --fail-with-body "$API_BASE_URL/sandboxes/$SANDBOX_ID/runs/$RUN_ID" -H "$AUTH" |
jq -r '"streamed run: \(.outcome)"'The stream sends these events, in order:
| Event | Data |
|---|---|
run | The run record, as it was when the stream opened |
started | started_at, once the run leaves the queue |
output | stream (stdout or stderr) and text, as the code prints it |
run | The finished run record |
end | The stream is over |
A run's live output can be replayed from the start for an hour after the run ends; after that the stream sends the recorded output instead.
Move files in and out
Files live in the sandbox's workspace, /workspace. Every file route takes a path relative to it (data/numbers.csv; a leading /workspace/ is accepted too). A path containing .. is refused, so no path can reach outside the workspace.
PUT /v1/sandboxes/{sandbox_id}/files/content?path=…uploads a file as the multipart partfile, replacing any file at that path and creating parent directories.GET /v1/sandboxes/{sandbox_id}/files?path=…lists a directory.GET /v1/sandboxes/{sandbox_id}/files/content?path=…downloads a file, streamed.DELETE /v1/sandboxes/{sandbox_id}/files?path=…deletes a file, or a directory with everything in it.
A file is at most 64 MiB each way, and the whole workspace shares the sandbox's disk. File operations count as activity for the idle timeout.
# Paths are relative to /workspace; parent directories are created.
printf 'n\n1\n2\n3\n' > "$WORK/numbers.csv"
curl -sS --fail-with-body -X PUT "$API_BASE_URL/sandboxes/$SANDBOX_ID/files/content?path=data/numbers.csv" \
-H "$AUTH" -F "file=@$WORK/numbers.csv" >/dev/null
curl -sS --fail-with-body "$API_BASE_URL/sandboxes/$SANDBOX_ID/files?path=data" -H "$AUTH" |
jq -r '.data[] | "file: \(.path) \(.size) bytes"'
run python 'import csv
with open("data/numbers.csv") as f:
print("sum:", sum(int(row["n"]) for row in csv.DictReader(f)))' | jq -r '.stdout | rtrimstr("\n")'
curl -sS --fail-with-body "$API_BASE_URL/sandboxes/$SANDBOX_ID/files/content?path=data/numbers.csv" \
-H "$AUTH" -o "$WORK/downloaded.csv"
echo "downloaded numbers.csv ($(wc -c < "$WORK/downloaded.csv") bytes)"
cmp -s "$WORK/numbers.csv" "$WORK/downloaded.csv" || { echo "changed"; exit 1; }End it
end_sandbox() {
curl -sS --fail-with-body -X POST "$API_BASE_URL/sandboxes/$SANDBOX_ID/end" -H "$AUTH" |
jq -r '"ended \(.id) \(.status.state)"'
rm -rf "$WORK"
}
trap end_sandbox EXITNetwork
A sandbox can reach the internet, so code can download packages and data. It can never reach the machine it runs on, the cloud provider's metadata service, the platform's control plane or anything belonging to another customer. Each project's sandboxes sit on a sandbox network of their own, apart from the project's pods. The platform never opens a port into a sandbox: code and files reach it only through the API.
A key for an AI agent
An agent that writes and runs code needs to reach sandboxes and nothing else. In the console, create an API key with only the Sandboxes scopes (sandbox:*: sandbox:read, sandbox:create, sandbox:update, sandbox:delete) and give the agent that key. It can create sandboxes, run code, move files, extend and end sandboxes in its project, and gets 403 for everything else, such as pods, secrets or models. See Projects and API keys.
Next
- Sandboxes API reference: every route and field.
- Your first pod: a container that keeps running until you stop it, with the hardware you choose.