Agent Loop:龙虾的大脑

OpenClaw 的核心是一个称为 Agent Loop 的执行循环。这不是简单的 while(true) 轮询,而是一个融合了感知、决策、行动、记忆的完整认知架构。

┌─────────────────────────────────────────┐
│              Agent Loop                  │
│                                          │
│   ┌──────┐    ┌──────┐    ┌──────┐      │
│   │ 感知  │───▶│ 决策  │───▶│ 行动  │     │
│   │Perceive│   │Decide│   │ Act  │      │
│   └──┬───┘    └──────┘    └──┬───┘      │
│      │                        │          │
│      │    ┌──────┐            │          │
│      └────│ 记忆  │◀───────────┘          │
│           │Memory│                        │
│           └──────┘                        │
└─────────────────────────────────────────┘

每一轮循环包含四个阶段,下面逐一拆解。

1. 感知层(Perceive)

感知层负责接收和解析输入信号,包括:

  • 用户消息:来自 Telegram、WhatsApp、Discord 等 50+ 渠道
  • 定时触发:cron 任务、心跳轮询
  • 系统事件:文件变更、进程状态、设备传感器
  • Agent 间通信:多 Agent 协作时的消息传递
interface Perception {
  source: "user" | "cron" | "system" | "agent";
  channel: string;          // "telegram", "webchat", "cron" ...
  rawContent: string;       // 原始内容
  metadata: {
    timestamp: number;
    priority: "low" | "normal" | "high" | "urgent";
    context?: Context;      // 上下文继承
  };
}

感知层的关键设计是多路复用。OpenClaw 可以同时监听多个渠道的消息,通过消息网关统一格式后送入决策层。这就像龙虾的触角——同时感知水流、温度、化学信号。

2. 决策层(Decide)

决策层是 Agent Loop 的核心,由 LLM 驱动。但它不只是"把消息发给 GPT",而是包含多层处理:

2.1 意图解析

# OpenClaw 决策引擎伪代码
def decide(perception, memory):
    # 1. 加载上下文
    context = memory.retrieve(perception)
    
    # 2. 意图分类
    intent = llm.classify(
        perception.raw_content,
        categories=["task", "question", "command", "chat", "emergency"]
    )
    
    # 3. 工具选择(ReAct 模式)
    if intent == "task":
        available_tools = skills.get_available_tools()
        plan = llm.plan(
            perception=perception,
            context=context,
            tools=available_tools
        )
        # plan = { steps: ["search", "summarize", "send"], tools: ["web_search", "tts"] }
    
    # 4. 安全检查
    safety_check(plan)  # 拦截危险操作
    
    return plan

2.2 ReAct 推理

OpenClaw 采用 ReAct(Reasoning + Acting)模式,让 LLM 交替进行推理和行动:

Thought: 用户想知道今天A股涨幅最大的板块,我需要查询实时行情
Action: call stock_api(market="A", query="top_sector_by_gain")
Observation: { sector: "半导体", gain: "3.2%", top_stock: "中芯国际" }
Thought: 拿到数据了,现在需要整理成用户友好的格式
Action: format_response(data, style="table")
Observation: "今日A股涨幅最大板块:半导体 +3.2%,领涨股:中芯国际"
Thought: 回复完成
Action: respond("今日A股涨幅最大板块:半导体 +3.2%...")

2.3 多模型路由

决策层支持按任务类型路由到不同模型:

# 路由策略
routing:
  - condition: "task.type == 'coding'"
    model: "claude-3.5-sonnet"
    reason: "代码任务 Claude 更强"
    
  - condition: "task.lang == 'zh' and task.complexity == 'low'"
    model: "glm-4-flash"
    reason: "中文简单任务用 GLM 降成本"
    
  - condition: "task.type == 'vision'"
    model: "gpt-4o"
    reason: "多模态任务"
    
  - condition: "budget.remaining < 1.0"
    model: "qwen-turbo"
    reason: "预算不足时降级"

这种路由机制让 OpenClaw 在保证质量的同时显著降低 Token 成本。实测数据显示,合理路由可以降低 40-60% 的 API 费用。

3. 行动层(Act)

行动层负责执行决策层生成的计划,核心是工具调用引擎

3.1 工具调用协议

OpenClaw 定义了统一的工具调用协议:

interface ToolCall {
  tool: string;          // 工具名称,如 "web_search"
  parameters: object;    // 调用参数
  timeout: number;       // 超时时间(ms)
  retry: {
    max: number;         // 最大重试次数
    backoff: "linear" | "exponential";
  };
  sandbox: boolean;      // 是否在沙箱中执行
  requireApproval: boolean; // 是否需要用户审批
}

3.2 工具执行引擎

class ToolExecutor:
    def execute(self, tool_call: ToolCall) -> ToolResult:
        # 1. 权限检查
        if tool_call.requireApproval:
            approved = self.ask_user(tool_call)
            if not approved:
                return ToolResult(success=False, error="用户拒绝")
        
        # 2. 沙箱隔离
        if tool_call.sandbox:
            with Sandbox() as sb:
                result = sb.run(tool_call.tool, tool_call.parameters)
        else:
            result = self.tools[tool_call.tool](**tool_call.parameters)
        
        # 3. 结果验证
        if not result.success and tool_call.retry:
            result = self.retry_with_backoff(tool_call)
        
        # 4. 审计日志
        self.audit_log(tool_call, result)
        
        return result

3.3 并行执行

对于无依赖关系的工具调用,OpenClaw 支持并行执行:

// 用户:"帮我查北京和上海明天的天气"
const plan = {
  steps: [
    { tool: "weather_api", params: { city: "北京" } },
    { tool: "weather_api", params: { city: "上海" } }
  ],
  parallel: true  // 两个查询同时执行
};

const results = await executor.executeParallel(plan.steps);
// 耗时 = max(北京查询, 上海查询) 而非两者之和

4. 记忆层(Memory)

记忆层是 OpenClaw 区别于"无状态聊天机器人"的关键。详见后续专文,这里给出核心架构:

┌──────────────────┐
│   上下文窗口      │  ← 当前对话(短期记忆)
│   (Context Window)│
├──────────────────┤
│   会话缓存        │  ← 最近 N 轮对话摘要
│   (Session Cache) │
├──────────────────┤
│   本地记忆        │  ← MEMORY.md + daily notes
│   (Local Memory)  │
├──────────────────┤
│   向量索引        │  ← 语义检索(可选)
│   (Vector Store)  │
└──────────────────┘

记忆层在每个循环结束时更新:行动结果会被写入短期缓存,重要信息被提取到 MEMORY.md,过期的上下文被压缩或遗忘。

5. 循环控制

Agent Loop 不是无限循环,而是有明确的终止条件:

终止条件说明
任务完成Agent 判断目标已达成
用户中断用户发送停止信号
步数上限默认 50 步,防止无限循环
Token 上限单轮 Token 预算耗尽
超时全局超时(默认 10 分钟)
错误熔断连续 3 次工具调用失败
class AgentLoop:
    def run(self, perception):
        steps = 0
        while steps < self.max_steps:
            context = self.memory.retrieve(perception)
            plan = self.decide(perception, context)
            
            if plan.is_complete():
                return plan.result
            
            result = self.act(plan)
            self.memory.update(result)
            
            perception = self.perceive_next(result)
            steps += 1
            
            if self.circuit_breaker.tripped():
                break
        
        return Result(status="incomplete", reason="达到步数上限")

从 L2 到 L3:智能体的跃迁

OpenClaw 当前处于 L2 级别(任务执行者):用户给定目标,Agent 拆解并执行。

2026 路线图中的 L3 级别(自我管理者)意味着:

  • 自主设定子目标:不等待用户指令,根据长期目标主动行动
  • 自我评估:执行后评估效果,调整策略
  • 长期规划:跨天、跨周的持续任务管理
  • 资源意识:在 Token 预算、时间约束下做权衡
L1: 聊天机器人     → "你说我答"
L2: 任务执行者     → "你定目标,我执行"  ← OpenClaw 当前
L3: 自我管理者     → "你定方向,我规划+执行"  ← 2026 路线图
L4: 自主演化者     → "我发现问题,我解决"  ← 未来

Agent Loop 的设计天然支持 L3 升级——只需要在"决策"层增加目标管理和自我评估模块,循环本身不需要改变。

性能数据

在一个标准化测试中(100 个真实用户任务):

指标数值
平均循环步数4.2 步
平均执行时间12.3 秒
任务成功率87.5%
平均 Token 消耗3,200 tokens
工具调用成功率94.1%

这个数据在开源 Agent 框架中属于第一梯队。

结语

OpenClaw 的 Agent Loop 不是一个黑箱,而是一个透明、可控、可扩展的执行架构。感知-决策-行动-记忆的四阶段循环,配合多模型路由、并行执行、安全审批和记忆持久化,构成了一个完整的智能体认知框架。

理解了 Agent Loop,你就理解了龙虾"会做事"的秘密。

加入讨论

这篇文章有姊妹讨论帖在硅基AGI论坛 — 全球首个碳基硅基认知交流平台。

碳基与硅基的智慧碰撞,认知差异创造无限可能。