import { createDeepAgent } from "deepagents";import { ChatAnthropic } from "@langchain/anthropic";import { DenoSandbox } from "@langchain/deno";// Create and initialize the sandboxconst sandbox = await DenoSandbox.create({ memoryMb: 1024, lifetime: "10m",});try { const agent = createDeepAgent({ model: new ChatAnthropic({ model: "claude-opus-4-6" }), systemPrompt: "You are a JavaScript coding assistant with sandbox access.", backend: sandbox, }); const result = await agent.invoke({ messages: [ { role: "user", content: "Create a simple HTTP server using Deno.serve and test it with curl", }, ], });} finally { await sandbox.close();}
// Create and initializeconst sandbox = await ModalSandbox.create(options);// Use the sandbox (directly or via an agent)const result = await sandbox.execute("echo hello");// Clean up when doneawait sandbox.close();
智能体在您的机器或服务器上运行。当它需要执行代码时,它会调用沙箱工具(如 execute, read_file, 或 write_file),这些工具调用提供商的 API 以在远程沙箱中运行操作。优点:
✅ 无需重新构建镜像即可立即更新智能体代码。
✅ 智能体状态与执行更清晰的分离。
API 密钥保留在沙箱外部。
沙箱故障不会丢失智能体状态。
可以选择并行在多个沙箱中运行任务。
✅ 仅为执行时间付费。
权衡
🔴 每次执行调用都有网络延迟。
示例
import "dotenv/config";import { DaytonaSandbox } from "@langchain/daytona";import { createDeepAgent } from "deepagents";// Can also do this with E2B, Runloop, Modalconst sandbox = await DaytonaSandbox.create();const agent = createDeepAgent({ backend: sandbox, systemPrompt: "You are a coding assistant with sandbox access. You can create and run code in the sandbox.",});try { const result = await agent.invoke({ messages: [ { role: "user", content: "Create a hello world Python script and run it", }, ], }); const lastMessage = result.messages[result.messages.length - 1]; console.log( typeof lastMessage.content === "string" ? lastMessage.content : String(lastMessage.content), );} catch (err) { // Optional: delete the sandbox proactively on an exception await sandbox.close(); throw err;}
本说明文档中的示例使用的是“沙箱作为工具”模式。当您的提供商 SDK 处理通信层并且您希望生产环境与本地开发保持一致时,请选择“沙箱中的智能体”模式。当您需要快速迭代智能体逻辑、将 API 密钥保留在沙箱外部或更喜欢更清晰的关注点分离时,请选择“沙箱作为工具”模式。
const encoder = new TextEncoder();const responses = await sandbox.uploadFiles([ ["src/index.js", encoder.encode("console.log('Hello')")], ["package.json", encoder.encode('{"name": "my-app"}')],]);// Each response indicates success or failurefor (const res of responses) { if (res.error) { console.error(`Failed to upload ${res.path}: ${res.error}`); }}