执行上下文

更新时间:
复制 MD 格式

执行上下文用于在多次代码执行之间保留变量、导入、工作目录和解释器状态。它适合多轮数据分析、交互式代码解释器和 Agent 逐步生成代码的场景。

创建并使用上下文

context = sandbox.create_code_context(
    cwd="/home/user",
    language="python",
    request_timeout=60_000,
)

sandbox.run_code("value = 7", context=context)
execution = sandbox.run_code("value * 6", context=context)

print(execution.text)

常用上下文参数:

参数说明
cwd代码执行的工作目录。
language上下文默认语言,例如 python
request_timeout创建上下文或请求上下文服务的超时时间,单位为毫秒。

TypeScript 示例

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

const sandbox = 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 context = await sandbox.createCodeContext({
    cwd: "/home/user",
    language: "python",
    requestTimeoutMs: 60_000,
  });

  await sandbox.runCode("value = 7", { context });
  const execution = await sandbox.runCode("value * 6", { context });

  console.log(execution.text);
} finally {
  await sandbox.kill();
}

查询上下文

contexts = sandbox.list_code_contexts()
for context in contexts:
    print(context)

TypeScript 使用 sandbox.listCodeContexts()

重启上下文

重启上下文会清空变量、导入和解释器状态,但保留同一个上下文标识。

context = sandbox.create_code_context()
sandbox.run_code("value = 7", context=context)

sandbox.restart_code_context(context)

也可以传入上下文 ID。TypeScript 使用 sandbox.restartCodeContext(context)sandbox.restartCodeContext(context.contextId)

删除上下文

不再需要上下文时应主动删除:

context = sandbox.create_code_context()
sandbox.remove_code_context(context)

也可以传入上下文 ID。TypeScript 使用 sandbox.removeCodeContext(context)sandbox.removeCodeContext(context.contextId)

使用建议

上下文只适合保存短期计算状态。业务关键状态应写入文件、对象存储或业务数据库。多用户场景应为不同会话创建独立上下文,避免变量和中间结果互相影响。