Skip to main content

PillDrops Python SDK

The Python client for PillDrops, a self-hosted engine that runs untrusted code in isolated microVMs. Create a sandbox, run commands and code in it, move files, start a server and get its preview URL, pause and resume it.

pip install pilldrops

Sign in

export PILLDROPS_API_KEY=sf_live_...                     # from pilldrops.com/dashboard

Self-hosting? Point it at your own server too:

export PILLDROPS_API_URL=http://localhost:8080          # your PillDrops server
export PILLDROPS_API_KEY=$(cat /var/lib/sandboxd/bootstrap.key)

Settings resolve from explicit arguments, then PILLDROPS_API_URL / PILLDROPS_API_KEY (E2B_*, SANDFORGE_* and SANDBOX_* are read as fallbacks, so code written for the E2B SDK runs unchanged), then ~/.sandforge/config.json. With no URL set, it uses https://pilldrops.com.

Use it

from pilldrops import Sandbox

with Sandbox.create(template="python-3.11") as sb:          # destroyed on exit
    print(sb.run("python3 -c 'print(6*7)'").stdout)          # 42
    sb.files.write("app/main.py", "print('hello')")           # relative to the sandbox home
    print(sb.run("python3 app/main.py").stdout)              # hello
    sb.upload("./project", "/project")                       # a whole directory
    sb.pause()
    sb.resume()                                              # same memory, same processes

# A server, reachable at a preview URL
app = Sandbox.create(template="python-3.11", start="python3 -m http.server 8080", ports=[8080])
print(app.url)
app.kill()
Sandbox.create(template, *, image, start, ports, env, vcpu, mem_mb, storage_mb, timeout) a new sandbox
Sandbox.connect(id) · Sandbox.list() an existing one · all of them
sb.run(cmd, cwd, timeout, env) · sb.run_code(code, lang) ExecResult with stdout, stderr, exit_code, .ok, .check()
sb.files.write/read/list · sb.upload · sb.download files and directories
sb.url · sb.host(port) preview URLs
sb.pause() · sb.resume() · sb.set_timeout(s) · sb.kill() lifecycle
sb.logs() · sb.metrics() observability
build_image(context_dir, tag) build a custom image from a Dockerfile; launch it with Sandbox.create(image=…)

Agents

Sandboxes from an agent template (claude, codex, ...) run a coding agent you talk to in chats. This is enough to build your own chat or code-generation app.

from pilldrops import Sandbox

sb = Sandbox.create(template="claude", secret_refs=["ANTHROPIC_API_KEY"], agent_mode="autonomous")

turn = sb.agent.run("write a fizzbuzz in fizz.py and run it", thread="new",
                    on_text=lambda text: print(text, end="", flush=True))   # live output
print(turn["state"], turn["response"], turn.get("cost_usd"))

sb.agent.run("now make it go to 30", thread=turn["chat"])   # same chat, same memory
print(sb.agent.chats())                                     # title, turns, state, cost

secret_refs names vault secrets put in the sandbox's environment. Save your model key in the vault first.

sb.agent.run(message, thread=, mode=, priority=, wake=, repo=, ref=, on_text=) queue a task, stream its output, return the finished turn
sb.agent.ask(message, ...) queue a task and return at once with {"turn_id", "seq"}
sb.agent.events(since_seq=0) iterator of live events (turn.output, turn.finished, tool.started, approval.requested, ...); break or .close() to end it
sb.agent.turn(id) · sb.agent.turns() · sb.agent.interrupt(id, grace_seconds=) one turn with its response and cost_usd · all, newest first · stop a running one
sb.agent.chats() · sb.agent.update_chat(id, title=, archived=) chats, read without waking a paused sandbox · rename or archive
sb.agent.pull_request(chat_id, title=, body=, draft=) for a chat started with repo: commit, push its branch, open a GitHub pull request; {"url", "number", "branch", "base"}
sb.agent.approvals() · sb.agent.decide(id, "allow" | "deny", remember=) tool calls waiting for review in guided mode
sb.agent.status() {"agent", "session"}: the agent, then session state, current turn, queue depth
sb.agent.create_token(scopes, label=, ttl_seconds=) a token for this sandbox only (agent:read, agent:write, agent:approve, ...); token.secret is returned once

thread is latest (the default), new, or a chat id to continue that chat. Agent(sandbox_id) reaches an existing sandbox's agent without Sandbox.connect.

A chat can work on a repo. It gets its own clone on its own claude/... branch, and its changes can become a pull request. Set GIT_TOKEN in the sandbox, for example with secret_refs=["GIT_TOKEN"]:

turn = sb.agent.run("fix the failing test", thread="new", repo="https://github.com/you/app")
pr = sb.agent.pull_request(turn["chat"], draft=True)
print(pr["url"])

Give a script, a CI job or a teammate a token instead of your org key. A token works only on the sandbox's own origin:

from pilldrops import Agent

token = sb.agent.create_token(["agent:read", "agent:write"], ttl_seconds=3600)["token"]
agent = Agent(sb.id, api_url=f"https://agent-{sb.id}.pilldrops.app", api_key=token["secret"])
agent.run("run the tests")

Webhooks

Get a signed POST when a sandbox in your org changes state. These take the org API key.

from pilldrops import Webhooks, verify_webhook_signature

hooks = Webhooks()
created = hooks.create("https://example.com/hook", ["sandbox.ended"])
secret = created["secret"]                                   # store it now: returned only here

# in your endpoint, with the raw request body
ok = verify_webhook_signature(secret, headers["x-pilldrops-timestamp"],
                              headers["x-pilldrops-signature"], raw_body)
hooks.list() · hooks.create(url, events) · hooks.delete(id) manage endpoints
hooks.test(id) send one signed probe: {"ok", "status", "error"}
hooks.set_enabled(id, enabled) pause or resume deliveries
hooks.deliveries() recent deliveries, newest first
verify_webhook_signature(secret, timestamp, signature, body, tolerance=300) True when the signature matches and the timestamp is fresh

Events: sandbox.created, sandbox.ended, sandbox.paused, sandbox.resumed, sandbox.checkpointed, sandbox.forked, sandbox.restarted, sandbox.crashed, sandbox.out_of_memory, sandbox.unreachable. The body is {"id", "type", "at", "sandbox": {"id", "template"}, "data"}. Retries reuse id (also in x-pilldrops-delivery), so dedupe on it.

Functions

Code that starts on request and scales to zero when idle. These take the org API key.

from pilldrops import Functions

fns = Functions()
fn = fns.create("hello", "python app.py", port=8000,
                files=[{"path": "app.py", "content": open("app.py").read()}])
r = fns.invoke("hello", "/greet", json={"name": "Ada"})   # a requests.Response, any status
print(r.status_code, r.headers["content-type"], r.text)    # r.content for bytes

fns.update("hello", public=True)                          # only the fields given change
pub = fns.get("hello")["public_id"]
fns.invoke_public(pub, method="GET")                      # no API key sent
fns.list() · fns.get(name) · fns.delete(name) read and remove
fns.create(name, start, template=, port=, vcpu=, memory_mb=, max_replicas=, replica_concurrency=, idle_timeout=, public=, env=, files=) deploy; idle_timeout=0 keeps one replica warm
fns.update(name, **same fields) change only what is passed; public=False turns key-less invoke off, env={} clears env
fns.invoke(name, path="", method="POST", **requests_kwargs) call it; returns the handler's raw response and never raises on its status
fns.public_url(public_id) · fns.invoke_public(public_id, path="", method="POST", ...) key-less invoke of a public function
fns.rename(name, new_name) the old invoke URL forwards until old_name_forwards_until (7 days)
fns.deployments(name) · fns.rollback(name, deployment_id) newest first, the first one runs; rollback raises APIError with status 409 when that code was not kept

import sandforge and import yoursandbox still work: they ship in this package as aliases of its earlier names.

Tests

python3 -m pytest tests            # unit tests; the integration test skips without a server

License

MIT.

Metadata

Release files for pilldrops 1.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pilldrops 1.5.1
File Size Uploaded Provenance Actions
pilldrops-1.5.1.tar.gz 24.7 kB Without provenance Details for pilldrops-1.5.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pilldrops 1.5.1
File Interpreter ABI Platform Actions
pilldrops-1.5.1-py3-none-any.whl Python 3 none any Details for pilldrops-1.5.1-py3-none-any.whl

Total release size: 43.7 kB

Release files / pilldrops-1.5.1.tar.gz

Download URL pilldrops-1.5.1.tar.gz
Size 24.7 kB
Tags Source
SHA-256 checksum
How to use checksums
9dd41376938bccd3f1328922eb395777df030bb28c17ebe5ddcad5c132f67ef0
BLAKE2b-256 checksum
How to use checksums
7e1a6d45f050488e1d44f86a6a217e4a5372227bafb03802504cf2282469cf4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.0

Release files / pilldrops-1.5.1-py3-none-any.whl

Download URL pilldrops-1.5.1-py3-none-any.whl
Size 18.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cd85f8b87e4f32638241dc147215aa21b112c4de11b244b8879223c10871a8b9
BLAKE2b-256 checksum
How to use checksums
7539789f45ef2adb021a79d6575b2d43776a513d97e402b881c20986c74043ce
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.0

Security for pilldrops 1.5.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page