@vectorx/ai-sandbox
v1.1.0
Published
AI sandbox for VectorX
Readme
@vectorx/ai-sandbox
阿里云 Code 沙箱 SDK,提供类似 @vercel/sandbox 的 API 接口,支持在安全的沙箱环境中执行代码、管理文件系统、执行命令等功能。
功能特性
- 🚀 沙箱管理: 创建、获取、停止和删除沙箱实例
- 💻 代码执行: 支持 Python 和 JavaScript 代码的安全执行
- 📁 文件操作: 上传、下载、读取、写入、移动、删除文件和目录
- 🔧 命令执行: 在沙箱中执行 shell 命令
- 📦 上下文管理: 独立的代码执行环境,支持多个上下文
- ⏱️ 超时控制: 灵活的沙箱生命周期和超时管理
安装
npm install @vectorx/ai-sandbox
# 或
pnpm add @vectorx/ai-sandbox快速开始
基本使用
import { Sandbox } from '@vectorx/ai-sandbox';
import ms from 'ms';
async function main() {
// 创建沙箱
const sandbox = await Sandbox.create({
// 阿里云配置
accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID!,
accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET!,
accountId: process.env.ALIYUN_ACCOUNT_ID!,
region: 'cn-hangzhou',
// 沙箱配置
templateName: 'python-sandbox', // 模板名称
timeout: ms('5m'), // 超时时间
});
try {
// 执行命令
const echo = await sandbox.runCommand('echo', ['Hello sandbox!']);
console.log(`Message: ${await echo.stdout()}`);
console.log(`Exit code: ${echo.exitCode}`);
// 执行 Python 代码
const result = await sandbox.executeCode(`
import math
print(f"π = {math.pi}")
result = 2 + 2
print(f"2 + 2 = {result}")
`, 'python');
console.log('Code execution results:');
result.results.forEach((r) => {
if (r.type === 'stdout' && r.text) {
console.log(r.text);
}
});
// 写入文件
await sandbox.writeFiles([
{
path: '/tmp/test.txt',
content: Buffer.from('Hello, World!'),
},
]);
// 读取文件
const buffer = await sandbox.readFileToBuffer({ path: '/tmp/test.txt' });
if (buffer) {
console.log('File content:', buffer.toString());
}
// 列出目录
const files = await sandbox.listFiles({ path: '/tmp' });
console.log('Files:', files.entries.map((e) => e.name));
} finally {
// 停止沙箱
await sandbox.stop();
}
}
main().catch(console.error);获取已有沙箱
import { Sandbox } from '@vectorx/ai-sandbox';
const sandbox = await Sandbox.get({
sandboxId: 'your-sandbox-id',
accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID!,
accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET!,
accountId: process.env.ALIYUN_ACCOUNT_ID!,
region: 'cn-hangzhou',
});执行命令
// 简单形式
const result = await sandbox.runCommand('ls', ['-la', '/tmp']);
// 对象形式
const result = await sandbox.runCommand({
cmd: 'python',
args: ['script.py'],
cwd: '/workspace',
env: { PYTHONPATH: '/workspace' },
});
console.log(await result.stdout());
console.log(await result.stderr());
console.log(result.exitCode);执行代码
// Python 代码
const pythonResult = await sandbox.executeCode(`
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
print(df)
`, 'python');
// JavaScript 代码
const jsResult = await sandbox.executeCode(`
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((a, b) => a + b, 0);
console.log('Sum:', sum);
`, 'javascript');文件操作
// 写入文件
await sandbox.writeFiles([
{ path: '/tmp/file1.txt', content: Buffer.from('Content 1') },
{ path: '/tmp/file2.txt', content: Buffer.from('Content 2') },
]);
// 读取文件
const buffer = await sandbox.readFileToBuffer({ path: '/tmp/file1.txt' });
if (buffer) {
console.log(buffer.toString());
}
// 创建目录
await sandbox.mkDir('/tmp/my-dir');
// 列出目录
const dir = await sandbox.listFiles({ path: '/tmp', depth: 2 });
dir.entries.forEach((entry) => {
console.log(`${entry.type}: ${entry.path}`);
});API 参考
Sandbox
Sandbox.create(params)
创建新沙箱实例。
参数:
accessKeyId: 阿里云 AccessKey IDaccessKeySecret: 阿里云 AccessKey SecretaccountId: 阿里云主账号 IDregion: 区域,如cn-hangzhoutemplateName: 模板名称(必需)sandboxId: 自定义沙箱 ID(可选)timeout: 超时时间(毫秒)baseUrl: 自定义数据面 API 基础 URL(可选)fetch: 自定义 fetch 函数(可选)
返回: Promise<Sandbox>
Sandbox.get(params)
获取已有沙箱实例。
参数:
sandboxId: 沙箱 IDaccessKeyId: 阿里云 AccessKey IDaccessKeySecret: 阿里云 AccessKey SecretaccountId: 阿里云主账号 IDregion: 区域
返回: Promise<Sandbox>
sandbox.runCommand(cmd, args?, opts?)
执行命令。
返回: Promise<CommandFinished>
sandbox.executeCode(code, language?, opts?)
执行代码(Python 或 JavaScript)。
返回: Promise<CodeExecutionResult>
sandbox.writeFiles(files, opts?)
写入文件。
sandbox.readFile(file, opts?)
读取文件为流。
sandbox.readFileToBuffer(file, opts?)
读取文件为 Buffer。
sandbox.mkDir(path, opts?)
创建目录。
sandbox.listFiles(opts?)
列出目录内容。
sandbox.stop(opts?)
停止沙箱。
sandbox.delete(opts?)
删除沙箱。
返回: Promise<SandboxMetadata> - 删除后的沙箱元数据,包含沙箱 ID、状态、创建时间等信息。
CommandFinished
command.stdout()
获取标准输出。
返回: Promise<string>
command.stderr()
获取标准错误输出。
返回: Promise<string>
command.output()
获取所有输出。
返回: Promise<string>
配置说明
环境变量
建议使用环境变量存储敏感信息:
ALIYUN_ACCESS_KEY_ID=your_access_key_id
ALIYUN_ACCESS_KEY_SECRET=your_access_key_secret
ALIYUN_ACCOUNT_ID=your_account_id模板创建
在使用 SDK 之前,需要先在阿里云控制台创建代码解释器模板,或通过控制面 API 创建。
注意事项
- 认证方式: 使用阿里云 AccessKey/SecretKey + 签名认证
- API 端点: 数据面和控制面使用不同的 baseUrl
- 超时处理: 沙箱最长生命周期为 6 小时
- 上下文管理: 代码执行需要先创建 context,命令执行不需要
- 文件限制: 上传文件最大 100MB,只支持文本文件扩展名
错误处理
import { APIError } from '@vectorx/ai-sandbox';
try {
const sandbox = await Sandbox.create({ ... });
} catch (error) {
if (error instanceof APIError) {
console.error('API Error:', error.message);
console.error('Status:', error.response.status);
console.error('Response:', error.json);
} else {
console.error('Unknown error:', error);
}
}示例代码
更多使用示例请参考 example/ 目录:
example/basic-usage.ts- 基本使用示例example/advanced-usage.ts- 高级功能示例
运行示例:
# 设置环境变量
export ALIYUN_ACCESS_KEY_ID="your_key"
export ALIYUN_ACCESS_KEY_SECRET="your_secret"
export ALIYUN_ACCOUNT_ID="your_account_id"
# 运行示例
cd example
pnpm install
pnpm example许可证
ISC
