Agent Loop 代理循环

zxbandzby
0
2026-07-08

Agent Loop 代理循环

核心机制

Agent Loop 是 OpenClaw 中代理的核心执行循环,负责处理消息、执行工具调用和生成响应。

循环流程

接收消息 → 解析意图 → 执行工具 → 生成响应 → 返回结果
    ↑                                            ↓
    └──────────────── 循环继续 ──────────────────┘

关键组件

1. 消息处理器

class MessageHandler {
    async process(message) {
        // 消息预处理
        const processed = await this.preprocess(message);
        
        // 意图识别
        const intent = await this.identifyIntent(processed);
        
        // 路由到相应处理器
        return await this.route(intent, processed);
    }
}

2. 工具执行器

class ToolExecutor {
    async execute(toolCall) {
        // 验证工具调用
        await this.validate(toolCall);
        
        // 执行工具
        const result = await this.run(toolCall);
        
        // 后处理结果
        return this.postprocess(result);
    }
}

3. 响应生成器

class ResponseGenerator {
    async generate(context) {
        // 构建响应上下文
        const prompt = this.buildPrompt(context);
        
        // 调用语言模型
        const response = await this.callModel(prompt);
        
        // 格式化输出
        return this.format(response);
    }
}

配置选项

agent_loop:
  max_iterations: 10           # 最大循环次数
  timeout: 30000              # 超时时间(ms)
  parallel_tools: true        # 并行工具执行
  streaming: true             # 流式响应
  
  # 工具配置
  tools:
    max_concurrent: 5         # 最大并发工具数
    timeout_per_tool: 10000   # 单个工具超时

监控指标

metrics:
  - name: "loop_iterations"
    type: "histogram"
    description: "每次循环的迭代次数"
    
  - name: "tool_execution_time"
    type: "histogram"
    description: "工具执行耗时"
    
  - name: "response_generation_time"
    type: "histogram"
    description: "响应生成耗时"

故障处理

超时处理

async function handleTimeout(operation, timeout) {
    return Promise.race([
        operation(),
        new Promise((_, reject) => 
            setTimeout(() => reject(new Error('Timeout')), timeout)
        )
    ]);
}

错误恢复

class ErrorRecovery {
    async recover(error, context) {
        // 记录错误
        this.logger.error(error);
        
        // 尝试恢复策略
        switch(error.type) {
            case 'tool_failure':
                return await this.retryTool(context);
            case 'model_error':
                return await this.fallbackModel(context);
            default:
                return await this.humanIntervention(context);
        }
    }
}

最佳实践

  1. 合理的超时设置: 根据业务需求设置适当的超时时间
  2. 错误边界: 为每个组件设置错误处理边界
  3. 性能监控: 持续监控循环性能指标
  4. 日志记录: 详细记录循环执行过程

官方文档: https://docs.openclaw.ai/concepts/agent-loop.md

动物装饰