1
0

knowledge.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # services/learning_knowledge_service.py
  2. from hello_agents.tools import MemoryTool, RAGTool
  3. from datetime import datetime
  4. from typing import Optional
  5. class LearningKnowledgeService:
  6. """
  7. 学习记忆 + 知识检索服务
  8. 供多智能体通过 A2A 调用
  9. """
  10. def __init__(self, user_id: str):
  11. self.user_id = user_id
  12. self.session_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
  13. self.memory = MemoryTool(user_id=user_id)
  14. self.rag = RAGTool(rag_namespace=f"learning_{user_id}")
  15. self.active_learning_plan = {}
  16. def set_active_learning_plan(self, plan_id: str):
  17. self.active_learning_plan_id = plan_id
  18. def get_active_learning_plan(self):
  19. return self.active_learning_plan_id
  20. # ======================
  21. # 知识库相关
  22. # ======================
  23. def add_learning_material(self, file_path: str):
  24. return self.rag.run({
  25. "action": "add_document",
  26. "file_path": file_path,
  27. "chunk_size": 1000,
  28. "chunk_overlap": 200
  29. })
  30. def ask_knowledge(self, question: str):
  31. self._log_working_memory(f"提问: {question}")
  32. answer = self.rag.run({
  33. "action": "ask",
  34. "question": question,
  35. "limit": 5,
  36. "enable_advanced_search": True,
  37. "enable_mqe": True,
  38. "enable_hyde": True
  39. })
  40. self._log_episodic_memory(f"围绕问题 `{question}` 的学习")
  41. return answer
  42. # ======================
  43. # 记忆系统
  44. # ======================
  45. def add_note(self, content: str, concept: Optional[str] = None):
  46. self.memory.run({
  47. "action": "add",
  48. "content": content,
  49. "memory_type": "semantic",
  50. "importance": 0.8,
  51. "concept": concept or "general",
  52. "session_id": self.session_id
  53. })
  54. def recall(self, query: str):
  55. return self.memory.run({
  56. "action": "search",
  57. "query": query,
  58. "limit": 5
  59. })
  60. def summarize_learning(self):
  61. return self.memory.run({
  62. "action": "summary",
  63. "limit": 10
  64. })
  65. # ======================
  66. # 内部日志
  67. # ======================
  68. def _log_working_memory(self, content: str):
  69. self.memory.run({
  70. "action": "add",
  71. "content": content,
  72. "memory_type": "working",
  73. "importance": 0.6,
  74. "session_id": self.session_id
  75. })
  76. def _log_episodic_memory(self, content: str):
  77. self.memory.run({
  78. "action": "add",
  79. "content": content,
  80. "memory_type": "episodic",
  81. "importance": 0.7,
  82. "session_id": self.session_id
  83. })