AI创想

标题: OpenClaw 完全指南 [打印本页]

作者: 米落枫    时间: 昨天 23:00
标题: OpenClaw 完全指南
作者:CSDN博客
OpenClaw 完全指南

文档版本:2026年2月 | 项目地址:github.com/openclaw/openclaw

目录


1. 项目简介与背景

1.1 什么是 OpenClaw?

OpenClaw(曾用名 Clawdbot、Moltbot)是由奥地利开发者 Peter Steinberger 开发的开源、自托管个人 AI 智能体。它运行在用户自己的设备上,通过 WhatsApp、Telegram、Discord、Slack、iMessage、Signal 等你已经在用的即时通讯平台来接受指令、执行任务,并返回结果。
截至 2026 年 2 月,该项目已在 GitHub 上获得约 196,000 Stars33,900 Forks,是近期最火爆的开源 AI 项目之一。项目以 MIT 协议开源,使用 TypeScript 编写。
1.2 命名历程

时间名称原因
2025年11月Clawdbot项目创建,名称来自 Anthropic 的 Claude
2026年1月27日MoltbotAnthropic 法务要求更名,社区 Discord 头脑风暴后更名(龙虾蜕壳主题)
2026年2月初OpenClaw最终品牌,完成商标搜索、域名购买与代码迁移
注:2026 年 2 月 14 日,项目创始人 Steinberger 宣布加入 OpenAI,项目将移交开源基金会继续维护。
1.3 核心理念


2. 核心原理与架构

2.1 整体架构

OpenClaw 的架构分为两个核心部分:
“大脑”(Brain) — 推理引擎
“双手”(Hands) — 执行环境
2.2 Gateway(网关)

Gateway 是整个系统的控制平面(Control Plane),监听在本地 ws://127.0.0.1:18789。
  1. WhatsApp / Telegram / Slack / Discord / iMessage / Signal / ...
  2.                           │
  3.                           ▼
  4.               ┌───────────────────────────┐
  5.               │         Gateway           │
  6.               │      (控制平面)            │
  7.               │   ws://127.0.0.1:18789    │
  8.               └─────────────┬─────────────┘
  9.                             │
  10.               ┌─────────────┼──────────────┐
  11.               ▼             ▼              ▼
  12.          Pi Agent(RPC)  WebChat UI   CLI (openclaw...)
  13.               │             │              │
  14.          macOS App      iOS/Android      控制台
复制代码
Gateway 核心功能:
2.3 工作流程(ReAct 模式)

OpenClaw 采用经典的 ReAct(Reasoning + Acting)循环
  1. 用户发送消息
  2.       │
  3.       ▼
  4. Gateway 接收并预处理
  5.       │
  6.       ▼
  7. 组装系统提示词(含 Skills、权限、用户画像、历史记忆)
  8.       │
  9.       ▼
  10. 调用 LLM API(Claude/GPT/DeepSeek…)
  11.       │
  12.   ┌───┴────────────────────────────┐
  13.   │ LLM 决策:是否需要调用工具?      │
  14.   │  ├─ 是 → 发出 tool_call 指令    │
  15.   │  └─ 否 → 直接生成回复            │
  16.   └─────────────────────────────────┘
  17.       │ (tool_call 分支)
  18.       ▼
  19. Gateway 执行对应 Skill(Shell/文件/浏览器/API…)
  20.       │
  21.       ▼
  22. 将 tool_result 返回 LLM,继续推理
  23.       │
  24.       ▼(可能多轮循环)
  25. LLM 生成最终回复
  26.       │
  27.       ▼
  28. Gateway 通过原消息渠道返回给用户
复制代码
2.4 Skills(技能)系统

Skills 是 OpenClaw 的能力扩展单元,类似插件,每个 Skill 是一段可以被 LLM 调用的代码(工具函数)。
内置核心 Skills 包括:
2.5 MCP 集成

OpenClaw 通过 mcporter 支持 MCP(Model Context Protocol),以解耦的桥接模式集成外部 MCP Server,无需重启 Gateway 即可增删 MCP 工具。
2.6 内存与状态管理


3. 安装部署

3.1 环境要求

项目要求
操作系统macOS、Linux(Ubuntu/Debian 等)、Windows(WSL2)
Node.js22.12.0 及以上版本
包管理器npm 或 pnpm
LLM API KeyAnthropic / OpenAI / Google / DeepSeek 等任一
网络可访问 LLM API 服务
安全提示:强烈建议在专用 VPS、虚拟机或 Docker 容器中部署,不要在存有个人数据的主力机上运行。绝不要以 root 用户运行。

3.2 方法一:推荐 — npm 一键安装(最快)
  1. # 安装 OpenClaw CLInpminstall -g openclaw@latest
  2. # 运行 onboarding 向导(自动安装后台守护进程)
  3. openclaw onboard --install-daemon
复制代码
向导会自动引导你完成:
pnpm 用户:
  1. pnpmadd -g openclaw@latest
  2. openclaw onboard --install-daemon
复制代码

3.3 方法二:一键安装脚本(无需手动安装 Node)

脚本会自动检测操作系统、安装 Node.js 并完成 OpenClaw 安装:
macOS / Linux:
  1. curl -fsSL https://install.openclaw.ai |bash# 安装完成后运行向导
  2. openclaw onboard --install-daemon
复制代码
Windows(PowerShell):
  1. # 先安装 WSL2
  2. wsl --install
  3. # 在 WSL2 终端内,执行上述 Linux 命令
复制代码

3.4 方法三:Docker 部署(推荐用于生产/隔离环境)
  1. # 克隆仓库git clone https://github.com/openclaw/openclaw.git
  2. cd openclaw
  3. # 运行 Docker 安装脚本
  4. ./docker-setup.sh
  5. # 或使用 Docker Composedocker-compose up -d
复制代码
Docker 会挂载两个卷:

3.5 方法四:源码编译(开发者)
  1. git clone https://github.com/openclaw/openclaw.git
  2. cd openclaw
  3. # 安装依赖pnpminstall# 构建 UIpnpm ui:build
  4. # 构建项目pnpm build
  5. # 运行 onboarding 向导pnpm openclaw onboard --install-daemon
  6. # 开发模式(热重载)pnpm gateway:watch
复制代码

3.6 云服务器部署(以 DigitalOcean 为例)

DigitalOcean 提供 OpenClaw 1-Click 镜像,预装所有依赖,安全强化配置(认证 Token、防火墙规则、非 root 用户)已开箱即用。
在 DigitalOcean Droplet Marketplace 搜索 “OpenClaw” 即可一键部署。

3.7 验证安装
  1. # 检查网关状态
  2. openclaw gateway status
  3. # 全面健康检查与自动修复
  4. openclaw doctor --fix
  5. # 查看实时日志
  6. openclaw logs --follow
复制代码
如果 Control UI(http://localhost:18789)能正常加载,说明 Gateway 已就绪。

3.8 更新与升级
  1. # 升级到最新版本
  2. openclaw update
  3. # 指定更新渠道
  4. openclaw update --channel stable   # 稳定版
  5. openclaw update --channel beta     # 测试版
  6. openclaw update --channel dev      # 开发版# 升级后健康检查
  7. openclaw doctor
复制代码

4. 基本使用

4.1 通过命令行(CLI)交互
  1. # 直接发送消息给本地 Gateway
  2. openclaw message send --target "自己的Telegram/WhatsApp" --message "帮我查一下今天的天气"# 进入交互式 TUI
  3. openclaw chat
复制代码
4.2 通过消息平台交互(推荐)

完成 onboarding 后,直接打开 Telegram/WhatsApp/Discord 等,找到你配置的 Bot,像聊天一样发消息:
  1. 用户: 帮我总结一下 ~/Documents/report.pdf
  2. Bot:  [读取文件,调用 LLM,返回摘要]
  3. 用户: 每天早上 9 点提醒我喝水
  4. Bot:  [调用 cron skill,创建定时任务] 好的,已设置每天 9:00 提醒。
  5. 用户: 搜索一下最新的 OpenAI 新闻
  6. Bot:  [调用 web_search skill,返回搜索结果]
复制代码
4.3 通过 WebChat UI 交互

Gateway 内置 WebChat,打开浏览器访问 http://localhost:18789 即可使用。
4.4 常用 CLI 命令参考
  1. openclaw gateway start          # 启动 Gateway
  2. openclaw gateway stop           # 停止 Gateway
  3. openclaw gateway restart        # 重启 Gateway
  4. openclaw gateway status         # 查看状态
  5. openclaw doctor                 # 健康检查
  6. openclaw logs --follow          # 实时日志
  7. openclaw onboard                # 重新运行配置向导
  8. openclaw cron list              # 列出定时任务
  9. openclaw cronadd# 添加定时任务
  10. openclaw update                 # 更新到最新版
复制代码
4.5 配置文件

主配置文件位于 ~/.openclaw/config.json(或 YAML 格式),可直接编辑进行高级配置:
  1. {"gateway":{"host":"127.0.0.1","port":18789,"token":"your-secret-token"},"model":{"provider":"anthropic","name":"claude-sonnet-4-6","failover":["openai/gpt-4o","deepseek/deepseek-chat"]},"exec":{"ask":"on"}}
复制代码
强烈建议开启 exec.ask: "on",在执行写入/Shell 命令前要求手动确认。

5. Skills(技能)系统

5.1 查看与安装 Skills
  1. # 搜索社区 Skill
  2. clawhub search "keyword"# 安装 Skill
  3. clawhub install<slug># 查看已安装 Skill
  4. clawhub list
  5. # 更新所有 Skill
  6. clawhub update --all
  7. # 卸载 Skill
  8. clawhub uninstall <slug>
复制代码
5.2 编写自定义 Skill

Skill 是一个 Markdown 文件(SKILL.md),在 YAML Frontmatter 中声明元数据,文件内描述工具的功能与使用方式。实际执行代码通过 bins(可执行文件)调用。
  1. ---
  2. name: my-weather-skill
  3. description: 查询指定城市的实时天气。
  4. metadata:
  5.   openclaw:
  6.     requires:
  7.       env:
  8.         - WEATHER_API_KEY
  9.       bins:
  10.         - curl
  11.     primaryEnv: WEATHER_API_KEY
  12. ---
  13. # Weather Skill
  14. 查询天气,返回 JSON 格式结果。
  15. ## 使用方式
  16. 调用 `weather <城市名>` 即可获取当前天气。
复制代码
5.3 Lobster 工作流 Shell

Lobster 是 OpenClaw 原生的工作流 Shell,将多个 Skills 组合成可复用的自动化流水线,支持类型安全、本地优先。

6. 安全注意事项

OpenClaw 赋予 AI 对本地系统的实际控制权,因此安全是首要考虑
关键安全措施

措施说明
隔离部署在专用 VPS、VM 或 Docker 中运行,不安装在主力机
非 root 用户绝不以 root 身份运行 Gateway
绑定 localhost将 Gateway 配置为 127.0.0.1 而非 0.0.0.0
开启 exec 确认exec.ask: "on",执行命令前人工审批
审查 Community Skills安装第三方 Skill 前用 Cisco Skill Scanner 扫描
设置访问 Token配置 Gateway Token,防止未授权访问
Tailscale 远程访问使用 Tailscale Serve/Funnel 替代公网暴露
Cisco AI 安全团队曾发现第三方 Skill 存在数据外泄和 Prompt Injection 攻击。OpenClaw 项目本身的一名维护者也警告称,如果用户不了解命令行,该项目对其而言危险性过高。

7. 借鉴 OpenClaw 构建自己的智能体

OpenClaw 提供了一套成熟的"个人 AI 智能体"架构模式。以下是可以借鉴的核心设计要点:
7.1 架构层次拆分

将系统分为清晰的三层:
  1. [用户接口层]  消息平台 / Web UI / CLI
  2.       ↓
  3. [控制平面层]  Gateway:路由、认证、编排
  4.       ↓
  5. [执行层]     Skills/Tools:Shell、文件、API、浏览器…
复制代码
7.2 采用 ReAct 智能体循环

LLM 不直接输出最终结果,而是在 Reason → Act → Observe 循环中迭代:
  1. defagent_loop(user_message, tools, llm_client):
  2.     messages =[{"role":"user","content": user_message}]whileTrue:
  3.         response = llm_client.call(messages, tools=tools)if response.stop_reason =="end_turn":return response.content  # 最终回答if response.stop_reason =="tool_use":
  4.             tool_results =[]for tool_call in response.tool_calls:
  5.                 result = execute_tool(tool_call.name, tool_call.input)
  6.                 tool_results.append({"type":"tool_result","tool_use_id": tool_call.id,"content": result
  7.                 })# 将工具结果追加到对话,继续推理
  8.             messages.append({"role":"assistant","content": response.content})
  9.             messages.append({"role":"user","content": tool_results})
复制代码
7.3 工具(Tool)标准化定义

每个工具需要提供 LLM 能理解的 JSON Schema 描述:
  1. tools =[{"name":"web_search","description":"搜索互联网,返回最新信息。适合查询时事、产品信息等。","input_schema":{"type":"object","properties":{"query":{"type":"string","description":"搜索关键词"}},"required":["query"]}},{"name":"execute_shell","description":"在本地执行 Shell 命令,返回 stdout 和 stderr。","input_schema":{"type":"object","properties":{"command":{"type":"string"},"require_approval":{"type":"boolean","default":True}},"required":["command"]}}]
复制代码
7.4 持久化记忆设计

参考 OpenClaw 的 workspace 模式,用简单的 Markdown 文件做持久化记忆:
  1. import json
  2. from pathlib import Path
  3. MEMORY_FILE = Path.home()/".my_agent"/"memory.md"defload_memory()->str:if MEMORY_FILE.exists():return MEMORY_FILE.read_text()return"## 用户信息\n(暂无)\n\n## 进行中的任务\n(暂无)\n"defupdate_memory(key:str, value:str):# 让 LLM 帮你更新记忆文件,或简单追加passdefbuild_system_prompt()->str:
  4.     memory = load_memory()returnf"""你是一个自动化助手。以下是你的记忆:
  5. {memory}
  6. 请根据记忆中的用户信息,以个性化方式响应请求。"""
复制代码
7.5 消息渠道抽象

通过适配器模式将不同消息平台统一为相同接口,OpenClaw 的 Gateway 就是这一思路的实现:
  1. from abc import ABC, abstractmethod
  2. classChannelAdapter(ABC):@abstractmethodasyncdefreceive_message(self)->dict:"""返回 {'user_id': ..., 'text': ..., 'timestamp': ...}"""pass@abstractmethodasyncdefsend_message(self, user_id:str, text:str):passclassTelegramAdapter(ChannelAdapter):asyncdefreceive_message(self):# 调用 Telegram Bot APIpassasyncdefsend_message(self, user_id, text):# 调用 Telegram sendMessage APIpassclassCLIAdapter(ChannelAdapter):asyncdefreceive_message(self):
  3.         text =input("You: ")return{"user_id":"local","text": text}asyncdefsend_message(self, user_id, text):print(f"Agent: {text}")
复制代码
7.6 权限与安全设计

OpenClaw 的经验教训:AI 智能体有实际执行权限,必须有权限控制机制:
  1. TOOL_PERMISSIONS ={"web_search":"always_allow",# 只读,始终允许"read_file":"always_allow",# 只读,始终允许"write_file":"require_approval",# 写操作,需确认"execute_shell":"require_approval",# 危险操作,需确认"delete_file":"always_deny",# 默认禁止}defcheck_permission(tool_name:str, user_id:str)->str:
  2.     policy = TOOL_PERMISSIONS.get(tool_name,"require_approval")if policy =="require_approval":
  3.         confirm =input(f"[安全确认] 是否允许执行 '{tool_name}'? (y/N): ")return"allow"if confirm.lower()=="y"else"deny"return policy
复制代码
7.7 后台守护进程模式

OpenClaw 作为 daemon 运行,支持主动推送消息、定时任务。可用 Python schedule 库或 APScheduler 实现类似能力:
  1. import schedule
  2. import time
  3. import threading
  4. defrun_scheduled_tasks(agent):defcheck_and_run():# 定时检查 heartbeat 文件,执行待办任务if Path("heartbeat.md").exists():
  5.             tasks = parse_unchecked_tasks("heartbeat.md")for task in tasks:
  6.                 agent.run(task)
  7.    
  8.     schedule.every(30).minutes.do(check_and_run)whileTrue:
  9.         schedule.run_pending()
  10.         time.sleep(60)# 在后台线程运行
  11. t = threading.Thread(target=run_scheduled_tasks, args=(my_agent,), daemon=True)
  12. t.start()
复制代码
7.8 最简可运行示例(Python + Anthropic API)

以下是一个遵循 OpenClaw 核心设计模式的最小实现:
  1. import anthropic
  2. import subprocess
  3. import json
  4. client = anthropic.Anthropic()
  5. tools =[{"name":"bash","description":"执行 Bash 命令并返回输出。","input_schema":{"type":"object","properties":{"command":{"type":"string","description":"要执行的命令"}},"required":["command"]}}]defexecute_bash(command:str)->str:
  6.     confirm =input(f"\n[确认执行]: {command}\n是否继续? (y/N): ")if confirm.lower()!="y":return"用户拒绝执行。"
  7.     result = subprocess.run(command, shell=True, capture_output=True, text=True)return result.stdout or result.stderr
  8. defagent_run(user_input:str):
  9.     messages =[{"role":"user","content": user_input}]whileTrue:
  10.         response = client.messages.create(
  11.             model="claude-sonnet-4-6",
  12.             max_tokens=4096,
  13.             tools=tools,
  14.             messages=messages
  15.         )if response.stop_reason =="end_turn":for block in response.content:ifhasattr(block,"text"):print(f"\nAgent: {block.text}")breakif response.stop_reason =="tool_use":
  16.             messages.append({"role":"assistant","content": response.content})
  17.             tool_results =[]for block in response.content:if block.type=="tool_use":
  18.                     result = execute_bash(block.input["command"])
  19.                     tool_results.append({"type":"tool_result","tool_use_id": block.id,"content": result
  20.                     })
  21.             messages.append({"role":"user","content": tool_results})# 主循环whileTrue:
  22.     user_input =input("\nYou: ")if user_input.lower()in["exit","quit"]:break
  23.     agent_run(user_input)
复制代码

8. 常见问题排查

问题原因解决方案
command not found: openclawPATH 未更新重启终端,或手动添加 npm global bin 到 PATH
Gateway 不响应 / “0 tokens used”守护进程停止或 API Key 失效openclaw gateway restart,检查 API Key
RPC probe: failed端口 18789 被占用sudo lsof -i :18789,终止占用进程
Access not configured用户 ID 未加入白名单运行配对授权命令,输入 Bot 提供的配对码
Docker EACCES 权限错误Node 用户(UID 1000)无挂载卷权限修改宿主机挂载目录权限
Skill 安装失败缺少依赖或 env 变量检查 SKILL.md frontmatter 中的 requires 字段

9. 参考资源


原文地址:https://blog.csdn.net/u011265143/article/details/158380246




欢迎光临 AI创想 (https://llms-ai.com/) Powered by Discuz! X3.4