code-interpreter-v1 模板

更新时间:
复制 MD 格式

code-interpreter-v1 模板提供安全隔离的代码执行沙箱环境,支持在云端安全地执行 Python、JavaScript 等语言代码,并保持跨调用的执行上下文(变量、导入、函数可跨调用引用)。

code-interpreter-v1 模板对齐 E2B Code Interpreter 的代码上下文与代码执行能力,可直接使用 E2B Code Interpreter SDK 访问。

功能特性

特性说明
多语言代码执行支持 Python、JavaScript、TypeScript、R、Java、Bash 等语言,通过 run_code/runCode 执行
上下文保持默认上下文中变量、导入、函数跨调用保留
代码上下文管理支持创建、列出、重启、删除独立的代码上下文,各上下文变量状态互相隔离
文件系统操作支持上传、下载、读写文件,创建目录、移动、删除,覆盖文本与二进制文件
终端命令执行支持同步命令执行与交互式终端(PTY)
安全隔离基于函数实例独占隔离,每个沙箱实例拥有独立的文件系统和进程空间

适用场景

场景说明
AI Agent 代码沙箱为 AI Agent 提供安全的代码执行环境,防止不可信代码访问或篡改宿主系统资源
数据分析在沙箱中运行 Python 数据分析脚本,配合 pandas、numpy 等库处理数据
文件处理上传文件到沙箱,执行格式转换、数据清洗等操作后下载结果
脚本执行与自动化执行 Shell 命令、安装依赖、运行自动化脚本

默认配置

code-interpreter-v1 模板的默认配置如下:

配置项默认值说明
默认端口5000沙箱服务监听端口
CPU2 vCPU最低要求
内存2048 MB最低要求
磁盘大小10240 MB

SDK 使用方式

使用 code-interpreter-v1 模板时,是否需要显式指定 template 取决于 SDK:

SDKtemplate 参数说明
e2b_code_interpreter SDK不需要指定专用 SDK 默认创建 code-interpreter-v1 沙箱
e2b SDK需要指定 code-interpreter-v1通用 SDK 默认创建 base 沙箱,需要显式选择 code-interpreter-v1 模板

创建沙箱与执行代码

使用 e2b_code_interpreter SDK 创建沙箱并通过 run_code 执行代码:

import os
from e2b_code_interpreter import Sandbox

sbx = Sandbox.create(
    api_key=os.environ["E2B_API_KEY"],
    api_url=os.environ["E2B_API_URL"],
    domain=os.environ["E2B_DOMAIN"],
)
try:
    execution = sbx.run_code("print('hello from code interpreter')")
    print("".join(execution.logs.stdout))
finally:
    sbx.kill()

TypeScript 示例:

import { Sandbox } from "@e2b/code-interpreter";

const sbx = await Sandbox.create("code-interpreter-v1", {
  apiKey: process.env.E2B_API_KEY,
  apiUrl: process.env.E2B_API_URL,
  domain: process.env.E2B_DOMAIN,
});

try {
  const execution = await sbx.runCode("print('hello from code interpreter')");
  console.log(execution.logs.stdout.join(""));
} finally {
  await sbx.kill();
}

logs.stdoutlogs.stderr 均为字符串列表,需 "".join(...)(Python)或 .join("")(TypeScript)拼接为完整文本。

run_code / runCode 的主要参数:

参数说明
code要执行的代码
language执行语言,未指定时默认 python;与 context 互斥
context指定在哪个代码上下文中执行;与 language 互斥
timeout / timeoutMs代码执行超时(Python 单位为秒,TypeScript 单位为毫秒),默认 30 秒
envs自定义环境变量
on_stdout / onStdout流式回调,逐行接收 stdout/stderr/结果/错误

执行结果 Execution 包含 logs(stdout/stderr 列表)、results(富文本结果,含 textpng 等)、error(执行异常)、execution_count

上下文保持

同一沙箱的默认上下文中,变量、导入、函数跨调用保留:

sbx = Sandbox.create(**kwargs)
try:
    sbx.run_code("x = 42")
    execution = sbx.run_code("print(x)")
    print("".join(execution.logs.stdout))  # 42
finally:
    sbx.kill()

代码上下文管理

每个代码上下文(Context)拥有独立的变量状态。通过 context 参数将代码路由到指定上下文执行;未指定 context 时使用默认上下文。

操作Python SDK 方法TypeScript SDK 方法
创建上下文create_code_context(cwd=None, language=None)createCodeContext({ cwd?, language? })
列出上下文list_code_contexts()listCodeContexts()
重启上下文restart_code_context(context)restartCodeContext(context)
删除上下文remove_code_context(context)removeCodeContext(context)
在指定上下文执行run_code(code, context=ctx)runCode(code, { context: ctx })

context 参数可传 Context 对象或上下文 ID 字符串。create_code_contextcwd 默认为 /home/userlanguage 默认为 python

from e2b_code_interpreter import Sandbox

sbx = Sandbox.create(**kwargs)
try:
    # 创建独立上下文
    ctx = sbx.create_code_context(language="python", cwd="/home/user")
    sbx.run_code("y = 100", context=ctx)
    execution = sbx.run_code("print(y)", context=ctx)
    print("".join(execution.logs.stdout))  # 100

    # 默认上下文中无法访问 ctx 的变量,execution.error 包含 NameError
    default_execution = sbx.run_code("print(y)")

    # 重启上下文后变量被清空,execution.error 包含 NameError
    sbx.restart_code_context(ctx)
    restarted_execution = sbx.run_code("print(y)", context=ctx)

    # 列出与删除
    print(sbx.list_code_contexts())
    sbx.remove_code_context(ctx)
finally:
    sbx.kill()

TypeScript SDK 的上下文管理方法(createCodeContext / listCodeContexts / restartCodeContext / removeCodeContext)签名与上表一致,用法参考 E2B 官方 Code Contexts 文档

多语言执行

通过 language 参数指定执行语言,默认为 python

sbx = Sandbox.create(**kwargs)
try:
    execution = sbx.run_code("console.log('hello js')", language="javascript")
    print("".join(execution.logs.stdout))
finally:
    sbx.kill()
const sbx = await Sandbox.create("code-interpreter-v1", {
  apiKey: process.env.E2B_API_KEY,
  apiUrl: process.env.E2B_API_URL,
  domain: process.env.E2B_DOMAIN,
});
try {
  const execution = await sbx.runCode("console.log('hello js')", { language: "javascript" });
  console.log(execution.logs.stdout.join(""));
} finally {
  await sbx.kill();
}

使用通用 e2b SDK

使用 e2b SDK 需显式指定模板 code-interpreter-v1,此时可使用沙箱的基础能力(文件、命令、进程),但不包含 run_code

import os
from e2b import Sandbox

sbx = Sandbox.create(
    template="code-interpreter-v1",
    api_key=os.environ["E2B_API_KEY"],
    api_url=os.environ["E2B_API_URL"],
    domain=os.environ["E2B_DOMAIN"],
)
try:
    result = sbx.commands.run("python --version")
    print(result.stdout)
finally:
    sbx.kill()

使用流程

  1. 创建沙箱实例:使用 e2b_code_interpreter SDK 调用 Sandbox.create(),自动选择 code-interpreter-v1 模板。

  2. 执行代码:通过 run_code / runCode 执行代码;默认上下文自动保持变量状态。

  3. 隔离执行:如需隔离变量状态,使用 create_code_context 创建独立上下文,并通过 context 参数路由执行。

  4. 清理资源:完成后调用 kill() 释放沙箱;不再需要的上下文可用 remove_code_context 删除。

沙箱实例状态

沙箱实例在生命周期内经历以下状态:

状态说明
running就绪,可以使用
paused已暂停(浅休眠),可恢复
terminated已终止

使用限制

限制项约束
沙箱生命周期单个沙箱实例最长生命周期为 24 小时(timeout 参数上限 86400 秒)
浅休眠超时可通过 sandboxIdleTimeoutSeconds 参数设置
代码执行超时单次 run_code / runCode 同步执行默认超时 30 秒,可通过 timeout / timeoutMs 调整

最佳实践

及时清理资源:完成任务后删除不需要的上下文和沙箱实例,监控存储空间使用情况。

合理配置超时时间:短期任务使用较短的超时时间(5~10 分钟),长期任务适当延长(最长不超过 24 小时)。

错误处理:建议对 5xx 服务器错误实施指数退避重试,对 429 限流错误等待后重试。

相关文档