跳转到主要内容
学习如何将工具与AG-Kit Agent集成,通过全面的工具包创建能与外部世界交互的强大AI工作流。

基础Agent集成

简单工具集成

最基本的Agent集成形式是创建一个自定义工具并将其提供给Agent。这使得Agent能够执行超出其基础语言能力的特定操作。
import { Agent, OpenAIProvider } from '@ag-kit/agents';
import { tool } from '@ag-kit/tools';
import { z } from 'zod';

// 创建提供者
const provider = new OpenAIProvider({
  apiKey: process.env.OPENAI_API_KEY!,
  defaultModel: 'gpt-4'
});

// 创建一个简单工具
const calculatorTool = tool(
  async ({ operation, a, b }) => {
    if (operation === 'divide' && b === 0) {
      return { success: false, error: 'Division by zero', error_type: 'validation' };
    }
    
    const operations = { add: a + b, subtract: a - b, multiply: a * b, divide: a / b };
    return {
      success: true,
      data: { result: operations[operation], operation, operands: [a, b] }
    };
  },
  {
    name: 'calculator',
    description: 'Perform basic mathematical calculations',
    schema: z.object({
      operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
      a: z.number(),
      b: z.number()
    })
  }
);

// 创建带工具的Agent
const mathAgent = new Agent({
  name: 'math-assistant',
  description: 'A helpful math assistant',
  model: provider,
  instructions: 'You are a helpful math assistant. Always show your work and explain the steps.',
  tools: [calculatorTool],
  modelSettings: { temperature: 0.1, maxTokens: 1000 }
});

// 使用Agent
const response = await mathAgent.run('What is 15 multiplied by 23?');
Agent集成的关键组件:
  • 模型提供者:配置LLM提供者(OpenAI、Anthropic等)
  • 工具定义:创建具有清晰模式和错误处理的工具
  • Agent配置:设置Agent的指令、工具和模型参数
  • 执行:使用自然语言输入运行Agent

多工具集成

对于更复杂的工作流,您可以将多个工具和工具包与单个Agent集成。这能创建出能够处理不同领域多样化任务的强大助手。
import { Agent } from '@ag-kit/agents';
import { 
  FilesystemToolkit,
  BuiltInCodeExecutor,
  createBashTool,
  LocalFileOperator
} from '@ag-kit/tools';

// 设置文件系统上下文
const fsContext = {
  workingDirectory: process.cwd(),
  fsOperator: new LocalFileOperator()
};

// 创建文件系统工具包
const filesystemToolkit = new FilesystemToolkit({
  name: 'filesystem-toolkit',
  context: fsContext
});

// 创建综合Agent
const developmentAgent = new Agent({
  name: 'development-assistant',
  description: 'A comprehensive development assistant',
  model: provider,
  instructions: 'You are a helpful development assistant with access to file operations, code execution, and command line tools.',
  tools: [
    ...filesystemToolkit.getTools(),
    new BuiltInCodeExecutor(),
    createBashTool(fsContext),
    calculatorTool
  ],
  modelSettings: { temperature: 0.1, maxTokens: 4000 }
});

const response = await developmentAgent.run(
  'Create a Python script that calculates the factorial of a number and save it to factorial.py'
);
这种方法使得Agent能够:
  • 读写文件 使用文件系统工具包
  • 执行代码 在安全的沙盒环境中
  • 运行命令行操作 实现系统交互
  • 执行计算 使用自定义工具

高级集成模式

智能工具选择

高级Agent可以配置多种专用工具和智能选择策略。Agent会根据任务上下文和用户需求自动选择最合适的工具。
// 为不同数据格式创建专用工具
const dataProcessingTools = [
  tool(
    async ({ filePath, operation }) => {
      // 实现细节...
      return { success: true, data: { processed: true, operation } };
    },
    {
      name: 'csv_processor',
      description: 'Process CSV data files and perform data analysis',
      schema: z.object({ 
        filePath: z.string(),
        operation: z.enum(['parse', 'analyze', 'transform'])
      })
    }
  ),
  tool(
    async ({ url, method, headers }) => {
      // 实现细节...
      return { success: true, data: { status: 200, response: 'API response' } };
    },
    {
      name: 'http_client',
      description: 'Make HTTP requests to external APIs',
      schema: z.object({ 
        url: z.string(),
        method: z.enum(['GET', 'POST', 'PUT', 'DELETE']).default('GET'),
        headers: z.record(z.string()).optional()
      })
    }
  )
];

// 创建包含多种专用工具的Agent
const smartAgent = /* Agent初始化 */ {
  /* ... */
  tools: [...dataProcessingTools, ...filesystemToolkit.getTools()],
  /* ... */
};
智能工具选择的优势:
  • 自动工具路由 基于任务需求
  • 上下文决策 优化工具使用
  • 可扩展架构 方便添加新专用工具
  • 清晰推理 工具选择逻辑透明

错误处理与容错机制

优雅的错误恢复

构建能够优雅处理工具故障的稳健Agent对生产应用至关重要。AG-Kit提供了多种错误处理和恢复机制。
// 创建具备错误处理能力的稳健Agent
const resilientAgent = /* Agent初始化 */ {
  /* ... */
  tools: [
    ...filesystemToolkit.getTools(),
    new BuiltInCodeExecutor()
  ],
  /* controlFlow: { errorRetryLimit: 2, maxSteps: 10 } */
};

// 使用时的错误处理
try {
  const response = await resilientAgent.run('Process this complex request');
  console.log('Success:', response);
} catch (error) {
  console.error('Agent error:', error.message);
  // 实施回退策略或用户通知
}

输入验证与安全

在工具中实施适当的输入验证和安全措施对Agent的安全操作至关重要,特别是在处理文件系统或外部API时。
const validatedTool = tool(
  async ({ filePath, operation }) => {
    try {
      const fs = await import('fs/promises');
      
      // 执行前验证
      try {
        await fs.access(filePath);
        const stats = await fs.stat(filePath);
        if (stats.size > 10 * 1024 * 1024) { // 10MB限制
          return { 
            success: false, 
            error: 'File too large (max 10MB)', 
            error_type: 'validation' 
          };
        }
      } catch {
        return { 
          success: false, 
          error: 'File does not exist', 
          error_type: 'validation' 
        };
      }
      
      // 带错误处理的操作执行
      const operations = {
        read: async () => ({ content: await fs.readFile(filePath, 'utf-8') }),
        analyze: async () => {
          const content = await fs.readFile(filePath, 'utf-8');
          return { 
            lines: content.split('\n').length,
            characters: content.length,
            words: content.split(/\s+/).length
          };
        },
        transform: async () => ({ message: 'Transform operation completed' })
      };
      
      const result = await operations[operation]();
      
      // 执行后验证
      if (!result || typeof result !== 'object') {
        return {
          success: false,
          error: 'Invalid processing result',
          error_type: 'execution'
        };
      }
      
      return { success: true, data: result };
      
    } catch (error) {
      return { 
        success: false, 
        error: error.message, 
        error_type: 'execution' 
      };
    }
  },
  {
    name: 'validated_file_processor',
    description: 'Process files with comprehensive validation and security checks',
    schema: z.object({
      filePath: z.string().refine(
        (path) => !path.includes('..') && !path.startsWith('/'),
        'File path must be relative and safe'
      ),
      operation: z.enum(['read', 'analyze', 'transform'])
    })
  }
);

// 在Agent中使用已验证工具
const secureAgent = /* Agent初始化 */ {
  /* ... */
  tools: [validatedTool],
  /* ... */
};
关键验证实践:
  • 输入净化 防止路径遍历攻击
  • 文件大小限制 避免资源耗尽
  • 执行前后验证 确保数据完整性
  • 结构化错误响应 包含适当的错误类型

流式处理与实时集成

流式工具响应

对于长时间运行的操作或实时数据处理,AG-Kit支持流式响应,可向用户提供进度更新和中间结果。
import { EventEmitter } from 'events';

// 为长时间运行操作创建流式工具
const streamingTool = tool(
  async ({ dataset, batchSize }) => {
    const stream = new EventEmitter();
    
    // 模拟带进度更新的流式处理
    [25, 50, 75, 100].forEach((progress, index) => {
      setTimeout(() => {
        const event = progress === 100 ? 'complete' : 'progress';
        stream.emit(event, { 
          progress, 
          message: `Processing batch ${index + 1}`,
          timestamp: new Date().toISOString()
        });
      }, (index + 1) * 1000);
    });
    
    return {
      success: true,
      stream,
      data: { 
        message: 'Streaming processing started', 
        batchSize,
        estimatedDuration: '4 seconds'
      }
    };
  },
  {
    name: 'streaming_processor',
    description: 'Process large datasets with real-time progress updates',
    schema: z.object({
      dataset: z.string(),
      batchSize: z.number().default(100)
    })
  }
);

// 创建流式Agent
const streamingAgent = /* Agent初始化 */ {
  /* ... */
  tools: [streamingTool],
  /* ... */
};

// 启用流式的使用方式
const response = await streamingAgent.run(
  'Process the large dataset with real-time progress updates',
  /* state, options */
);

// 处理流式响应
if (response.stream) {
  response.stream.subscribe({
    next: (chunk) => {
      console.log('Streaming chunk:', chunk);
      // 使用进度信息更新UI
    },
    error: (error) => {
      console.error('Stream error:', error);
      // 处理流式错误
    },
    complete: () => {
      console.log('Stream completed');
      // 完成UI更新
    }
  });
}
流式处理能力可实现:
  • 实时进度追踪 针对长时间运行的操作
  • 中间结果交付 提供更好的用户体验
  • 响应式UI更新 在处理过程中
  • 早期错误检测 和处理

性能优化

并行工具执行

AG-Kit Agent可以自动并行执行独立的工具调用,显著提升不相互依赖操作的性能。
// 创建支持并行执行的Agent
const parallelAgent = /* Agent初始化 */ {
  /* ... */
  tools: [
    calculatorTool,
    ...filesystemToolkit.getTools()
  ],
  /* ... */
};

// Agent会自动并行执行独立的工具调用
const response = await parallelAgent.run(
  'Calculate 15 * 23, read the config.json file, and check if package.json exists'
);
性能优势:
  • 减少执行时间 针对独立操作
  • 更好的资源利用率 通过并发处理
  • 改进用户体验 响应速度更快
  • 自动优化 无需手动协调

后续步骤