執行內容用於在多次代碼執行之間保留變數、匯入、工作目錄和解譯器狀態。它適合多輪資料分析、互動式代碼解譯器和 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)也可以傳入內容識別碼。TypeScript 使用 sandbox.restartCodeContext(context) 或 sandbox.restartCodeContext(context.contextId)。
刪除上下文
不再需要上下文時應主動刪除:
context = sandbox.create_code_context()
sandbox.remove_code_context(context)也可以傳入內容識別碼。TypeScript 使用 sandbox.removeCodeContext(context) 或 sandbox.removeCodeContext(context.contextId)。
使用建議
上下文只適合儲存短期計算狀態。業務關鍵狀態應寫入檔案、Object Storage Service或業務資料庫。多使用者情境應為不同會話建立獨立上下文,避免變數和中間結果互相影響。