Agent Loop 解析
核心流程
OpenClaw 的 Agent Loop 是整个系统的执行引擎,每次用户发送消息都会触发一个完整的 Loop:
用户消息
↓
[1] 构建 Context
加载系统提示 + 记忆 + 历史对话
↓
[2] 调用 AI 模型
发送 Context → 等待响应(流式)
↓
[3] 解析响应
文本输出 or 工具调用请求?
↓ (工具调用) ↓ (纯文本)
[4] 执行工具 [5] 输出结果
等待工具返回 结束 Loop
↓
[回到步骤 2]
循环直到无工具调用关键设计
流式输出
AI 响应通过流式(Streaming)传输,用户看到逐字输出:
typescript
// 伪代码:流式处理
for await (const chunk of aiStream) {
if (chunk.type === 'text') {
output(chunk.text)
} else if (chunk.type === 'tool_use') {
const result = await executeTool(chunk.tool, chunk.input)
continueWithToolResult(result)
}
}工具调用并发
同一轮 AI 响应中,如果有多个工具调用请求,OpenClaw 会并行执行,而不是顺序执行:
AI 请求调用:
- readFile("a.txt")
- readFile("b.txt")
- httpGet("https://api.example.com")
OpenClaw 并行执行三个工具,同时等待结果
→ 比顺序执行快 3x中断与恢复
Agent Loop 支持中断:
- 用户发送
Ctrl+C或/stop - 工具执行超时
- Token 上限触发 Compaction
中断后可恢复继续,或开启新的 Loop。
性能优化
- 工具并发:如上所述,多工具并行执行
- 流式输出:减少感知延迟
- Prompt Caching:缓存固定前缀,减少重复 Token 计算
- Compaction:防止上下文无限增长
调试 Agent Loop
bash
# 开启详细日志
openclaw config set logging.level debug
# 查看每次 Loop 的详情
openclaw logs --filter agent-loop
# 示例日志输出:
# [AgentLoop] Turn 1: input=120 tokens, output=450 tokens
# [AgentLoop] Tool call: readFile("config.json")
# [AgentLoop] Turn 2: tool_result=200 tokens
# [AgentLoop] Completed in 3.2s, total=770 tokens