Pydantic AI have put together a very clever, secure and lightweight sandbox that agents can run code in.
I show how to use the sandbox and how it compares with Docker and with the restricted CPython approach taken by SmolAgents.
Cheers, Ronan
P.S. The scripts are in the ADVANCED-inference repo:
Video Links:
Trelis Links:
🤝 Are you a talented developer? Work for Trelis
💡 Need Technical or Market Assistance? Book a Consult Here
💸 Starting a New Project/Venture? Apply for a Trelis Grant
Secure Code Execution: A Guide to Python Sandboxing Approaches
Three main approaches exist for sandboxing Python code execution, each with distinct tradeoffs in security, speed, and capability:
Deno-Pyodide Approach
Converts Python code to WebAssembly
Runs via Deno runtime instead of Node.js
Provides granular control over:
Folder access permissions
Network access
Sub-second startup time
Limited to WebAssembly-compatible libraries
Cannot run PyTorch or use CUDA
Docker/Podman Approach
Full container isolation
Supports all Python libraries
Slower startup (several seconds)
Higher resource usage
Can run GPU-accelerated code
Restricted CPython
Uses abstract syntax tree parsing
Implements operation counting
Whitelists allowed imports
Bans dangerous commands (exec, eval, open)
Limited filesystem protection
Fastest startup time
Implementation Details: DenoPyodide
The recommended DenoPyodide approach works by:
Converting Python code to WebAssembly
Executing via Deno runtime with permission controls
Using MCP (Machine Code Protocol) server from Pydantic AI
Required setup:
Install Deno runtime
Install UV package manager
Configure MCP server with:
Network access controls
Read/write permissions for node_modules only
JSR repository configuration
Limitations
DenoPyodide restrictions:
No PyTorch support
No CUDA support
Limited to WebAssembly-compatible libraries
NumPy and core Python features work well
For cases requiring full PyTorch/CUDA support or other unsupported libraries, Docker/Podman approaches remain necessary despite their slower startup times.
Security Considerations
The DenoPyodide approach provides multiple security layers:
WebAssembly isolation
Deno permission controls
Limited filesystem access
Optional network restrictions
This makes it suitable for running untrusted code while maintaining reasonable performance characteristics.