06_Memory_Consolidation_Demo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 代码示例 06: 记忆整合机制演示
  5. 展示从短期记忆到长期记忆的智能转化过程
  6. """
  7. import time
  8. from datetime import datetime, timedelta
  9. from hello_agents.tools import MemoryTool
  10. class MemoryConsolidationDemo:
  11. """记忆整合演示类"""
  12. def __init__(self):
  13. self.memory_tool = MemoryTool(
  14. user_id="consolidation_demo_user",
  15. memory_types=["working", "episodic", "semantic", "perceptual"]
  16. )
  17. def setup_initial_memories(self):
  18. """设置初始记忆数据"""
  19. print("📝 设置初始记忆数据")
  20. print("=" * 50)
  21. # 添加不同重要性的工作记忆
  22. working_memories = [
  23. {
  24. "content": "学习了Transformer架构的基本原理",
  25. "importance": 0.9,
  26. "topic": "deep_learning",
  27. "session": "study_session_1"
  28. },
  29. {
  30. "content": "完成了Python代码调试任务",
  31. "importance": 0.8,
  32. "topic": "programming",
  33. "task_type": "debugging"
  34. },
  35. {
  36. "content": "参加了团队会议讨论项目进展",
  37. "importance": 0.7,
  38. "topic": "teamwork",
  39. "meeting_type": "progress_review"
  40. },
  41. {
  42. "content": "查看了今天的天气预报",
  43. "importance": 0.3,
  44. "topic": "daily_life",
  45. "category": "routine"
  46. },
  47. {
  48. "content": "阅读了关于注意力机制的论文",
  49. "importance": 0.85,
  50. "topic": "research",
  51. "paper_type": "technical"
  52. },
  53. {
  54. "content": "喝了一杯咖啡",
  55. "importance": 0.2,
  56. "topic": "daily_life",
  57. "category": "routine"
  58. },
  59. {
  60. "content": "解决了一个复杂的算法问题",
  61. "importance": 0.9,
  62. "topic": "problem_solving",
  63. "difficulty": "high"
  64. },
  65. {
  66. "content": "整理了桌面文件",
  67. "importance": 0.4,
  68. "topic": "organization",
  69. "category": "maintenance"
  70. }
  71. ]
  72. print("添加工作记忆:")
  73. for i, memory in enumerate(working_memories):
  74. content = memory.pop("content")
  75. importance = memory.pop("importance")
  76. result = self.memory_tool.execute("add",
  77. content=content,
  78. memory_type="working",
  79. importance=importance,
  80. **memory)
  81. print(f" {i+1}. {content[:40]}... (重要性: {importance})")
  82. print(f"\n✅ 已添加 {len(working_memories)} 条工作记忆")
  83. # 显示当前状态
  84. stats = self.memory_tool.execute("stats")
  85. print(f"\n📊 当前记忆统计:\n{stats}")
  86. def demonstrate_consolidation_criteria(self):
  87. """演示整合标准和筛选过程"""
  88. print("\n🎯 记忆整合标准演示")
  89. print("-" * 50)
  90. print("整合标准:")
  91. print("• 重要性阈值筛选")
  92. print("• 按重要性排序")
  93. print("• 类型转换处理")
  94. print("• 元数据更新")
  95. # 获取当前工作记忆摘要
  96. print("\n📋 整合前的工作记忆状态:")
  97. summary = self.memory_tool.execute("summary", limit=10)
  98. print(summary)
  99. # 测试不同阈值的整合效果
  100. thresholds = [0.5, 0.7, 0.8]
  101. for threshold in thresholds:
  102. print(f"\n🔍 测试重要性阈值 {threshold}:")
  103. # 模拟整合过程(不实际执行,只是分析)
  104. working_memories = []
  105. # 这里应该从实际的工作记忆中获取,简化演示
  106. print(f" 阈值 {threshold} 下符合整合条件的记忆:")
  107. print(f" • 重要性 >= {threshold} 的记忆将被整合")
  108. print(f" • 整合后类型: working → episodic")
  109. print(f" • 重要性提升: importance × 1.1")
  110. def demonstrate_consolidation_process(self):
  111. """演示实际的整合过程"""
  112. print("\n🔄 记忆整合过程演示")
  113. print("-" * 50)
  114. print("整合过程步骤:")
  115. print("1. 筛选符合条件的记忆")
  116. print("2. 按重要性排序")
  117. print("3. 创建新的记忆项")
  118. print("4. 更新类型和元数据")
  119. print("5. 添加整合标记")
  120. # 执行不同阈值的整合
  121. consolidation_tests = [
  122. (0.6, "低阈值整合 - 整合更多记忆"),
  123. (0.8, "高阈值整合 - 只整合最重要的记忆")
  124. ]
  125. for threshold, description in consolidation_tests:
  126. print(f"\n🔄 {description} (阈值: {threshold}):")
  127. # 获取整合前状态
  128. stats_before = self.memory_tool.execute("stats")
  129. print(f"整合前状态: {stats_before}")
  130. # 执行整合
  131. start_time = time.time()
  132. consolidation_result = self.memory_tool.execute("consolidate",
  133. from_type="working",
  134. to_type="episodic",
  135. importance_threshold=threshold)
  136. consolidation_time = time.time() - start_time
  137. print(f"整合结果: {consolidation_result}")
  138. print(f"整合耗时: {consolidation_time:.3f}秒")
  139. # 获取整合后状态
  140. stats_after = self.memory_tool.execute("stats")
  141. print(f"整合后状态: {stats_after}")
  142. # 查看整合后的情景记忆
  143. print(f"\n📚 整合后的情景记忆:")
  144. episodic_search = self.memory_tool.execute("search",
  145. query="",
  146. memory_type="episodic",
  147. limit=5)
  148. print(episodic_search)
  149. def demonstrate_consolidation_metadata(self):
  150. """演示整合过程中的元数据处理"""
  151. print("\n📋 整合元数据处理演示")
  152. print("-" * 50)
  153. print("元数据处理:")
  154. print("• 保留原始元数据")
  155. print("• 添加整合标记")
  156. print("• 记录整合时间")
  157. print("• 保存原始ID引用")
  158. # 添加一个特殊的工作记忆用于演示
  159. special_memory_result = self.memory_tool.execute("add",
  160. content="这是一个用于演示整合元数据处理的特殊记忆",
  161. memory_type="working",
  162. importance=0.85,
  163. special_tag="metadata_demo",
  164. original_context="demonstration",
  165. creation_purpose="show_consolidation_metadata"
  166. )
  167. print(f"添加特殊记忆: {special_memory_result}")
  168. # 执行整合
  169. print(f"\n🔄 执行整合...")
  170. consolidation_result = self.memory_tool.execute("consolidate",
  171. from_type="working",
  172. to_type="episodic",
  173. importance_threshold=0.8)
  174. print(f"整合结果: {consolidation_result}")
  175. # 搜索整合后的记忆查看元数据
  176. print(f"\n🔍 查看整合后的记忆元数据:")
  177. search_result = self.memory_tool.execute("search",
  178. query="特殊记忆",
  179. memory_type="episodic",
  180. limit=1)
  181. print(search_result)
  182. def demonstrate_multi_type_consolidation(self):
  183. """演示多类型记忆整合"""
  184. print("\n🔀 多类型记忆整合演示")
  185. print("-" * 50)
  186. print("多类型整合场景:")
  187. print("• working → episodic (经历记录)")
  188. print("• working → semantic (知识提取)")
  189. print("• episodic → semantic (经验总结)")
  190. # 添加一些适合不同整合路径的记忆
  191. consolidation_candidates = [
  192. {
  193. "content": "学习了深度学习中的反向传播算法原理",
  194. "memory_type": "working",
  195. "importance": 0.9,
  196. "learning_type": "concept",
  197. "suitable_for": "semantic"
  198. },
  199. {
  200. "content": "今天下午参加了AI技术分享会",
  201. "memory_type": "working",
  202. "importance": 0.8,
  203. "event_type": "meeting",
  204. "suitable_for": "episodic"
  205. },
  206. {
  207. "content": "通过多次实践掌握了Transformer的实现技巧",
  208. "memory_type": "episodic",
  209. "importance": 0.85,
  210. "experience_type": "skill",
  211. "suitable_for": "semantic"
  212. }
  213. ]
  214. print(f"\n📝 添加整合候选记忆:")
  215. for memory in consolidation_candidates:
  216. content = memory.pop("content")
  217. memory_type = memory.pop("memory_type")
  218. importance = memory.pop("importance")
  219. suitable_for = memory.pop("suitable_for")
  220. result = self.memory_tool.execute("add",
  221. content=content,
  222. memory_type=memory_type,
  223. importance=importance,
  224. **memory)
  225. print(f" • {content[:50]}... → 适合整合为{suitable_for}")
  226. # 执行不同类型的整合
  227. consolidation_paths = [
  228. ("working", "episodic", 0.75, "经历记录整合"),
  229. ("working", "semantic", 0.85, "知识提取整合"),
  230. ("episodic", "semantic", 0.8, "经验总结整合")
  231. ]
  232. for from_type, to_type, threshold, description in consolidation_paths:
  233. print(f"\n🔄 {description} ({from_type} → {to_type}):")
  234. result = self.memory_tool.execute("consolidate",
  235. from_type=from_type,
  236. to_type=to_type,
  237. importance_threshold=threshold)
  238. print(f"整合结果: {result}")
  239. def demonstrate_consolidation_benefits(self):
  240. """演示记忆整合的益处"""
  241. print("\n✨ 记忆整合益处演示")
  242. print("-" * 50)
  243. print("整合益处:")
  244. print("• 长期保存重要信息")
  245. print("• 释放工作记忆空间")
  246. print("• 形成知识体系")
  247. print("• 提升检索效率")
  248. # 获取最终的记忆系统状态
  249. print(f"\n📊 最终记忆系统状态:")
  250. final_stats = self.memory_tool.execute("stats")
  251. print(final_stats)
  252. # 获取各类型记忆的摘要
  253. print(f"\n📋 各类型记忆摘要:")
  254. memory_types = ["working", "episodic", "semantic"]
  255. for memory_type in memory_types:
  256. print(f"\n{memory_type.upper()}记忆:")
  257. type_summary = self.memory_tool.execute("search",
  258. query="",
  259. memory_type=memory_type,
  260. limit=3)
  261. print(type_summary)
  262. # 演示整合后的检索效果
  263. print(f"\n🔍 整合后的检索效果测试:")
  264. search_queries = [
  265. ("深度学习", "测试跨类型检索"),
  266. ("学习经历", "测试整合记忆检索"),
  267. ("重要概念", "测试语义记忆检索")
  268. ]
  269. for query, description in search_queries:
  270. print(f"\n查询: '{query}' ({description})")
  271. result = self.memory_tool.execute("search",
  272. query=query,
  273. limit=3)
  274. print(result)
  275. def main():
  276. """主函数"""
  277. print("🔄 记忆整合机制演示")
  278. print("展示从短期记忆到长期记忆的智能转化过程")
  279. print("=" * 60)
  280. try:
  281. demo = MemoryConsolidationDemo()
  282. # 1. 设置初始记忆数据
  283. demo.setup_initial_memories()
  284. # 2. 演示整合标准
  285. demo.demonstrate_consolidation_criteria()
  286. # 3. 演示整合过程
  287. demo.demonstrate_consolidation_process()
  288. # 4. 演示元数据处理
  289. demo.demonstrate_consolidation_metadata()
  290. # 5. 演示多类型整合
  291. demo.demonstrate_multi_type_consolidation()
  292. # 6. 演示整合益处
  293. demo.demonstrate_consolidation_benefits()
  294. print("\n" + "=" * 60)
  295. print("🎉 记忆整合机制演示完成!")
  296. print("=" * 60)
  297. print("\n✨ 记忆整合核心特性:")
  298. print("1. 🎯 智能筛选 - 基于重要性阈值的自动筛选")
  299. print("2. 🔄 类型转换 - 灵活的记忆类型转换机制")
  300. print("3. 📋 元数据保持 - 完整保留原始上下文信息")
  301. print("4. ⚡ 自动化处理 - 无需人工干预的自动整合")
  302. print("5. 🔀 多路径支持 - 支持多种整合路径")
  303. print("\n🎯 设计理念:")
  304. print("• 仿生性 - 模拟人类大脑的记忆固化过程")
  305. print("• 智能性 - 自动识别和处理重要信息")
  306. print("• 灵活性 - 支持多种整合策略和路径")
  307. print("• 完整性 - 保持记忆的完整性和可追溯性")
  308. print("\n💡 应用价值:")
  309. print("• 知识管理 - 将临时学习转化为长期知识")
  310. print("• 经验积累 - 保存重要的实践经验")
  311. print("• 系统优化 - 释放短期记忆空间")
  312. print("• 智能决策 - 基于历史经验的决策支持")
  313. except Exception as e:
  314. print(f"\n❌ 演示过程中发生错误: {e}")
  315. import traceback
  316. traceback.print_exc()
  317. if __name__ == "__main__":
  318. main()