作者:CSDN博客
OpenClaw 完全指南
文档版本:2026年2月 | 项目地址:github.com/openclaw/openclaw
目录
项目简介与背景核心原理与架构安装部署基本使用Skills(技能)系统安全注意事项借鉴 OpenClaw 构建自己的智能体常见问题排查参考资源
1. 项目简介与背景
1.1 什么是 OpenClaw?
OpenClaw(曾用名 Clawdbot、Moltbot)是由奥地利开发者 Peter Steinberger 开发的开源、自托管个人 AI 智能体。它运行在用户自己的设备上,通过 WhatsApp、Telegram、Discord、Slack、iMessage、Signal 等你已经在用的即时通讯平台来接受指令、执行任务,并返回结果。
截至 2026 年 2 月,该项目已在 GitHub 上获得约 196,000 Stars、33,900 Forks,是近期最火爆的开源 AI 项目之一。项目以 MIT 协议开源,使用 TypeScript 编写。
1.2 命名历程
| 时间 | 名称 | 原因 | | 2025年11月 | Clawdbot | 项目创建,名称来自 Anthropic 的 Claude | | 2026年1月27日 | Moltbot | Anthropic 法务要求更名,社区 Discord 头脑风暴后更名(龙虾蜕壳主题) | | 2026年2月初 | OpenClaw | 最终品牌,完成商标搜索、域名购买与代码迁移 |
注:2026 年 2 月 14 日,项目创始人 Steinberger 宣布加入 OpenAI,项目将移交开源基金会继续维护。
1.3 核心理念
对话优先(Conversation-first):通过自然语言而非配置文件交互,普通用户也能上手本地优先(Local-first):运行在自己的设备或服务器上,数据不经过第三方云端始终在线(Always-on):作为后台守护进程(daemon)运行,可以主动发起消息可黑客化(Hackable):TypeScript 编写,易于阅读、修改、扩展
2. 核心原理与架构
2.1 整体架构
OpenClaw 的架构分为两个核心部分:
“大脑”(Brain) — 推理引擎
负责调用大型语言模型 API(Claude、GPT-4、DeepSeek、Gemini 等)处理会话上下文、工具调用编排管理模型故障转移(failover)
“双手”(Hands) — 执行环境
运行 Skills(技能),如文件操作、Shell 命令、浏览器控制提供工具接口,供 LLM 调用(Function Calling / Tool Use)沙箱化执行,按权限控制
2.2 Gateway(网关)
Gateway 是整个系统的控制平面(Control Plane),监听在本地 ws://127.0.0.1:18789。- WhatsApp / Telegram / Slack / Discord / iMessage / Signal / ...
- │
- ▼
- ┌───────────────────────────┐
- │ Gateway │
- │ (控制平面) │
- │ ws://127.0.0.1:18789 │
- └─────────────┬─────────────┘
- │
- ┌─────────────┼──────────────┐
- ▼ ▼ ▼
- Pi Agent(RPC) WebChat UI CLI (openclaw...)
- │ │ │
- macOS App iOS/Android 控制台
复制代码 Gateway 核心功能:
接收来自各消息渠道的入站消息将消息路由到 LLM 进行推理根据 LLM 的工具调用决策,分发执行任务给对应 Skill将执行结果返回 LLM,完成多轮推理后将最终回答发回用户提供 Control UI(Web 管理界面)和 WebChat
2.3 工作流程(ReAct 模式)
OpenClaw 采用经典的 ReAct(Reasoning + Acting)循环:- 用户发送消息
- │
- ▼
- Gateway 接收并预处理
- │
- ▼
- 组装系统提示词(含 Skills、权限、用户画像、历史记忆)
- │
- ▼
- 调用 LLM API(Claude/GPT/DeepSeek…)
- │
- ┌───┴────────────────────────────┐
- │ LLM 决策:是否需要调用工具? │
- │ ├─ 是 → 发出 tool_call 指令 │
- │ └─ 否 → 直接生成回复 │
- └─────────────────────────────────┘
- │ (tool_call 分支)
- ▼
- Gateway 执行对应 Skill(Shell/文件/浏览器/API…)
- │
- ▼
- 将 tool_result 返回 LLM,继续推理
- │
- ▼(可能多轮循环)
- LLM 生成最终回复
- │
- ▼
- Gateway 通过原消息渠道返回给用户
复制代码 2.4 Skills(技能)系统
Skills 是 OpenClaw 的能力扩展单元,类似插件,每个 Skill 是一段可以被 LLM 调用的代码(工具函数)。
内置核心 Skills 包括:
exec / bash:执行 Shell 命令filesystem:文件读写、目录操作browser:CDP 控制 Chrome/Chromium,网页截图、交互web_search / web_fetch:联网搜索与抓取cron:定时任务调度gmail / calendar:Google 服务集成notifications:系统通知推送
2.5 MCP 集成
OpenClaw 通过 mcporter 支持 MCP(Model Context Protocol),以解耦的桥接模式集成外部 MCP Server,无需重启 Gateway 即可增删 MCP 工具。
2.6 内存与状态管理
每次对话将相关信息写入工作区目录(~/.openclaw/workspace)的 Markdown 文件支持按用户画像(persona)、项目上下文构建持久化记忆会话剪枝(session pruning)控制上下文窗口长度
3. 安装部署
3.1 环境要求
| 项目 | 要求 | | 操作系统 | macOS、Linux(Ubuntu/Debian 等)、Windows(WSL2) | | Node.js | 22.12.0 及以上版本 | | 包管理器 | npm 或 pnpm | | LLM API Key | Anthropic / OpenAI / Google / DeepSeek 等任一 | | 网络 | 可访问 LLM API 服务 |
安全提示:强烈建议在专用 VPS、虚拟机或 Docker 容器中部署,不要在存有个人数据的主力机上运行。绝不要以 root 用户运行。
3.2 方法一:推荐 — npm 一键安装(最快)
- # 安装 OpenClaw CLInpminstall -g openclaw@latest
- # 运行 onboarding 向导(自动安装后台守护进程)
- openclaw onboard --install-daemon
复制代码 向导会自动引导你完成:
选择操作系统与 Node 版本确认选择 LLM 提供商并输入 API Key设置 Gateway(端口、Token 认证)连接消息渠道(Telegram / WhatsApp / Discord 等)安装后台守护服务(macOS: launchd;Linux: systemd)
pnpm 用户:- pnpmadd -g openclaw@latest
- openclaw onboard --install-daemon
复制代码 3.3 方法二:一键安装脚本(无需手动安装 Node)
脚本会自动检测操作系统、安装 Node.js 并完成 OpenClaw 安装:
macOS / Linux:- curl -fsSL https://install.openclaw.ai |bash# 安装完成后运行向导
- openclaw onboard --install-daemon
复制代码 Windows(PowerShell):- # 先安装 WSL2
- wsl --install
- # 在 WSL2 终端内,执行上述 Linux 命令
复制代码 3.4 方法三:Docker 部署(推荐用于生产/隔离环境)
- # 克隆仓库git clone https://github.com/openclaw/openclaw.git
- cd openclaw
- # 运行 Docker 安装脚本
- ./docker-setup.sh
- # 或使用 Docker Composedocker-compose up -d
复制代码 Docker 会挂载两个卷:
~/.openclaw:配置文件与凭据~/openclaw/workspace:智能体工作区(沙箱)
3.5 方法四:源码编译(开发者)
- git clone https://github.com/openclaw/openclaw.git
- cd openclaw
- # 安装依赖pnpminstall# 构建 UIpnpm ui:build
- # 构建项目pnpm build
- # 运行 onboarding 向导pnpm openclaw onboard --install-daemon
- # 开发模式(热重载)pnpm gateway:watch
复制代码 3.6 云服务器部署(以 DigitalOcean 为例)
DigitalOcean 提供 OpenClaw 1-Click 镜像,预装所有依赖,安全强化配置(认证 Token、防火墙规则、非 root 用户)已开箱即用。
在 DigitalOcean Droplet Marketplace 搜索 “OpenClaw” 即可一键部署。
3.7 验证安装
- # 检查网关状态
- openclaw gateway status
- # 全面健康检查与自动修复
- openclaw doctor --fix
- # 查看实时日志
- openclaw logs --follow
复制代码 如果 Control UI(http://localhost:18789)能正常加载,说明 Gateway 已就绪。
3.8 更新与升级
- # 升级到最新版本
- openclaw update
- # 指定更新渠道
- openclaw update --channel stable # 稳定版
- openclaw update --channel beta # 测试版
- openclaw update --channel dev # 开发版# 升级后健康检查
- openclaw doctor
复制代码 4. 基本使用
4.1 通过命令行(CLI)交互
- # 直接发送消息给本地 Gateway
- openclaw message send --target "自己的Telegram/WhatsApp" --message "帮我查一下今天的天气"# 进入交互式 TUI
- openclaw chat
复制代码 4.2 通过消息平台交互(推荐)
完成 onboarding 后,直接打开 Telegram/WhatsApp/Discord 等,找到你配置的 Bot,像聊天一样发消息:- 用户: 帮我总结一下 ~/Documents/report.pdf
- Bot: [读取文件,调用 LLM,返回摘要]
- 用户: 每天早上 9 点提醒我喝水
- Bot: [调用 cron skill,创建定时任务] 好的,已设置每天 9:00 提醒。
- 用户: 搜索一下最新的 OpenAI 新闻
- Bot: [调用 web_search skill,返回搜索结果]
复制代码 4.3 通过 WebChat UI 交互
Gateway 内置 WebChat,打开浏览器访问 http://localhost:18789 即可使用。
4.4 常用 CLI 命令参考
- openclaw gateway start # 启动 Gateway
- openclaw gateway stop # 停止 Gateway
- openclaw gateway restart # 重启 Gateway
- openclaw gateway status # 查看状态
- openclaw doctor # 健康检查
- openclaw logs --follow # 实时日志
- openclaw onboard # 重新运行配置向导
- openclaw cron list # 列出定时任务
- openclaw cronadd# 添加定时任务
- openclaw update # 更新到最新版
复制代码 4.5 配置文件
主配置文件位于 ~/.openclaw/config.json(或 YAML 格式),可直接编辑进行高级配置:- {"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
- # 搜索社区 Skill
- clawhub search "keyword"# 安装 Skill
- clawhub install<slug># 查看已安装 Skill
- clawhub list
- # 更新所有 Skill
- clawhub update --all
- # 卸载 Skill
- clawhub uninstall <slug>
复制代码 5.2 编写自定义 Skill
Skill 是一个 Markdown 文件(SKILL.md),在 YAML Frontmatter 中声明元数据,文件内描述工具的功能与使用方式。实际执行代码通过 bins(可执行文件)调用。- ---
- name: my-weather-skill
- description: 查询指定城市的实时天气。
- metadata:
- openclaw:
- requires:
- env:
- - WEATHER_API_KEY
- bins:
- - curl
- primaryEnv: WEATHER_API_KEY
- ---
- # Weather Skill
- 查询天气,返回 JSON 格式结果。
- ## 使用方式
- 调用 `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 架构层次拆分
将系统分为清晰的三层:- [用户接口层] 消息平台 / Web UI / CLI
- ↓
- [控制平面层] Gateway:路由、认证、编排
- ↓
- [执行层] Skills/Tools:Shell、文件、API、浏览器…
复制代码 7.2 采用 ReAct 智能体循环
LLM 不直接输出最终结果,而是在 Reason → Act → Observe 循环中迭代:- defagent_loop(user_message, tools, llm_client):
- messages =[{"role":"user","content": user_message}]whileTrue:
- response = llm_client.call(messages, tools=tools)if response.stop_reason =="end_turn":return response.content # 最终回答if response.stop_reason =="tool_use":
- tool_results =[]for tool_call in response.tool_calls:
- result = execute_tool(tool_call.name, tool_call.input)
- tool_results.append({"type":"tool_result","tool_use_id": tool_call.id,"content": result
- })# 将工具结果追加到对话,继续推理
- messages.append({"role":"assistant","content": response.content})
- messages.append({"role":"user","content": tool_results})
复制代码 7.3 工具(Tool)标准化定义
每个工具需要提供 LLM 能理解的 JSON Schema 描述:- 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 文件做持久化记忆:- import json
- from pathlib import Path
- 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:
- memory = load_memory()returnf"""你是一个自动化助手。以下是你的记忆:
- {memory}
- 请根据记忆中的用户信息,以个性化方式响应请求。"""
复制代码 7.5 消息渠道抽象
通过适配器模式将不同消息平台统一为相同接口,OpenClaw 的 Gateway 就是这一思路的实现:- from abc import ABC, abstractmethod
- 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):
- text =input("You: ")return{"user_id":"local","text": text}asyncdefsend_message(self, user_id, text):print(f"Agent: {text}")
复制代码 7.6 权限与安全设计
OpenClaw 的经验教训:AI 智能体有实际执行权限,必须有权限控制机制:- 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:
- policy = TOOL_PERMISSIONS.get(tool_name,"require_approval")if policy =="require_approval":
- confirm =input(f"[安全确认] 是否允许执行 '{tool_name}'? (y/N): ")return"allow"if confirm.lower()=="y"else"deny"return policy
复制代码 7.7 后台守护进程模式
OpenClaw 作为 daemon 运行,支持主动推送消息、定时任务。可用 Python schedule 库或 APScheduler 实现类似能力:- import schedule
- import time
- import threading
- defrun_scheduled_tasks(agent):defcheck_and_run():# 定时检查 heartbeat 文件,执行待办任务if Path("heartbeat.md").exists():
- tasks = parse_unchecked_tasks("heartbeat.md")for task in tasks:
- agent.run(task)
-
- schedule.every(30).minutes.do(check_and_run)whileTrue:
- schedule.run_pending()
- time.sleep(60)# 在后台线程运行
- t = threading.Thread(target=run_scheduled_tasks, args=(my_agent,), daemon=True)
- t.start()
复制代码 7.8 最简可运行示例(Python + Anthropic API)
以下是一个遵循 OpenClaw 核心设计模式的最小实现:- import anthropic
- import subprocess
- import json
- client = anthropic.Anthropic()
- tools =[{"name":"bash","description":"执行 Bash 命令并返回输出。","input_schema":{"type":"object","properties":{"command":{"type":"string","description":"要执行的命令"}},"required":["command"]}}]defexecute_bash(command:str)->str:
- confirm =input(f"\n[确认执行]: {command}\n是否继续? (y/N): ")if confirm.lower()!="y":return"用户拒绝执行。"
- result = subprocess.run(command, shell=True, capture_output=True, text=True)return result.stdout or result.stderr
- defagent_run(user_input:str):
- messages =[{"role":"user","content": user_input}]whileTrue:
- response = client.messages.create(
- model="claude-sonnet-4-6",
- max_tokens=4096,
- tools=tools,
- messages=messages
- )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":
- messages.append({"role":"assistant","content": response.content})
- tool_results =[]for block in response.content:if block.type=="tool_use":
- result = execute_bash(block.input["command"])
- tool_results.append({"type":"tool_result","tool_use_id": block.id,"content": result
- })
- messages.append({"role":"user","content": tool_results})# 主循环whileTrue:
- user_input =input("\nYou: ")if user_input.lower()in["exit","quit"]:break
- agent_run(user_input)
复制代码 8. 常见问题排查
| 问题 | 原因 | 解决方案 | | command not found: openclaw | PATH 未更新 | 重启终端,或手动添加 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. 参考资源
GitHub 主仓库:github.com/openclaw/openclaw官方文档:docs.openclaw.ai官方博客:openclaw.ai/blogSkill 市场(ClawHub):github.com/openclaw/clawhubMCP 集成(mcporter):github.com/steipete/mcporterDiscord 社区:项目 README 中有链接维基百科词条:en.wikipedia.org/wiki/OpenClawDigitalOcean 部署教程:digitalocean.com/community/tutorials/how-to-run-openclaw
原文地址:https://blog.csdn.net/u011265143/article/details/158380246 |