快速创建Agent沙箱
更新时间 2026-03-13 16:15:52
最近更新时间: 2026-03-13 16:15:52
概述
本章节将通过sdk快速创建一个沙箱,并在沙箱隔离环境里面运行一段python代码
控制台操作
创建API Key
登录控制台,在身份凭证管理菜单,创建API Key
创建自定义域名
登录控制台,进入“域名管理”菜单,按照提示完成自定义域名创建
客户端操作
安装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
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()
sbx = Sandbox.create(template="code-interpreter")
# 代码执行
execution = sbx.run_code("print('hello world')")
print(execution.logs)
# 不再使用时,关闭沙箱
sbx.kill()运行代码
python main.py输出内容如下:
Logs(stdout: ['hello world\n'], stderr: [])