1
0

02_context_builder_with_agent.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. """
  2. ContextBuilder 与 Agent 集成示例
  3. 展示如何将 ContextBuilder 集成到 Agent 中,实现:
  4. 1. 上下文感知的 Agent
  5. 2. 自动构建优化的上下文
  6. 3. 记忆管理与上下文构建的协同
  7. """
  8. from dotenv import load_dotenv
  9. load_dotenv()
  10. from hello_agents import SimpleAgent, HelloAgentsLLM, ToolRegistry
  11. from hello_agents.context import ContextBuilder, ContextConfig
  12. from hello_agents.tools import MemoryTool, RAGTool
  13. from hello_agents.core.message import Message
  14. from datetime import datetime
  15. class ContextAwareAgent(SimpleAgent):
  16. """具有上下文感知能力的 Agent"""
  17. def __init__(self, name: str, llm: HelloAgentsLLM, **kwargs):
  18. super().__init__(name=name, llm=llm, **kwargs)
  19. #(Optional)
  20. # self.memory_tool = MemoryTool(user_id=kwargs.get("user_id", "default"))
  21. # self.rag_tool = RAGTool(knowledge_base_path=kwargs.get("knowledge_base_path", "./kb"))
  22. # 初始化上下文构建器
  23. self.context_builder = ContextBuilder(
  24. # memory_tool=self.memory_tool,
  25. # rag_tool=self.rag_tool,
  26. config=ContextConfig(max_tokens=4000)
  27. )
  28. self.conversation_history = []
  29. def run(self, user_input: str) -> str:
  30. """运行 Agent,自动构建优化的上下文"""
  31. # 1. 使用 ContextBuilder 构建优化的上下文
  32. optimized_context = self.context_builder.build(
  33. user_query=user_input,
  34. conversation_history=self.conversation_history,
  35. system_instructions=self.system_prompt
  36. )
  37. # 2. 使用优化后的上下文调用 LLM
  38. messages = [
  39. {"role": "system", "content": optimized_context},
  40. {"role": "user", "content": user_input}
  41. ]
  42. response = self.llm.invoke(messages)
  43. # 3. 更新对话历史
  44. self.conversation_history.append(
  45. Message(content=user_input, role="user", timestamp=datetime.now())
  46. )
  47. self.conversation_history.append(
  48. Message(content=response, role="assistant", timestamp=datetime.now())
  49. )
  50. # 4. 将重要交互记录到记忆系统
  51. # self.memory_tool.run({
  52. # "action": "add",
  53. # "content": f"Q: {user_input}\nA: {response[:200]}...", # 摘要
  54. # "memory_type": "episodic",
  55. # "importance": 0.6
  56. # })
  57. return response
  58. def main():
  59. print("=" * 80)
  60. print("ContextBuilder 与 Agent 集成示例")
  61. print("=" * 80 + "\n")
  62. # 配置 LLM
  63. from hello_agents.core.llm import HelloAgentsLLM
  64. llm = HelloAgentsLLM()
  65. # 使用示例
  66. agent = ContextAwareAgent(
  67. name="数据分析顾问",
  68. llm=llm,
  69. system_prompt="你是一位资深的Python数据工程顾问。"
  70. )
  71. # 进行对话
  72. response = agent.run("如何优化Pandas的内存占用?")
  73. print(f"助手回答:\n{response}\n")
  74. # 继续对话
  75. response = agent.run("能给出具体的代码示例吗?")
  76. print(f"助手回答:\n{response}\n")
  77. print("=" * 80)
  78. if __name__ == "__main__":
  79. main()