Active Planning 和 Tools 如何对接业务需求

🤖 AI Agent 架构实施指南

Agent = LLM + Memory + Active Planning + Tools

重点:Active Planning 和 Tools 如何对接业务需求


📋 目录


🎯 核心概念

Agent 四大组件

┌────────────────────────────────────────────────────────┐
│                    AI Agent 架构                        │
├────────────────────────────────────────────────────────┤
│                                                        │
│  1️⃣  LLM (大语言模型) ✅ 成熟                          │
│      └─ 理解、推理、生成                               │
│                                                        │
│  2️⃣  Memory (记忆系统) ✅ 成熟                         │
│      ├─ 短期记忆: 对话历史                             │
│      └─ 长期记忆: 向量数据库 + RAG                     │
│                                                        │
│  3️⃣  Active Planning (主动规划) 🔥 关键               │
│      ├─ 任务分解: 复杂任务 → 子任务                    │
│      ├─ 执行计划: 确定执行顺序                         │
│      ├─ 动态调整: 根据执行结果调整计划                 │
│      └─ 自我反思: 评估结果质量                         │
│                                                        │
│  4️⃣  Tools (工具系统) 🔥 关键                          │
│      ├─ 工具注册: 定义可用工具                         │
│      ├─ 工具选择: 选择合适的工具                       │
│      ├─ 参数提取: 从用户输入提取参数                   │
│      └─ 结果处理: 整合工具执行结果                     │
│                                                        │
└────────────────────────────────────────────────────────┘

核心流程

用户输入
    ↓
[理解意图] ← LLM
    ↓
[制定计划] ← Active Planning
    ↓
    ├─ 任务1 → [选择工具] → [执行] → 结果1
    ├─ 任务2 → [选择工具] → [执行] → 结果2
    └─ 任务3 → [选择工具] → [执行] → 结果3
    ↓
[整合结果] ← Memory
    ↓
[自我反思] → 是否需要重新规划?
    ↓
生成回答

📚 四大组件详解

1. LLM (大语言模型) - 已成熟 ✅

作用:Agent 的"大脑",负责理解、推理、决策

实现方式

// 本地 Ollama
const llm = {
  url: 'http://localhost:11434/api/generate',
  model: 'qwen2.5:7b'
};

// 或云端 API
const llm = {
  url: 'https://api.openai.com/v1/chat/completions',
  model: 'gpt-4'
};

关键能力

  • ✅ 自然语言理解
  • ✅ 逻辑推理
  • ✅ 代码生成
  • ✅ 决策制定

2. Memory (记忆系统) - 已成熟 ✅

作用:Agent 的"记忆",存储对话历史和知识

2.1 短期记忆

class ShortTermMemory {
  constructor(maxTurns = 10) {
    this.history = [];
    this.maxTurns = maxTurns;
  }

  add(role, content) {
    this.history.push({ role, content, timestamp: Date.now() });
    
    // 保持最近 N 轮对话
    if (this.history.length > this.maxTurns * 2) {
      this.history = this.history.slice(-this.maxTurns * 2);
    }
  }

  getHistory() {
    return this.history;
  }

  clear() {
    this.history = [];
  }
}

2.2 长期记忆

class LongTermMemory {
  constructor(vectorDB) {
    this.vectorDB = vectorDB;  // Qdrant/Milvus/Weaviate
  }

  async store(content, metadata) {
    // 存储到向量数据库
    await this.vectorDB.insert({
      content: content,
      metadata: {
        ...metadata,
        timestamp: Date.now()
      }
    });
  }

  async recall(query, topK = 5) {
    // 从向量数据库检索
    return await this.vectorDB.search(query, topK);
  }
}

整合使用

class Memory {
  constructor(vectorDB) {
    this.shortTerm = new ShortTermMemory();
    this.longTerm = new LongTermMemory(vectorDB);
  }

  async remember(query) {
    // 1. 获取对话历史(短期)
    const history = this.shortTerm.getHistory();
    
    // 2. 检索相关知识(长期)
    const relevant = await this.longTerm.recall(query);
    
    return {
      history: history,
      knowledge: relevant
    };
  }
}

3. Active Planning (主动规划) - 🔥 重点 1

作用:Agent 的"规划能力",将复杂任务分解并制定执行计划

核心概念

复杂任务
    ↓
[任务分解]
    ↓
子任务1, 子任务2, 子任务3, ...
    ↓
[规划执行顺序]
    ↓
执行计划: [步骤1] → [步骤2] → [步骤3]
    ↓
[动态执行]
    ↓
根据结果调整计划

3.1 任务分解器

/**
 * 任务分解器
 * 将复杂任务分解为可执行的子任务
 */
class TaskDecomposer {
  constructor(llm) {
    this.llm = llm;
  }

  /**
   * 分解任务
   */
  async decompose(task) {
    const prompt = `
你是一个任务规划专家。请将以下复杂任务分解为具体的、可执行的子任务。

任务: ${task}

要求:
1. 每个子任务应该是具体的、可执行的
2. 子任务之间应该有逻辑顺序
3. 考虑依赖关系
4. 输出JSON格式

输出格式:
{
  "tasks": [
    {
      "id": "task_1",
      "description": "子任务描述",
      "dependencies": [],
      "estimatedTime": "预计耗时"
    }
  ]
}

你的输出:`;

    const response = await this.llm.generate(prompt);
    
    try {
      const parsed = JSON.parse(response);
      return parsed.tasks;
    } catch (error) {
      console.error('任务分解失败:', error);
      // 回退方案:返回单个任务
      return [{
        id: 'task_1',
        description: task,
        dependencies: [],
        estimatedTime: 'unknown'
      }];
    }
  }
}

示例

输入: "帮我分析竞争对手的产品,并生成一份对比报告"

输出:
[
  {
    id: "task_1",
    description: "收集竞争对手列表",
    dependencies: [],
    estimatedTime: "5分钟"
  },
  {
    id: "task_2",
    description: "查询每个竞争对手的产品信息",
    dependencies: ["task_1"],
    estimatedTime: "10分钟"
  },
  {
    id: "task_3",
    description: "提取关键特性和价格",
    dependencies: ["task_2"],
    estimatedTime: "5分钟"
  },
  {
    id: "task_4",
    description: "生成对比表格",
    dependencies: ["task_3"],
    estimatedTime: "3分钟"
  },
  {
    id: "task_5",
    description: "撰写分析报告",
    dependencies: ["task_4"],
    estimatedTime: "10分钟"
  }
]

3.2 执行规划器

/**
 * 执行规划器
 * 根据任务依赖关系规划执行顺序
 */
class ExecutionPlanner {
  /**
   * 生成执行计划
   */
  plan(tasks) {
    // 1. 构建依赖图
    const graph = this.buildDependencyGraph(tasks);
    
    // 2. 拓扑排序
    const executionOrder = this.topologicalSort(graph);
    
    // 3. 识别可并行执行的任务
    const executionStages = this.identifyParallelStages(executionOrder, tasks);
    
    return {
      order: executionOrder,
      stages: executionStages,
      totalTasks: tasks.length
    };
  }

  /**
   * 构建依赖图
   */
  buildDependencyGraph(tasks) {
    const graph = new Map();
    
    tasks.forEach(task => {
      graph.set(task.id, {
        task: task,
        dependencies: task.dependencies || [],
        dependents: []
      });
    });
    
    // 构建反向依赖
    tasks.forEach(task => {
      (task.dependencies || []).forEach(depId => {
        if (graph.has(depId)) {
          graph.get(depId).dependents.push(task.id);
        }
      });
    });
    
    return graph;
  }

  /**
   * 拓扑排序
   */
  topologicalSort(graph) {
    const result = [];
    const visited = new Set();
    const inDegree = new Map();
    
    // 计算入度
    graph.forEach((node, id) => {
      inDegree.set(id, node.dependencies.length);
    });
    
    // 找到所有入度为0的节点
    const queue = [];
    inDegree.forEach((degree, id) => {
      if (degree === 0) {
        queue.push(id);
      }
    });
    
    // BFS
    while (queue.length > 0) {
      const current = queue.shift();
      result.push(current);
      visited.add(current);
      
      // 更新依赖此节点的其他节点
      graph.get(current).dependents.forEach(depId => {
        const newDegree = inDegree.get(depId) - 1;
        inDegree.set(depId, newDegree);
        
        if (newDegree === 0) {
          queue.push(depId);
        }
      });
    }
    
    return result;
  }

  /**
   * 识别可并行执行的阶段
   */
  identifyParallelStages(executionOrder, tasks) {
    const taskMap = new Map(tasks.map(t => [t.id, t]));
    const stages = [];
    const completed = new Set();
    
    while (completed.size < tasks.length) {
      const currentStage = [];
      
      for (const taskId of executionOrder) {
        if (completed.has(taskId)) continue;
        
        const task = taskMap.get(taskId);
        const depsCompleted = (task.dependencies || []).every(dep => 
          completed.has(dep)
        );
        
        if (depsCompleted) {
          currentStage.push(taskId);
          completed.add(taskId);
        }
      }
      
      if (currentStage.length > 0) {
        stages.push(currentStage);
      }
    }
    
    return stages;
  }
}

示例输出

{
  order: ["task_1", "task_2", "task_3", "task_4", "task_5"],
  stages: [
    ["task_1"],           // 阶段1: 只有task_1
    ["task_2"],           // 阶段2: task_2依赖task_1
    ["task_3"],           // 阶段3: task_3依赖task_2
    ["task_4", "task_5"]  // 阶段4: task_4和task_5可并行
  ],
  totalTasks: 5
}

3.3 自我反思器

/**
 * 自我反思器
 * 评估任务执行结果,决定是否需要重新规划
 */
class SelfReflection {
  constructor(llm) {
    this.llm = llm;
  }

  /**
   * 评估执行结果
   */
  async evaluate(task, result) {
    const prompt = `
评估以下任务的执行结果质量:

任务: ${task.description}
执行结果: ${JSON.stringify(result)}

评估维度:
1. 完整性: 是否完成了任务要求?(0-10分)
2. 准确性: 结果是否准确?(0-10分)
3. 可用性: 结果是否可以用于后续任务?(0-10分)

输出JSON格式:
{
  "completeness": 分数,
  "accuracy": 分数,
  "usability": 分数,
  "overallScore": 总分,
  "needsRetry": true/false,
  "suggestions": "改进建议"
}

你的评估:`;

    const response = await this.llm.generate(prompt);
    
    try {
      return JSON.parse(response);
    } catch (error) {
      return {
        completeness: 5,
        accuracy: 5,
        usability: 5,
        overallScore: 5,
        needsRetry: false,
        suggestions: '评估失败'
      };
    }
  }

  /**
   * 决定是否需要重新规划
   */
  shouldReplan(evaluations) {
    // 如果平均分低于6分,或有任务需要重试
    const avgScore = evaluations.reduce((sum, e) => sum + e.overallScore, 0) 
      / evaluations.length;
    
    const hasRetry = evaluations.some(e => e.needsRetry);
    
    return avgScore < 6 || hasRetry;
  }
}

3.4 完整的规划系统

/**
 * Active Planning 系统
 */
class ActivePlanning {
  constructor(llm) {
    this.decomposer = new TaskDecomposer(llm);
    this.planner = new ExecutionPlanner();
    this.reflection = new SelfReflection(llm);
  }

  /**
   * 制定并执行计划
   */
  async planAndExecute(complexTask, toolExecutor) {
    console.log('🎯 开始规划...');
    
    // 1. 任务分解
    const subtasks = await this.decomposer.decompose(complexTask);
    console.log(`   ✓ 分解为 ${subtasks.length} 个子任务`);

    // 2. 生成执行计划
    const plan = this.planner.plan(subtasks);
    console.log(`   ✓ 生成执行计划: ${plan.stages.length} 个阶段`);

    // 3. 执行计划
    const results = [];
    let attemptCount = 0;
    const maxAttempts = 2;

    while (attemptCount < maxAttempts) {
      attemptCount++;
      console.log(`\n📋 执行计划 (尝试 ${attemptCount}/${maxAttempts})...`);

      // 按阶段执行
      for (let stageIdx = 0; stageIdx < plan.stages.length; stageIdx++) {
        const stage = plan.stages[stageIdx];
        console.log(`\n   阶段 ${stageIdx + 1}/${plan.stages.length}:`);

        // 并行执行本阶段的任务
        const stageResults = await Promise.all(
          stage.map(async taskId => {
            const task = subtasks.find(t => t.id === taskId);
            console.log(`      → 执行: ${task.description}`);

            const result = await toolExecutor.execute(task, results);
            return { task, result };
          })
        );

        results.push(...stageResults);
      }

      // 4. 自我反思
      console.log('\n🤔 自我反思...');
      const evaluations = await Promise.all(
        results.map(({ task, result }) => 
          this.reflection.evaluate(task, result)
        )
      );

      const avgScore = evaluations.reduce((sum, e) => sum + e.overallScore, 0) 
        / evaluations.length;
      console.log(`   平均得分: ${avgScore.toFixed(1)}/10`);

      // 5. 决定是否需要重新规划
      if (!this.reflection.shouldReplan(evaluations)) {
        console.log('   ✓ 质量合格,完成');
        break;
      } else if (attemptCount < maxAttempts) {
        console.log('   ⚠️  质量不佳,重新规划...');
        // 重置结果,重新执行
        results.length = 0;
      }
    }

    return {
      subtasks: subtasks,
      plan: plan,
      results: results,
      attempts: attemptCount
    };
  }
}

4. Tools (工具系统) - 🔥 重点 2

作用:Agent 的"手脚",赋予 Agent 与外部世界交互的能力

核心概念

工具 = 接口 + 描述 + 参数定义 + 执行逻辑

Agent通过工具可以:
  - 查询数据库
  - 调用API
  - 执行代码
  - 操作文件
  - 发送消息
  - ...

4.1 工具定义规范

/**
 * 工具基类
 */
class Tool {
  constructor(config) {
    this.name = config.name;           // 工具名称
    this.description = config.description;  // 功能描述
    this.parameters = config.parameters;    // 参数定义
    this.returns = config.returns;          // 返回值说明
    this.examples = config.examples || [];  // 使用示例
  }

  /**
   * 执行工具(子类需实现)
   */
  async execute(params) {
    throw new Error('子类必须实现 execute 方法');
  }

  /**
   * 验证参数
   */
  validateParams(params) {
    for (const [key, schema] of Object.entries(this.parameters)) {
      if (schema.required && !(key in params)) {
        throw new Error(`缺少必需参数: ${key}`);
      }

      if (key in params) {
        const value = params[key];
        const expectedType = schema.type;

        if (typeof value !== expectedType) {
          throw new Error(`参数 ${key} 类型错误: 期望 ${expectedType}, 实际 ${typeof value}`);
        }
      }
    }
  }

  /**
   * 获取工具描述(用于LLM理解)
   */
  getDescription() {
    const paramDesc = Object.entries(this.parameters)
      .map(([name, schema]) => {
        const required = schema.required ? '(必需)' : '(可选)';
        return `  - ${name} ${required}: ${schema.description}`;
      })
      .join('\n');

    return `
工具名称: ${this.name}
功能: ${this.description}
参数:
${paramDesc}
返回: ${this.returns}
`;
  }
}

4.2 工具示例

示例 1: 数据库查询工具
class DatabaseQueryTool extends Tool {
  constructor(database) {
    super({
      name: 'database_query',
      description: '查询数据库获取数据',
      parameters: {
        table: {
          type: 'string',
          required: true,
          description: '表名'
        },
        conditions: {
          type: 'object',
          required: false,
          description: '查询条件'
        },
        limit: {
          type: 'number',
          required: false,
          description: '返回记录数量限制'
        }
      },
      returns: '查询结果数组'
    });

    this.database = database;
  }

  async execute(params) {
    this.validateParams(params);

    const { table, conditions = {}, limit = 10 } = params;

    try {
      const results = await this.database
        .collection(table)
        .find(conditions)
        .limit(limit)
        .toArray();

      return {
        success: true,
        data: results,
        count: results.length
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }
}
示例 2: API 调用工具
class APICallTool extends Tool {
  constructor() {
    super({
      name: 'api_call',
      description: '调用外部API接口',
      parameters: {
        url: {
          type: 'string',
          required: true,
          description: 'API端点URL'
        },
        method: {
          type: 'string',
          required: false,
          description: 'HTTP方法 (GET/POST/PUT/DELETE)'
        },
        body: {
          type: 'object',
          required: false,
          description: '请求体'
        },
        headers: {
          type: 'object',
          required: false,
          description: '请求头'
        }
      },
      returns: 'API响应结果'
    });
  }

  async execute(params) {
    this.validateParams(params);

    const { url, method = 'GET', body, headers = {} } = params;

    try {
      const response = await fetch(url, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        body: body ? JSON.stringify(body) : undefined
      });

      const data = await response.json();

      return {
        success: true,
        status: response.status,
        data: data
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }
}
示例 3: 计算器工具
class CalculatorTool extends Tool {
  constructor() {
    super({
      name: 'calculator',
      description: '执行数学计算',
      parameters: {
        expression: {
          type: 'string',
          required: true,
          description: '数学表达式,如 "2 + 3 * 4"'
        }
      },
      returns: '计算结果',
      examples: [
        { input: '2 + 3', output: 5 },
        { input: '10 * (5 + 3)', output: 80 }
      ]
    });
  }

  async execute(params) {
    this.validateParams(params);

    const { expression } = params;

    try {
      // 安全评估表达式
      const result = this.safeEval(expression);

      return {
        success: true,
        expression: expression,
        result: result
      };
    } catch (error) {
      return {
        success: false,
        error: '表达式无效或计算错误'
      };
    }
  }

  safeEval(expr) {
    // 只允许数字、运算符和括号
    if (!/^[\d\s\+\-\*\/\(\)\.]+$/.test(expr)) {
      throw new Error('包含非法字符');
    }

    return eval(expr);
  }
}
示例 4: 搜索工具
class SearchTool extends Tool {
  constructor(vectorDB) {
    super({
      name: 'search',
      description: '在知识库中搜索相关信息',
      parameters: {
        query: {
          type: 'string',
          required: true,
          description: '搜索查询'
        },
        topK: {
          type: 'number',
          required: false,
          description: '返回结果数量'
        }
      },
      returns: '相关文档列表'
    });

    this.vectorDB = vectorDB;
  }

  async execute(params) {
    this.validateParams(params);

    const { query, topK = 5 } = params;

    try {
      const results = await this.vectorDB.search(query, topK);

      return {
        success: true,
        query: query,
        results: results.map(r => ({
          content: r.content,
          score: r.score,
          metadata: r.metadata
        }))
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }
}

4.3 工具注册表

/**
 * 工具注册表
 * 管理所有可用工具
 */
class ToolRegistry {
  constructor() {
    this.tools = new Map();
  }

  /**
   * 注册工具
   */
  register(tool) {
    if (!(tool instanceof Tool)) {
      throw new Error('必须是 Tool 类的实例');
    }

    this.tools.set(tool.name, tool);
    console.log(`✓ 注册工具: ${tool.name}`);
  }

  /**
   * 批量注册
   */
  registerAll(tools) {
    tools.forEach(tool => this.register(tool));
  }

  /**
   * 获取工具
   */
  get(name) {
    return this.tools.get(name);
  }

  /**
   * 列出所有工具
   */
  list() {
    return Array.from(this.tools.values());
  }

  /**
   * 获取工具目录(给LLM看的)
   */
  getCatalog() {
    return this.list().map(tool => tool.getDescription()).join('\n---\n');
  }
}

4.4 工具选择器

/**
 * 工具选择器
 * 根据任务选择合适的工具
 */
class ToolSelector {
  constructor(llm, registry) {
    this.llm = llm;
    this.registry = registry;
  }

  /**
   * 选择工具
   */
  async selectTool(task) {
    const catalog = this.registry.getCatalog();

    const prompt = `
你是一个工具选择专家。根据任务选择最合适的工具。

任务: ${task.description}

可用工具:
${catalog}

要求:
1. 只选择一个最合适的工具
2. 提取任务中的参数
3. 输出JSON格式

输出格式:
{
  "tool": "工具名称",
  "params": {
    "参数名": "参数值"
  },
  "reasoning": "选择原因"
}

你的选择:`;

    const response = await this.llm.generate(prompt);

    try {
      const selection = JSON.parse(response);
      return selection;
    } catch (error) {
      console.error('工具选择失败:', error);
      return null;
    }
  }
}

4.5 工具执行器

/**
 * 工具执行器
 * 执行选定的工具
 */
class ToolExecutor {
  constructor(registry, selector) {
    this.registry = registry;
    this.selector = selector;
  }

  /**
   * 执行任务
   */
  async execute(task, previousResults = []) {
    console.log(`\n🔧 执行任务: ${task.description}`);

    // 1. 选择工具
    const selection = await this.selector.selectTool(task);

    if (!selection) {
      return {
        success: false,
        error: '未找到合适的工具'
      };
    }

    console.log(`   选择工具: ${selection.tool}`);
    console.log(`   原因: ${selection.reasoning}`);

    // 2. 获取工具实例
    const tool = this.registry.get(selection.tool);

    if (!tool) {
      return {
        success: false,
        error: `工具不存在: ${selection.tool}`
      };
    }

    // 3. 执行工具
    try {
      const result = await tool.execute(selection.params);
      console.log(`   ✓ 执行完成`);

      return {
        success: true,
        tool: selection.tool,
        params: selection.params,
        result: result
      };
    } catch (error) {
      console.error(`   ✗ 执行失败:`, error.message);

      return {
        success: false,
        tool: selection.tool,
        error: error.message
      };
    }
  }
}

🎯 业务对接方案

如何将 Active Planning + Tools 对接到业务

方案 1: 客服助手场景

业务需求:自动处理客户咨询,完成订单查询、退款申请等操作

// 1. 定义业务工具
const tools = [
  new OrderQueryTool(database),      // 订单查询
  new RefundTool(paymentAPI),        // 退款处理
  new ProductSearchTool(productDB),  // 产品搜索
  new TicketCreateTool(ticketSystem) // 创建工单
];

// 2. 注册工具
const registry = new ToolRegistry();
registry.registerAll(tools);

// 3. 创建Agent
const agent = new Agent({
  llm: llm,
  memory: memory,
  planning: new ActivePlanning(llm),
  tools: { registry, selector, executor }
});

// 4. 处理用户请求
const userInput = "我想退款,订单号是12345";
const response = await agent.handle(userInput);

// Agent会自动:
// - 理解意图: 退款
// - 规划任务: 1)查询订单 2)验证状态 3)发起退款
// - 选择工具: OrderQueryTool → RefundTool
// - 执行并返回结果

方案 2: 数据分析场景

业务需求:根据用户问题,自动查询数据、分析并生成报告

// 1. 定义分析工具
const tools = [
  new SQLQueryTool(database),        // SQL查询
  new DataVisualizationTool(charts), // 数据可视化
  new StatisticsCalculatorTool(),    // 统计计算
  new ReportGeneratorTool()          // 报告生成
];

// 2. 处理分析请求
const userInput = "分析最近一个月的销售趋势";

// Agent会自动:
// - 分解任务:
//   1. 查询最近一个月的销售数据
//   2. 计算每日销售额
//   3. 生成趋势图
//   4. 撰写分析报告
// - 执行工具: SQL → Calculator → Visualization → Report

方案 3: 工作流自动化场景

业务需求:自动化审批流程、通知发送等

// 1. 定义流程工具
const tools = [
  new ApprovalTool(workflowAPI),     // 审批
  new EmailTool(emailService),       // 发邮件
  new SlackNotifyTool(slackAPI),     // Slack通知
  new DocumentGeneratorTool()        // 文档生成
];

// 2. 处理流程请求
const userInput = "处理这个采购申请: 5台服务器,金额10万元";

// Agent会自动:
// - 规划流程:
//   1. 生成采购申请文档
//   2. 提交审批
//   3. 如果批准 → 发送通知
//   4. 如果拒绝 → 通知申请人原因

🚀 完整实现

完整的 Agent 类

/**
 * 完整的 AI Agent
 */
class Agent {
  constructor(config) {
    this.llm = config.llm;
    this.memory = config.memory;
    this.planning = config.planning;
    this.toolRegistry = config.tools.registry;
    this.toolSelector = config.tools.selector;
    this.toolExecutor = config.tools.executor;
  }

  /**
   * 处理用户输入
   */
  async handle(userInput) {
    console.log('\n🤖 Agent 启动...');
    console.log(`用户输入: ${userInput}\n`);

    // 1. 记忆检索
    console.log('💭 检索记忆...');
    const memoryContext = await this.memory.remember(userInput);

    // 2. 理解意图
    console.log('🧠 理解意图...');
    const intent = await this.understandIntent(userInput, memoryContext);
    console.log(`   意图: ${intent.type}`);
    console.log(`   复杂度: ${intent.complexity}`);

    // 3. 决定策略
    let response;

    if (intent.complexity === 'simple') {
      // 简单任务:直接回答
      console.log('\n📝 直接回答...');
      response = await this.directAnswer(userInput, memoryContext);
    } else {
      // 复杂任务:规划执行
      console.log('\n🎯 复杂任务,启动规划...');
      const executionResult = await this.planning.planAndExecute(
        userInput,
        this.toolExecutor
      );

      // 4. 整合结果
      console.log('\n📊 整合结果...');
      response = await this.synthesizeResults(
        userInput,
        executionResult
      );
    }

    // 5. 存储到记忆
    this.memory.shortTerm.add('user', userInput);
    this.memory.shortTerm.add('assistant', response);

    console.log('\n✅ 完成\n');
    return response;
  }

  /**
   * 理解意图
   */
  async understandIntent(input, context) {
    const prompt = `
分析用户意图并判断任务复杂度:

用户输入: ${input}

历史对话: ${JSON.stringify(context.history.slice(-3))}

输出JSON:
{
  "type": "query|command|conversation",
  "complexity": "simple|complex",
  "requiresTools": true/false
}`;

    const response = await this.llm.generate(prompt);

    try {
      return JSON.parse(response);
    } catch {
      return {
        type: 'query',
        complexity: 'simple',
        requiresTools: false
      };
    }
  }

  /**
   * 直接回答
   */
  async directAnswer(input, context) {
    const prompt = `
基于历史对话和知识回答用户问题:

历史: ${JSON.stringify(context.history)}

相关知识: ${JSON.stringify(context.knowledge)}

用户问题: ${input}

你的回答:`;

    return await this.llm.generate(prompt);
  }

  /**
   * 整合执行结果
   */
  async synthesizeResults(input, executionResult) {
    const resultsText = executionResult.results
      .map(({ task, result }) => {
        return `任务: ${task.description}\n结果: ${JSON.stringify(result.result)}`;
      })
      .join('\n\n');

    const prompt = `
基于任务执行结果,生成对用户的回复:

用户请求: ${input}

执行结果:
${resultsText}

要求:
1. 用自然语言总结结果
2. 突出关键信息
3. 如果有错误,说明原因

你的回复:`;

    return await this.llm.generate(prompt);
  }
}

📚 实战案例

案例 1: 竞品分析 Agent

// 1. 定义工具
class CompetitorSearchTool extends Tool {
  constructor() {
    super({
      name: 'competitor_search',
      description: '搜索竞争对手信息',
      parameters: {
        industry: { type: 'string', required: true, description: '行业' },
        limit: { type: 'number', required: false, description: '数量限制' }
      },
      returns: '竞争对手列表'
    });
  }

  async execute({ industry, limit = 5 }) {
    // 实际对接业务数据库或API
    return {
      success: true,
      competitors: [
        { name: '竞品A', market_share: 0.3 },
        { name: '竞品B', market_share: 0.25 }
      ]
    };
  }
}

class ProductInfoTool extends Tool {
  constructor() {
    super({
      name: 'product_info',
      description: '获取产品详细信息',
      parameters: {
        company: { type: 'string', required: true, description: '公司名称' }
      },
      returns: '产品信息'
    });
  }

  async execute({ company }) {
    // 调用爬虫或API获取产品信息
    return {
      success: true,
      products: [
        { name: '产品X', price: 999, features: ['特性1', '特性2'] }
      ]
    };
  }
}

// 2. 创建Agent
const competitorAgent = new Agent({
  llm: llm,
  memory: memory,
  planning: new ActivePlanning(llm),
  tools: {
    registry: new ToolRegistry(),
    selector: new ToolSelector(llm, registry),
    executor: new ToolExecutor(registry, selector)
  }
});

// 注册工具
competitorAgent.toolRegistry.registerAll([
  new CompetitorSearchTool(),
  new ProductInfoTool(),
  new DataVisualizationTool(),
  new ReportGeneratorTool()
]);

// 3. 使用
const result = await competitorAgent.handle(
  "分析AI行业的主要竞争对手,对比他们的产品特性和价格"
);

console.log(result);

案例 2: 智能运维 Agent

// 1. 定义运维工具
const devOpsTools = [
  new ServerMonitorTool(),      // 服务器监控
  new LogAnalysisTool(),        // 日志分析
  new AlertTool(),              // 告警
  new AutoRestartTool(),        // 自动重启
  new BackupTool()              // 备份
];

// 2. 创建运维Agent
const devOpsAgent = new Agent({/* ... */});
devOpsAgent.toolRegistry.registerAll(devOpsTools);

// 3. 处理运维请求
await devOpsAgent.handle("检测服务器异常并自动修复");

// Agent会:
// - 检查服务器状态
// - 分析错误日志
// - 尝试自动修复(重启服务)
// - 如果失败,创建告警工单

🎊 总结

关键要点

  1. Active Planning 的核心

    • ✅ 任务分解:复杂 → 简单
    • ✅ 执行规划:考虑依赖关系
    • ✅ 动态调整:根据结果优化
    • ✅ 自我反思:评估质量
  2. Tools 的核心

    • ✅ 标准化接口:统一的工具定义
    • ✅ 智能选择:让LLM理解工具功能
    • ✅ 参数提取:从自然语言提取参数
    • ✅ 结果整合:将工具输出转化为自然语言
  3. 业务对接的关键

    • ✅ 从业务场景出发定义工具
    • ✅ 工具粒度要合适(不要太大也不要太小)
    • ✅ 提供清晰的工具描述和示例
    • ✅ 处理好错误和异常情况

实施步骤

第1步: 分析业务需求
  └─ 识别高频任务
  └─ 确定自动化价值

第2步: 设计工具体系
  └─ 定义工具清单
  └─ 实现工具类
  └─ 测试工具功能

第3步: 实现规划能力
  └─ 任务分解逻辑
  └─ 执行计划生成
  └─ 自我反思机制

第4步: 集成测试
  └─ 单工具测试
  └─ 多工具协同测试
  └─ 复杂场景测试

第5步: 优化迭代
  └─ 收集用户反馈
  └─ 分析失败案例
  └─ 持续改进

posted @ 2026-01-26 17:42  XiaoZhengTou  阅读(2)  评论(0)    收藏  举报