跳到主要内容

智能体框架与 SDK

Mastra

将 Mastra 工作区连接到 E2B 沙箱。使用 @mastra/e2b,Mastra 智能体运行的命令会在隔离的云端沙箱中执行,而不是在您的机器上。

维护方
Mastra
集成方式
Mastra 工作区沙箱
软件包
@mastra/e2b
语言
TypeScript

配置

快速开始

将提示词粘贴到您的编程智能体中,或按以下步骤自行配置。

粘贴到您的编程智能体中

为这个 Mastra 项目添加 E2B 沙箱。

  1. 1.使用项目的包管理器安装 @mastra/core 和 @mastra/e2b。
  2. 2.沙箱需要 E2B_API_KEY 环境变量。如果尚未设置,请向我索要 API 密钥(在 https://console.e2b.dev/?tab=keys 获取)。切勿将其硬编码。
  3. 3.按照 https://docs.e2b.dev/agents/mastra 上的 Mastra 指南操作。为我的智能体提供一个带 E2BSandbox 的 Workspace,在运行前调用 workspace.init(),并在 finally 块中调用 workspace.destroy()。
  4. 4.运行一个任务,并展示来自沙箱的输出。

或自行配置

  1. 1. 安装 Mastra 和 E2B 提供方

    npm init -y && npm pkg set type=module
    npm install @mastra/core @mastra/e2b zod
    npm install --save-dev tsx typescript @types/node
  2. 2. 设置 API 密钥

    export E2B_API_KEY="e2b_***"
    export OPENAI_API_KEY="sk-***"
  3. 3. 为智能体提供沙箱工作区

    import { Agent } from '@mastra/core/agent'
    import { Workspace } from '@mastra/core/workspace'
    import { E2BSandbox } from '@mastra/e2b'
    
    const workspace = new Workspace({
      sandbox: new E2BSandbox({
        id: `mastra-coding-agent-${Date.now()}`,
        timeout: 600_000,
      }),
    })
    
    const agent = new Agent({
      id: 'coding-agent',
      name: 'Coding Agent',
      model: 'openai/gpt-5.4-mini',
      instructions: 'You are a software engineer working in an isolated E2B sandbox.',
      workspace,
    })
  4. 4. 运行智能体

    const task = process.argv.slice(2).join(' ') || 'Create a small Express API with a health endpoint and test it'
    
    try {
      await workspace.init()
    
      const stream = await agent.stream(task, { maxSteps: 30 })
    
      for await (const chunk of stream.textStream) {
        process.stdout.write(chunk)
      }
    } finally {
      await workspace.destroy()
    }

安全

沙箱中运行的内容

Mastra 智能体在本地运行;它选择执行的命令在隔离的沙箱中运行。

  • 命令智能体发起的 execute_command 调用,由 @mastra/e2b 路由到 E2B 命令执行。
  • 文件仅含沙箱的工作区没有 read_file 或 write_file 工具,因此智能体通过 Shell 处理文件。
  • 生命周期workspace.init() 创建或重新连接沙箱,workspace.destroy() 将其终止。timeout 以毫秒为单位。
  • 模板向 E2BSandbox 传入模板 ID 或名称,即可预装运行时和依赖。

已启动 30亿+ 个沙箱

为每个智能体 配一台机器