04-agentic-loop.md 7.59 KB

4. Agentic Loop 循环引擎

每一层 Agent 都运行独立的循环引擎,这是 LemonBoss 的核心机制。

4.1 单 Agent 循环流程

    ┌─────────────────────────────────────────┐
    │                                         │
    │   ┌─────────────────────────────┐       │
    │   │  1. Perceive Env &          │       │
    │   │     Understand Goal         │◄──────┼──── External Env Input
    │   └────────────┬────────────────┘       │
    │                │                        │
    │                ▼                        │
    │   ┌─────────────────────────────┐       │
    │   │  2. Reason, Plan &          │◄─────►│──── Memory (读/写)
    │   │     Decomposition           │       │
    │   └────────────┬────────────────┘       │
    │                │                        │
    │                ▼                        │
    │   ┌─────────────────────────────┐       │
    │   │  3. Execute                 │       │
    │   │     (调用 Data / Tools)     │───────┼──── Actions → External Env
    │   └────────────┬────────────────┘       │
    │                │                        │
    │                ▼                        │
    │   ┌─────────────────────────────┐       │
    │   │  4. Feedback                │       │
    │   │     (环境反馈回流)          │◄──────┼──── External Env Feedback
    │   └────────────┬────────────────┘       │
    │                │                        │
    │                ▼                        │
    │   ┌─────────────────────────────┐       │
    │   │  5. Reflect & Adapt         │       │
    │   │     (反思与自适应)          │       │
    │   └────────────┬────────────────┘       │
    │                │                        │
    │          ┌─────▼─────┐                  │
    │          │ Goal       │                  │
    │          │ Achieved?  │                  │
    │          └─────┬──────┘                  │
    │           No   │   Yes                   │
    │           │    │    │                    │
    │           ▼    │    ▼                    │
    │    ┌──────┐    │  ┌──────┐              │
    │    │Loop  │    │  │ Done │              │
    │    │Back  │────┘  └──────┘              │
    │    └──────┘                              │
    │                                         │
    └─────────────────────────────────────────┘

4.2 循环引擎各阶段详细设计

Phase 1: Perceive & Understand Goal(感知与目标理解)

class PerceptionModule {
  async perceive(agent) {
    return {
      externalInputs: await agent.gateway.getMessages(),       // IM 消息
      cronTriggers:   await agent.cron.getPendingTasks(),       // 定时触发
      parentTasks:    await agent.getAssignedTasks(),           // 上级下发
      currentState:   await agent.memory.getShortTerm(),        // 当前状态
      goal:           agent.goal,                               // 目标定义
    };
  }
}

Phase 2: Reason, Plan & Decomposition(推理与任务拆解)

class ReasoningModule {
  async reason(envState, memory) {
    const experiences = await memory.longTerm.query(envState.goal);
    const plan = await this.acpClient.reason({
      prompt: this.buildReasoningPrompt(envState, experiences),
      agentDefine: this.agent.define,
    });
    await memory.shortTerm.save({ reasoning: plan });
    return plan; // { tasks: [...], priority: [...], dependencies: [...] }
  }
}

Phase 3: Execute(执行与工具调用)

class ExecutionModule {
  async execute(plan) {
    const results = [];
    for (const task of plan.tasks) {
      // 对 SubAgent:直接执行
      // 对 RoleAgent:分派给 SubAgent
      // 对 BossAgent:分派给 RoleAgent
      const result = await this.dispatch(task);
      results.push(result);
    }
    return results;
  }
}

Phase 4: Feedback(环境反馈)

class FeedbackModule {
  async collect(results) {
    return {
      success:    results.filter(r => r.status === 'success'),
      failures:   results.filter(r => r.status === 'failed'),
      metrics:    this.calculateMetrics(results),
      envChanges: await this.detectEnvChanges(),
    };
  }
}

Phase 5: Reflect & Adapt(反思与自适应)

注意:v1.1 中此阶段已升级为三层差异化反思,详见 第 8 章。

class ReflectionModule {
  async reflect(feedback, goal) {
    const progress = this.evaluateProgress(feedback, goal);
    if (progress.achieved) {
      return { adapted: false, goalAchieved: true };
    }
    const adaptation = await this.acpClient.reflect({
      feedback, goal, progress,
      memory: await this.agent.memory.longTerm.getRecentReflections(),
    });
    await this.agent.memory.longTerm.saveReflection(adaptation);
    return { adapted: true, newPlan: adaptation.revisedPlan };
  }
}

4.3 三层循环嵌套

每一层的 Loop 独立运行,但通过 任务下发 和 结果上报 形成嵌套关系:

BossAgent Loop (每 5 分钟)
│
├─ Perceive: 收集所有 RoleAgent 状态
├─ Reason:   对比公司 Goal,分配任务给 RoleAgent
├─ Execute:  ─────► RoleAgent Loop (持续运行)
│                    │
│                    ├─ Perceive: 接收 Boss 下发任务 + 监控 SubAgent
│                    ├─ Reason:   拆解为 SubAgent 任务
│                    ├─ Execute:  ─────► SubAgent Loop (任务级)
│                    │                    │
│                    │                    ├─ Perceive: 读取任务
│                    │                    ├─ Reason:   规划执行步骤
│                    │                    ├─ Execute:  调用工具执行
│                    │                    ├─ Feedback: 收集结果
│                    │                    └─ Reflect:  评估完成度
│                    │                    │
│                    │                    ◄── 上报结果给 RoleAgent
│                    │
│                    ├─ Feedback: 汇总 SubAgent 结果
│                    └─ Reflect:  优化调度策略
│                    │
│                    ◄── 上报状态给 BossAgent
│
├─ Feedback: 汇总所有 RoleAgent 报告
└─ Reflect:  调整全局策略,进入下一轮