跳转到主要内容
AG-Kit通过两种主要执行器提供强大的代码执行能力:沙盒化执行保障安全,本地执行追求性能。本指南将帮助您选择合适的工具,并有效应用于Agent的工作流程中。

何时使用代码执行工具

当您的Agent需要运行动态代码片段或脚本时使用这些工具。

快速入门

import { BuiltInCodeExecutor, UnsafeLocalCodeExecutor } from '@ag-kit/tools';

// 根据场景选择执行器
const executor = process.env.USE_SANDBOX
  ? new BuiltInCodeExecutor()
  : new UnsafeLocalCodeExecutor({});

// 运行Python代码片段
const result = await executor.execute({
  language: 'python',
  code: 'print(3 * 7)'
});

if (result.success) {
  console.log('Output:', result.data.stdout); // '21'
}

典型工作流

  • 数据处理:读取文件,执行Python脚本进行分析并输出结果
  • 代码生成与测试:让LLM生成代码,在沙盒中验证正确性并反馈
  • DevOps自动化:运行Shell脚本搭建项目、检查代码或运行测试

选择适合的执行器

执行器使用场景核心优势
BuiltInCodeExecutor不可信代码(来自LLM或用户)安全隔离
UnsafeLocalCodeExecutor可信代码(自有脚本)性能速度
  • 优先选择BuiltInCodeExecutor(沙盒化):当安全性至关重要时使用,提供执行隔离、允许安装包并控制环境
  • 使用UnsafeLocalCodeExecutor(本地化):在开发环境或受控CI环境中运行可信脚本,需要最高性能和直接访问本地文件时

核心功能与配置

两种执行器共享通用应用程序接口但采用不同后端实现。

配置选项

  • 超时设置:通过timeoutMs防止脚本失控运行
  • 环境变量:通过envs注入密钥或配置
  • 流式输出:使用onStdoutonStderr获取长时间任务的实时反馈
// 示例:带配置的沙盒执行器
const executor = new BuiltInCodeExecutor();
// 或创建可在代码中使用的沙盒环境
import { Sandbox } from '@e2b/code-interpreter';
const executor = new BuiltInCodeExecutor({
  sandbox: Sandbox.create({
    apiKey: process.env.E2B_API_KEY,
    timeoutMs: 60000, // 1分钟超时
    envs: { CUSTOM_VAR: 'value' },
  })
});

支持语言

可执行多种语言代码并获取结构化结果:
const result = await executor.execute({ 
  language: 'python', 
  code: 'import pandas as pd\nprint(pd.__version__)' 
});
// result.data: { stdout: '2.1.4\n', stderr: '', exitCode: 0 }

工作流示例:Agent集成

将代码执行与FilesystemToolkit等工具结合,构建强大的Agent。