🔄 Agent Loop 智能体循环

OpenClaw 循环机制 核心概念

凌晨1点37分,AI在第47次循环时终于写出了对的代码。
在这47次循环中,它观察了47次,思考了47次,行动了47次——就像一个永不放弃的程序员,只是它不用喝咖啡。
这就是Agent Loop——AI版本的"永不放弃"

📚 什么是 Agent Loop?

Agent Loop(智能体循环)是AI Agent执行任务时的核心控制流程:观察 → 推理 → 行动 → 评估 → 重复。它让Agent能够处理复杂任务,而不是一次性生成答案。

👀 观察
🧠 思考
⚡ 行动
📊 评估

🔍 循环各阶段详解

1. 观察(Observe)

收集当前状态信息,包括用户输入、工具返回、历史上下文。

// 观察阶段
const observe = async (agent) => {
  const observations = [];
  
  // 用户输入
  observations.push({
    type: 'user_input',
    content: agent.pendingInput,
    timestamp: Date.now()
  });
  
  // 工具执行结果
  if (agent.lastToolResult) {
    observations.push({
      type: 'tool_result',
      content: agent.lastToolResult,
      tool: agent.lastToolName
    });
  }
  
  // 环境状态
  observations.push({
    type: 'environment',
    state: agent.getState()
  });
  
  // 历史轨迹(最近N步)
  observations.push({
    type: 'history',
    trajectory: agent.getRecentSteps(5)
  });
  
  return observations;
};

2. 思考(Think)

基于观察结果,决定下一步行动。

// 思考阶段
const think = async (agent, observations) => {
  // 构建思考Prompt
  const thoughtPrompt = `
当前任务: ${agent.taskDescription}
可用工具: ${agent.availableTools.join(', ')}

最近观察:
${observations.map(o => `- ${o.type}: ${JSON.stringify(o.content)}`).join('\n')}

历史步骤:
${agent.history.map((h, i) => `${i+1}. ${h.action} -> ${h.result}`).join('\n')}

请决定下一步行动:
1. 应该调用哪个工具?
2. 工具参数是什么?
3. 如何判断任务完成?

输出格式:
{
  "reasoning": "你的思考过程",
  "action": "工具名或final_answer",
  "parameters": { ... },
  "shouldComplete": true/false,
  "completionReason": "如果完成,说明原因"
}
`;
  
  const thought = await agent.llm.complete(thoughtPrompt);
  return thought;
};

3. 行动(Act)

执行决定的工具调用或返回最终答案。

// 行动阶段
const act = async (agent, thought) => {
  // 如果是完成信号,返回最终答案
  if (thought.shouldComplete) {
    return {
      type: 'complete',
      content: thought.finalAnswer,
      reasoning: thought.reasoning
    };
  }
  
  // 执行工具调用
  const tool = agent.getTool(thought.action);
  
  if (!tool) {
    return {
      type: 'error',
      content: `Unknown tool: ${thought.action}`
    };
  }
  
  try {
    const result = await tool.execute(thought.parameters, agent.context);
    
    return {
      type: 'tool_result',
      tool: thought.action,
      result
    };
  } catch (error) {
    return {
      type: 'error',
      tool: thought.action,
      error: error.message
    };
  }
};

4. 评估(Evaluate)

评估行动结果,决定是否继续循环。

// 评估阶段
const evaluate = (agent, result) => {
  // 检查是否出错
  if (result.type === 'error') {
    return {
      continue: true,
      reason: `Tool error: ${result.error}. Will retry.`,
      maxRetries: 3
    };
  }
  
  // 检查结果是否有效
  if (result.type === 'tool_result' && !result.result) {
    return {
      continue: true,
      reason: 'Empty result, retrying...'
    };
  }
  
  // 检查是否达到最大循环次数
  if (agent.loopCount >= agent.maxLoops) {
    return {
      continue: false,
      reason: 'Max loops reached'
    };
  }
  
  // 检查是否超时
  if (Date.now() - agent.startTime > agent.timeout) {
    return {
      continue: false,
      reason: 'Timeout reached'
    };
  }
  
  return {
    continue: true,
    reason: 'Continue to next iteration'
  };
};

🔀 循环模式

1. 简单循环(Simple Loop)

最基本的观察-行动循环。

// 简单循环
async function simpleAgentLoop(task, maxLoops = 10) {
  let state = { task, loop: 0, history: [] };
  
  while (state.loop < maxLoops) {
    // 观察
    const observations = await observe(state);
    
    // 思考
    const thought = await think(observations);
    
    // 行动
    const result = await act(thought);
    
    // 记录历史
    state.history.push({ loop: state.loop, thought, result });
    state.loop++;
    
    // 评估
    if (thought.shouldComplete) {
      return result.content;
    }
  }
  
  return "Max loops reached";
}

2. 反思循环(Reflection Loop)

加入自我反思能力,从错误中学习。

// 反思循环
async function reflectiveAgentLoop(task) {
  let state = { task, history: [] };
  
  while (true) {
    const observations = await observe(state);
    const thought = await think(observations);
    const result = await act(thought);
    
    state.history.push({ thought, result });
    
    // 反思:检查结果是否合理
    if (result.type === 'tool_result') {
      const reflection = await reflect({
        action: thought.action,
        result: result.result,
        history: state.history
      });
      
      // 如果反思发现问题,尝试修复
      if (reflection.issuesFound) {
        console.log('反思发现问题:', reflection.issues);
        // 根据反思调整策略
        thought.parameters = await adjustBasedOnReflection(
          thought.parameters, 
          reflection
        );
        // 重新执行
        continue;
      }
    }
    
    if (thought.shouldComplete) {
      return thought.finalAnswer;
    }
  }
}

async function reflect(ctx) {
  const prompt = `
检查以下执行历史,判断结果是否合理:

执行的动作: ${ctx.action}
返回结果: ${JSON.stringify(ctx.result)}

历史:
${ctx.history.map(h => `${h.thought.action} -> ${h.result.type}`).join('\n')}

请分析:
1. 结果是否符合预期?
2. 有哪些异常?
3. 需要重试吗?

输出: { issuesFound: boolean, issues: string[], shouldRetry: boolean }
`;
  
  return await llm.complete(prompt);
}

3. 层次化循环(Hierarchical Loop)

多层次的规划和执行循环。

// 层次化循环
class HierarchicalAgent {
  async execute(task) {
    // 高层循环:规划
    const plan = await this.planningLoop(task);
    
    // 低层循环:执行计划
    for (const step of plan.steps) {
      const result = await this.executionLoop(step);
      
      // 检查进度
      const progress = await this.checkProgress(result);
      if (!progress.onTrack) {
        // 重新规划
        plan = await this.replan(task, progress);
      }
    }
    
    return plan.finalResult;
  }
  
  async planningLoop(task) {
    // 生成计划
    const prompt = `为以下任务制定执行计划:${task}`;
    const plan = await llm.complete(prompt);
    
    // 验证计划
    const validated = await this.validatePlan(plan);
    if (!validated.valid) {
      return this.planningLoop(task); // 重新规划
    }
    
    return plan;
  }
  
  async executionLoop(step) {
    // 执行单个步骤
    while (!step.complete) {
      const thought = await this.think(step);
      const result = await this.act(thought);
      step.complete = await this.evaluate(result);
    }
    return step.result;
  }
}

🚀 OpenClaw Agent Loop 实现

import { Agent, LoopConfig } from '@openclaw/core';

// 配置Agent循环
const agent = new Agent({
  name: 'ResearchAssistant',
  
  // 循环配置
  loop: new LoopConfig({
    maxIterations: 20,        // 最多循环次数
    timeout: 300000,          // 5分钟超时
    earlyTermination: {
      enabled: true,
      checkInterval: 5         // 每5次循环检查一次
    },
    reflection: {
      enabled: true,
      triggerOnError: true,
      maxReflections: 3
    }
  }),
  
  // 自定义循环阶段
  observe: async (ctx) => {
    return {
      userInput: ctx.input,
      toolResults: ctx.toolResults.slice(-3),
      agentState: ctx.getState()
    };
  },
  
  think: async (observations) => {
    const prompt = `
任务: ${observations.userInput}
工具结果: ${JSON.stringify(observations.toolResults)}
状态: ${JSON.stringify(observations.agentState)}

决定下一步行动...
`;
    return llm.complete(prompt);
  },
  
  evaluate: (result, history) => {
    // 自定义评估逻辑
    if (result.type === 'error' && history.errors > 3) {
      return { continue: false, reason: 'Too many errors' };
    }
    return { continue: true };
  }
});

// 执行任务
const result = await agent.execute({
  input: '帮我找一下最新的AI新闻并总结',
  context: { userId: 'user123' }
});

⚡ 循环优化技巧

性能优化
  • 缓存观察结果 - 避免重复获取相同信息
  • 并行工具调用 - 独立工具同时执行
  • 提前终止 - 任务完成立即退出循环
  • 增量状态 - 只更新变化的部分
常见问题
  • 🔴 无限循环 - 没有退出条件
  • 🔴 循环依赖 - 工具A调用工具B,B又调用A
  • 🔴 状态泄露 - 不同任务状态混淆
  • 🔴 资源泄漏 - 未释放的连接和内存