Skip to content
← all posts

How to use BoxLite with Python?

Run untrusted Python code inside an isolated microVM with SimpleBox, or target BoxLite Cloud from the same SDK.

Cocona L4 min read

How to use BoxLite with Python?

Install the BoxLite Python SDK with pip install boxlite (Python 3.10 or later), then run commands inside a local microVM using async with boxlite.SimpleBox(image="python:slim") as box: and await box.exec(...). The Apache-2.0 open-source runtime runs embedded microVMs directly in your Python process, while the SDK's REST client (Boxlite.rest) also lets you target self-hosted boxlite serve or BoxLite Cloud, the managed isolated compute service for AI agents.

Calling subprocess.run executes model-generated code straight on your laptop or server. With BoxLite, your Python process embeds hardware virtualization and boots a dedicated microVM for each Box from standard OCI images like python:slim.

Install the SDK and check virtualization

You need Python 3.10 or later:

pip install boxlite

Running Boxes locally requires CPU virtualization: Apple Silicon macOS 12+ (Hypervisor.framework), /dev/kvm on Linux, or KVM inside WSL2 on Windows (our embedded sandbox guide covers the local architecture).

If your CI runner doesn't expose KVM, install boxlite anyway. You can point your client at a remote boxlite serve instance or BoxLite Cloud.

Run your first command with SimpleBox

Start an async with block with an OCI image, then pass your command to box.exec:

import asyncio
import boxlite


async def main():
    async with boxlite.SimpleBox(image="python:slim") as box:
        result = await box.exec("python", "-c", "print('Hello from BoxLite')")
        print(result.stdout)


asyncio.run(main())

On the first run, BoxLite pulls python:slim and caches the OCI image layers under ~/.boxlite so later runs skip the download. When the async with block exits, SimpleBox stops and removes that temporary Box for you.

Lock down files, egress, and API keys

Untrusted code with plain environment variables and open outbound networking has an easy path to leak your keys.

Mount only the repository directory the task needs instead of exposing your home directory. Use NetworkSpec(mode="disabled") for offline code runs, or NetworkSpec(mode="enabled", allow_net=[...]) so BoxLite resolves only allowlisted hostnames, sinkholes other DNS lookups to 0.0.0.0, and inspects TLS SNI and HTTP Host headers.

For API keys, Secret keeps the real token out of the guest environment by passing a placeholder like <BOXLITE_SECRET:anthropic>. When the Box sends an outbound HTTPS request to an allowlisted host in Secret(..., hosts=[...]), the host proxy swaps in the real value.

import asyncio
import os
import boxlite


async def main():
    secret = boxlite.Secret(
        name="anthropic",
        value=os.environ["ANTHROPIC_API_KEY"],
        hosts=["api.anthropic.com"],
    )
    net = boxlite.NetworkSpec(
        mode="enabled",
        allow_net=["api.anthropic.com"],
    )

    async with boxlite.SimpleBox(
        image="python:slim",
        network=net,
        secrets=[secret],
        volumes=[("/path/to/repo", "/workspace", False)],
        env=[("ANTHROPIC_API_KEY", "<BOXLITE_SECRET:anthropic>")],
    ) as box:
        res = await box.exec("sh", "-c", "echo $ANTHROPIC_API_KEY")
        print(res.stdout)  # Prints only the placeholder <BOXLITE_SECRET:anthropic>


asyncio.run(main())

Even if generated code runs printenv, it sees only the placeholder string (walked through in our coding-agent isolation guide). That doesn't make the sandbox unconditionally safe, though. Code inside the Box can still call endpoints on hosts using your injected credential, and passing False as the third item in the volumes tuple mounts /workspace read-write so the agent can edit repository files.

Connect to local hardware or BoxLite Cloud

When you move workloads off your laptop, the Boxlite factory selects between your local embedded runtime and a remote endpoint using BOXLITE_REST_URL:

import os
from boxlite import Boxlite, BoxliteRestOptions


def get_runtime() -> Boxlite:
    if os.getenv("BOXLITE_REST_URL"):
        return Boxlite.rest(BoxliteRestOptions.from_env())
    return Boxlite.default()

With BOXLITE_REST_URL unset, Boxlite.default() runs the Apache-2.0 runtime embedded inside your process. Setting BOXLITE_REST_URL and credentials points Boxlite.rest(...) at a self-hosted boxlite serve instance you manage yourself or at BoxLite Cloud, where BoxLite manages the isolated compute infrastructure.

Mind persistence and idle auto-stop limits

SimpleBox removes its Box and virtual disk state when the context block exits. For longer-lived workflows or managed BoxLite Cloud instances, setting auto_delete=0 keeps disk state intact after compute stops.

Keep an eye on idle timeouts in BoxLite Cloud. Idle tracking for auto_stop measures activity at the box boundary, so long-running background processes inside a Box may not count as activity and can still be stopped.

Next steps with SkillBox and SyncBoxlite

If you don't want to wire raw shell commands into your agent loop, the SDK also includes SkillBox for calling agent skill packages (async with boxlite.SkillBox(skills=["anthropics/skills"]) as box: and await box.call(...) with CLAUDE_CODE_OAUTH_TOKEN). Synchronous scripts can use SyncBoxlite, shown in run_openclaw.py under examples/python/06_ai_agents/ in the BoxLite GitHub repository.