08_Agent_Tool_Integration.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 代码示例 08: Agent工具集成
  5. 展示如何在HelloAgents框架中集成MemoryTool和RAGTool
  6. """
  7. import time
  8. from hello_agents import SimpleAgent, HelloAgentsLLM, ToolRegistry
  9. from hello_agents.tools import MemoryTool, RAGTool
  10. class AgentIntegrationDemo:
  11. """Agent工具集成演示类"""
  12. def __init__(self):
  13. self.setup_agent()
  14. def setup_agent(self):
  15. """设置Agent和工具"""
  16. print("🤖 Agent工具集成设置")
  17. print("=" * 50)
  18. # 初始化工具
  19. print("1. 初始化工具...")
  20. self.memory_tool = MemoryTool(
  21. user_id="agent_integration_user",
  22. memory_types=["working", "episodic", "semantic", "perceptual"]
  23. )
  24. self.rag_tool = RAGTool(
  25. knowledge_base_path="./agent_integration_kb",
  26. rag_namespace="agent_demo"
  27. )
  28. print("✅ MemoryTool和RAGTool初始化完成")
  29. # 创建Agent
  30. print("\n2. 创建Agent...")
  31. self.llm = HelloAgentsLLM()
  32. self.agent = SimpleAgent(
  33. name="智能学习助手",
  34. llm=self.llm,
  35. description="集成记忆和RAG功能的智能助手"
  36. )
  37. print("✅ Agent创建完成")
  38. # 注册工具
  39. print("\n3. 注册工具...")
  40. self.tool_registry = ToolRegistry()
  41. self.tool_registry.register_tool(self.memory_tool)
  42. self.tool_registry.register_tool(self.rag_tool)
  43. self.agent.tool_registry = self.tool_registry
  44. print("✅ 工具注册完成")
  45. # 显示Agent状态
  46. print(f"\n📊 Agent状态:")
  47. print(f" 名称: {self.agent.name}")
  48. print(f" 描述: {self.agent.description}")
  49. print(f" 可用工具: {list(self.tool_registry.tools.keys())}")
  50. def demonstrate_tool_registry_pattern(self):
  51. """演示工具注册模式"""
  52. print("\n🔧 工具注册模式演示")
  53. print("-" * 50)
  54. print("工具注册模式特点:")
  55. print("• 🔌 统一的工具接口")
  56. print("• 📋 集中的工具管理")
  57. print("• 🔄 动态工具加载")
  58. print("• 🎯 工具能力发现")
  59. # 演示工具注册过程
  60. print(f"\n🔧 工具注册详情:")
  61. for tool_name, tool_instance in self.tool_registry.tools.items():
  62. print(f"\n工具: {tool_name}")
  63. print(f" 类型: {type(tool_instance).__name__}")
  64. print(f" 描述: {tool_instance.description}")
  65. # 显示工具的主要功能
  66. if tool_name == "memory":
  67. print(f" 主要功能: 记忆管理、搜索、整合、遗忘")
  68. print(f" 记忆类型: {tool_instance.memory_types}")
  69. elif tool_name == "rag":
  70. print(f" 主要功能: 文档处理、智能问答、知识检索")
  71. print(f" 命名空间: {tool_instance.rag_namespace}")
  72. # 演示工具发现机制
  73. print(f"\n🔍 工具能力发现:")
  74. available_tools = self.tool_registry.list_tools()
  75. print(f"可用工具列表: {available_tools}")
  76. # 演示工具获取
  77. memory_tool = self.tool_registry.get_tool("memory")
  78. rag_tool = self.tool_registry.get_tool("rag")
  79. print(f"\n✅ 工具获取成功:")
  80. print(f" Memory工具: {type(memory_tool).__name__}")
  81. print(f" RAG工具: {type(rag_tool).__name__}")
  82. def demonstrate_unified_interface(self):
  83. """演示统一接口模式"""
  84. print("\n🔗 统一接口模式演示")
  85. print("-" * 50)
  86. print("统一接口优势:")
  87. print("• 🎯 一致的调用方式")
  88. print("• 📝 标准化的参数传递")
  89. print("• 🛡️ 统一的错误处理")
  90. print("• 🔄 简化的工具切换")
  91. # 演示统一的execute接口
  92. print(f"\n🔗 统一execute接口演示:")
  93. # Memory工具操作
  94. print(f"\n1. Memory工具操作:")
  95. memory_operations = [
  96. ("add", {
  97. "content": "学习了Agent工具集成模式",
  98. "memory_type": "episodic",
  99. "importance": 0.8,
  100. "topic": "agent_integration"
  101. }),
  102. ("search", {
  103. "query": "Agent集成",
  104. "limit": 2
  105. }),
  106. ("stats", {})
  107. ]
  108. for operation, params in memory_operations:
  109. print(f" 操作: memory.execute('{operation}', {params})")
  110. result = self.memory_tool.execute(operation, **params)
  111. print(f" 结果: {str(result)[:100]}...")
  112. # RAG工具操作
  113. print(f"\n2. RAG工具操作:")
  114. # 先添加一些内容
  115. self.rag_tool.execute("add_text",
  116. text="Agent工具集成是HelloAgents框架的核心特性,允许Agent使用多种工具来完成复杂任务。",
  117. document_id="agent_integration_guide")
  118. rag_operations = [
  119. ("search", {
  120. "query": "Agent工具集成",
  121. "limit": 2
  122. }),
  123. ("ask", {
  124. "question": "什么是Agent工具集成?",
  125. "limit": 2
  126. }),
  127. ("stats", {})
  128. ]
  129. for operation, params in rag_operations:
  130. print(f" 操作: rag.execute('{operation}', {params})")
  131. result = self.rag_tool.execute(operation, **params)
  132. print(f" 结果: {str(result)[:100]}...")
  133. def demonstrate_collaborative_workflow(self):
  134. """演示协同工作流程"""
  135. print("\n🤝 协同工作流程演示")
  136. print("-" * 50)
  137. print("协同工作场景:")
  138. print("• 📚 学习新知识 → RAG存储 + Memory记录")
  139. print("• 🔍 回顾学习历程 → Memory检索 + RAG补充")
  140. print("• 💡 知识应用 → RAG查询 + Memory更新")
  141. print("• 📊 学习分析 → 两工具统计整合")
  142. # 场景1:学习新知识
  143. print(f"\n📚 场景1:学习新知识")
  144. # 向RAG添加学习资料
  145. learning_content = """# 设计模式:观察者模式
  146. ## 定义
  147. 观察者模式定义了对象间的一对多依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都会得到通知并自动更新。
  148. ## 结构
  149. - Subject(主题):维护观察者列表,提供注册和删除观察者的方法
  150. - Observer(观察者):定义更新接口
  151. - ConcreteSubject(具体主题):实现主题接口
  152. - ConcreteObserver(具体观察者):实现观察者接口
  153. ## 应用场景
  154. - GUI事件处理
  155. - 模型-视图架构
  156. - 发布-订阅系统
  157. """
  158. rag_result = self.rag_tool.execute("add_text",
  159. text=learning_content,
  160. document_id="observer_pattern")
  161. print(f"RAG添加结果: {rag_result}")
  162. # 记录学习活动到记忆系统
  163. memory_result = self.memory_tool.execute("add",
  164. content="学习了观察者设计模式的定义、结构和应用场景",
  165. memory_type="episodic",
  166. importance=0.8,
  167. topic="design_patterns",
  168. pattern_type="observer")
  169. print(f"Memory记录结果: {memory_result}")
  170. # 场景2:回顾学习历程
  171. print(f"\n🔍 场景2:回顾学习历程")
  172. # 从记忆系统检索学习历史
  173. memory_search = self.memory_tool.execute("search",
  174. query="设计模式学习",
  175. limit=3)
  176. print(f"学习历史回顾: {memory_search}")
  177. # 从RAG获取相关知识补充
  178. rag_search = self.rag_tool.execute("search",
  179. query="观察者模式",
  180. limit=2)
  181. print(f"知识内容补充: {rag_search}")
  182. # 场景3:知识应用
  183. print(f"\n💡 场景3:知识应用")
  184. # 通过RAG查询应用方法
  185. application_query = self.rag_tool.execute("ask",
  186. question="观察者模式适用于什么场景?",
  187. limit=2)
  188. print(f"应用场景查询: {application_query}")
  189. # 记录应用实践到记忆
  190. application_memory = self.memory_tool.execute("add",
  191. content="查询了观察者模式的应用场景,准备在GUI项目中使用",
  192. memory_type="working",
  193. importance=0.7,
  194. application_context="gui_project")
  195. print(f"应用记录: {application_memory}")
  196. # 场景4:学习分析
  197. print(f"\n📊 场景4:学习分析")
  198. # 获取记忆系统统计
  199. memory_stats = self.memory_tool.execute("stats")
  200. print(f"记忆统计: {memory_stats}")
  201. # 获取RAG系统统计
  202. rag_stats = self.rag_tool.execute("stats")
  203. print(f"知识库统计: {rag_stats}")
  204. # 生成学习摘要
  205. learning_summary = self.memory_tool.execute("summary", limit=5)
  206. print(f"学习摘要: {learning_summary}")
  207. def demonstrate_agent_orchestration(self):
  208. """演示Agent编排能力"""
  209. print("\n🎭 Agent编排能力演示")
  210. print("-" * 50)
  211. print("Agent编排特点:")
  212. print("• 🧠 智能工具选择")
  213. print("• 🔄 工具链式调用")
  214. print("• 📊 结果整合分析")
  215. print("• 🎯 目标导向执行")
  216. # 模拟复杂任务的工具编排
  217. print(f"\n🎭 复杂任务编排示例:")
  218. print(f"任务: 创建一个关于机器学习的学习计划")
  219. # 步骤1:从RAG获取机器学习知识结构
  220. print(f"\n步骤1: 获取知识结构")
  221. # 添加机器学习知识
  222. ml_content = """# 机器学习学习路径
  223. ## 基础阶段
  224. 1. 数学基础:线性代数、概率统计、微积分
  225. 2. 编程基础:Python、NumPy、Pandas
  226. 3. 机器学习概念:监督学习、无监督学习、强化学习
  227. ## 进阶阶段
  228. 1. 算法实现:从零实现经典算法
  229. 2. 深度学习:神经网络、CNN、RNN、Transformer
  230. 3. 实践项目:端到端机器学习项目
  231. ## 高级阶段
  232. 1. 模型优化:超参数调优、模型压缩
  233. 2. 部署运维:模型部署、监控、更新
  234. 3. 前沿技术:最新论文、开源项目
  235. """
  236. self.rag_tool.execute("add_text",
  237. text=ml_content,
  238. document_id="ml_learning_path")
  239. knowledge_structure = self.rag_tool.execute("ask",
  240. question="机器学习的学习路径是什么?",
  241. limit=3)
  242. print(f"知识结构: {knowledge_structure[:200]}...")
  243. # 步骤2:记录学习计划到记忆系统
  244. print(f"\n步骤2: 记录学习计划")
  245. plan_memory = self.memory_tool.execute("add",
  246. content="制定了机器学习学习计划,包括基础、进阶、高级三个阶段",
  247. memory_type="episodic",
  248. importance=0.9,
  249. plan_type="learning",
  250. subject="machine_learning")
  251. print(f"计划记录: {plan_memory}")
  252. # 步骤3:检索相关学习经验
  253. print(f"\n步骤3: 检索学习经验")
  254. experience_search = self.memory_tool.execute("search",
  255. query="学习计划 学习经验",
  256. limit=3)
  257. print(f"相关经验: {experience_search}")
  258. # 步骤4:整合生成最终建议
  259. print(f"\n步骤4: 生成最终建议")
  260. final_advice = self.rag_tool.execute("ask",
  261. question="如何制定有效的机器学习学习计划?",
  262. limit=4)
  263. print(f"最终建议: {final_advice[:300]}...")
  264. # 记录编排过程
  265. orchestration_memory = self.memory_tool.execute("add",
  266. content="完成了复杂的学习计划制定任务,使用了RAG和Memory的协同编排",
  267. memory_type="working",
  268. importance=0.8,
  269. task_type="orchestration")
  270. print(f"\n编排记录: {orchestration_memory}")
  271. def demonstrate_performance_analysis(self):
  272. """演示性能分析"""
  273. print("\n📊 性能分析演示")
  274. print("-" * 50)
  275. print("性能分析指标:")
  276. print("• ⏱️ 工具响应时间")
  277. print("• 🔄 工具切换开销")
  278. print("• 💾 内存使用情况")
  279. print("• 🎯 任务完成效率")
  280. # 性能测试
  281. print(f"\n📊 性能测试:")
  282. # 单工具性能测试
  283. print(f"\n1. 单工具性能:")
  284. # Memory工具性能
  285. start_time = time.time()
  286. for i in range(5):
  287. self.memory_tool.execute("add",
  288. content=f"性能测试记忆 {i+1}",
  289. memory_type="working",
  290. importance=0.5)
  291. memory_time = time.time() - start_time
  292. print(f"Memory工具 - 5次添加操作: {memory_time:.3f}秒")
  293. # RAG工具性能
  294. start_time = time.time()
  295. for i in range(3):
  296. self.rag_tool.execute("search",
  297. query=f"测试查询 {i+1}",
  298. limit=2)
  299. rag_time = time.time() - start_time
  300. print(f"RAG工具 - 3次搜索操作: {rag_time:.3f}秒")
  301. # 协同工作性能测试
  302. print(f"\n2. 协同工作性能:")
  303. start_time = time.time()
  304. # 模拟协同工作流程
  305. self.rag_tool.execute("add_text",
  306. text="这是一个性能测试文档",
  307. document_id="perf_test")
  308. self.memory_tool.execute("add",
  309. content="执行了性能测试",
  310. memory_type="working",
  311. importance=0.6)
  312. rag_result = self.rag_tool.execute("search",
  313. query="性能测试",
  314. limit=1)
  315. memory_result = self.memory_tool.execute("search",
  316. query="性能测试",
  317. limit=1)
  318. collaborative_time = time.time() - start_time
  319. print(f"协同工作流程: {collaborative_time:.3f}秒")
  320. # 性能分析总结
  321. print(f"\n📈 性能分析总结:")
  322. print(f"Memory工具平均响应: {memory_time/5:.3f}秒/操作")
  323. print(f"RAG工具平均响应: {rag_time/3:.3f}秒/操作")
  324. print(f"协同工作效率: {collaborative_time:.3f}秒/流程")
  325. # 获取最终统计
  326. final_memory_stats = self.memory_tool.execute("stats")
  327. final_rag_stats = self.rag_tool.execute("stats")
  328. print(f"\n📊 最终系统状态:")
  329. print(f"Memory系统: {final_memory_stats}")
  330. print(f"RAG系统: {final_rag_stats}")
  331. def main():
  332. """主函数"""
  333. print("🤖 Agent工具集成演示")
  334. print("展示如何在HelloAgents框架中集成MemoryTool和RAGTool")
  335. print("=" * 70)
  336. try:
  337. demo = AgentIntegrationDemo()
  338. # 1. 工具注册模式演示
  339. demo.demonstrate_tool_registry_pattern()
  340. # 2. 统一接口模式演示
  341. demo.demonstrate_unified_interface()
  342. # 3. 协同工作流程演示
  343. demo.demonstrate_collaborative_workflow()
  344. # 4. Agent编排能力演示
  345. demo.demonstrate_agent_orchestration()
  346. # 5. 性能分析演示
  347. demo.demonstrate_performance_analysis()
  348. print("\n" + "=" * 70)
  349. print("🎉 Agent工具集成演示完成!")
  350. print("=" * 70)
  351. print("\n✨ Agent集成核心特性:")
  352. print("1. 🔧 工具注册模式 - 统一的工具管理和发现")
  353. print("2. 🔗 统一接口设计 - 一致的工具调用方式")
  354. print("3. 🤝 协同工作流程 - 工具间的智能协作")
  355. print("4. 🎭 智能编排能力 - 复杂任务的自动分解")
  356. print("5. 📊 性能监控分析 - 全面的性能评估")
  357. print("\n🎯 设计优势:")
  358. print("• 模块化 - 工具独立开发,灵活组合")
  359. print("• 可扩展 - 支持动态添加新工具")
  360. print("• 高内聚 - 每个工具专注特定功能")
  361. print("• 低耦合 - 工具间依赖关系最小")
  362. print("\n💡 应用价值:")
  363. print("• 智能助手 - 构建多功能智能助手")
  364. print("• 知识管理 - 企业级知识管理系统")
  365. print("• 学习平台 - 个性化学习支持系统")
  366. print("• 决策支持 - 基于知识和经验的决策")
  367. except Exception as e:
  368. print(f"\n❌ 演示过程中发生错误: {e}")
  369. import traceback
  370. traceback.print_exc()
  371. if __name__ == "__main__":
  372. main()