快速创建Agent沙箱
更新时间 2026-05-11 18:20:24
最近更新时间: 2026-05-11 18:20:24
概述
本章节将通过SDK快速创建一个沙箱,并在沙箱隔离环境里面运行一段python代码
控制台操作
创建API Key
登录控制台,在“凭证管理”菜单,创建API Key
创建自定义域名
登录控制台,进入“域名管理”菜单,按照提示完成自定义域名创建
创建沙箱模板
登录控制台,进入“沙箱”菜单,创建一个类型为“代码沙箱”的沙箱模板,并填写好沙箱模板名称,例如:my_test_code_template
客户端操作
安装SDK
前置条件:已安装python 3.9+
安装依赖:
pip install e2b-code-interpreter==2.3.0
pip install e2b==2.6.0
pip install python-dotenv配置环境变量
在您的项目文件夹新建 .env 文件(如果之前不存在的话),并配置 API 密钥和自定义域名,参考如下替换为您的API Key和自定义域名
E2B_DOMAIN=your.domain # 如果您在控制台上面配置的泛域名为*.your.domain,则这里不需要填写*.,只需要填写your.domain
E2B_API_KEY=your.api.key编写代码创建Agent沙箱
创建一个main.py源文件,代码如下:
from dotenv import load_dotenv
from e2b_code_interpreter import Sandbox
# The .env file should be located in the project root directory
# dotenv will automatically look for .env in the current working directory
load_dotenv()
# 注意:修改下面模板为您的模板名称或者模板id
sbx = Sandbox.create(template="my_test_code_template")
# 代码执行
execution = sbx.run_code("print('hello world')")
print(execution.logs)
# 不再使用时,关闭沙箱
sbx.kill()运行代码
python main.py输出内容如下:
Logs(stdout: ['hello world\n'], stderr: [])