Sandboxing Python Code Execution
You'll learn how to safely execute dynamically generated Python code from AI agents without risking your system's security.
When an AI agent writes Python code as a tool action, you cannot simply run it with exec() or eval() — that would allow the agent to access files, network resources, or even delete critical system data. Sandboxing means creating an isolated, restricted environment where code runs with limited permissions.
The Core Idea
Think of sandboxing like giving someone a toy kitchen instead of your real one. They can "cook" and experiment, but they can't actually burn down your house or raid your fridge.
In Python, sandboxing involves two main techniques:
1. Restricted Globals
By default, exec() has access to built-in functions like open(), import, and __import__. You create a custom globals dictionary that excludes dangerous functions:
safe_globals = {
"__builtins__": {
"print": print,
"len": len,
"range": range,
# Only include safe built-ins
}
}
code = "print(sum(range(10)))"
exec(code, safe_globals) # Runs with limited access
2. Subprocess Isolation
For stronger isolation, run code in a separate process with resource limits. If it crashes or hangs, your main agent continues unaffected. Libraries like subprocess with timeouts provide this layer.
Why It Matters
AI agents can hallucinate dangerous code. Sandboxing prevents accidental (or malicious) actions like file deletion, infinite loops consuming resources, or network requests to external systems.
Key Takeaway: Sandboxing Python execution combines restricted globals to limit available functions and subprocess isolation to contain failures, ensuring AI-generated code runs safely within controlled boundaries.