02_context_builder_with_agent.py 3.2 KB

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