1
0

06_Memory_Consolidation_Demo.py 15 KB

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