Secure Python code execution sandbox for LLM-generated code
Project description
LLM Python Sandbox
A secure, multi-layered Python sandbox designed for executing code generated by Large Language Models (LLMs). It provides robust isolation mechanisms to ensure safe execution of untrusted code.
🚀 Features
-
🔒 Multi-layered Security:
- AST Validation: Blocks dangerous constructs (e.g., top-level code,
eval,exec) before execution. - Import Whitelisting: Strictly controls which modules can be imported.
- Restricted Builtins: Removes access to dangerous built-ins like
open,input, etc.
- AST Validation: Blocks dangerous constructs (e.g., top-level code,
-
🛡️ Process Isolation:
- Subprocess Mode: Executes code in a separate process for maximum isolation.
- Resource Limits: Enforces memory usage and CPU time limits (on supported systems).
- Wall-clock Timeouts: Prevents infinite loops and hanging processes.
-
🐼 Data Science Ready:
- Optimized for
pandasDataFrame operations. - Supports passing DataFrames in and out of the sandbox.
- Optimized for
-
🔌 Flexible Execution Modes:
safe_context: Lightweight in-process isolation (faster, for trusted code).subprocess_sandbox: Full process isolation (safer, for untrusted code).
📦 Installation
This project is configured as a Python package. You can install it using pip:
# Clone the repository
git clone https://github.com/yourusername/llm-python-sandbox.git
cd llm-python-sandbox
# Install in editable mode
pip install -e .
# Install development dependencies
pip install -e ".[dev]"
🛠️ Usage
Basic Execution
The CodeExecutor provides a high-level API for running code.
from src.executor import CodeExecutor
executor = CodeExecutor()
# Execute simple code
code = """
def greet(name):
return f"Hello, {name}!"
"""
result = executor.execute_code(
code=code,
input_variables={"name": "World"},
verification_code="assert result == 'Hello, World!'",
execution_mode="subprocess_sandbox"
)
print(result["stdout"])
# Output: Hello, World!
Working with DataFrames
The sandbox is designed to handle data transformations safely.
import pandas as pd
from src.executor import CodeExecutor
executor = CodeExecutor()
# Input DataFrame
df = pd.DataFrame({"value": [1, 2, 3, 4, 5]})
# Code to execute
code = """
import pandas as pd
def transform_data(df):
df['doubled'] = df['value'] * 2
return df
"""
result = executor.execute_code(
code=code,
input_variables={"df": df},
return_variables=["transform_data"], # Capture return value
execution_mode="subprocess_sandbox"
)
# Access returned data
processed_df = result["returned_values"]["transform_data"]
print(processed_df)
Execution Modes
| Mode | Description | Security Level | Performance | Use Case |
|---|---|---|---|---|
default |
Standard exec() |
🔴 Low | ⚡ Very High | Trusted, local scripts only |
safe_context |
In-process sandbox | 🟡 Medium | 🚀 High | Trusted LLMs, internal tools |
subprocess_sandbox |
Separate process | 🟢 High | 🐢 Medium | Untrusted LLM code, public APIs |
🏗️ Architecture
The project consists of several core components:
CodeExecutor: The main entry point that orchestrates execution.SubprocessSandbox: Handles process lifecycle, resource limits, and IPC.SafeFunctionContext: Manages the in-process execution environment.ASTValidator: Statically analyzes code structure to reject unsafe patterns.SafeImporter: Intercepts imports to enforce the whitelist.
🔒 Security Model
The sandbox uses a "defense in depth" strategy:
- Static Analysis: Code is first parsed into an AST. If it contains forbidden nodes (e.g.,
exec,eval) or disallowed top-level statements, it is rejected immediately. - Runtime Restrictions: The execution environment has a stripped-down
__builtins__dictionary. - Import Control: A custom
__import__hook verifies strictly against an allowlist (default:math,json,pandas,numpy, etc.). - Process Isolation: Using the
subprocessmode adds OS-level isolation, protecting the main application from crashes and memory exhaustion.
⚠️ Note: While robust, no sandbox is 100% impenetrable. Always run untrusted code in a highly restricted environment (e.g., Docker container, gVisor) in production.
🤝 Contributing
Contributions are welcome! Please follow these steps:
- install dev dependencies:
pip install -e ".[dev]" - Run tests:
pytest - Format code:
black . - Submit a Pull Request.
📄 License
MIT License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file llm_python_sandbox-0.1.0.tar.gz.
File metadata
- Download URL: llm_python_sandbox-0.1.0.tar.gz
- Upload date:
- Size: 19.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
527c9a4417db9a21f95d7d315bee7b8076b834f3667bc87a65632c731af5697f
|
|
| MD5 |
e2a3a4c1b24f67e6ae9a420d05d0f9f2
|
|
| BLAKE2b-256 |
b743104ddacecc816b3684695746cd7ef32c58bc34ca479ba4ab4cbc5a71302c
|
Provenance
The following attestation bundles were made for llm_python_sandbox-0.1.0.tar.gz:
Publisher:
publish.yml on binzhango/llm_python_sandbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
llm_python_sandbox-0.1.0.tar.gz -
Subject digest:
527c9a4417db9a21f95d7d315bee7b8076b834f3667bc87a65632c731af5697f - Sigstore transparency entry: 845544227
- Sigstore integration time:
-
Permalink:
binzhango/llm_python_sandbox@5308dfaf53b518a9810f9ca1e0db4b30ded359be -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/binzhango
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@5308dfaf53b518a9810f9ca1e0db4b30ded359be -
Trigger Event:
release
-
Statement type:
File details
Details for the file llm_python_sandbox-0.1.0-py3-none-any.whl.
File metadata
- Download URL: llm_python_sandbox-0.1.0-py3-none-any.whl
- Upload date:
- Size: 15.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6141d82481e8937964b95fec37c2555467faf596e7159f02157e89979071d08b
|
|
| MD5 |
ed64d636f6e1675c81d883ed56dfc730
|
|
| BLAKE2b-256 |
a8604e67a0368649bd8900a280479da79de633477273d5c9b08aecd6c86fe7f5
|
Provenance
The following attestation bundles were made for llm_python_sandbox-0.1.0-py3-none-any.whl:
Publisher:
publish.yml on binzhango/llm_python_sandbox
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
llm_python_sandbox-0.1.0-py3-none-any.whl -
Subject digest:
6141d82481e8937964b95fec37c2555467faf596e7159f02157e89979071d08b - Sigstore transparency entry: 845544233
- Sigstore integration time:
-
Permalink:
binzhango/llm_python_sandbox@5308dfaf53b518a9810f9ca1e0db4b30ded359be -
Branch / Tag:
refs/tags/v0.1.0 - Owner: https://github.com/binzhango
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@5308dfaf53b518a9810f9ca1e0db4b30ded359be -
Trigger Event:
release
-
Statement type: