OpenClaw 会话持久化:让 Agent 拥有"长期记忆"
世界上有一种 Agent,它记得你说过的话,知道你的偏好,理解你的上下文。而另一种 Agent,每次对话都像第一次见面,永远在问"你好,有什么可以帮你的?"。区别就在于——会话持久化。今天,我们聊聊如何让你的 Agent 变成前者。
会话持久化的层次
OpenClaw 的记忆系统分为三个层次,就像人类的记忆一样:
| 层次 | 类比 | 存储位置 | 生命周期 |
|---|---|---|---|
| 工作记忆 | 正在思考的事 | 内存 | 单次请求 |
| 会话记忆 | 短期记忆 | 内存/缓存 | 单次会话(几小时) |
| 持久记忆 | 长期记忆 | 数据库 | 永久/用户定义 |
会话记忆配置
基础配置
# .openclaw/config.yaml
session:
# 会话存储后端
storage: "redis" # memory | redis | file | database
# Redis 配置
redis:
host: "${REDIS_HOST}"
port: 6379
db: 0
password: "${REDIS_PASSWORD}"
# 会话超时
ttl: 7200 # 2 小时
# 上下文窗口大小
context_window:
max_messages: 50 # 最大消息数
max_tokens: 4000 # 最大 Token 数
summary_threshold: 30 # 超过 30 条消息时自动摘要
会话恢复
# 从之前的会话恢复
openclaw session resume --id "session-abc123"
# 在代码中恢复
import openclaw
agent = openclaw.Agent(
session_id="session-abc123",
resume=True # 自动恢复上次的上下文
)
# 手动保存会话状态
await agent.save_session()
# 列出用户的会话历史
sessions = await openclaw.list_sessions(user_id="user-123")
持久记忆系统
记忆类型
OpenClaw 支持多种记忆类型,适用于不同场景:
1. 用户偏好记忆
# MEMORY.md 或通过 API 存储
user_preferences:
language: "zh-CN"
timezone: "Asia/Shanghai"
preferred_model: "claude-3-sonnet"
response_style: "concise" # concise | detailed
interests:
- "AI Agent"
- "OpenClaw"
- "编程"
2. 事件记忆
# 记录重要事件
events:
- type: "task_completed"
timestamp: "2026-04-30T01:00:00Z"
details:
task: "数据分析"
result: "成功生成报告"
- type: "user_feedback"
timestamp: "2026-04-29T18:30:00Z"
details:
feedback: "回答太长了"
action_taken: "已调整响应风格"
3. 知识记忆(RAG)
# 存储到向量数据库
knowledge_base:
enabled: true
backend: "pinecone" # pinecone | weaviate | milvus
embedding:
model: "text-embedding-3-small"
dimension: 1536
retrieval:
top_k: 5
threshold: 0.75
记忆 API 使用
import openclaw
# 存储记忆
await openclaw.memory.store(
user_id="user-123",
type="preference",
key="language",
value="zh-CN"
)
# 检索记忆
lang = await openclaw.memory.get(
user_id="user-123",
key="language"
)
# 搜索相关记忆
memories = await openclaw.memory.search(
user_id="user-123",
query="上次分析的数据",
limit=5
)
# 删除记忆
await openclaw.memory.delete(
user_id="user-123",
key="old_preference"
)
状态管理最佳实践
1. 分离短期状态和长期状态
不要把所有东西都塞进持久记忆:
- 短期状态:当前任务进度、临时变量 → 会话内存
- 长期状态:用户偏好、历史记录 → 数据库
2. 实现状态压缩
# 当上下文过长时,自动压缩
async def compress_context(messages):
if len(messages) > 30:
# 保留最近 10 条 + 摘要
recent = messages[-10:]
summary = await summarize(messages[:-10])
return [{"role": "system", "content": f"历史摘要:{summary}"}] + recent
return messages
3. 设置记忆过期策略
memory:
retention:
events: 90 # 事件记忆保留 90 天
preferences: -1 # 偏好永久保留
knowledge: 365 # 知识记忆保留 1 年
cleanup:
enabled: true
schedule: "0 3 * * *" # 每天凌晨 3 点清理
跨会话恢复实战
场景:用户第二天回来继续任务
class TaskAgent:
async def resume_or_start(self, user_id):
# 检查是否有未完成的任务
session = await openclaw.session.get_last(user_id)
if session and session.status == "in_progress":
# 恢复会话
agent = await openclaw.Agent.resume(session.id)
# 加载之前的上下文
context = await openclaw.memory.search(
user_id=user_id,
query=f"任务进度 {session.task_id}",
limit=3
)
return agent, context
else:
# 开始新会话
return await openclaw.Agent.create(user_id=user_id)
常见问题与解决方案
Q: 记忆太多会影响性能吗?
A: 会。建议:
- 定期清理过期记忆
- 使用摘要代替原始对话
- 检索时设置合理的 top_k
Q: 多设备同步如何处理?
A: OpenClaw 默认基于 user_id 隔离记忆。同一用户在不同设备的会话可以共享长期记忆,但会话记忆独立。
Q: 如何处理敏感信息?
A: 使用记忆过滤和加密:
# 标记敏感信息
await openclaw.memory.store(
user_id="user-123",
key="api_key",
value="sk-xxx",
sensitive=True, # 加密存储
ttl=3600 # 1 小时后自动删除
)