第 2 章

15分钟搭建第一个 Agent:安装、配置、跑通第一次对话

第二章:15分钟搭建第一个 Agent:安装、配置、跑通第一次对话

2.1 系统要求详解

在开始安装之前,理解每一项系统要求背后的原因将帮助你避免常见错误。

Node.js 24+

OpenClaw 强制要求 Node.js 24 或更高版本。这不是一个随意的版本限制,背后有明确的技术原因:

# 检查当前 Node.js 版本
node --version
# 应输出 v24.x.x 或更高

# 如果版本不满足,使用 nvm 安装
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc  # 或 source ~/.zshrc
nvm install 24
nvm use 24
nvm alias default 24

内存要求:8GB RAM

8GB 是推荐的最低配置,原因是:

如果你使用云端 LLM API(Anthropic、OpenAI),本地内存需求可以降低到 2GB,但 8GB 仍是推荐配置以应对多 Session 并发。

LLM API Key

OpenClaw 需要至少一个 LLM Provider 的 API Key。支持的 Provider:

Provider 环境变量 推荐模型
Anthropic ANTHROPIC_API_KEY claude-opus-4-5、claude-sonnet-4-5
OpenAI OPENAI_API_KEY gpt-4o、gpt-4o-mini
Google GOOGLE_API_KEY gemini-2.0-flash
Ollama(本地) 无需 Key llama3.3、qwen2.5
OpenAI 兼容 CUSTOM_API_KEY 任意兼容 API

存储要求

端口要求

端口 用途 可配置
18789 Gateway WebSocket
18790 Control UI HTTP
18791 Plugin Registry HTTP

2.2 三种安装方式

方式一:curl 脚本安装(推荐新手)

curl -fsSL https://openclaw.ai/install.sh | bash

此脚本会:

  1. 检测操作系统和 Node.js 版本
  2. 使用 npm 全局安装 openclaw CLI
  3. 创建默认配置目录 ~/.openclaw/
  4. openclaw 添加到 PATH
  5. 运行安装后的自检(openclaw doctor

安装完成后会看到:

✓ OpenClaw v1.5.2 installed successfully
✓ Node.js v24.3.0 detected
✓ Default config directory created at ~/.openclaw/
✓ Run `openclaw onboard` to get started

注意:在中国大陆网络环境下,可能需要使用镜像:

# 使用 npm 淘宝镜像安装
npm install -g openclaw@latest --registry=https://registry.npmmirror.com

方式二:npm 全局安装

# 使用 npm
npm install -g openclaw@latest

# 使用 pnpm(推荐,与框架本身的包管理器一致)
pnpm add -g openclaw@latest

# 使用 yarn
yarn global add openclaw@latest

全局安装后,openclaw CLI 即可在任意目录使用。

方式三:源码安装(开发者 / 深度定制)

源码安装适合需要修改核心代码、参与贡献或使用最新未发布功能的用户。

# 克隆仓库
git clone https://github.com/openclaw/openclaw.git
cd openclaw

# 安装依赖(必须使用 pnpm,monorepo 结构依赖 pnpm workspace)
pnpm install

# 构建所有包
pnpm build

# 链接到全局(使本地版本覆盖已安装的全局版本)
pnpm link --global

# 验证
openclaw --version

monorepo 的包结构:

packages/
  openclaw-cli/        # CLI 入口
  pi-ai/               # LLM Provider 适配层
  pi-agent-core/       # Pi 核心执行引擎
  pi-coding-agent/     # 编码场景的扩展 Agent
  pi-tui/              # Terminal UI(Control UI 的 TUI 模式)
  gateway/             # Integration Gateway
  plugin-sdk/          # Plugin 开发 SDK
  skills-runtime/      # Skills 执行运行时
integrations/
  whatsapp/            # WhatsApp Business Channel Bridge
  telegram/            # Telegram Channel Bridge
  slack/               # Slack Channel Bridge
  ... (50+ 集成包)

2.3 onboard 初始化流程

安装完成后,运行 openclaw onboard 启动交互式初始化向导:

openclaw onboard

向导会引导你完成以下步骤:

? Welcome to OpenClaw! Let's set up your first agent.
  
? Choose your primary LLM provider:
  ❯ Anthropic (Claude)
    OpenAI
    Google Gemini
    Ollama (local)
    Custom OpenAI-compatible

? Enter your Anthropic API Key: sk-ant-api03-...
  ✓ API Key validated

? Choose your first channel:
  ❯ Terminal (for testing)
    Telegram
    Discord
    Slack
    WhatsApp Business
    Skip (configure later)

? Choose a channel name: my-terminal

? Enter a name for your agent: MyFirstAgent

? Choose agent personality:
  ❯ General Assistant
    Customer Support
    Developer Assistant
    Custom

  ✓ Configuration written to ~/.openclaw/openclaw.json
  ✓ First agent "MyFirstAgent" created

? Run the agent now? (Y/n) Y

初始化完成后,配置文件会自动生成。

2.4 openclaw.json 最小化配置详解

onboard 生成的最小化配置文件位于 ~/.openclaw/openclaw.json

{
  "version": "1",
  "gateway": {
    "port": 18789,
    "controlUiPort": 18790
  },
  "llm": {
    "providers": [
      {
        "id": "anthropic-primary",
        "type": "anthropic",
        "apiKey": "${ANTHROPIC_API_KEY}",
        "defaultModel": "claude-sonnet-4-5-20251201"
      }
    ],
    "defaultProvider": "anthropic-primary"
  },
  "channels": [
    {
      "id": "terminal-test",
      "type": "terminal",
      "name": "Terminal Test Channel"
    }
  ],
  "agents": [
    {
      "id": "my-first-agent",
      "name": "MyFirstAgent",
      "llmProvider": "anthropic-primary",
      "channels": ["terminal-test"],
      "systemPrompt": "You are a helpful assistant named MyFirstAgent.",
      "memory": {
        "shortTerm": {
          "maxMessages": 50
        }
      }
    }
  ]
}

配置项详解

gateway 部分:控制 Gateway 进程的网络配置。port 是内部 WebSocket 端口,只供 Pi 进程连接;controlUiPort 是 Control UI 的 HTTP 端口,供浏览器访问。

llm.providers 部分:支持配置多个 Provider,Pi 根据 Agent 配置选择使用哪个。apiKey 支持环境变量引用语法 ${ENV_VAR}强烈建议不要将 API Key 硬编码在配置文件中

channels 部分:定义消息来源。terminal 类型是内置的测试 Channel,直接在终端输入消息,无需配置任何外部账号。

agents 部分:每个 Agent 指定使用哪个 LLM Provider、监听哪些 Channel、使用什么 System Prompt。

使用环境变量

# 在 shell profile 中设置(~/.bashrc 或 ~/.zshrc)
export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

# 或使用 .env 文件(OpenClaw 会自动加载项目目录下的 .env)
cat > ~/.openclaw/.env << 'EOF'
ANTHROPIC_API_KEY=sk-ant-api03-your-key-here
OPENAI_API_KEY=sk-your-openai-key
EOF

2.5 连接 Anthropic Claude 并发送第一条消息

配置完成后,启动 OpenClaw:

# 方式一:前台运行(开发调试)
openclaw start

# 方式二:后台守护进程运行
openclaw start --daemon

# 方式三:仅启动 Terminal Channel 进行快速测试
openclaw chat

使用 openclaw chat 命令时,你会直接进入 Terminal Channel 的交互界面:

OpenClaw v1.5.2 | Agent: MyFirstAgent | Channel: terminal-test
Type your message and press Enter. Type /help for commands.
──────────────────────────────────────────────────────────────
You: 你好!请介绍一下你自己。

MyFirstAgent: 你好!我是 MyFirstAgent,一个由 Anthropic Claude 驱动的 AI 助手,
运行在 OpenClaw 框架上。我可以帮助你处理各种任务,包括回答问题、分析信息、
协助写作等。有什么我可以帮助你的吗?

You: /stats

Session Stats:
  Session ID: sess_01HX7K2M...
  Messages: 2 (1 user, 1 assistant)
  Tokens used: 312 (input: 278, output: 34)
  LLM Provider: anthropic-primary (claude-sonnet-4-5-20251201)
  Latency: 1.23s (last response)

You: /quit
Goodbye!

验证 API 连接

如果想在启动前验证 API Key 是否有效:

openclaw doctor --check-llm

# 输出示例:
✓ Anthropic API: Connected (claude-sonnet-4-5-20251201 available)
✓ Latency: 342ms
✓ Rate limit: 50 RPM remaining

2.6 Gateway 启动与 Control UI 访问

当 Agent 处理的消息量增加,或者需要同时管理多个 Channel 时,需要启动完整的 Gateway 进程并使用 Control UI。

启动完整 Gateway

openclaw start

启动日志示例:

[2026-04-26T10:00:00Z] INFO  Gateway starting...
[2026-04-26T10:00:00Z] INFO  Plugin Registry initialized (0 plugins loaded)
[2026-04-26T10:00:01Z] INFO  Channel Bridge: terminal-test → READY
[2026-04-26T10:00:01Z] INFO  Command Queue initialized
  └─ Lanes: Global(4) Session(1) SubAgent(8) Cron(∞)
[2026-04-26T10:00:01Z] INFO  Pi Agent "MyFirstAgent" registered
[2026-04-26T10:00:01Z] INFO  WebSocket server listening on ws://localhost:18789
[2026-04-26T10:00:01Z] INFO  Control UI available at http://localhost:18790
[2026-04-26T10:00:01Z] INFO  OpenClaw ready ✓

访问 Control UI

在浏览器中打开 http://localhost:18790,你会看到 Control UI 界面。Control UI 提供:

配置远程访问 Control UI

默认情况下,Control UI 仅绑定到 localhost。如果需要从其他机器访问(例如服务器部署),需要配置:

{
  "gateway": {
    "controlUi": {
      "host": "0.0.0.0",
      "port": 18790,
      "auth": {
        "enabled": true,
        "username": "admin",
        "passwordHash": "${CONTROL_UI_PASSWORD_HASH}"
      }
    }
  }
}

生成密码哈希:

openclaw util hash-password "your-secure-password"
# 输出:$argon2id$v=19$m=65536,t=3,p=4$...

安全警告:在生产环境中,强烈建议在 Control UI 前面放置反向代理(Nginx/Caddy),并启用 HTTPS 和强密码。

2.7 常见报错排查

错误一:端口冲突

Error: Address already in use (EADDRINUSE): 18789

原因:另一个进程(可能是旧的 OpenClaw 实例)占用了 18789 端口。

排查步骤

# 查找占用端口的进程
lsof -i :18789
# 或
ss -tulpn | grep 18789

# 终止旧进程
openclaw stop  # 使用 OpenClaw 自带的停止命令
# 或强制终止
kill -9 $(lsof -t -i:18789)

配置方案:如果需要运行多个实例,修改配置中的端口:

{
  "gateway": {
    "port": 18800,
    "controlUiPort": 18801
  }
}

错误二:Node.js 版本不满足

Error: OpenClaw requires Node.js >= 24.0.0, found v20.11.0

解决方案

# 使用 nvm 切换版本
nvm install 24 && nvm use 24

# 验证
node --version  # 应输出 v24.x.x

# 重新运行
openclaw start

错误三:API Key 无效或过期

LLM Error: Authentication failed (401)
Provider: anthropic-primary
Model: claude-sonnet-4-5-20251201

排查步骤

# 检查环境变量是否正确设置
echo $ANTHROPIC_API_KEY

# 使用 doctor 命令验证
openclaw doctor --check-llm --verbose

# 如果需要更新 Key,编辑配置或更新环境变量
export ANTHROPIC_API_KEY="sk-ant-api03-new-key"
openclaw restart

错误四:pnpm 未安装(源码安装时)

Error: pnpm is required for monorepo management
# 安装 pnpm
npm install -g pnpm@latest

# 验证
pnpm --version

错误五:配置文件 JSON 解析错误

Error: Failed to parse openclaw.json
SyntaxError: Unexpected token } in JSON at position 847

排查步骤

# 使用内置的配置验证工具
openclaw config validate

# 或使用 jq 检查 JSON 语法
cat ~/.openclaw/openclaw.json | jq .

常见 JSON 错误:

错误六:Memory 数据库锁定

Error: SQLite database is locked
Path: ~/.openclaw/data/memory.db

原因:另一个 OpenClaw 实例正在写入数据库,OpenClaw 使用 Single-writer pattern,不支持多进程同时写入。

# 停止所有 OpenClaw 进程
openclaw stop --all

# 如果进程已无响应,强制清理
rm ~/.openclaw/data/memory.db-wal
rm ~/.openclaw/data/memory.db-shm
openclaw start

快速诊断命令

遇到任何问题,首先运行:

openclaw doctor

输出示例(包含问题时):

OpenClaw Doctor v1.5.2
──────────────────────────────────────
✓ Node.js: v24.3.0
✗ Port 18789: In use by PID 12847
✓ Anthropic API: Connected
✓ Config: Valid JSON
✗ Memory DB: Locked (stale WAL file detected)
  → Run: openclaw fix --memory-db

Suggested fixes:
  openclaw fix --port-conflict
  openclaw fix --memory-db

小结

在本章中,我们完成了 OpenClaw 从安装到第一次对话的完整流程:

  1. 理解了 Node.js 24+、8GB RAM 等系统要求背后的原因
  2. 掌握了三种安装方式及其适用场景
  3. 通过 onboard 向导完成了初始化配置
  4. 理解了 openclaw.json 每个配置项的含义
  5. 成功发送了第一条消息并验证了 API 连接
  6. 学会了访问 Control UI 进行可视化管理
  7. 掌握了六类常见错误的排查方法

在下一章中,我们将深入理解 OpenClaw 的核心概念:Gateway、Pi、Skills、Plugin 和 Memory 之间的关系,以及数据如何在这些组件之间流动。

本章评分
4.6  / 5  (108 评分)

💬 留言讨论