沙箱实例管理
沙箱实例是AgentSphere的核心运行单元。本节介绍如何创建、获取列表、获取信息、连接、暂停和删除沙箱实例。
前提条件
以下示例均基于E2B SDK,请确保已完成配置本地E2B SDK执行环境。
沙箱实例管理
创建沙箱实例
您可以使用Sandbox.create方法创建沙箱实例,创建时需指定模板名称,也可以指定超时时间、环境变量等参数。
from e2b import Sandbox # template字段的值为已有的template_id sandbox = Sandbox.create(template="<template_id>") # 您可以在创建时指定超时时间,单位为秒 # 当沙箱的运行时间超过超时时间时,沙箱将会被自动删除 sandbox = Sandbox.create( template="<template_id>", api_key="<your_api_key>", envs={"MY_ENV": "value"}, timeout=300 )
| 参数 | 说明 |
|---|---|
| template | 沙箱模板ID,指定沙箱实例的配置模板。 |
| timeout | 沙箱实例的超时时间,单位为秒。超时后沙箱实例将自动终止。 |
| api_key | 访问API Key。 |
| envs | 沙箱环境变量,以字典形式传入。 |
获取沙箱实例信息
您可以通过sandbox.get_info方法获取沙箱实例的详细信息,包括实例ID、模板ID、运行状态、启动时间、结束时间等。
from e2b import Sandbox
# 创建沙箱实例
sandbox = Sandbox.create(template="<template_id>")
# 获取沙箱实例信息
info = sandbox.get_info()
print(info) 获取沙箱实例指标数据
您可以通过sandbox._envd_api.get("/metrics")方法查看沙箱实例的监控数据指标。
from e2b import Sandbox
sandbox = Sandbox.create(template="<template_id>")
# 获取沙箱实例的监控数据指标
resp = sandbox._envd_api.get("/metrics")
metrics_data = resp.json()
# 返回字段包括:
# cpu_count, cpu_used_pct, mem_total, mem_used, mem_cache, disk_total, disk_used
print(metrics_data) 检查沙箱运行状态
您可以通过sandbox.is_running方法检查沙箱实例是否处于运行状态。
from e2b import Sandbox
sandbox = Sandbox.create(template="<template_id>")
# 检查沙箱是否处于运行状态
running = sandbox.is_running()
print(f"沙箱运行状态: {running}") 修改沙箱超时时间
您可以通过sandbox.set_timeout方法修改沙箱实例的超时时间,避免长时间运行的任务被意外终止。
from e2b import Sandbox
sandbox = Sandbox.create(template="<template_id>")
# 修改超时时间为600秒
sandbox.set_timeout(600) 连接已有沙箱实例
您可以通过Sandbox.connect方法,使用沙箱ID连接到已存在的沙箱实例,适用于跨会话复用沙箱的场景。
import os
from e2b import Sandbox
E2B_API_KEY = os.environ.get("E2B_API_KEY", "")
# 通过沙箱ID连接到已存在的沙箱实例
sandbox = Sandbox.connect("<your_sandbox_id>", api_key=E2B_API_KEY)
print(f"已连接沙箱实例,ID: {sandbox.sandbox_id}") 查询沙箱实例列表
您可以通过Sandbox.list方法,返回沙箱实例列表。
import os from getpass import getpass from e2b import Sandbox API_URL = "https://agentsphere.<region>.myhuaweicloud.com" # 根据真实情况修改 E2B_API_KEY = os.environ.get("E2B_API_KEY", "") paginator = Sandbox.list( limit=10, api_key=E2B_API_KEY, api_url=API_URL, domain="agentsphere.<region>.myhuaweicloud.com", # 根据真实情况修改 request_timeout=30, ) sandboxes = paginator.next_items() print(f"count={len(sandboxes)}, has_next={paginator.has_next}") for sandbox in sandboxes: print( f"sandbox_id={sandbox.sandbox_id}, " f"template_id={sandbox.template_id}, state={sandbox.state.value}" )
暂停沙箱实例
您可以通过sandbox.pause方法暂停沙箱实例以节省资源,暂停后可通过Sandbox.connect方法重新连接并恢复。
from e2b import Sandbox
sandbox = Sandbox.create(template="<template_id>")
# 暂停沙箱实例
sandbox.pause()
print("沙箱实例已暂停")
沙箱最大运行时长不能超过24小时。
删除沙箱实例
删除操作不可逆,沙箱实例内的所有数据将被清除且无法恢复。请在删除前确认已保存必要数据。
您可以通过sandbox.kill方法删除沙箱实例。
from e2b import Sandbox
sandbox = Sandbox.create(template="<template_id>")
# 删除沙箱实例
sandbox.kill()
print("沙箱实例已删除") 完整代码示例
通过指定模板创建沙箱实例,创建成功后返回沙箱对象,您可以基于该对象执行后续操作。
import os
import time
from e2b import Sandbox
# 从环境变量中读取API Key
E2B_API_KEY = os.environ.get("E2B_API_KEY", "")
# 使用模板创建沙箱实例,超时时间300秒
def test_create_sandbox():
sandbox = Sandbox.create(
template="<template_id>",
api_key=E2B_API_KEY,
timeout=300,
)
assert sandbox.sandbox_id is not None and sandbox.sandbox_id != ""
print(f"[PASS] create sandbox: {sandbox.sandbox_id}")
return sandbox
# 获取沙箱实例的详细信息
def test_get_info(sandbox):
info = sandbox.get_info()
assert info is not None
print(f"[PASS] get_info: {info}")
# 检查沙箱实例是否处于运行状态
def test_is_running(sandbox):
running = sandbox.is_running()
assert running is True
print(f"[PASS] is_running: {running}")
# 修改沙箱实例的超时时间为600秒
def test_set_timeout(sandbox):
sandbox.set_timeout(600)
print("[PASS] set_timeout(600)")
# 查询当前账号下所有沙箱实例
def test_list_sandboxes():
E2B_API_KEY = os.environ.get("E2B_API_KEY", "")
API_URL = os.environ.get("API_URL", "")
paginator = Sandbox.list(
limit=10,
api_key=E2B_API_KEY,
api_url=API_URL,
domain="agentsphere.<region>.myhuaweicloud.com", # 根据真实情况修改
request_timeout=30,
)
sandboxes = paginator.next_items()
print(f"count={len(sandboxes)}, has_next={paginator.has_next}")
for sandbox in sandboxes:
print(
f"sandbox_id={sandbox.sandbox_id}, "
f"template_id={sandbox.template_id}, state={sandbox.state.value}"
)
# 通过沙箱ID连接到已存在的沙箱实例
def test_connect_sandbox(sandbox_id):
sandbox = Sandbox.connect(sandbox_id, api_key=E2B_API_KEY)
assert sandbox.sandbox_id == sandbox_id
print(f"[PASS] connect sandbox: {sandbox.sandbox_id}")
return sandbox
# 暂停沙箱实例以节省资源
def test_pause_sandbox(sandbox):
try:
sandbox.pause()
print("[PASS] pause sandbox")
except Exception as e:
print(f"[SKIP] pause not supported or error: {e}")
# 删除沙箱实例,操作不可逆
def test_kill_sandbox(sandbox):
sandbox.kill()
print(f"[PASS] kill sandbox: {sandbox.sandbox_id}") 相关文档
- 创建沙箱模板:了解如何创建自定义沙箱模板,预装所需的运行环境和依赖包。
- 创建API Key:了解如何创建和管理API Key,获取访问凭据。
- 创建网关实例:了解Agent网关的配置和管理,获取数据面访问地址。
- E2B SDK官方文档:了解E2B SDK的完整接口说明和更多用法示例。
- 如果在使用SDK时遇到连接失败、认证错误等问题,请先检查环境变量配置是否正确,特别是E2B_API_URL、E2B_SANDBOX_URL和E2B_API_KEY是否与控制台中的信息一致。