Skip to content
Wardcase Docs

Python SDK

The Python SDK wraps the REST API and mirrors the TypeScript SDK with snake_case names. It needs Python 3.10 or later. It has a synchronous client, Vivarium, and an asyncio client, AsyncVivarium, with the same methods.

Terminal window
pip install vivarium
import os
from vivarium import Vivarium
vv = Vivarium(api_key=os.environ["VIVARIUM_API_KEY"], base_url="https://api.wardcase.com")
ArgumentMeaning
api_keyYour API key. Defaults to the VIVARIUM_API_KEY environment variable.
base_urlThe API to call, https://api.wardcase.com. Defaults to https://api. followed by the VIVARIUM_DOMAIN environment variable. With neither set, the constructor raises ValueError.
max_retriesRetries for 429, 502, 503, network errors and, on idempotent calls, other 5xx responses. Default 3.
timeoutTimeout per request in seconds. Default 60.

Use with on the client, or call close() when you are done.

# Returns once the sandbox is running.
sbx = vv.sandboxes.create(
image="python",
size="small",
region="eu-west",
idle_timeout_s=600,
)
print(sbx.id) # sbx_4f9k2m8q1z7x3c5v

create returns once the sandbox is running, and raises if it ends up in any other state. Pass wait=False to get it back while it is still creating. The keyword arguments are the fields of POST /v1/sandboxes: image, size, region, idle_timeout_s, hard_timeout_s, egress_policy_id, env, metadata and snapshot_id. The SDK sends an Idempotency-Key on every create, so a retried request never makes two sandboxes. See Sandboxes for what each argument does.

Sandbox.create(...) takes the same arguments:

from vivarium import Sandbox
# The same call on the class. Without client=, it builds a client from
# VIVARIUM_API_KEY and VIVARIUM_DOMAIN.
sbx = Sandbox.create(client=vv, image="python", region="eu-west")
result = sbx.run("python -c 'print(sum(range(10)))'", timeout_s=60)
print(result.exit_code, result.stdout.strip(), result.duration_ms) # 0 45 ...

A string runs through /bin/sh -c; a list is an argument list with no shell. The result has exit_code, stdout, stderr, duration_ms, truncated (true when the output passed 10 MiB and was cut) and timed_out. A non-zero exit code is a result, not an error. timeout_s defaults to 300 seconds and can be up to 3600. Commands run in /work unless you pass cwd.

Pass on_stdout and on_stderr to receive output while the command runs:

import sys
sbx.run(
"pip install requests",
timeout_s=300,
on_stdout=lambda chunk: sys.stdout.write(chunk),
on_stderr=lambda chunk: sys.stderr.write(chunk),
)
sbx.files.write("/work/app.py", "print('hello')\n")
data = sbx.files.read("/work/app.py") # bytes
print(data.decode())
entries = sbx.files.list("/work")

Paths must be under /work, the sandbox’s writable volume; relative paths are resolved against it. write accepts files up to 50 MiB and creates parent directories. read returns bytes. list returns entries with name, path, type, size, mode and mtime.

# Start a server that listens on all interfaces, then expose its port.
sbx.run("nohup python -m http.server 8000 --bind 0.0.0.0 > /tmp/http.log 2>&1 &")
exposure = sbx.expose(8000, access="public")
print(exposure.url) # https://8000-4f9k2m8q1z7x3c5v.wardcase.com
# Token access (the default) returns the token once.
private = sbx.expose(8080)
print(private.url, private.token)
sbx.unexpose(8080)

expose returns the exposure with its url, and with token access its token, which the API shows only once. The API’s default access is token. See Port exposure.

ssh = sbx.ssh_command()
print(ssh.command) # ssh sbx_4f9k2m8q1z7x3c5v@ssh.wardcase.com
# ssh.token is the password. It expires at ssh.expires_at.

ssh_command() mints a short-lived token and returns command, username, host, port, token and expires_at. Run the command and use the token as the password. See SSH access.

# Returns once the snapshot is ready.
snap = sbx.snapshot(name="deps-installed")
copy = vv.sandboxes.create(snapshot_id=snap.id, region="eu-west")
snaps = vv.snapshots.list(sandbox_id=sbx.id)

snapshot() saves /work and returns once the snapshot is ready, or pass wait=False. Create a new sandbox from it with snapshot_id. vv.snapshots.list() takes an optional sandbox_id, and vv.snapshots.get(snapshot_id) reads one.

page = sbx.audit.list(type="exec.")
for event in page.data:
print(event.type, event.payload)
# Returns once the export is ready.
exported = vv.audit.export(sandbox_id=sbx.id)
print(exported.url) # signed JSONL download, valid for one hour

sbx.audit.list() returns a page of the sandbox’s events with data and next_cursor. vv.audit.list() does the same across the organization with sandbox_id, type, since and until filters. vv.audit.export() takes sandbox_id, since, until and types, and returns once the export is ready, or pass wait=False.

sbx.keepalive() # reset the idle timer
info = sbx.refresh() # reload status and timestamps
print(info.status, info.expires_at)
me = vv.me() # org, scopes of this key
usage = vv.usage(group_by="sandbox")
print(me.org.name, usage.totals.estimated_usd)
sbx.kill()

kill() returns at once. The status moves to stopping, then stopped.

import asyncio
import os
from vivarium import AsyncVivarium
async def main() -> None:
async with AsyncVivarium(api_key=os.environ["VIVARIUM_API_KEY"], base_url="https://api.wardcase.com") as vv:
sbx = await vv.sandboxes.create(image="python", region="eu-west")
result = await sbx.run("python -c 'print(sum(range(10)))'")
print(result.stdout)
await sbx.kill()
asyncio.run(main())

Failed requests raise VivariumError, which carries the problem document’s status, type, title, detail and instance, plus code, the problem slug such as free-tier-limit. See Errors. The SDK retries 429, 502, 503, network errors and, on idempotent calls, other 5xx responses on its own, waiting as long as Retry-After says.

from vivarium import VivariumError
try:
vv.sandboxes.create(image="python", size="large", region="eu-west")
except VivariumError as err:
# err.code is the problem slug, for example "free-tier-limit".
print(err.status, err.code, err.detail)
raise