下载与资源
https://sandbox.agent-infra.com/zh/
运行容器
开启服务端,然后用SDK与它相连。
# 大小约13G
docker run --security-opt seccomp=unconfined --rm -it \
-e SANDBOX_API_KEY=your-secret-key \
-p 127.0.0.1:8080:8080 ghcr.io/agent-infra/sandbox:latest
curl -H "X-AIO-API-Key: your-secret-key" \
http://localhost:8080/v1/shell/sessions
#重新运行容器
docker run --security-opt seccomp=unconfined --rm -it -d\
-p 127.0.0.1:8080:8080 ghcr.io/agent-infra/sandbox:latest
容器生命周期:你带了 --rm,容器退出即销毁,工作区不保留;调试期可去掉 --rm 或加 -v $(pwd)/workspace:/home/gem 持久化文件。
绑定地址:127.0.0.1:8080 只对本机开放;如果 Agent 跑在另一个容器/WSL 里,把它改成 -p 8080:8080 或对应可达地址,但公网部署务必走反向代理且保持 key 认证(README 特意强调 8080 要私有发布)
#指定开发目录
mkdir -p ~/aio-workspace # 宿主机目录,需预先创建
docker run --security-opt seccomp=unconfined --rm -it \
-e SANDBOX_API_KEY=your-secret-key \
-e WORKSPACE=/home/gem/workspace \
-p 127.0.0.1:8080:8080 \
-v ~/aio-workspace:/home/gem/workspace \
ghcr.io/agent-infra/sandbox:latest
-v ~/aio-workspace:/home/gem/workspace:左边是宿主机路径,右边是容器内工作区,两边实时双向同步
之后你在宿主机 ~/aio-workspace 里改代码,沙箱内(VSCode、Shell、Jupyter、浏览器下载的文件)立即可见
docker-compose
创建docker-compose.yml,用它来启动可以配置更多参数, docker compose up -d
services:
sandbox:
container_name: aio-sandbox
image: ghcr.io/agent-infra/sandbox:latest
security_opt:
- seccomp:unconfined
ports:
- "127.0.0.1:8080:8080"
volumes:
- ~/aio-workspace:/home/gem/workspace
- ~/datasets:/home/gem/datasets:ro
extra_hosts:
- "host.docker.internal:host-gateway"
shm_size: "2gb"
environment:
SANDBOX_API_KEY: "your-secret-key"
WORKSPACE: /home/gem/workspace
TZ: Asia/Shanghai
重新进入容器
docker exec -it aio-sandbox /bin/bash
exit //退出
SDK
uv add agent-sandbox
# pip install agent-sandbox
from agent_sandbox import Sandbox
# 你设置了 SANDBOX_API_KEY,通过 X-AIO-API-Key 头传递
sandbox = Sandbox(
base_url="http://localhost:8080",
headers={"X-AIO-API-Key": "your-secret-key"}
)
# Shell
result = sandbox.shell.exec_command(command="ls -la", timeout=30)
print(result.data)
# 代码执行(Python / Node.js)
resp = sandbox.jupyter.execute_code(code="print(1+1)")
print(resp.data)
# 浏览器
img = sandbox.browser.screenshot()
open("shot.png", "wb").write(img.read())
调用案例
from agent_sandbox import Sandbox
# Initialize client
client = Sandbox(base_url="http://localhost:8080")
home_dir = client.sandbox.get_context().home_dir
# Execute shell commands
result = client.shell.exec_command(command="ls -la")
print(result.data.output)
# File operations
content = client.file.read_file(file=f"{home_dir}/.bashrc")
print(content.data.content)
# Browser automation
screenshot = client.browser.screenshot()
# jupyter python / nodejs
res_str = return client.jupyter.execute_code(code=code).data
res_str = return client.nodejs.execute_nodejs_code(code=code).data
DeepAgents集成
from agent_sandbox import Sandbox
from deepagents import create_deep_agent
from langchain_openai import ChatOpenAI
from aioBackend import AIOSandboxBackend #deepagents-integration集成文件
# 设置模型
llm = ChatOpenAI(model="gpt-5.4-mini", api_key=bai_api_key, base_url=baiBaseURL)
def main():
client = Sandbox(
base_url="http://localhost:8080",
headers={"X-AIO-API-Key": "your-secret-key"}
)
with AIOSandboxBackend(client) as backend:
agent = create_deep_agent(
model=llm,
backend=backend,
skills=["/home/gem/workspace/skills"] #沙箱里文件的路径
)
for chunk in agent.stream(
{"messages": [{"role": "user", "content": "您有哪些技能(skills)"}]},
stream_mode="values"
):
if "messages" in chunk:
chunk["messages"][-1].pretty_print()
if __name__ == "__main__":
main()
注意: Agent可以使用同步调用或异步调用,两个方法都是可以的。但`AIOSandboxBackend`的 `read` 方法有些兼容问题,会报错,如下:
`File "D:\agent\aioSandboxtest\.venv\Lib\site-packages\deepagents\middleware\filesystem.py", line 2384, in sync_read_file
return _handle_read_result(read_result, validated_path, runtime.tool_call_id, offset, limit)
File "D:\agent\aioSandboxtest\.venv\Lib\site-packages\deepagents\middleware\filesystem.py", line 2272, in _handle_read_result
if read_result.error:
^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'error'
During task with name 'tools' and id 'dcbd2953-b995-xxxx' `
问题出在 read() 方法的签名和返回类型:当前 read 返回的是带行号格式化的 str,但新版本 deepagents 的 FilesystemMiddleware(_handle_read_result)要求 read() 返回 ReadResult 对象,且内部传入的是原始(未加行号)的 FileData 字典,由中间件下游统一做行号格式化与分页展示。
# agent的异步调用, `AIOSandboxBackend` 原版本不会发生错误
async for chunk in agent.astream(
{"messages": [{"role": "user", "content": "您有哪些技能(skills)"}]},
stream_mode="values"
):
if "messages" in chunk:
chunk["messages"][-1].pretty_print()
eg2: 改用ExitStack的写法
from contextlib import ExitStack
stack = ExitStack()
try:
backend = stack.enter_context(AIOSandboxBackend(client))
agent = create_deep_agent(model=llm, backend=backend, skills=["/home/gem/workspace/skills"])
# 业务逻辑
finally:
stack.close() # 最后手动释放所有入栈的上下文
注意:MongoDBSaver不能传入stack, TypeError: 'langgraph.checkpoint.mongodb.saver.MongoDBSaver' object does not support the context manager protocol
AIOSandboxBackend错误修复
DeepAgents集成中有个'str' 的错误(如上文)。此为对原版中的错误进行修复,主要是导入和 read 函数
from deepagents.backends.protocol import (
EditResult,
ExecuteResponse,
FileData,
FileDownloadResponse,
FileInfo,
FileUploadResponse,
ReadResult,
WriteResult,
)
def read(
self,
file_path: str,
offset: int = 0,
limit: int = 2000,
) -> ReadResult:
"""Read file content via file API and return a structured ReadResult."""
if limit <= 0:
return ReadResult(
file_data=FileData(
content="",
encoding="utf-8",
created_at="",
modified_at="",
),
no_lines_requested=True,
)
start = max(0, offset)
end = start + limit
try:
resp = self.client.file.read_file(
file=file_path,
start_line=start,
end_line=end,
)
raw_content = getattr(resp.data, "content", "") or ""
lines = raw_content.splitlines()
sliced_lines = lines[start:end] if len(lines) > limit else lines
sliced_content = "\n".join(sliced_lines)
file_data = FileData(
content=sliced_content,
encoding="utf-8",
created_at="",
modified_at="",
)
if not sliced_lines:
return ReadResult(
file_data=file_data,
start_line=None,
end_line=None,
next_offset=None,
)
actual_start_1based = start + 1
actual_end_1based = start + len(sliced_lines)
has_more = len(lines) >= limit and (start + len(sliced_lines) < len(lines) or len(lines) == limit)
next_off = (start + len(sliced_lines)) if has_more else None
return ReadResult(
file_data=file_data,
start_line=actual_start_1based,
end_line=actual_end_1based,
next_offset=next_off,
)
except ApiError as e:
msg = ""
if isinstance(e.body, dict):
msg = e.body.get("message", "")
return ReadResult(error=msg or f"Error: File '{file_path}' not found")
except Exception as e:
return ReadResult(error=f"Error reading file '{file_path}': {e}")
关键改动点
- **导入
FileData与ReadResult**:从deepagents.backends.protocol引入FileData和ReadResult。 - **返回
ReadResult而非str**:
- 出错或文件不存在时,返回
ReadResult(error=...)(file_data=None)。 - 成功时,构造
FileData({"content": sliced_content, "encoding": "utf-8", "created_at": "", "modified_at": ""})并填入ReadResult(file_data=..., start_line=..., end_line=..., next_offset=...)。
- 不要在
read()里手动拼接行号(6d\t):_handle_read_result期望的是原始文本窗口,手动加行号会导致行号重复或分页计算错乱。
python_repl
专用 Python REPL 工具(提供持久变量状态的交互执行):AIO Sandbox 本身内置了 Jupyter Kernel 代码执行接口;将其封装为 LangChain @tool 传给 create_deep_agent(tools=[...]),这样 Agent 既能像写脚本一样跑命令,也能像用 Jupyter 一样跨轮次保留变量与计算状态。
# return sandbox.jupyter.execute_code(code=code).data
# return sandbox.nodejs.execute_nodejs_code(code=code).data
from langchain_core.tools import tool
from agent_sandbox import Sandbox
@tool
def python_repl(code: str) -> str:
"""Execute Python code in an isolated AIO Sandbox Jupyter kernel; variables and state are preserved within the session."""
client = Sandbox(
base_url="http://localhost:8080",
headers={"X-AIO-API-Key": AIOSANDBOX_KEY}
return client.jupyter.execute_code(code=code).data