世界上有一种遗忘叫"上下文限制",它让AI像一个只有7秒记忆的金鱼。 但人类不会——我们有日记、相册、备忘录。OpenClaw的Memory系统,就是AI的"数字日记本"。
📚 OpenClaw记忆分层架构
🔢 三层记忆模型
- L0 - 原始对话:当前session的完整对话历史,临时存储
- L1 - 结构化记忆:抽取的key-value对,如用户偏好、重要决策
- L2 - 场景记忆:按场景组织的长期知识,支持语义搜索
| 层级 | 存储 | 检索 | 寿命 | 容量 |
|---|---|---|---|---|
| L0 | 对话历史 | 顺序扫描 | Session | 10万token |
| L1 | Key-Value | 精确匹配 | 永久 | 无限制 |
| L2 | 语义向量 | 相似度搜索 | 永久 | 无限制 |
💾 L1结构化记忆操作
# memory_set - 写入记忆
tool call memory_set namespace="user_preferences" key="timezone" value="Asia/Shanghai"
# memory_get - 读取记忆
tool call memory_get namespace="user_preferences" key="timezone"
# → "Asia/Shanghai"
# memory_list - 列出记忆
tool call memory_list namespace="user_preferences"
# → { timezone: "Asia/Shanghai", language: "zh-CN", theme: "dark" }
# memory_delete - 删除记忆
tool call memory_delete namespace="user_preferences" key="theme"
# memory_search - 搜索记忆
tool call memory_search namespace="*" query="时区"
💡 命名空间规范
user_preferences- 用户偏好设置project_{name}- 项目专属记忆workflow_{id}- 工作流状态agent_{name}- Agent自学习数据
🌐 L2场景记忆(Semantic Memory)
适合存储非结构化知识,支持自然语言查询:
# scene_memory_record - 记录场景事件
tool call scene_memory_record
scene="OpenClaw玩法资讯网站运营"
type="episodic"
content="2026-04-15完成大规模SEO生成,创建9个教程页面"
importance="high"
# scene_memory_search - 语义搜索
tool call scene_memory_search query="SEO优化历史操作"
# scene_memory_update - 更新场景热度
tool call scene_memory_update scene="OpenClaw玩法资讯网站运营" heat_boost=10
# scene_memory_get - 获取场景详情
tool call scene_memory_get scene="OpenClaw玩法资讯网站运营"
记忆类型定义
| 类型 | 用途 | 示例 |
|---|---|---|
| persona | 用户画像/偏好 | "用户喜欢幽默风格" |
| episodic | 事件记录 | "2026-04-15完成XXX任务" |
| instruction | 规则/指令 | "所有代码必须用Python" |
🎯 实战模式:用户画像构建
# Agent启动时读取用户画像
def load_user_profile():
preferences = memory_get(namespace="user_preferences", key="*")
habits = scene_memory_search(
type="persona",
query="用户习惯 工作模式"
)
return {
"preferences": preferences,
"habits": habits,
"recent_context": get_recent_episodes(limit=5)
}
# 对话中动态更新
def update_from_conversation(message):
# 提取新偏好
if "我喜欢早上处理复杂任务" in message:
memory_set(
namespace="user_preferences",
key="peak_hours",
value="morning"
)
# 记录重要事件
if contains_achievement(message):
scene_memory_record(
scene="用户成就",
type="episodic",
content=extract_achievement(message),
importance="high"
)
📊 工作流状态持久化
# 复杂工作流使用Memory做断点续传
class StatefulWorkflow:
def __init__(self, workflow_id):
self.workflow_id = workflow_id
self.checkpoint_key = f"workflow:{workflow_id}:checkpoint"
def save_checkpoint(self, step_name, data):
memory_set(
namespace="workflows",
key=f"{self.workflow_id}:{step_name}",
value={
"timestamp": time.time(),
"data": data,
"status": "in_progress"
}
)
def resume_from_checkpoint(self):
checkpoint = memory_get(
namespace="workflows",
key=self.checkpoint_key
)
if checkpoint and checkpoint["status"] == "in_progress":
return checkpoint["data"]
return None
def complete(self):
memory_set(
namespace="workflows",
key=self.checkpoint_key,
value={"status": "completed", "completed_at": time.time()}
)
🧹 记忆维护策略
自动清理规则
- 过期清理:设置TTL,临时记忆自动删除
- 重要性过滤:仅保留importance >= medium的记忆
- 去重合并:相似记忆自动合并,保留最新
- 热度衰减:长期不访问的记忆降级或归档
# 设置记忆TTL
tool call memory_set
namespace="temp_calculations"
key="session_123"
value={"result": 42}
ttl=3600 # 1小时后自动删除
# 定期归档旧记忆
def archive_old_memories(days=30):
old_episodes = scene_memory_search(
query="*",
before=time.time() - days * 86400,
importance="low"
)
for episode in old_episodes:
move_to_archive(episode)
delete_from_active(episode)
🔍 记忆检索优化
# 多路召回策略
def retrieve_relevant_context(query, k=10):
results = []
# 1. 精确匹配(L1)
exact = memory_get(namespace="*", key=query)
if exact:
results.append({"source": "exact", "score": 1.0, "data": exact})
# 2. 语义搜索(L2)
semantic = scene_memory_search(query=query, limit=k)
results.extend([{"source": "semantic", "score": r.score, "data": r} for r in semantic])
# 3. 场景匹配
scenes = scene_memory_list()
for scene in scenes:
if query_matches_scene(query, scene):
scene_data = scene_memory_get(scene)
results.append({"source": "scene", "score": 0.8, "data": scene_data})
# 重排序
return rerank_by_relevance(results, query)
# 记忆注入提示词
def build_prompt_with_memory(user_query):
context = retrieve_relevant_context(user_query)
return f"""
[用户画像]
{format_user_profile()}
[相关历史]
{format_context(context)}
[当前问题]
{user_query}
请基于以上信息回答。
"""
⚠️ 常见坑点
- Memory没有版本控制,覆盖前最好备份
- 命名空间滥用导致key冲突,建议前缀隔离
- L2语义搜索返回相关性低的结果,需要阈值过滤
- 高频写入可能导致性能问题,考虑批量操作