Python SDK
tangle-sandbox drives sandboxes from Python: create one, run commands, read and write text files, give a coding agent a task, snapshot the workspace and delete it.
Sandbox is the synchronous client and AsyncSandbox is its asyncio twin with the same methods.
Install
The SDK needs Python 3.10 or newer.
pip install tangle-sandbox| Extra | Adds | Unlocks |
|---|---|---|
tangle-sandbox[gateway] | websockets | tangle_sandbox.session_gateway, a WebSocket client for a session’s live events |
tangle-sandbox[tangle] | web3, eth-account | tangle_sandbox.tangle, which creates sandboxes on Tangle Network operators |
tangle-sandbox[all] | both | both |
Everything else, including fleets, batches, secrets, teams and trace export, is in the base install.
Create a client
import os
from tangle_sandbox import Sandbox
client = Sandbox(
api_key=os.environ["TANGLE_API_KEY"],
base_url="https://sandbox.tangle.tools",
)Pass both arguments. The SDK reads no environment variables and has no default host.
Keys start with sk-tan-; create one at id.tangle.tools/app/keys. API keys and tokens covers scopes and budgets.
timeout_ms (default 30000) bounds each request. Use the client as a context manager, or call client.close(), to close its connection pool.
Run your first sandbox
import os
from tangle_sandbox import Sandbox, SandboxStatus
with Sandbox(
api_key=os.environ["TANGLE_API_KEY"],
base_url="https://sandbox.tangle.tools",
) as client:
box = client.create(name="hello-python")
try:
# create() returns before the sandbox runs; runtime calls need RUNNING.
box.wait_for(SandboxStatus.RUNNING)
result = box.exec("python3 -c 'print(sum(range(1_000_000)))'")
print(result.exit_code, result.stdout.strip())
box.write("notes.md", "first draft\n")
print(box.read("notes.md").strip())
turn = box.prompt("Reply with exactly the word OK")
if not turn.success:
raise RuntimeError(turn.error)
print(turn.response)
finally:
box.delete()0 499999500000
first draft
OKA sandbox created without a backend runs the opencode coding agent. Run a coding agent shows how to pick Claude Code, Codex or another one.
Stop and resume
stop() keeps the disk and stops billing for compute. resume() starts it again; wait for RUNNING before the next runtime call.
box.write("notes.md", "first draft\n")
box.stop()
print(box.status.value)
box.resume()
box.wait_for(SandboxStatus.RUNNING)
print(box.read("notes.md").strip())stopped
first draftAsync client
import asyncio
import os
from tangle_sandbox import AsyncSandbox, SandboxStatus
async def word_count(client: AsyncSandbox, text: str) -> str:
box = await client.create()
try:
await box.wait_for(SandboxStatus.RUNNING)
await box.write("input.txt", text)
return (await box.exec("wc -w < input.txt")).stdout.strip()
finally:
await box.delete()
async def main() -> None:
async with AsyncSandbox(
api_key=os.environ["TANGLE_API_KEY"],
base_url="https://sandbox.tangle.tools",
) as client:
texts = ["one two three", "four five", "six"]
print(await asyncio.gather(*(word_count(client, t) for t in texts)))
asyncio.run(main())['3', '2', '1']Things that catch Python users
create()returns while the sandbox is stillpendingorprovisioning.exec,read,write,search,prompt,gitandsnapshotraiseStateErroruntil you callwait_for(SandboxStatus.RUNNING).- Pass
SandboxStatusmembers, not strings.wait_for("running")raisesAttributeErrorinstead ofTimeoutErrorwhen it times out, andListSandboxOptions(status="running")raises at once. execruns the command with bash and merges stderr into stdout, soExecResult.stderris empty. A non-zero exit code is returned, not raised.- A
cwdthat does not exist is ignored: the command runs in the default directory,/home/agent, or the cloned repository when the sandbox was created withgit. prompt()returnssuccess=Falsewitherrorset when the turn fails. Checksuccess.readandwritehandle UTF-8 text only.health()returnsTruefor any key, because/healthneeds no key. Make a real call, such asclient.list(limit=1), to check a key.tangle_sandbox.TimeoutErroris not the built-inTimeoutError. Catch the SDK’s class, or catchSandboxErrorand readcode.confidentialandtangle_secretsonCreateSandboxOptionsare ignored bySandboxandAsyncSandbox. Only the[tangle]client sends them.
Timeouts and retries
| What | Limit |
|---|---|
| Each request | timeout_ms on the client, default 30000 ms |
exec | ExecOptions.timeout_ms (default 30000 ms) plus 15 s for the response |
prompt, stream_prompt, stream_batch | 300 s without an event, or PromptOptions.timeout_ms |
wait_for | WaitForOptions.timeout_ms, default 120000 ms, polling every 2000 ms |
snapshot, restore_paths | up to 600 s for the operation |
| Fleet dispatch | the larger of timeout_ms and 600 s, plus 15 s |
GET, PUT, DELETE, HEAD and OPTIONS requests are retried up to 3 times on a 429, 502, 503 or 504 whose error code is retryable, waiting for Retry-After.
create() sends an Idempotency-Key with every attempt. When the service is out of capacity it sends the same request again for up to 150 s or the client timeout, whichever comes first, so a retry joins the first create instead of making a second sandbox.
If create() times out, the TimeoutError message names the key. Call create() again with CreateSandboxOptions(idempotency_key=...) set to that key to pick up the same sandbox.
What Python can do, and what to use for the rest
The Python SDK covers the core lifecycle, commands, text files, git, snapshots, network rules, coding agent prompts, batches, secrets, teams and traces.
For anything below, use the TypeScript SDK or the CLI, or call the REST route with client.fetch(method, path, json=..., params=...).
client.fetch sends your key, returns the raw httpx.Response and does not raise on a 4xx or 5xx status.
| Task | TypeScript | CLI | REST |
|---|---|---|---|
| Interactive terminal | box.terminals | tangle ssh, tangle agent prompt --interactive | WebSocket; see Shells and terminals |
| List, move, upload and download files; binary files | box.fs.*, box.uploadDirectory | tangle fs | see Files |
| Run code with structured output | box.runCode | tangle run | see Run commands and code |
| Background processes and logs | box.process.* | tangle process | see Run commands and code |
| Separate stderr | box.exec | tangle exec | |
| Expose a port or share a preview link | box.network.exposePort, box.previewLinks | tangle sandbox expose, tangle preview | see Ports and preview links |
| Named agent sessions, answers and history | box.createSession, box.sessions | tangle agent prompt --session | see Sessions |
| Branch or fork a running sandbox | box.branch, box.fork | tangle branch create | see Snapshots and forks |
| Revert to or delete a snapshot | box.revertToSnapshot, box.deleteSnapshot | tangle snapshot revert, tangle snapshot delete | see Snapshots and forks |
| Rebuild a sandbox, poll an operation | box.rebuild, box.getOperation | ||
| Resource usage and runtime health | box.resourceUsage, box.runtimeHealth | ||
| MCP endpoint and computer use | box.getMcpEndpoint | GET /v1/sandboxes/{id}/mcp | |
| TEE sandboxes and attestation | confidential on create, box.getTeeAttestation | tangle sandbox create --tee, tangle sandbox attestation | |
| Egress usage and activity | box.egress.usage, box.egress.activity | GET /v1/sandboxes/{id}/egress/usage, GET /v1/sandboxes/{id}/egress/activity | |
| GPU leases | box.gpu.* | tangle sandbox gpu | see GPU leases |
| SSH keys, public templates, lines, runs | client.sshKeys, client.publicTemplates, client.lines, client.runs | tangle ssh-keys, tangle template, tangle lines | |
| Sizes and coding agents on offer | client.shapes(), client.listBackends() | tangle sandbox shapes | GET /v1/shapes, GET /v1/backends |
| List team or all sandboxes | client.list({ scope }) | tangle sandbox list --team, --all-scopes | GET /v1/sandboxes?scope=team |
| Team secrets and templates, ownership transfer | client.teams.upsertSecret, createTemplate, transferOwnership | tangle team secret, tangle team templates, tangle team transfer | see Teams |
Create fields Python lacks: cwd, ephemeral, retain, startupScriptIds, gpuLease, compliance | client.create | some as tangle sandbox create flags | POST /v1/sandboxes |
| List every fleet | client.fleets | tangle fleet list | GET /v1/fleets |
For example, list the coding agents the service offers:
response = client.fetch("GET", "/v1/backends")
print(response.status_code, [b["type"] for b in response.json()["backends"]][:3])Reference
- Sandbox and AsyncSandbox: the client and its sub-clients.
- SandboxInstance: everything you do to one sandbox.
- Fleets and optional modules: fleets, the agent tool, trace export and the extras.
- Types and errors: every option and result type, and
SandboxError. - Python examples: complete programs with their output.