Execute AI-generated code in an isolated sandbox environment to protect the user's system security. Supports two modes: Docker local sandbox (free) and E2B cloud sandbox.
Use Cases
- User says "help me write a script to analyze this CSV file" → execute in the sandbox without polluting the main system
- User says "help me draw a chart" → matplotlib runs in the sandbox and outputs an image file
- User says "run this code and see the result" → safe isolated execution
- Scenarios such as data analysis, prototype validation, and temporary scripts that are not suitable for direct execution on the main system
- Execute code snippets of unknown origin or high complexity
When to Use This Skill (Instead of Direct system.run)
判断逻辑:
Need to execute code ├── Simple system commands (ls, git, pip, etc.) → direct system.run ├── Complete script provided by the user → code-sandbox ✅ safer ├── AI-generated analysis/processing code → code-sandbox ✅ recommended ├── Code that requires installing additional dependencies → code-sandbox ✅ does not pollute the main environment └── Crawlers/API calls that require network access → code-sandbox ✅ isolates risk
## 前置条件(二选一)
### 方式一:Docker 本地沙箱(推荐,免费)
1. 安装 Docker:https://www.docker.com/get-started
2. 确保 Docker 正在运行:`docker info`
3. 无需额外配置,首次使用时自动拉取基础镜像
### 方式二:E2B 云沙箱
1. 注册 E2B 账号:https://e2b.dev/
2. 设置环境变量:`export E2B_API_KEY="your-key"`
3. 提供免费额度,适合不想装 Docker 的用户
## 执行方式
### Docker 本地沙箱模式
#### 执行 Python 脚本
```python
import asyncio
import tempfile
import os
async def run_in_sandbox(code: str, files: dict = None, timeout: int = 60):
"""在 Docker 沙箱中执行 Python 代码"""
# 创建临时工作目录
work_dir = tempfile.mkdtemp(prefix="sandbox_")
# 写入用户代码
script_path = os.path.join(work_dir, "script.py")
with open(script_path, "w") as f:
f.write(code)
# 如果有输入文件,复制到工作目录
if files:
for name, content in files.items():
fpath = os.path.join(work_dir, name)
if isinstance(content, bytes):
with open(fpath, "wb") as f:
f.write(content)
else:
with open(fpath, "w") as f:
f.write(content)
# Docker 执行命令
cmd = [
"docker", "run", "--rm",
"--network=none", # 默认禁用网络(需要时可开启)
"--memory=512m", # 内存限制
"--cpus=1.0", # CPU 限制
"-v", f"{work_dir}:/workspace", # 挂载工作目录
"-w", "/workspace",
"python:3.12-slim",
"python", "script.py"
]
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(), timeout=timeout
)
return {
"success": proc.returncode == 0,
"stdout": stdout.decode(),
"stderr": stderr.decode(),
"output_dir": work_dir, # 检查输出文件
}
Execution with Dependency Installation
async def run_with_deps(code: str, packages: list, files: dict = None):
"""安装依赖后执行"""
pip_install = " ".join(packages)
wrapper = f"""
import subprocess, sys
subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", {', '.join(repr(p) for p in packages)}])
{code}
"""
return await run_in_sandbox(wrapper, files, timeout=120)
E2B Cloud Sandbox Mode
# 需要 pip install e2b-code-interpreter
from e2b_code_interpreter import Sandbox
async def run_e2b(code: str):
sandbox = Sandbox()
execution = sandbox.run_code(code)
return {
"success": not execution.error,
"stdout": execution.text,
"error": str(execution.error) if execution.error else None,
"results": execution.results, # 包含图表等富媒体输出
}
Typical Workflow
Data Analysis:
用户:分析一下这个 sales.csv 文件
→ 读取用户提供的 CSV 文件
→ 生成 pandas 分析代码
→ 在沙箱中执行(挂载 CSV 文件)
→ 提取输出的统计结果和图表
→ 向用户展示分析报告
Code Prototyping:
用户:帮我写个爬虫抓取 xxx 网站的标题
→ 生成 requests + BeautifulSoup 代码
→ 在沙箱中执行(开启网络: --network=bridge)
→ 返回抓取结果
→ 如果用户满意,可选择在主系统中保存脚本
Security Policy
| Dimension | Default Policy | Adjustable |
|---|---|---|
| Network | Disabled (--network=none) |
Can be enabled after user confirmation |
| Memory | 512MB limit | Maximum 2GB |
| CPU | 1 core | Maximum 2 cores |
| Timeout | 60 seconds | Maximum 300 seconds |
| File System | Only the working directory is writable | - |
| Privileges | No root privileges | - |
Output Specifications
- Distinguish between stdout and stderr in execution results
- If files are generated (charts, reports, etc.), inform the user of the output path
- Provide clear error information when execution times out or OOM occurs
- When code execution fails, analyze the cause of the error and suggest directions for fixing it
- Do not perform operations involving user credentials in the sandbox (API keys, etc. should be passed in via environment variables)