从内存管理到性能调优,系统掌握 OpenClaw 的高效使用方法
一、MEMORY.md 优化策略
1.1 核心原则:索引而非仓库
MEMORY.md 应该是一个 路由索引,而不是知识库。它在每次交互时都会被注入 system prompt,所以必须精简。
经验法则:MEMORY.md 控制在 50 行以内,20000 字符以内。
1.2 推荐结构
# 项目:MyProject
## 技术栈
- 语言:TypeScript + Python
- 框架:Next.js 14, FastAPI
- 数据库:PostgreSQL + Redis
- 部署:Docker + K8s
## 关键决策
- [2026-03-01] 认证方案选择 JWT → memory/decisions/auth.md
- [2026-03-05] 数据库从 MySQL 迁移到 PG → memory/decisions/db-migration.md
## 当前状态
- 进行中:用户模块重构
- 阻塞项:等待第三方 API 审批
## 代码规范
- 提交信息格式:conventional commits
- 分支策略:trunk-based
## 详细文档索引
- 架构设计 → memory/architecture.md
- API 规范 → memory/api-spec.md
- 进度跟踪 → memory/progress.md
- 踩坑记录 → memory/lessons.md1.3 应该写入 MEMORY.md 的内容
- 项目元信息(技术栈、目录结构概要)
- 关键架构决策及原因(简述 + 指向详情文件)
- 当前工作状态和阻塞项
- 代码规范和约定
- agent 需要长期记住的偏好(如"不要使用 any 类型")
1.4 不应该写入 MEMORY.md 的内容
- 详细的实现方案(放到 memory/*.md)
- 完整的代码片段(agent 可以直接读源码)
- 日常对话记录(这是日志,不是记忆)
- 已完成且不再相关的任务
- 可以通过读取文件获得的信息
1.5 定期维护
建议每周清理一次 MEMORY.md:
# 检查当前大小
wc -c ~/.openclaw/workspace/MEMORY.md
# 查看哪些内容可以归档
# 把已完成的决策、过时的状态信息移到 memory/archive/ 下二、核心配置参数详解
2.1 配置文件位置
OpenClaw 的配置文件支持多种格式,按优先级排列:
~/.openclaw/openclaw.json(全局配置)项目根目录/.openclaw.json(项目级配置)openclaw.config.ts(TypeScript 格式)
项目级配置会覆盖全局配置的对应字段。
2.2 Bootstrap 相关参数
| 参数 | 默认值 | 说明 |
|---|---|---|
bootstrapMaxChars | 20,000 | 单个 bootstrap 文件的最大注入字符数 |
bootstrapTotalMaxChars | 150,000 | 所有 bootstrap 文件的总注入上限 |
{
"agents": {
"defaults": {
"bootstrapMaxChars": 30000,
"bootstrapTotalMaxChars": 150000
}
}
}截断策略:超限时按 70/20/10 分割 — 70% 头部、20% 尾部、10% 截断标记。 所以 MEMORY.md 的开头和结尾最重要,中间部分最容易被丢弃。
2.3 压缩(Compaction)参数
| 参数 | 默认值 | 说明 |
|---|---|---|
reserveTokensFloor | 20,000 | 为 bootstrap 注入预留的 token 数 |
memoryFlush.enabled | false | 压缩前是否自动持久化记忆 |
memoryFlush.softThresholdTokens | 4,000 | 触发 flush 的提前量 |
{
"agents": {
"defaults": {
"compaction": {
"reserveTokensFloor": 20000,
"memoryFlush": {
"enabled": true,
"softThresholdTokens": 4000,
"systemPrompt": "Session nearing compaction. Store durable memories now.",
"prompt": "Write any lasting notes to memory/YYYY-MM-DD.md; reply with NO_REPLY if nothing to store."
}
}
}
}
}重要:默认配置中
memoryFlush是 关闭的! 这意味着上下文压缩时信息会直接丢失。强烈建议开启。
2.4 记忆搜索参数
{
"memorySearch": {
"enabled": true,
"chunkSize": 400,
"chunkOverlap": 80,
"extraPaths": ["docs/important/*.md"],
"maxResults": 10
}
}记忆搜索会将 Markdown 文件切分为 ~400 token 的块(80 token 重叠),建立语义索引存储在 SQLite 中。
三、工作区文件组织
3.1 推荐目录结构
~/.openclaw/workspace/
├── MEMORY.md # 主索引文件(精简)
├── memory/
│ ├── architecture.md # 架构设计详情
│ ├── api-spec.md # API 规范
│ ├── progress.md # 进度跟踪
│ ├── lessons.md # 踩坑与经验
│ ├── decisions/ # 决策记录
│ │ ├── auth.md
│ │ └── db-migration.md
│ ├── archive/ # 归档旧内容
│ └── 2026-03-08.md # 每日笔记(自动生成)
└── .openclaw.json # 项目级配置3.2 文件命名规范
- 使用小写 + 短横线:
api-spec.md(非API_Spec.md) - 日期格式统一:
YYYY-MM-DD.md - 决策文件以主题命名:
decisions/auth.md - 只用
.md格式 — 只有 Markdown 会被索引
3.3 每日笔记 vs 长期记忆
每日笔记 memory/YYYY-MM-DD.md | 长期记忆 memory/*.md | |
|---|---|---|
| 内容 | 当天的操作记录、发现、临时想法 | 经过整理的持久知识 |
| 更新频率 | 自动/高频 | 人工/低频 |
| 生命周期 | 短期(可定期清理) | 长期保留 |
| 写入者 | agent 自动(memoryFlush) | 用户手动或定期整理 |
四、上下文窗口管理
4.1 理解 Token 分配
一个典型的 OpenClaw 会话中,token 的分配如下:
┌─────────────────────────────────────────┐
│ System Prompt(固定) │ ~2,000 tokens
├─────────────────────────────────────────┤
│ Bootstrap 注入(MEMORY.md 等) │ ~5,000-15,000 tokens
├─────────────────────────────────────────┤
│ 对话历史 │ 动态伸缩
├─────────────────────────────────────────┤
│ 当前请求 + 响应 │ 动态
├─────────────────────────────────────────┤
│ 预留空间(reserveTokensFloor) │ 20,000 tokens
└─────────────────────────────────────────┘4.2 压缩触发时机
当对话历史使得总 token 接近:
contextWindow - reserveTokensFloor - softThresholdTokens例如使用 200K 上下文窗口时:200,000 - 20,000 - 4,000 = 176,000 tokens 时触发。
4.3 减少不必要的上下文消耗
- 避免在对话中粘贴大段代码 — 让 agent 自己读取文件
- 大文件修改用精确指令("修改第 45 行的函数名"),而非附带全文
- 定期开启新会话,避免单个会话积累过多历史
- 使用
/compact命令手动触发压缩
五、会话压缩与记忆持久化
5.1 压缩是什么
当对话历史过长时,OpenClaw 会将旧的对话总结为一段摘要,释放 token 空间。这个过程叫做 compaction(压缩)。
5.2 压缩中的信息丢失
压缩会导致:
- 详细的对话内容被摘要化(细节丢失)
- 代码片段可能被省略
- 中间步骤的推理过程被压缩
5.3 开启 memoryFlush 防止信息丢失
memoryFlush 会在压缩前触发一个隐藏的 agent 回合,提示模型将重要信息写入持久化文件:
{
"compaction": {
"memoryFlush": {
"enabled": true,
"prompt": "Write any lasting notes to memory/YYYY-MM-DD.md; reply with NO_REPLY if nothing to store."
}
}
}自定义 flush prompt 的建议:
- 聚焦于:决策、状态变更、经验教训
- 排除:日常对话、重复信息、临时调试内容
- bad prompt → 产生大量噪音文件,污染未来的上下文
5.4 手动触发压缩
# 在 OpenClaw 会话中输入
/compact
# 或带自定义摘要提示
/compact 请重点保留架构决策和 API 变更相关的内容六、Token 成本优化
6.1 成本构成分析
OpenClaw 每次交互的 token 消耗:
总消耗 = system_prompt + bootstrap_injection + conversation_history + user_input + model_output其中 bootstrap_injection 是固定开销,每条消息都要支付一次。
6.2 降低固定开销
| 优化手段 | 效果 |
|---|---|
| 精简 MEMORY.md 到 5000 字符 | 节省 ~10,000 tokens/次 |
| 移除不常用的 bootstrap 文件 | 视文件大小而定 |
| 使用 extraPaths 按需加载 | 避免全量注入 |
6.3 降低动态开销
- 用简洁明确的指令替代冗长描述
- 及时开启新会话,避免历史堆积
- 代码审查等大量输出任务,考虑分批处理
- 利用
/compact在合适时机主动压缩
6.4 实际效果参考
社区用户反馈:优化 MEMORY.md + 开启 memoryFlush 后,日均 token 消耗从 $4.20 降至 $1.80,且 agent 不再重复提问和重复研究。
七、Rate Limit 应对策略
7.1 理解限流类型
| 限流类型 | 含义 | 常见限额 |
|---|---|---|
| RPM | 每分钟请求数 | 60-4000(视 tier) |
| TPM | 每分钟 token 数 | 40K-2M(视 tier) |
| RPD | 每日请求数 | 部分 provider 有此限制 |
7.2 快速诊断
# 查看 OpenClaw 日志
# 如果看到类似以下错误,说明触发了 rate limit:
# isError=true error=⚠️ API rate limit reached. Please try again later.
# 检查你的 API provider 后台:
# Anthropic: https://console.anthropic.com/settings/limits
# OpenAI: https://platform.openai.com/account/rate-limits7.3 应对方案
- 短期:等待 1-2 分钟后重试
- 中期:
- 精简 bootstrap 注入,减少每次请求的 token 消耗
- 避免短时间内连续发送复杂请求
- 使用
/compact减少对话历史长度
- 长期:
- 升级 API plan,获取更高限额
- 配置多个 API Key 轮换
- 考虑使用更小的模型处理简单任务
7.4 配置重试策略
{
"api": {
"retryOnRateLimit": true,
"maxRetries": 3,
"retryDelayMs": 2000,
"retryBackoffMultiplier": 2
}
}八、Prompt 工程技巧
8.1 有效的指令格式
# 差 — 模糊、冗长
"帮我看看这个文件有没有什么问题,如果有问题的话帮我改一下"
# 好 — 明确、具体
"检查 src/auth/login.ts 中的 handleLogin 函数,修复 JWT token 过期时未正确刷新的 bug"8.2 利用 MEMORY.md 设置持久偏好
在 MEMORY.md 中写入你的编码偏好,agent 会在每次交互时遵循:
## 编码偏好
- 使用 TypeScript strict mode
- 函数参数超过 3 个时使用 options object
- 错误处理统一用 Result 模式,不用 try-catch
- 注释用英文
- commit message 用 conventional commits 格式8.3 分步骤指令
复杂任务分解为步骤,让 agent 逐步执行:
"请按以下步骤重构用户模块:
1. 先读取 src/user/ 下所有文件,理解当前结构
2. 将 UserService 拆分为 UserAuthService 和 UserProfileService
3. 更新所有 import 引用
4. 运行测试确保没有 break"8.4 引导 agent 读取而非猜测
# 差 — agent 可能基于过时的记忆回答
"这个项目用的什么数据库?"
# 好 — 让 agent 直接看代码
"读取 docker-compose.yml 和 .env.example,告诉我项目使用了哪些数据库"九、多 Agent 协作
9.1 Agent 模式概览
OpenClaw 支持配置多个 agent profile,各自有独立的:
- System prompt
- 模型选择
- 工具权限
- 记忆空间(独立的 SQLite 索引)
9.2 典型多 Agent 场景
{
"agents": {
"coder": {
"model": "claude-sonnet-4.5",
"systemPrompt": "You are a senior software engineer...",
"tools": ["read", "write", "bash", "search"]
},
"reviewer": {
"model": "claude-sonnet-4.5",
"systemPrompt": "You are a code reviewer. Focus on security, performance, and maintainability...",
"tools": ["read", "search"]
},
"planner": {
"model": "claude-opus-4.6",
"systemPrompt": "You are a technical architect...",
"tools": ["read", "search"]
}
}
}9.3 切换 Agent
# 切换到 reviewer agent
/agent reviewer
# 切换回默认 agent
/agent main十、调试与排查
10.1 常见错误及解决
| 错误信息 | 原因 | 解决方案 |
|---|---|---|
MEMORY.md is N chars (limit M); truncating | 文件超过 bootstrapMaxChars | 精简 MEMORY.md 或调大限制 |
API rate limit reached | 触发 API 速率限制 | 见第七章 |
context window exceeded | 总 token 超过模型上下文窗口 | 使用 /compact 或开启新会话 |
tool execution timeout | 工具执行超时 | 检查命令复杂度,增加超时时间 |
memory index corrupted | SQLite 索引损坏 | 删除 .sqlite 文件,重新索引 |
10.2 查看日志
# 查看 gateway 日志
docker logs openclaw-gateway --tail 100 -f
# 过滤错误信息
docker logs openclaw-gateway 2>&1 | grep -i "error\|warn"
# 查看 agent 运行日志
docker logs openclaw-gateway 2>&1 | grep "\[agent/"10.3 检查记忆索引状态
# 查看索引文件大小
ls -lh ~/.openclaw/memory/*.sqlite
# 如果索引异常,删除后重启让它重建
rm ~/.openclaw/memory/main.sqlite
# 重启 OpenClaw10.4 调试 Bootstrap 注入
在日志中关注以下关键字:
[agent/embedded] workspace bootstrap— 查看注入了哪些文件truncating in injected context— 哪些文件被截断了sessionKey— 确认当前使用的 agent profile
十一、安全与隐私
11.1 敏感信息保护
- 永远不要在 MEMORY.md 或 memory/*.md 中存储密码、API Key、token 等
- 使用
.env文件存储敏感配置,确保在.gitignore中 - 注意:bootstrap 注入的内容会发送到 LLM 提供商的服务器
11.2 工具权限控制
{
"agents": {
"defaults": {
"tools": {
"bash": {
"enabled": true,
"allowedCommands": ["git", "npm", "node", "python"],
"blockedPaths": ["/etc", "/root/.ssh"]
},
"write": {
"enabled": true,
"blockedPaths": ["*.env", "*.pem", "*.key"]
}
}
}
}
}11.3 网络访问控制
如果你的 OpenClaw 实例需要访问外部服务,建议配置白名单:
{
"network": {
"allowedDomains": ["api.github.com", "registry.npmjs.org"],
"blockExternalByDefault": true
}
}十二、最佳实践 Checklist
初始设置
- ☐ 开启
memoryFlush(默认是关闭的!) - ☐ MEMORY.md 精简到 50 行以内
- ☐ 建立
memory/目录结构 - ☐ 配置工具权限,限制敏感路径访问
- ☐ 确认 API Key 的 rate limit tier
日常使用
- ☐ 给出明确、具体的指令
- ☐ 让 agent 读文件而非粘贴代码
- ☐ 复杂任务分步骤执行
- ☐ 长对话后适时开启新会话或 /compact
- ☐ 在 MEMORY.md 中记录重要决策
定期维护
- ☐ 每周清理 MEMORY.md,归档旧内容
- ☐ 清理过期的每日笔记
- ☐ 检查 memory/*.md 是否有冗余或过时信息
- ☐ 监控 token 用量趋势
- ☐ 更新编码偏好和项目状态
本指南基于 OpenClaw 社区实践整理,持续更新中。