前言

如果说 Gateway 是 OpenClaw 的心脏,那么 Agents 模块就是它的大脑。本篇文章将深入剖析 Agents 如何实现 AI 推理、工具调用和上下文管理。


1. Agents 模块概述

Agents 是 OpenClaw 的 AI 核心引擎,负责:

┌─────────────────────────────────────────────────────────────────┐
│                       Agents 核心职责                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  🧠 AI 推理                                                     │
│  ├── 模型调用 (Claude/GPT/Gemini)                              │
│  ├── Prompt 构建与优化                                          │
│  └── 多模态支持 (文本/图像/音频)                                 │
│                                                                  │
│  🔧 工具执行                                                    │
│  ├── 工具注册与发现                                             │
│  ├── 工具调用编排                                               │
│  └── 执行结果处理                                                │
│                                                                  │
│  💾 上下文管理                                                  │
│  ├── 上下文构建                                                 │
│  ├── 对话历史管理                                               │
│  └── 上下文压缩                                                 │
│                                                                  │
│  🛡️ 安全保障                                                    │
│  ├── 操作审批                                                   │
│  ├── 敏感信息过滤                                               │
│  └── 资源限制                                                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

2. 目录结构

src/agents/
├── agent-command.ts           # Agent 命令执行入口
├── agent-loop.ts              # Agent 主循环
├── bash-tools.ts              # Shell 命令执行
├── cli-runner.ts              # CLI 运行器
├── context.ts                 # 上下文管理
├── context-compaction.ts      # 上下文压缩
├── identity.ts                # AI 身份配置
├── auth-profiles.ts           # 认证配置
├── prompt-builder.ts          # Prompt 构建
├── token-counter.ts           # Token 计数
├── retry-handler.ts           # 重试处理
└── ...

3. Agent 执行流程

3.1 完整执行链路

┌─────────────────────────────────────────────────────────────────┐
│                      Agent 执行流程                              │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   [用户消息]                                                      │
│        │                                                          │
│        ▼                                                          │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │  1. 上下文构建 (Context Building)                        │   │
│   │                                                          │   │
│   │   ┌─────────────┐  ┌─────────────┐  ┌─────────────┐  │   │
│   │   │ 系统提示词   │  │  技能指令   │  │  会话历史   │  │   │
│   │   │ System      │  │  Skills     │  │  History    │  │   │
│   │   │ Prompt      │  │  Instructions│  │             │  │   │
│   │   └─────────────┘  └─────────────┘  └─────────────┘  │   │
│   │                      │                                  │   │
│   │                      ▼                                  │   │
│   │              ┌─────────────┐                           │   │
│   │              │  记忆注入    │                           │   │
│   │              │  Memory     │                           │   │
│   │              └─────────────┘                           │   │
│   │                      │                                  │   │
│   │                      ▼                                  │   │
│   │              ┌─────────────┐                           │   │
│   │              │ 完整上下文   │                           │   │
│   │              └─────────────┘                           │   │
│   └─────────────────────────────────────────────────────────┘   │
│        │                                                          │
│        ▼                                                          │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │  2. AI 模型调用 (Model Invocation)                        │   │
│   │                                                          │   │
│   │              ┌─────────────┐                            │   │
│   │              │    AI       │                            │   │
│   │              │   Model     │                            │   │
│   │              │ Claude/GPT  │                            │   │
│   │              └─────────────┘                            │   │
│   │                    │                                    │   │
│   │         ┌──────────┴──────────┐                        │   │
│   │         │                      │                        │   │
│   │         ▼                      ▼                        │   │
│   │   ┌──────────┐         ┌──────────┐                   │   │
│   │   │ 文本响应  │         │ 工具调用  │                   │   │
│   │   │  Text    │         │  Tool    │                   │   │
│   │   │  Reply   │         │  Calls   │                   │   │
│   │   └──────────┘         └────┬─────┘                   │   │
│   │         │                   │                         │   │
│   │         │            ┌──────▼──────┐                │   │
│   │         │            │  工具执行    │                │   │
│   │         │            │   Executor   │                │   │
│   │         │            └──────┬──────┘                │   │
│   │         │                   │                         │   │
│   │         │            ┌──────▼──────┐                │   │
│   │         │            │  结果返回   │                │   │
│   │         │            │   Result    │                │   │
│   │         │            └──────┬──────┘                │   │
│   │         │                   │                         │   │
│   │         │◄──────────────────┘                         │   │
│   │         │                                              │   │
│   │         │  (继续调用模型,直到不需要工具)                │   │
│   │         │                                              │   │
│   └─────────┼──────────────────────────────────────────────┘   │
│             │                                                    │
│             ▼                                                    │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │  3. 响应处理 (Response Processing)                       │   │
│   │                                                          │   │
│   │   ├── 格式化输出                                         │   │
│   │   ├── 更新会话历史                                       │   │
│   │   └── 触发后续钩子                                       │   │
│   └─────────────────────────────────────────────────────────┘   │
│             │                                                    │
│             ▼                                                    │
│      [最终响应]                                                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

4. 上下文管理

4.1 上下文构建

// src/agents/context.ts (简化版)
export class ContextBuilder {
  async build(session: Session): Promise<Context> {
    // 1. 加载系统提示词
    const systemPrompt = await this.loadSystemPrompt(session);

    // 2. 加载技能指令
    const skillsInstructions = await this.loadSkills(session);

    // 3. 加载会话历史
    const historyMessages = await this.loadHistory(session);

    // 4. 加载记忆
    const memoryContext = await this.loadMemory(session);

    // 5. Token 预算分配
    const tokenBudget = this.calculateTokenBudget();

    // 6. 组装上下文
    return {
      system: systemPrompt,
      skills: skillsInstructions,
      history: this.truncateToTokenLimit(historyMessages, tokenBudget.history),
      memory: memoryContext,
      tools: this.getAvailableTools(),
    };
  }
}

4.2 上下文压缩

当对话历史过长时,需要进行压缩:

┌─────────────────────────────────────────────────────────────────┐
│                      上下文压缩流程                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   [对话历史 (100+ 条消息)]                                        │
│              │                                                   │
│              ▼                                                   │
│   ┌───────────────────────┐                                      │
│   │    识别关键信息        │                                      │
│   │                       │                                      │
│   │   • 用户偏好          │                                      │
│   │   • 重要决策          │                                      │
│   │   • 未完成任务        │                                      │
│   │   • 关键上下文        │                                      │
│   └───────────┬───────────┘                                      │
│               │                                                  │
│               ▼                                                  │
│   ┌───────────────────────┐                                      │
│   │    AI 总结压缩        │                                      │
│   │                       │                                      │
│   │   "之前讨论了 X、Y,  │                                      │
│   │    用户偏好 A、B,    │                                      │
│   │    当前任务 Z 未完成" │                                      │
│   └───────────┬───────────┘                                      │
│               │                                                  │
│               ▼                                                  │
│   [压缩后的上下文 (保留摘要 + 最近对话)]                            │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

5. 工具系统

5.1 工具注册表

// 工具定义
interface Tool {
  name: string;                 // 工具名称
  description: string;          // 功能描述
  parameters: z.ZodSchema;      // 参数 schema
  handler: ToolHandler;          // 执行函数
  capabilities: string[];        // 所需能力
  riskLevel: RiskLevel;         // 风险等级
}

// 工具注册
@registerTool({
  name: "bash",
  description: "Execute shell commands",
  riskLevel: "high",
  capabilities: ["shell:exec"],
})
export class BashTool {
  async execute(params: { command: string }) {
    // 执行命令
    return { output, error, exitCode };
  }
}

5.2 内置工具一览

工具 功能 风险等级
bash Shell 命令执行 🔴 高
file_read 读取文件 🟡 中
file_write 写入文件 🔴 高
web_search 网页搜索 🟢 低
web_fetch 获取网页内容 🟢 低
browser 浏览器控制 🟡 中
code_execute 代码执行 🔴 高
http_request HTTP 请求 🟡 中
image_generation 图像生成 🟢 低
tts 文本转语音 🟢 低

6. Prompt 构建

6.1 Prompt 层次结构

┌─────────────────────────────────────────────────────────────────┐
│                    Prompt 层次结构                                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │  Level 1: System Prompt (系统级)                         │  │
│   │                                                         │  │
│   │  你是一个专业、可靠的 AI 助手。                          │  │
│   │  始终以用户利益为先,保护用户隐私...                      │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │  Level 2: Identity Prompt (身份级)                       │  │
│   │                                                         │  │
│   │  [SOUL.md 内容]                                         │  │
│   │  名称:Bobby                                            │  │
│   │  性格:友善、专业、幽默...                               │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │  Level 3: Skills Instructions (技能级)                  │  │
│   │                                                         │  │
│   │  [相关技能指令]                                          │  │
│   │  - 邮件管理技能                                          │  │
│   │  - 日程管理技能                                          │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │  Level 4: Session Context (会话级)                      │  │
│   │                                                         │  │
│   │  [历史消息 + 记忆]                                       │  │
│   └─────────────────────────────────────────────────────────┘  │
│                              │                                  │
│                              ▼                                  │
│   ┌─────────────────────────────────────────────────────────┐  │
│   │  Level 5: Current Input (输入级)                        │  │
│   │                                                         │  │
│   │  用户当前消息                                            │  │
│   └─────────────────────────────────────────────────────────┘  │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

7. 模型适配

7.1 多模型支持

OpenClaw 支持多种 AI 模型:

// 模型配置
interface ModelConfig {
  provider: "anthropic" | "openai" | "google" | "custom";
  model: string;
  apiKey: string;
  baseUrl?: string;              // 自定义端点
  parameters?: {
    temperature?: number;
    maxTokens?: number;
    topP?: number;
  };
}

// 使用示例
const config: ModelConfig = {
  provider: "anthropic",
  model: "claude-sonnet-4-20250514",
  apiKey: process.env.ANTHROPIC_API_KEY,
  parameters: {
    temperature: 0.7,
    maxTokens: 4096,
  },
};

7.2 Provider 适配器

┌─────────────────────────────────────────────────────────────────┐
│                      模型适配器架构                               │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│                    ┌─────────────┐                               │
│                    │    Agent    │                               │
│                    └──────┬──────┘                               │
│                           │                                      │
│                           ▼                                      │
│              ┌────────────────────────┐                          │
│              │    Model Adapter       │                          │
│              │    (统一接口)          │                          │
│              └────────────────────────┘                          │
│                         │                                        │
│     ┌───────────────────┼───────────────────┐                    │
│     │                   │                   │                    │
│     ▼                   ▼                   ▼                    │
│  ┌─────────┐      ┌─────────┐        ┌─────────┐              │
│  │Anthropic│      │ OpenAI  │        │ Google  │              │
│  │Adapter  │      │ Adapter │        │ Adapter │              │
│  └────┬────┘      └────┬────┘        └────┬────┘              │
│       │                 │                  │                    │
│       ▼                 ▼                  ▼                    │
│  ┌─────────┐      ┌─────────┐        ┌─────────┐              │
│  │ Claude  │      │   GPT   │        │ Gemini  │              │
│  └─────────┘      └─────────┘        └─────────┘              │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

8. 本章小结

┌─────────────────────────────────────────────────────────────────┐
│                        本章要点                                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  🧠 Agent 核心职责                                              │
│  ├── AI 推理: 模型调用、Prompt 构建                              │
│  ├── 工具执行: 工具注册、编排、结果处理                          │
│  ├── 上下文管理: 构建、压缩、记忆注入                            │
│  └── 安全保障: 审批、过滤、限流                                  │
│                                                                  │
│  🔄 执行流程                                                     │
│  └── 上下文构建 → 模型调用 → 工具执行 → 响应处理                 │
│                                                                  │
│  💾 上下文压缩                                                   │
│  └── 当历史过长时,AI 总结 + 保留关键摘要                        │
│                                                                  │
│  🔧 工具系统                                                     │
│  └── 内置工具(bash/file/web) + MCP 扩展                         │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

系列导航

章节 标题 状态
01 OpenClaw 是什么? ✅ 已发布
02 系统架构全景图 ✅ 已发布
03 Gateway 网关层 ✅ 已发布
04 Agents 模块(本文) ✅ 已发布
05 Channels 消息渠道 🔜 下一章

如有问题欢迎在评论区留言!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐