title: Agent 内存管理 - 打造有记忆的智能体 tags: [agent, 内存]


Agent 内存管理 - 打造有记忆的智能体

深入解析 OpenCLAW Agent 的内存系统,了解如何让 AI 智能体记住上下文、用户偏好,实现真正的个性化交互。

为什么需要内存?

没有记忆的 Agent 就像金鱼,每次对话都是全新的开始:

用户: 我喜欢 Python
Agent: 好的,Python 是一门很棒的语言

用户: 我刚才说我喜欢什么?
Agent: 对不起,我不知道你刚才说了什么

有内存的 Agent 可以记住上下文:

用户: 我喜欢 Python
Agent: 好的,Python 是一门很棒的语言

用户: 我刚才说我喜欢什么?
Agent: 你刚才说你喜欢 Python

内存类型概述

OpenCLAW 提供多种内存类型:

类型 用途 存储方式 适用场景
短期记忆 对话上下文 内存/文件 单轮/多轮对话
长期记忆 持久化存储 文件/数据库 跨会话记忆
向量记忆 语义搜索 向量数据库 知识检索
工作记忆 任务中间态 内存 复杂任务处理

基础配置

文件系统内存

最简单的内存配置:

memory:
  type: filesystem
  path: ./agents/my-agent/memory
  max_history: 100

完整内存配置

memory:
  # 内存类型
  type: filesystem

  # 存储路径
  path: ./agents/my-agent/memory

  # 对话历史保留轮数
  max_history: 100

  # 启用对话摘要
  summary:
    enabled: true
    interval: 10      # 每10轮总结一次
    max_length: 500  # 摘要最大长度

  # 向量存储(可选)
  vector:
    enabled: true
    provider: chroma
    collection: agent_memory
    dimension: 1536

短期记忆:对话上下文

工作原理

短期记忆存储当前会话的对话历史:

# 对话历史结构
conversation_history = [
    {"role": "user", "content": "你好"},
    {"role": "agent", "content": "你好!有什么可以帮你的?"},
    {"role": "user", "content": "我喜欢 Python"},
    {"role": "agent", "content": "Python 确实是一门很棒的语言!"},
]

配置选项

memory:
  type: filesystem
  path: ./memory

  # 对话历史设置
  max_history: 50           # 保留最近50轮
  max_tokens: 4000         # 或限制 token 数量
  include_system: true     # 是否包含系统提示词

  # 窗口滑动
  window_type: sliding     # sliding | full
  window_size: 10          # 滑动窗口大小

代码示例

from openclaw.memory import ConversationBuffer

# 初始化对话缓冲区
buffer = ConversationBuffer(
    max_history=50,
    max_tokens=4000
)

# 添加对话
buffer.add_message("user", "你好")
buffer.add_message("agent", "你好!")

# 获取历史(用于构建提示词)
context = buffer.get_context()
# 输出: "用户: 你好\n助手: 你好!\n..."

对话摘要:处理长对话

何时使用

当对话轮数较多时,直接传递全部历史会: - 超出模型 token 限制 - 增加响应延迟 - 浪费 API 配额

对话摘要可以压缩历史:

memory:
  summary:
    enabled: true
    interval: 10      # 每10轮执行一次摘要
    max_length: 500  # 摘要后保留的 token 数
    model: gpt-3.5-turbo  # 用于摘要的模型

摘要策略

memory:
  summary:
    # 简单策略:保留首尾
    strategy: first_last

    # 高级策略:AI 摘要
    strategy: ai_summary

    # 提取关键信息
    extract:
      - user_preferences
      - important_facts
      - task_progress

自定义摘要提示词

memory:
  summary:
    prompt: |
      请将以下对话历史压缩成简短的摘要,包含:
      1. 用户的主要需求
      2. 已达成的一致
      3. 待解决的问题

      对话历史:
      {history}

      摘要格式:
      ## 需求
      [用户需求]

      ## 进展
      [已达成的一致]

      ## 待办
      [待解决问题]

长期记忆:跨会话持久化

数据库存储

memory:
  type: database
  driver: postgresql
  connection_string: ${DATABASE_URL}
  table_name: agent_memory

  # 自动保存
  auto_save: true
  save_interval: 60   # 每60秒保存一次

  # 记忆类型
 记忆类型:
    user_profile: true    # 用户画像
    preferences: true     # 用户偏好
    facts: true           # 重要事实
    skills: true          # 学习到的技能

Redis 缓存

memory:
  type: redis
  host: ${REDIS_HOST}
  port: 6379
  db: 0

  # 缓存策略
  ttl: 86400           # 24小时过期
  key_prefix: agent:

  # 数据结构
  data_structure: hash  # hash | list | json

用户画像示例

# 自动构建的用户画像
user_profile = {
    "name": "张三",
    "language": "中文",
    "programming_languages": ["Python", "JavaScript"],
    "expertise_level": "intermediate",
    "communication_style": "direct",
    "preferred_code_style": "pep8",
    "last_seen": "2024-01-15T10:30:00Z",
    "total_conversations": 42
}

# 保存用户偏好
agent.remember("user_preference", "language", "Python")
agent.remember("user_preference", "framework", "FastAPI")

向量记忆:语义搜索

配置向量存储

memory:
  vector:
    enabled: true

    # 向量数据库选择
    provider: chroma  # chroma | pinecone | weaviate | qdrant

    # Chroma 配置
    chroma:
      persist_directory: ./vector_db
      collection_name: agent_memory

    # Pinecone 配置(可选)
    # pinecone:
    #   api_key: ${PINECONE_API_KEY}
    #   environment: us-west1
    #   index_name: agent-memory

添加记忆到向量库

from openclaw.memory import VectorStore

# 初始化向量存储
vector_store = VectorStore(
    provider="chroma",
    collection="agent_memory"
)

# 添加记忆
vector_store.add(
    content="用户喜欢使用 Python 的 FastAPI 框架开发 API",
    metadata={"type": "preference", "source": "conversation"},
    tags=["python", "fastapi", "api"]
)

# 添加更多
vector_store.add(
    content="用户的工作主要是后端开发,有3年经验",
    metadata={"type": "profile", "source": "conversation"},
    tags=["backend", "experience"]
)

语义检索

# 语义搜索
results = vector_store.search(
    query="用户会什么编程技能",
    top_k=3,
    filter={"type": "preference"}
)

for result in results:
    print(f"内容: {result.content}")
    print(f"相似度: {result.score}")
    print(f"标签: {result.tags}")

工作记忆:任务中间态

使用场景

处理复杂任务时,需要记住中间状态:

from openclaw.memory import WorkingMemory

# 初始化工作记忆
working_memory = WorkingMemory()

# 任务:分析代码并重构
task = {
    "id": "task_001",
    "type": "code_refactor",
    "original_code": "def foo(x): return x*2",
    "status": "analyzing",  # analyzing | processing | completed
    "progress": 0.3,
    "findings": ["函数名不清晰", "缺少类型提示"],
    "current_step": 2,
    "total_steps": 5
}

# 保存任务状态
working_memory.set_task("code_refactor", task)

# 获取任务状态
task_state = working_memory.get_task("code_refactor")

检查点机制

# 设置检查点
working_memory.checkpoint("step_1_complete", {
    "files_analyzed": 10,
    "issues_found": 5,
    "timestamp": "2024-01-15T10:30:00"
})

# 恢复检查点
state = working_memory.restore("step_1_complete")

内存操作 API

基本操作

from openclaw import Agent

agent = Agent("my-agent")

# 记住信息
agent.remember("user_likes", "Python")
agent.remember("user_name", "张三")

# 读取记忆
likes = agent.recall("user_likes")
name = agent.recall("user_name")

# 搜索记忆
results = agent.search_memory("编程语言偏好")

# 删除记忆
agent.forget("old_preference")

# 列出所有记忆
all_memories = agent.list_memories()

高级操作

# 批量记住
agent.remember_batch({
    "language": "Python",
    "framework": "FastAPI",
    "experience_years": 3
})

# 带过期时间的记忆
agent.remember_with_ttl(
    "temporary_code", 
    "some_value",
    ttl=3600  # 1小时后过期
)

# 记忆优先级
agent.remember("important_fact", priority="high")
agent.remember("minor_detail", priority="low")

# 记忆分类
agent.remember("user_preference", category="preferences")
agent.remember("project_context", category="context")

内存优化策略

1. 分层存储

memory:
  # 热数据:最近对话
  hot:
    type: memory
    max_items: 100

  # 温数据:近期记忆
  warm:
    type: filesystem
    path: ./memory/recent
    max_age: 7d

  # 冷数据:长期记忆
  cold:
    type: database
    table: long_term_memory
    max_age: 30d

2. 自动清理

memory:
  cleanup:
    enabled: true

    # 策略
    strategy: lru  # lru | lfu | time_based

    # 阈值
    max_items: 1000
    max_size_mb: 100

    # 保留规则
    keep:
      - user_profile
      - important_facts
      - custom_tags: [bookmarked, pinned]

3. 压缩存储

memory:
  compression:
    enabled: true
    algorithm: gzip
    level: 6

    # 压缩阈值
    min_size_kb: 10

监控与调试

查看内存状态

# 查看内存使用情况
openclaw agent memory-stats my-agent

# 输出示例
# Memory Usage:
# - Conversation: 45 items, 12KB
# - Long-term: 230 items, 1.2MB
# - Vector: 500 items, 2.5MB
# - Working: 3 tasks, 0.5KB

调试内存问题

# 启用内存调试日志
openclaw agent debug my-agent --memory

# 查看记忆内容
openclaw agent memory-dump my-agent --type long_term

# 搜索记忆
openclaw agent memory-search my-agent --query "Python"

最佳实践

1. 合理设置历史长度

# 简单任务
memory:
  max_history: 20

# 复杂多轮任务
memory:
  max_history: 100
  summary:
    enabled: true

2. 定期清理无用记忆

# 清理三个月前的记忆
agent.cleanup(before="2024-01-01")

# 清理低优先级记忆
agent.cleanup(priority="low")

# 清理特定标签
agent.cleanup(tags=["temporary"])

3. 敏感信息处理

memory:
  # 自动过滤敏感信息
  filter_sensitive:
    enabled: true

    # 脱敏规则
    patterns:
      - credit_card
      - password
      - api_key

    # 脱敏方式
    action: hash  # hash | remove | mask

小结

本文全面介绍了 OpenCLAW Agent 的内存管理系统:

  1. 内存类型 - 短期、长期、向量、工作记忆
  2. 对话摘要 - 压缩长对话,保持关键信息
  3. 持久化存储 - 数据库、Redis、文件系统
  4. 向量搜索 - 语义检索历史记忆
  5. 工作记忆 - 复杂任务的中间状态管理
  6. 优化策略 - 分层存储、自动清理、压缩
  7. 监控调试 - 查看状态、排查问题

继续学习: - Agent 技能调用 - 赋予 Agent 超能力 - 定时任务设置 - 实现自动化运营