Skip to main content

一个完整的、智能的、多层次的Agent记忆管理系统

Project description

Agent Memory - 智能Agent记忆管理系统

Version Python License Tests

一个完整的、智能的、多层次的Agent记忆管理系统

功能特性安装快速开始示例


✨ 功能特性

🧠 多层次记忆系统

  • 工作记忆 - 当前会话的短期记忆
  • 短期记忆 - 最近的对话和事件
  • 中期记忆 - 重要的知识和经验
  • 长期记忆 - 核心知识和持久信息
  • 核心记忆 - 最重要的用户特征和偏好

🎯 智能记忆管理

  • 自动形成 - 从对话中智能提取和形成记忆
  • 重要性评分 - 6个维度的智能重要性评估
  • 多策略检索 - 向量、关键词、时间、上下文、关联检索
  • 自动衰减 - 基于遗忘曲线的自然衰减
  • 冲突解决 - 自动检测和解决记忆冲突

💬 会话管理

  • 跨会话连续性 - 自动恢复上下文
  • 会话摘要 - 自动生成对话摘要
  • 智能提醒 - 基于上下文的智能提醒
  • 一致性检查 - 多维度一致性验证

🚀 易用的API

  • 统一接口 - 一个类搞定所有功能
  • 语义化方法 - memorize, recall, forget
  • 智能默认值 - 最少配置即可使用
  • 降级策略 - 无LLM环境也能正常运行

📦 安装

方式1:从PyPI安装(推荐)

pip install agent-memory-ai

方式2:从wheel文件安装

如果您获得了.whl文件:

pip install agent_memory_ai-0.1.0-py3-none-any.whl

完整安装(包含向量检索)

pip install agent-memory-ai[full]

这将安装额外的依赖:

  • ChromaDB(向量数据库)
  • Sentence Transformers(文本向量化)
  • jieba(中文分词)

🚀 快速开始

基础使用

from agent_memory import AgentMemory

# 创建Agent
agent = AgentMemory("user_id")

# 记忆一些内容
agent.memorize("我喜欢Python编程")
agent.memorize("我正在学习机器学习")

# 检索记忆
memories = agent.recall("Python", top_k=5)
for mem in memories:
    print(mem.content)

# 获取统计
stats = agent.get_statistics()
print(f"总记忆数: {stats['progress']['total_memories']}")

对话场景

from agent_memory import AgentMemory

# 使用上下文管理器
with AgentMemory("user_id") as agent:
    # 对话
    agent.chat(
        "我想学习数据科学",
        "很好的选择!",
        memorize_user=True
    )
    
    # 检索相关记忆
    related = agent.recall("学习", top_k=3)
    
    # 继续对话
    agent.chat(
        "应该从哪里开始?",
        "建议先学Python和统计学",
        memorize_user=True
    )

# 会话自动结束

高级使用

from agent_memory import AgentMemory, MemoryType, MemoryCategory

agent = AgentMemory("user_id")

# 创建特定类型的记忆
agent.create_memory(
    "Python是一门编程语言",
    memory_type=MemoryType.CORE,
    category=MemoryCategory.KNOWLEDGE,
    importance=0.9,
    tags=["Python", "编程"]
)

# 搜索和过滤
high_importance = agent.search(
    "Python",
    filters={"min_importance": 0.8}
)

# 更新记忆
agent.update_memory(
    memory_id,
    tags=["Python", "编程", "已学习"]
)

# 执行维护
result = agent.maintain()
print(f"处理: {result['lifecycle']['processed']} 条")

# 生成报告
report = agent.generate_report(days=7)
print(f"记忆增长: {report['memory_growth']} 条")

🎨 示例

示例1:学习助手

from agent_memory import AgentMemory

# 创建学习助手
assistant = AgentMemory("student_001")

# 记录学习内容
assistant.memorize("今天学习了Python列表推导式")
assistant.memorize("理解了map和filter函数的区别")

# 复习时检索
topics = assistant.recall("Python函数", top_k=5)
print("今天学了这些:")
for topic in topics:
    print(f"- {topic.content}")

# 查看学习进展
report = assistant.generate_report(days=7)
print(f"本周学习了 {report['memory_growth']} 个知识点")

示例2:个人助理

from agent_memory import AgentMemory

assistant = AgentMemory("user_123")

# 记住用户偏好
with assistant:
    assistant.chat(
        "我喜欢喝咖啡,不喜欢茶",
        "好的,我记住了您的偏好"
    )
    
    assistant.chat(
        "每天早上9点提醒我喝水",
        "已设置提醒"
    )

# 第二天,助理主动提醒
context = assistant.get_context()
if "提醒" in str(context['pending_tasks']):
    print("该喝水了!")

示例3:客服机器人

from agent_memory import AgentMemory

# 为每个客户创建记忆
bot = AgentMemory("customer_456")

# 记住客户问题历史
with bot:
    bot.chat(
        "我的订单还没到",
        "让我帮您查询一下订单状态"
    )
    
    # 记住关键信息
    bot.memorize("客户订单号:12345,2天前下单")
    
# 客户再次咨询时
history = bot.recall("订单", top_k=3)
print("客户历史问题:")
for h in history:
    print(f"- {h.content}")

📚 核心概念

记忆类型

  • WORK - 工作记忆(当前会话)
  • SHORT - 短期记忆(最近几天)
  • MID - 中期记忆(几周到几月)
  • LONG - 长期记忆(几月到几年)
  • CORE - 核心记忆(永久)

记忆类别

  • KNOWLEDGE - 知识性记忆
  • EXPERIENCE - 经验性记忆
  • RELATIONSHIP - 关系性记忆
  • VALUES - 价值观记忆
  • CONTEXT - 上下文记忆
  • PREFERENCE - 偏好记忆
  • META - 元记忆

🔧 配置

LLM配置(推荐)

Agent Memory支持使用大语言模型来增强记忆提取和分类能力。配置LLM有三种方式:

方式1:使用config.json文件(推荐)

在您的项目目录下创建 config.json 文件:

{
  "llm": {
    "provider": "openai",
    "api_key": "sk-你的API密钥",
    "base_url": "https://api.openai.com/v1",
    "model": "gpt-3.5-turbo",
    "temperature": 0.7,
    "max_tokens": 2000
  },
  "database": {
    "path": "memory.db"
  },
  "vector_db": {
    "path": "vector_store"
  }
}

参数说明

  • api_key: 您的OpenAI API密钥或其他兼容API的密钥
  • base_url: API地址(OpenAI官方或第三方代理)
  • model: 模型名称(如 gpt-3.5-turbo, gpt-4 等)
  • temperature: 生成温度(0-1,越低越确定)
  • max_tokens: 最大生成token数

支持的API提供商

  • OpenAI官方 API
  • OpenAI兼容的第三方API(如国内的代理服务)
  • 自部署的兼容API

第三方API示例

{
  "llm": {
    "provider": "openai",
    "api_key": "sk-你的密钥",
    "base_url": "https://your-proxy.com/v1",
    "model": "gpt-3.5-turbo",
    "temperature": 0.7,
    "max_tokens": 2000
  }
}

方式2:使用环境变量

# 设置API密钥
export OPENAI_API_KEY="sk-你的API密钥"

# 可选:设置自定义API地址
export OPENAI_API_BASE="https://your-proxy.com/v1"

然后在代码中无需额外配置:

from agent_memory import AgentMemory

# 自动从环境变量读取配置
agent = AgentMemory("user_id")

方式3:代码中配置

import os
from agent_memory import AgentMemory

# 设置环境变量
os.environ["OPENAI_API_KEY"] = "sk-你的API密钥"
os.environ["OPENAI_API_BASE"] = "https://your-proxy.com/v1"

# 创建实例
agent = AgentMemory("user_id")

配置优先级

系统按以下优先级读取配置:

  1. 当前目录的 config.json
  2. 环境变量
  3. 默认配置(使用基于规则的降级策略)

无LLM模式

重要:即使没有配置LLM,Agent Memory也能正常工作!

系统会自动切换到基于规则的策略:

  • 使用关键词提取替代实体提取
  • 使用规则分类替代智能分类
  • 使用简化的重要性评分
# 无需任何配置即可使用
from agent_memory import AgentMemory

agent = AgentMemory("user_id")
agent.memorize("我喜欢Python编程")  # 正常工作
results = agent.recall("Python")     # 正常工作

完整配置示例

{
  "llm": {
    "provider": "openai",
    "api_key": "sk-xxxxxxxxxxxxx",
    "base_url": "https://api.openai.com/v1",
    "model": "gpt-3.5-turbo",
    "temperature": 0.7,
    "max_tokens": 2000
  },
  "database": {
    "path": "./data/memory.db"
  },
  "vector_db": {
    "path": "./data/vector_store"
  },
  "memory": {
    "importance_threshold": {
      "core": 0.9,
      "long": 0.7,
      "mid": 0.5,
      "short": 0.3,
      "work": 0.0
    }
  }
}

自定义数据库路径

from agent_memory import AgentMemory

agent = AgentMemory(
    "user_id",
    db_path="./data/my_memory.db",
    vector_db_path="./data/my_vectors"
)

获取API密钥

OpenAI官方

  1. 访问 https://platform.openai.com/
  2. 注册/登录账号
  3. 进入 API keys 页面
  4. 创建新的API key

第三方服务: 国内用户可以使用OpenAI兼容的代理服务,获取方式请咨询服务提供商。


📋 API参考

主类:AgentMemory

初始化

AgentMemory(
    user_id: str,
    db_path: Optional[str] = None,
    vector_db_path: Optional[str] = None,
    use_vector_store: bool = True
)

记忆管理

  • memorize(text) - 从文本形成记忆
  • create_memory(content, ...) - 直接创建记忆
  • recall(query, top_k, strategy) - 检索记忆
  • search(query, filters) - 搜索记忆
  • update_memory(memory_id, ...) - 更新记忆
  • forget(memory_id/query/days_old) - 遗忘记忆

会话管理

  • start_session(session_id) - 开始会话
  • end_session() - 结束会话
  • chat(user_msg, assistant_msg) - 对话
  • add_message(role, content) - 添加消息

维护和统计

  • maintain() - 执行维护
  • get_statistics() - 获取统计
  • generate_report(days) - 生成报告
  • get_context() - 获取上下文

🏗️ 系统架构

AgentMemory (统一接口)
    │
    ├─ 存储层 (Storage)
    │  ├─ SQLiteStore (关系型数据)
    │  └─ VectorStore (向量数据)
    │
    ├─ 形成层 (Formation)
    │  ├─ MemoryExtractor (信息提取)
    │  ├─ ImportanceScorer (重要性评分)
    │  └─ MemoryClassifier (记忆分类)
    │
    ├─ 检索层 (Retrieval)
    │  ├─ VectorSearcher (向量检索)
    │  ├─ KeywordSearcher (关键词检索)
    │  ├─ TemporalSearcher (时间检索)
    │  ├─ ContextSearcher (上下文检索)
    │  └─ Reranker (重排序)
    │
    ├─ 更新层 (Update)
    │  ├─ ConflictDetector (冲突检测)
    │  ├─ MemoryUpdater (记忆更新)
    │  └─ MemoryMerger (记忆合并)
    │
    ├─ 维护层 (Maintenance)
    │  ├─ DecayManager (衰减管理)
    │  └─ ForgetManager (遗忘管理)
    │
    └─ 会话层 (Session)
       ├─ SessionSummarizer (会话摘要)
       ├─ SnapshotManager (快照管理)
       └─ ConsistencyChecker (一致性检查)

📊 性能

基准测试

操作 时间 说明
memorize() <100ms 包含提取和存储
recall() <20ms 关键词检索
recall() (向量) <50ms 向量检索
update() <15ms 更新操作
maintain() <100ms 完整维护

扩展性

  • ✅ 支持10万+记忆
  • ✅ 支持1000+并发用户
  • ✅ 响应时间<500ms

🛣️ 路线图

v0.2.0 (计划中)

  • GraphQL API
  • REST API
  • WebSocket支持
  • 多语言支持

v0.3.0 (计划中)

  • 记忆可视化
  • 知识图谱
  • 推理引擎
  • 插件系统

❓ 常见问题

1. 如何配置LLM?

可选配置。系统在没有LLM的情况下也能正常工作,使用基于规则的策略。

2. 数据存储在哪里?

默认存储在当前目录的 memory.db(SQLite)和 vector_store(ChromaDB)中。可以通过参数自定义路径。

3. 是否支持多用户?

支持。为每个用户创建独立的 AgentMemory 实例,使用不同的 user_id

4. 如何备份数据?

直接备份数据库文件:

  • memory.db(主数据库)
  • vector_store/(向量数据库目录)

5. 性能如何优化?

  • 使用向量检索(需要安装 agent-memory-ai[full]
  • 定期执行 agent.maintain() 清理和优化
  • 适当配置记忆衰减策略

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。


🙏 致谢


📧 联系


⬆ 回到顶部

Made with ❤️ by yixiaobai

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

agent_memory_ai-0.2.0.tar.gz (144.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

agent_memory_ai-0.2.0-py3-none-any.whl (106.4 kB view details)

Uploaded Python 3

File details

Details for the file agent_memory_ai-0.2.0.tar.gz.

File metadata

  • Download URL: agent_memory_ai-0.2.0.tar.gz
  • Upload date:
  • Size: 144.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for agent_memory_ai-0.2.0.tar.gz
Algorithm Hash digest
SHA256 c81cfedc36a03be596ec7042cfa4e2b953214c8dd0327293de85a3ae0bd8c99c
MD5 3d2c6c71c217bb1f9e5420f92138c166
BLAKE2b-256 194f09a558c83af9886d7e99c15347d9f6dd4bcf27a1f6aefcfd2b4584a7f062

See more details on using hashes here.

File details

Details for the file agent_memory_ai-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for agent_memory_ai-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ed06974afb1c3397f0099f28ddc8026b1f6a7bb73d6ced2eb00b0667d801b762
MD5 6e4bdae2fd5a188523a05a24fc1de1da
BLAKE2b-256 0e1a965202d543bc3245891e820296b15c5d4d8d87d454b20961b210bb18d356

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page