Skip to main content
Outcome: a working natural language -> generated code -> isolated execution -> result loop. Level: beginner · Time: ~10 minutes · Pattern: the box is a tool the model calls.

When to use this

Any application that executes model-generated code hits the same wall: you cannot review that code before it runs. It may delete files, loop forever, or read your environment variables. Calling exec() on it inside your own process hands your full privileges to a script nobody has read. CodeBox closes that gap. Each snippet runs in its own microVM with its own kernel, filesystem, and resource budget, and the VM is destroyed when the scope exits. Your process keeps the API keys and the business logic; only the untrusted code crosses the boundary. Typical products built this way: data-analysis assistants, “compute this in plain English” tools, AI programming helpers, and homework/grading systems that execute submissions.

Architecture

Orchestration, credentials, and business logic stay in the trusted process. Only the generated code enters the isolated environment, and it arrives in a clean python:slim with nothing of yours in it.

Prerequisites

  • BoxLite installed and a working virtualization host — see Installation.
  • An OpenAI-compatible LLM endpoint. This guide reads OPENAI_API_KEY, and OPENAI_BASE_URL if you point at a different provider.

Build it

The whole loop, ready to copy and run:
CodeBox.run(code) returns stdout as a string. When you need stderr or the exit code — which you will, as soon as the model writes code that raises — use exec instead:
Full parameter tables for both entry points: Run Python code in a box.

Run it

That list was computed inside the microVM, not on your machine. The first run also pulls python:slim, which can take tens of seconds; later runs start in about two seconds.

Trust and limits

  • What the boundary covers. The generated code gets its own kernel and filesystem and is memory-isolated from your process. rm -rf / inside the box cannot reach the host, and the box is destroyed when the scope exits.
  • The box has full outbound network by default. Isolation is not the same as containment: code in the box can still reach the internet. If the threat you care about is exfiltration rather than damage, add an egress allowlist — see Harden the box for untrusted code.
  • Failures are catchable. A missing hypervisor or a failed image pull raises RuntimeError in Python (a bare Error in Node), not a process crash.
  • run() hides errors by design. It returns stdout only. A traceback lands in stderr and you will see an empty string. Use exec while you are debugging what the model produced.

Troubleshooting

Next steps