agentsphere-sandbox-base
v1.0.14
Published
云端代码沙箱 SDK - 为 AI agents 提供安全的代码执行环境
Maintainers
Readme
agentsphere-sandbox-base
云端代码沙箱 SDK - 为 AI agents 提供安全的代码执行环境
简介
这是一个强大的云端代码执行平台 SDK,专为 AI agents 和自动化系统设计。提供安全隔离的沙箱环境,支持在云端运行各种编程语言的代码。
安装
npm install agentsphere-sandbox-base快速开始
1. 获取 API 密钥
- 注册云沙箱服务账号
- 获取您的 API 密钥
- 设置环境变量:
SANDBOX_API_KEY=your_api_key_here2. 使用代码解释器
import { Sandbox } from 'agentsphere-sandbox-base'
// 创建云端沙箱实例(推荐使用新版API)
const sandbox = await Sandbox.betaCreate({
autoPause: true // 超时后自动暂停而不是终止,节省资源
})
// 执行 Python 代码
const result = await sandbox.runCode(`
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10))
`)
console.log(result.stdout) // 输出: 55
await sandbox.close()💡 提示: 推荐使用
Sandbox.betaCreate()而不是Sandbox.create(),新版本支持自动暂停功能,更加节省资源。
API 文档
传统 API(稳定版本)
// 创建沙箱(传统方式 - 超时后直接终止)
const sandbox = await Sandbox.create({
timeoutMs: 300_000 // 5分钟后直接终止沙箱
})
// 执行代码
const result = await sandbox.runCode(code: string)
// 文件操作
await sandbox.writeFile('/path/to/file', content)
const content = await sandbox.readFile('/path/to/file')
// 管理沙箱
await sandbox.kill() // 终止沙箱
await sandbox.close() // 关闭连接新版 API(Beta版本 - 推荐使用)
// 创建沙箱(新方式 - 支持自动暂停)
const sandbox = await Sandbox.betaCreate({
autoPause: true, // 默认为 true,超时后自动暂停而不是终止
timeoutMs: 300_000 // 5分钟后暂停
})
// 执行代码(与传统API相同)
const result = await sandbox.runCode(code: string)
// 文件操作(与传统API相同)
await sandbox.writeFile('/path/to/file', content)
const content = await sandbox.readFile('/path/to/file')
// 新的沙箱管理功能
await sandbox.betaPause() // 手动暂停沙箱
await sandbox.kill() // 终止沙箱
await sandbox.close() // 关闭连接
// 恢复暂停的沙箱
const resumedSandbox = await Sandbox.resume(sandboxId, {
autoPause: true // 恢复时设置自动暂停
})版本差异对比
| 功能 | 传统 API (Sandbox.create) | 新版 API (Sandbox.betaCreate) |
|------|---------------------------|--------------------------------|
| 超时行为 | 直接终止沙箱 | 自动暂停沙箱(默认) |
| 资源消耗 | 超时后停止计费 | 暂停后停止计费 |
| 状态保留 | ❌ 完全丢失 | ✅ 完全保留 |
| 恢复速度 | 需要重新创建 | 快速恢复 |
| 兼容性 | 稳定版本 | Beta 版本 |
| 推荐使用 | 旧项目维护 | 新项目开发 |
自动暂停功能详解
自动暂停是新版 API 的核心功能,提供更灵活的资源管理:
// 新版本:超时后自动暂停
const sandbox = await Sandbox.betaCreate({
autoPause: true, // 默认为 true
timeoutMs: 300_000 // 5分钟后暂停
})
// 传统版本:超时后直接终止
const oldSandbox = await Sandbox.create({
timeoutMs: 300_000 // 5分钟后终止
})自动暂停的优势:
- 💰 节省成本: 暂停的沙箱不消耗计算资源
- 🔄 快速恢复: 比重新创建沙箱更快
- 💾 保留状态: 文件系统和环境变量都会保留
- 🎯 默认启用: 新创建的沙箱默认支持自动暂停
- 🛡️ 向后兼容: 可以选择禁用(设置
autoPause: false)
功能特性
- 🔒 安全隔离: 每个代码执行都在独立的容器环境中
- 🌐 多语言支持: Python, JavaScript, Node.js, Bash 等
- ⚡ 实时执行: 快速的代码执行和结果返回
- 📝 TypeScript: 完整的类型定义支持
- 🔄 跨平台: 支持浏览器和 Node.js 环境
- 📁 文件系统: 完整的文件读写和管理功能
- ⏸️ 自动暂停: 支持沙箱超时后自动暂停,节省资源并可恢复使用
- 🎯 AI 友好: 专为 AI agents 和自动化工作流设计
使用场景
- AI 代码助手: 安全执行 AI 生成的代码
- 在线代码编辑器: 构建 Web IDE 和代码演示
- 自动化测试: 在隔离环境中运行测试脚本
- 数据处理: 云端数据分析和处理管道
- 教育平台: 安全的编程学习环境
许可证
MIT License
开始使用云端沙箱,让您的应用拥有安全的代码执行能力! 🚀
