@agentsphere/code-interpreter
Version:
云端代码沙箱 SDK - 为 AI agents 提供安全的代码执行环境
134 lines (96 loc) • 3.76 kB
Markdown
# @agentsphere/code-interpreter
云端代码沙箱 SDK - 为 AI agents 提供安全的代码执行环境
## 简介
这是一个强大的云端代码执行平台 SDK,专为 AI agents 和自动化系统设计。提供安全隔离的沙箱环境,支持在云端运行各种编程语言的代码。基于 agentsphere-sandbox-base 构建,提供更好的性能和稳定性。
## ✨ 新特性 (v1.0.4)
- 🔄 **沙箱暂停/恢复功能** - 支持暂停沙箱状态并稍后恢复,保持代码执行上下文
- 🔧 **优化的依赖管理** - 从 e2b 迁移到 agentsphere-sandbox-base,提供更好的兼容性
- 🏷️ **包名重构** - 新的包名 `@agentsphere/code-interpreter` 更符合命名规范
- 🚀 **改进的模板系统** - 使用新的 `code-interpreter-v1` 模板,提供更好的性能
- 🔐 **增强的身份验证** - 支持访问令牌和更灵活的头部配置
- 📦 **TypeScript 优化** - 更好的类型定义和代码格式化
## 安装
```bash
npm install @agentsphere/code-interpreter
```
## 快速开始
### 1. 获取 API 密钥
1. 注册 agentsphere 账号 [这里](https://www.agentsphere.run)
2. 获取 API 密钥 [这里](https://www.agentsphere.run/apikey)
3. 设置环境变量:
```bash
AGENTSPHERE_API_KEY=your_api_key_here
```
### 2. 基础使用
```typescript
import { Sandbox } from '@agentsphere/code-interpreter'
const sandbox = await Sandbox.create()
console.log('沙箱已创建:', sandbox.sandboxId)
// 执行 Python 代码
const execution = await sandbox.runCode(`
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('正弦波')
plt.show()
`)
console.log('执行结果:', execution.text)
console.log('图表数据:', execution.results[0]?.data)
```
### 3. 沙箱暂停与恢复 🆕
```typescript
import { Sandbox } from '@agentsphere/code-interpreter'
// 创建沙箱并执行代码
const sbx = await Sandbox.create()
await sbx.runCode('x = 42')
// 暂停沙箱
const sandboxId = await sbx.betaPause()
console.log('沙箱已暂停:', sandboxId)
// 稍后恢复沙箱
const resumedSbx = await Sandbox.connect(sandboxId)
const result = await resumedSbx.runCode('print(f"x 的值是: {x}")')
console.log(result.text) // 输出: x 的值是: 42
await resumedSbx.kill()
```
## API 文档
### 核心方法
#### `Sandbox.create(template?: string)`
创建新的沙箱实例
#### `runCode(code: string, options?: RunCodeOpts)`
执行代码,支持回调和自定义配置
#### `createCodeContext(options?: CreateCodeContextOpts)`
创建新的代码执行上下文
#### `betaPause()` 🆕
暂停沙箱状态,返回沙箱ID用于后续恢复
#### `Sandbox.connect(sandboxId: string)` 🆕
连接到已暂停的沙箱实例
### 选项接口
```typescript
interface RunCodeOpts {
onStdout?: (output: OutputMessage) => Promise<any> | any
onStderr?: (output: OutputMessage) => Promise<any> | any
onResult?: (data: Result) => Promise<any> | any
onError?: (error: ExecutionError) => Promise<any> | any
envs?: Record<string, string>
timeoutMs?: number
requestTimeoutMs?: number
}
```
## 支持的语言
- Python (默认)
- JavaScript/TypeScript
- Java
- R
- Bash
- 更多语言持续添加中...
## 更新日志
### v1.0.4 (最新)
- ✅ 添加沙箱暂停/恢复功能
- ✅ 迁移到 agentsphere-sandbox-base 依赖
- ✅ 更新包名为 `@agentsphere/code-interpreter`
- ✅ 优化 TypeScript 类型定义
- ✅ 改进错误处理和超时机制
- ✅ 增强身份验证支持
**开始使用云端沙箱,让您的应用拥有安全的代码执行能力!** 🚀