OpenClaw 支持多种 API Key 配置方式,每种方式都有其适用场景和优先级。

配置方式对比

方式 优先级 适用场景 持久化 难度
环境变量 ⭐⭐⭐⭐⭐ 最高 临时测试、Docker、CI/CD ⭐ 简单
Agent 专属配置 ⭐⭐⭐⭐ 高 多 Agent 不同 Key ⭐⭐ 中等
全局配置 ⭐⭐⭐ 中 所有 Agent 共享 ⭐ 简单
配置向导 ⭐⭐ 低 首次安装 ⭐ 简单

🔄 配置优先级

优先级顺序(从高到低)

1. 环境变量(最高优先级)
   ↓
2. Agent 专属配置
   ↓
3. 全局配置
   ↓
4. 配置向导
   ↓
5. 默认值(最低优先级)

优先级示例

假设你同时配置了:

# 1. 环境变量
export ANTHROPIC_API_KEY="sk-ant-env"

# 2. Agent 配置
openclaw config set models.providers.anthropic.apiKey "sk-ant-agent" --agent tech-dev

# 3. 全局配置
openclaw config set models.providers.anthropic.apiKey "sk-ant-global"
```text
**实际使用**: `sk-ant-env`(环境变量优先级最高)

---

## 🎯 方式一:环境变量(推荐:临时测试)

### 适用场景

- ✅ 临时测试不同的 API Key
- ✅ Docker 容器部署
- ✅ CI/CD 自动化
- ✅ 不想写入配置文件
- ✅ 需要最高优先级

### 配置方法

#### 临时设置(当前会话)

```bash
# Anthropic
export ANTHROPIC_API_KEY="sk-ant-xxx"

# OpenAI
export OPENAI_API_KEY="sk-xxx"

# Google
export GOOGLE_API_KEY="xxx"

# DeepSeek
export DEEPSEEK_API_KEY="sk-xxx"

# Moonshot
export MOONSHOT_API_KEY="sk-xxx"
```text
#### 永久设置(写入 Shell 配置)

**macOS/Linux (zsh)**:
```bash
# 添加到 ~/.zshrc
echo 'export ANTHROPIC_API_KEY="sk-ant-xxx"' >> ~/.zshrc
source ~/.zshrc
```text
**macOS/Linux (bash)**:
```bash
# 添加到 ~/.bashrc
echo 'export ANTHROPIC_API_KEY="sk-ant-xxx"' >> ~/.bashrc
source ~/.bashrc
```text
**Windows (PowerShell)**:
```powershell
# 临时设置
$env:ANTHROPIC_API_KEY="sk-ant-xxx"

# 永久设置(用户级)
[System.Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "sk-ant-xxx", "User")
```text
### 验证配置

```bash
# 查看环境变量
echo $ANTHROPIC_API_KEY

# 测试连接
openclaw models list
```text
### 优点和缺点

**优点**:
- ✅ 最高优先级,覆盖所有其他配置
- ✅ 灵活,易于切换
- ✅ 适合 Docker 和 CI/CD
- ✅ 不写入配置文件,更安全

**缺点**:
- ❌ 临时设置重启后失效
- ❌ 不适合多 Agent 场景
- ❌ 需要在每个终端会话中设置

---

## 🎯 方式二:Agent 专属配置(推荐:多 Agent)

### 适用场景

- ✅ 多个 Agent 使用不同的 API Key
- ✅ 需要隔离配置
- ✅ 长期使用
- ✅ 需要持久化

### 配置方法

#### 使用命令行

```bash
# 为特定 Agent 配置
openclaw config set models.providers.anthropic.apiKey "sk-ant-xxx" --agent tech-dev

# 为另一个 Agent 配置不同的 Key
openclaw config set models.providers.openai.apiKey "sk-yyy" --agent content-writer

# 验证配置
openclaw config get models.providers.anthropic.apiKey --agent tech-dev
```text
#### 直接编辑配置文件

**配置文件位置**: `~/.openclaw/agents/<agentId>/openclaw.json`

```bash
# 编辑配置文件
nano ~/.openclaw/agents/tech-dev/openclaw.json
```text
**配置内容**:
```json
{
  "models": {
    "default": "anthropic/claude-sonnet-4-5",
    "providers": {
      "anthropic": {
        "apiKey": "sk-ant-xxx",
        "baseUrl": "https://api.anthropic.com"
      }
    }
  }
}
```text
### 验证配置

```bash
# 查看 Agent 配置
openclaw config get --agent tech-dev

# 测试连接
openclaw agent --message --agent tech-dev "Hello"
```text
### 优点和缺点

**优点**:
- ✅ 每个 Agent 独立配置
- ✅ 配置隔离,互不影响
- ✅ 持久化存储
- ✅ 适合多 Agent 场景

**缺点**:
- ❌ 需要为每个 Agent 单独配置
- ❌ 管理成本较高
- ❌ 被环境变量覆盖

---

## 🎯 方式三:全局配置(推荐:单 Agent)

### 适用场景

- ✅ 所有 Agent 共享同一个 API Key
- ✅ 单 Agent 使用
- ✅ 长期使用
- ✅ 需要持久化

### 配置方法

#### 方法1:交互式命令(推荐新手)

```bash
# 运行交互式命令
openclaw models auth add

# 按提示操作:
# 1. 选择 provider(如 anthropic)
# 2. 输入 API Key
# 3. 确认保存
```text
#### 方法2:配置命令

```bash
# 直接设置
openclaw config set models.providers.anthropic.apiKey "sk-ant-xxx"

# 设置默认 model
openclaw config set models.default "anthropic/claude-sonnet-4-5"

# 验证配置
openclaw config get models.providers.anthropic.apiKey
```text
#### 方法3:直接编辑配置文件

**配置文件位置**: `~/.openclaw/openclaw.json`

```bash
# 编辑配置文件
nano ~/.openclaw/openclaw.json
```text
**配置内容**:
```json
{
  "models": {
    "default": "anthropic/claude-sonnet-4-5",
    "providers": {
      "anthropic": {
        "apiKey": "sk-ant-xxx"
      },
      "openai": {
        "apiKey": "sk-yyy"
      }
    }
  }
}
```text
### 验证配置

```bash
# 查看全局配置
openclaw config get

# 测试连接
openclaw models list
```text
### 优点和缺点

**优点**:
- ✅ 配置一次,全局生效
- ✅ 持久化存储
- ✅ 适合大多数场景
- ✅ 管理简单

**缺点**:
- ❌ 无法区分不同 Agent
- ❌ 被环境变量和 Agent 配置覆盖

---

## 🎯 方式四:配置向导(推荐:首次安装)

### 适用场景

- ✅ 首次安装 OpenClaw
- ✅ 不熟悉命令行
- ✅ 需要交互式引导

### 配置方法

```bash
# 运行配置向导
openclaw onboard

# 按提示操作:
# 1. 选择 provider
# 2. 输入 API Key
# 3. 选择默认 model
# 4. 完成配置
```text
### 验证配置

```bash
# 查看配置
openclaw config get

# 测试连接
openclaw channels status
```text
### 优点和缺点

**优点**:
- ✅ 交互式,不易出错
- ✅ 适合新手
- ✅ 一次性完成所有配置

**缺点**:
- ❌ 只能配置一次
- ❌ 修改配置需要其他方式
- ❌ 优先级最低

---

## 🔍 配置验证

### 检查配置是否生效

```bash
# 1. 查看配置
openclaw config get models.providers.anthropic.apiKey

# 2. 查看环境变量
echo $ANTHROPIC_API_KEY

# 3. 测试 API 连接
openclaw models list

# 4. 查看 Gateway 状态
openclaw channels status

# 5. 发送测试消息
openclaw agent --message "Hello, test API Key"
```text
### 查看生效的配置

```bash
# 查看当前使用的 model
openclaw config get models.default

# 查看所有 provider 配置
openclaw config get models.providers

# 以 JSON 格式输出
openclaw config get --json
```text
---

## 🔧 配置故障排查

### 问题1:配置后不生效

**症状**: 设置了 API Key,但仍然提示未配置

**排查步骤**:

1. **检查配置优先级**
   ```bash
   # 检查环境变量(最高优先级)
   echo $ANTHROPIC_API_KEY
   
   # 检查 Agent 配置
   openclaw config get models.providers.anthropic.apiKey --agent tech-dev
   
   # 检查全局配置
   openclaw config get models.providers.anthropic.apiKey
  1. 重启 Gateway

    openclaw gateway restart
  2. 查看日志

    openclaw logs --tail 50
  3. 验证 API Key 格式

    # Anthropic: sk-ant-xxx
    # OpenAI: sk-xxx
    # Google: xxx

问题2:多个 Agent 使用不同的 API Key

场景: 需要为不同的 Agent 配置不同的 API Key

解决方案:

# 方案1:使用 Agent 专属配置
openclaw config set models.providers.anthropic.apiKey "sk-ant-xxx" --agent tech-dev
openclaw config set models.providers.openai.apiKey "sk-yyy" --agent content-writer

# 方案2:使用环境变量(临时切换)
export ANTHROPIC_API_KEY="sk-ant-xxx"
openclaw agent --message --agent tech-dev "Hello"

export ANTHROPIC_API_KEY="sk-ant-yyy"
openclaw agent --message --agent content-writer "Hello"
```text
---

### 问题3:如何切换 provider

**场景**: 需要在不同的 AI provider 之间切换

**解决方案**:

```bash
# 查看当前 provider
openclaw config get models.default

# 切换到 Anthropic
openclaw config set models.default "anthropic/claude-sonnet-4-5"

# 切换到 OpenAI
openclaw config set models.default "openai/gpt-4"

# 切换到 Google
openclaw config set models.default "google/gemini-pro"

# 验证
openclaw models list
```text
---

### 问题4:API Key 泄露了怎么办

**应急措施**:

1. **立即撤销旧 Key**
   - 登录 provider 控制台
   - 撤销泄露的 API Key

2. **生成新 Key**
   - 在 provider 控制台生成新 Key

3. **更新配置**
   ```bash
   # 更新全局配置
   openclaw config set models.providers.anthropic.apiKey "sk-ant-new"
   
   # 或更新环境变量
   export ANTHROPIC_API_KEY="sk-ant-new"
  1. 清理旧配置
    # 检查所有配置文件
    grep -r "sk-ant-old" ~/.openclaw/
    
    # 删除旧 Key
    openclaw config unset models.providers.anthropic.apiKey

📋 配置最佳实践

推荐的配置策略

新手用户

  1. 使用配置向导

    openclaw onboard
  2. 或使用全局配置

    openclaw models auth add
  3. 验证配置

    openclaw models list

进阶用户

  1. 使用 Agent 专属配置

    openclaw config set models.providers.anthropic.apiKey "sk-ant-xxx" --agent tech-dev
  2. 合理利用配置优先级

    • 全局配置作为默认
    • Agent 配置作为覆盖
    • 环境变量作为临时切换
  3. 定期备份配置

    cp -r ~/.openclaw ~/.openclaw.backup-$(date +%Y%m%d)

企业用户

  1. 使用环境变量管理敏感信息

    # 在 Docker Compose 中
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
  2. 版本控制配置模板

    # 配置模板(不包含真实 Key)
    {
      "models": {
        "providers": {
          "anthropic": {
            "apiKey": "${ANTHROPIC_API_KEY}"
          }
        }
      }
    }
  3. 自动化配置部署

    # 使用脚本自动配置
    ./scripts/setup-config.sh

🔐 安全建议

API Key 安全管理

  1. 不要硬编码 API Key

    • ❌ 不要写在代码中
    • ❌ 不要提交到 Git
    • ✅ 使用环境变量或配置文件
  2. 使用 .gitignore

    # .gitignore
    .openclaw/openclaw.json
    .openclaw/agents/*/openclaw.json
    .openclaw/credentials/
    .env
  3. 定期轮换 API Key

    • 每 3-6 个月更换一次
    • 发现泄露立即更换
  4. 使用最小权限原则

    • 只授予必要的权限
    • 不同用途使用不同的 Key
  5. 监控 API 使用情况

    • 定期检查 API 调用量
    • 发现异常立即处理

💡 常见问题 FAQ

Q1: 我应该使用哪种配置方式?

A: 根据你的场景选择:

  • 新手:使用配置向导或全局配置
  • 多 Agent:使用 Agent 专属配置
  • 临时测试:使用环境变量
  • Docker 部署:使用环境变量

Q2: 配置优先级是怎样的?

A: 环境变量 > Agent 配置 > 全局配置 > 配置向导 > 默认值

Q3: 如何查看当前使用的 API Key?

A:

openclaw config get models.providers.anthropic.apiKey
```text
### Q4: 配置后不生效怎么办?

**A**: 
1. 检查配置优先级
2. 重启 Gateway
3. 查看日志
4. 验证 API Key 格式

### Q5: 如何为不同的 Agent 配置不同的 API Key?

**A**: 
```bash
openclaw config set models.providers.anthropic.apiKey "sk-ant-xxx" --agent agent1
openclaw config set models.providers.openai.apiKey "sk-yyy" --agent agent2

openclaw.json基础配置模板

1. 最小配置(新手推荐)

文件位置~/.openclaw/config.json

{
  "gateway": {
    "mode": "local",
    "port": 18789,
    "bind": "127.0.0.1"
  },
  "models": {
    "default": "deepseek-chat",
    "providers": {
      "deepseek": {
        "apiKey": "YOUR_DEEPSEEK_API_KEY",
        "baseURL": "https://api.deepseek.com"
      }
    }
  },
  "workspace": {
    "path": "~/Documents/OpenClaw"
  }
}

使用说明

  1. 替换 YOUR_DEEPSEEK_API_KEY 为你的API密钥
  2. 保存到 ~/.openclaw/config.json
  3. 运行 openclaw gateway run

2. 完整基础配置

{
  "gateway": {
    "mode": "local",
    "port": 18789,
    "bind": "127.0.0.1",
    "ssl": {
      "enabled": false
    },
    "cors": {
      "enabled": true,
      "origins": ["http://localhost:3000"]
    }
  },
  "models": {
    "default": "deepseek-chat",
    "streaming": true,
    "timeout": 60000,
    "providers": {
      "deepseek": {
        "apiKey": "YOUR_DEEPSEEK_API_KEY",
        "baseURL": "https://api.deepseek.com",
        "models": {
          "deepseek-chat": {
            "maxTokens": 4000,
            "temperature": 0.7
          }
        }
      }
    }
  },
  "workspace": {
    "path": "~/Documents/OpenClaw",
    "autoCreate": true
  },
  "files": {
    "searchPaths": [
      "~/Documents",
      "~/Desktop"
    ],
    "excludePaths": [
      "~/.ssh",
      "~/Documents/Private"
    ],
    "excludePatterns": [
      "node_modules",
      ".git",
      "*.log"
    ]
  },
  "cache": {
    "enabled": true,
    "ttl": 3600,
    "maxSize": 1000
  },
  "logging": {
    "level": "info",
    "file": "~/.openclaw/logs/gateway.log"
  }
}

🔑 openclaw.json API配置模板

1. 单一API配置(DeepSeek)

{
  "models": {
    "default": "deepseek-chat",
    "providers": {
      "deepseek": {
        "apiKey": "sk-xxx",
        "baseURL": "https://api.deepseek.com",
        "models": {
          "deepseek-chat": {
            "maxTokens": 4000,
            "temperature": 0.7
          },
          "deepseek-coder": {
            "maxTokens": 8000,
            "temperature": 0.2
          }
        }
      }
    }
  }
}

2. 多API配置(推荐)

{
  "models": {
    "default": "deepseek-chat",
    "code": "deepseek-coder",
    "longContext": "kimi",
    "vision": "gpt-4-vision",
    "providers": {
      "deepseek": {
        "apiKey": "sk-xxx",
        "baseURL": "https://api.deepseek.com",
        "models": {
          "deepseek-chat": {
            "maxTokens": 4000,
            "temperature": 0.7
          },
          "deepseek-coder": {
            "maxTokens": 8000,
            "temperature": 0.2
          }
        }
      },
      "moonshot": {
        "apiKey": "sk-xxx",
        "baseURL": "https://api.moonshot.cn",
        "models": {
          "kimi": {
            "maxTokens": 200000,
            "temperature": 0.7
          }
        }
      },
      "openai": {
        "apiKey": "sk-xxx",
        "baseURL": "https://api.openai.com",
        "models": {
          "gpt-4-vision": {
            "maxTokens": 4000,
            "temperature": 0.7
          }
        }
      }
    }
  }
}

3. 中转API配置

{
  "models": {
    "default": "gpt-3.5-turbo",
    "providers": {
      "relay": {
        "apiKey": "YOUR_RELAY_API_KEY",
        "baseURL": "https://api.middle-service.com/v1",
        "models": {
          "gpt-3.5-turbo": {
            "maxTokens": 4000,
            "temperature": 0.7
          },
          "gpt-4": {
            "maxTokens": 8000,
            "temperature": 0.7
          },
          "claude-3-opus": {
            "maxTokens": 4000,
            "temperature": 0.7
          }
        }
      }
    }
  }
}

4. 智能路由配置

{
  "models": {
    "routing": {
      "enabled": true,
      "rules": [
        {
          "condition": "tokens < 500",
          "model": "deepseek-chat",
          "description": "简单任务"
        },
        {
          "condition": "tokens >= 500 && tokens < 2000",
          "model": "gpt-3.5-turbo",
          "description": "中等任务"
        },
        {
          "condition": "tokens >= 2000",
          "model": "gpt-4",
          "description": "复杂任务"
        },
        {
          "condition": "hasImage",
          "model": "gpt-4-vision",
          "description": "图片理解"
        },
        {
          "condition": "isCode",
          "model": "deepseek-coder",
          "description": "代码生成"
        }
      ]
    }
  }
}

📱 openclaw channel多平台集成配置

1. 飞书Bot配置

{
  "channels": {
    "feishu": {
      "enabled": true,
      "appId": "cli_xxx",
      "appSecret": "xxx",
      "verificationToken": "xxx",
      "encryptKey": "xxx",
      "webhookUrl": "https://your-domain.com/webhook/feishu",
      "features": {
        "streaming": true,
        "fileUpload": true,
        "imageRecognition": true
      },
      "filters": {
        "onlyMentions": true,
        "ignoreGroups": ["闲聊群"],
        "keywords": ["openclaw", "帮助"]
      }
    }
  }
}

2. 企业微信Bot配置

{
  "channels": {
    "wecom": {
      "enabled": true,
      "corpId": "ww123456",
      "agentId": "1000001",
      "secret": "xxx",
      "token": "xxx",
      "encodingAESKey": "xxx",
      "webhookUrl": "https://your-domain.com/webhook/wecom",
      "features": {
        "fileUpload": true,
        "imageRecognition": true
      }
    }
  }
}

3. 钉钉Bot配置

{
  "channels": {
    "dingtalk": {
      "enabled": true,
      "appKey": "xxx",
      "appSecret": "xxx",
      "agentId": "xxx",
      "webhookUrl": "https://your-domain.com/webhook/dingtalk",
      "features": {
        "fileUpload": true
      }
    }
  }
}

4. Telegram Bot配置

{
  "channels": {
    "telegram": {
      "enabled": true,
      "botToken": "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
      "webhookUrl": "https://your-domain.com/webhook/telegram",
      "features": {
        "streaming": true,
        "fileUpload": true,
        "imageRecognition": true
      },
      "allowedUsers": [
        123456789,
        987654321
      ]
    }
  }
}

5. 多Agent配置

{
  "agents": {
    "work": {
      "name": "工作助手",
      "model": "gpt-4",
      "workspace": "~/Documents/Work",
      "channels": ["feishu"],
      "systemPrompt": "你是一个专业的工作助手,帮助处理工作相关的任务。",
      "skills": [
        "@openclaw/skill-file-search",
        "@openclaw/skill-calendar",
        "@openclaw/skill-email"
      ]
    },
    "personal": {
      "name": "个人助手",
      "model": "deepseek-chat",
      "workspace": "~/Documents/Personal",
      "channels": ["telegram"],
      "systemPrompt": "你是一个友好的个人助手,帮助处理日常生活中的各种问题。",
      "skills": [
        "@openclaw/skill-web-search",
        "@openclaw/skill-weather",
        "@openclaw/skill-news"
      ]
    },
    "code": {
      "name": "代码助手",
      "model": "deepseek-coder",
      "workspace": "~/Projects",
      "channels": ["telegram"],
      "systemPrompt": "你是一个专业的编程助手,精通多种编程语言。",
      "skills": [
        "@openclaw/skill-github",
        "@openclaw/skill-code-review",
        "@openclaw/skill-documentation"
      ]
    }
  }
}

🧩 openclaw Skills配置模板

1. 基础Skills配置

{
  "skills": {
    "enabled": true,
    "autoUpdate": false,
    "directory": "~/.openclaw/skills",
    "installed": [
      "@openclaw/skill-file-search",
      "@openclaw/skill-web-search",
      "@openclaw/skill-calendar"
    ],
    "priority": [
      "@openclaw/skill-file-search",
      "@openclaw/skill-web-search",
      "@openclaw/skill-calendar"
    ]
  }
}

2. Skills详细配置

{
  "skills": {
    "enabled": true,
    "autoUpdate": true,
    "updateSchedule": "0 3 * * 0",
    "directory": "~/.openclaw/skills",
    "registry": {
      "@openclaw/skill-calendar": {
        "version": "1.1.0",
        "enabled": true,
        "config": {
          "provider": "apple",
          "defaultCalendar": "工作"
        }
      }
    }
  }
}

🔄 自动化配置模板

1. 定时任务配置

{
  "automation": {
    "enabled": true,
    "tasks": [
      {
        "name": "每日AI日报",
        "schedule": "0 9 * * *",
        "action": "sendMessage",
        "params": {
          "channel": "feishu",
          "message": "请生成今天的AI行业日报"
        }
      },
      {
        "name": "每周工作总结",
        "schedule": "0 18 * * 5",
        "action": "sendMessage",
        "params": {
          "channel": "feishu",
          "message": "请生成本周的工作总结"
        }
      },
      {
        "name": "定时备份",
        "schedule": "0 2 * * *",
        "action": "runCommand",
        "params": {
          "command": "tar -czf ~/backups/openclaw-$(date +%Y%m%d).tar.gz ~/.openclaw"
        }
      }
    ]
  }
}

2. 网站监控配置

{
  "monitoring": {
    "enabled": true,
    "sites": [
      {
        "name": "OpenClaw官网",
        "url": "https://openclaw.ai",
        "interval": 3600,
        "selector": ".version",
        "notify": {
          "channel": "feishu",
          "message": "OpenClaw官网有更新:{content}"
        }
      },
      {
        "name": "Claude API",
        "url": "https://www.anthropic.com/news",
        "interval": 7200,
        "selector": "article:first-child",
        "notify": {
          "channel": "telegram",
          "message": "Claude有新动态:{title}"
        }
      }
    ]
  }
}

3. 文件监控配置

{
  "fileWatcher": {
    "enabled": true,
    "watches": [
      {
        "path": "~/Documents/Invoices",
        "pattern": "*.pdf",
        "action": "processInvoice",
        "notify": {
          "channel": "feishu",
          "message": "新发票已处理:{filename}"
        }
      },
      {
        "path": "~/Downloads",
        "pattern": "*.zip",
        "action": "autoExtract",
        "destination": "~/Documents/Extracted"
      }
    ]
  }
}

⚙️ 高级配置模板

1. 性能优化配置

{
  "performance": {
    "cache": {
      "enabled": true,
      "type": "redis",
      "redis": {
        "host": "localhost",
        "port": 6379,
        "db": 0,
        "ttl": 3600
      }
    },
    "rateLimit": {
      "enabled": true,
      "maxRequests": 100,
      "window": 60000
    },
    "concurrency": {
      "maxConcurrent": 10,
      "queue": {
        "enabled": true,
        "maxSize": 100
      }
    }
  }
}

2. 安全配置

{
  "security": {
    "authentication": {
      "enabled": true,
      "type": "jwt",
      "secret": "YOUR_SECRET_KEY",
      "expiresIn": "7d"
    },
    "authorization": {
      "enabled": true,
      "roles": {
        "admin": {
          "permissions": ["*"]
        },
        "user": {
          "permissions": [
            "read:files",
            "write:files",
            "execute:skills"
          ]
        }
      }
    },
    "encryption": {
      "enabled": true,
      "algorithm": "aes-256-gcm",
      "key": "YOUR_ENCRYPTION_KEY"
    },
    "firewall": {
      "enabled": true,
      "allowIPs": [
        "127.0.0.1",
        "192.168.1.0/24"
      ],
      "denyIPs": []
    }
  }
}

3. 监控和日志配置

{
  "monitoring": {
    "enabled": true,
    "metrics": {
      "enabled": true,
      "port": 9090,
      "path": "/metrics"
    },
    "healthCheck": {
      "enabled": true,
      "port": 8080,
      "path": "/health"
    },
    "alerts": {
      "enabled": true,
      "channels": ["email", "feishu"],
      "rules": [
        {
          "metric": "cpu_usage",
          "threshold": 80,
          "duration": 300,
          "message": "CPU使用率超过80%"
        },
        {
          "metric": "memory_usage",
          "threshold": 90,
          "duration": 300,
          "message": "内存使用率超过90%"
        },
        {
          "metric": "error_rate",
          "threshold": 5,
          "duration": 60,
          "message": "错误率过高"
        }
      ]
    }
  },
  "logging": {
    "level": "info",
    "format": "json",
    "outputs": [
      {
        "type": "file",
        "path": "~/.openclaw/logs/gateway.log",
        "rotation": {
          "maxSize": "10M",
          "maxFiles": 10,
          "compress": true
        }
      },
      {
        "type": "console",
        "colorize": true
      }
    ]
  }
}

4. 备份和恢复配置

{
  "backup": {
    "enabled": true,
    "schedule": "0 2 * * *",
    "destination": "~/openclaw-backups",
    "retention": {
      "daily": 7,
      "weekly": 4,
      "monthly": 12
    },
    "include": [
      "~/.openclaw/config.json",
      "~/.openclaw/skills",
      "~/.openclaw/data"
    ],
    "exclude": [
      "~/.openclaw/logs",
      "~/.openclaw/cache"
    ],
    "compression": {
      "enabled": true,
      "algorithm": "gzip"
    },
    "encryption": {
      "enabled": true,
      "key": "YOUR_BACKUP_ENCRYPTION_KEY"
    },
    "remote": {
      "enabled": false,
      "type": "s3",
      "bucket": "openclaw-backups",
      "region": "us-east-1",
      "accessKeyId": "xxx",
      "secretAccessKey": "xxx"
    }
  }
}

📦 完整配置示例

生产环境配置

{
  "gateway": {
    "mode": "production",
    "port": 18789,
    "bind": "0.0.0.0",
    "ssl": {
      "enabled": true,
      "cert": "/etc/ssl/certs/openclaw.crt",
      "key": "/etc/ssl/private/openclaw.key"
    },
    "cors": {
      "enabled": true,
      "origins": ["https://openclaw.yourdomain.com"]
    }
  },
  "models": {
    "default": "deepseek-chat",
    "code": "deepseek-coder",
    "longContext": "kimi",
    "streaming": true,
    "timeout": 60000,
    "routing": {
      "enabled": true,
      "rules": [
        {
          "condition": "tokens < 500",
          "model": "deepseek-chat"
        },
        {
          "condition": "tokens >= 500 && tokens < 2000",
          "model": "gpt-3.5-turbo"
        },
        {
          "condition": "tokens >= 2000",
          "model": "gpt-4"
        }
      ]
    },
    "providers": {
      "deepseek": {
        "apiKey": "${DEEPSEEK_API_KEY}",
        "baseURL": "https://api.deepseek.com"
      },
      "moonshot": {
        "apiKey": "${MOONSHOT_API_KEY}",
        "baseURL": "https://api.moonshot.cn"
      },
      "openai": {
        "apiKey": "${OPENAI_API_KEY}",
        "baseURL": "https://api.openai.com"
      }
    }
  },
  "workspace": {
    "path": "/data/openclaw/workspace",
    "autoCreate": true
  },
  "files": {
    "searchPaths": [
      "/data/openclaw/documents"
    ],
    "excludePaths": [
      "/data/openclaw/private"
    ],
    "index": {
      "enabled": true,
      "incremental": true,
      "schedule": "0 2 * * *"
    }
  },
  "channels": {
    "feishu": {
      "enabled": true,
      "appId": "${FEISHU_APP_ID}",
      "appSecret": "${FEISHU_APP_SECRET}",
      "features": {
        "streaming": true,
        "fileUpload": true
      }
    }
  },
  "skills": {
    "enabled": true,
    "autoUpdate": true,
    "updateSchedule": "0 3 * * 0"
  },
  "automation": {
    "enabled": true,
    "tasks": [
      {
        "name": "每日日报",
        "schedule": "0 9 * * *",
        "action": "sendMessage",
        "params": {
          "channel": "feishu",
          "message": "生成今日AI日报"
        }
      }
    ]
  },
  "performance": {
    "cache": {
      "enabled": true,
      "type": "redis",
      "redis": {
        "host": "localhost",
        "port": 6379
      }
    }
  },
  "security": {
    "authentication": {
      "enabled": true,
      "type": "jwt",
      "secret": "${JWT_SECRET}"
    },
    "firewall": {
      "enabled": true,
      "allowIPs": ["10.0.0.0/8"]
    }
  },
  "monitoring": {
    "enabled": true,
    "metrics": {
      "enabled": true,
      "port": 9090
    },
    "alerts": {
      "enabled": true,
      "channels": ["email"]
    }
  },
  "logging": {
    "level": "info",
    "format": "json",
    "outputs": [
      {
        "type": "file",
        "path": "/var/log/openclaw/gateway.log",
        "rotation": {
          "maxSize": "10M",
          "maxFiles": 10
        }
      }
    ]
  },
  "backup": {
    "enabled": true,
    "schedule": "0 2 * * *",
    "destination": "/backup/openclaw",
    "retention": {
      "daily": 7,
      "weekly": 4,
      "monthly": 12
    }
  }
}

🔧 配置工具

配置验证脚本

#!/bin/bash
# 文件名:validate-config.sh

CONFIG_FILE="$HOME/.openclaw/config.json"

echo "验证配置文件:$CONFIG_FILE"

# 检查文件是否存在
if [ ! -f "$CONFIG_FILE" ]; then
  echo "❌ 配置文件不存在"
  exit 1
fi

# 验证JSON格式
if ! jq empty "$CONFIG_FILE" 2>/dev/null; then
  echo "❌ JSON格式错误"
  exit 1
fi

echo "✅ JSON格式正确"

# 检查必需字段
required_fields=("gateway" "models" "workspace")
for field in "${required_fields[@]}"; do
  if ! jq -e ".$field" "$CONFIG_FILE" >/dev/null 2>&1; then
    echo "❌ 缺少必需字段:$field"
    exit 1
  fi
  echo "✅ 字段存在:$field"
done

echo "✅ 配置验证通过"

配置生成器

#!/bin/bash
# 文件名:generate-config.sh

echo "OpenClaw 配置生成器"
echo "===================="

# 询问基本信息
read -p "选择部署模式 (local/cloud): " mode
read -p "Gateway端口 (默认18789): " port
port=${port:-18789}

read -p "选择默认模型 (deepseek-chat/gpt-3.5-turbo): " model
model=${model:-deepseek-chat}

read -p "输入API密钥: " api_key

# 生成配置
cat > ~/.openclaw/config.json << EOF
{
  "gateway": {
    "mode": "$mode",
    "port": $port,
    "bind": "127.0.0.1"
  },
  "models": {
    "default": "$model",
    "providers": {
      "deepseek": {
        "apiKey": "$api_key",
        "baseURL": "https://api.deepseek.com"
      }
    }
  },
  "workspace": {
    "path": "~/Documents/OpenClaw"
  }
}
EOF

echo "✅ 配置文件已生成:~/.openclaw/config.json"