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. Callingexec() 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 cleanpython: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, andOPENAI_BASE_URLif 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:
Run it
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
RuntimeErrorin Python (a bareErrorin 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. Useexecwhile you are debugging what the model produced.
Troubleshooting
Next steps
- Give the model a tool interface instead of a one-shot call — Drive a sandbox from your agent loop.
- Analyze a real dataset — Data analysis agent adds
copy_in/copy_outand charts. - Lock the box down — Run untrusted tools safely.

