01_context_builder_basic.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """
  2. ContextBuilder 基础使用示例
  3. 展示如何使用 ContextBuilder 构建优化的上下文,包括:
  4. 1. 初始化 ContextBuilder
  5. 2. 准备对话历史
  6. 3. 添加记忆
  7. 4. 构建结构化上下文
  8. """
  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. def main():
  14. print("=" * 80)
  15. print("ContextBuilder 基础使用示例")
  16. print("=" * 80 + "\n")
  17. # 1. 初始化工具(Optional)
  18. print("1. 初始化工具...")
  19. # memory_tool = MemoryTool(user_id="user123")
  20. # rag_tool = RAGTool(knowledge_base_path="./knowledge_base")
  21. # 2. 创建 ContextBuilder
  22. print("2. 创建 ContextBuilder...")
  23. config = ContextConfig(
  24. max_tokens=3000,
  25. reserve_ratio=0.2,
  26. min_relevance=0,#最小相关性阈值,0代表所有历史信息会被保留,
  27. enable_compression=True
  28. )
  29. builder = ContextBuilder(
  30. # memory_tool=memory_tool,
  31. # rag_tool=rag_tool,
  32. config=config
  33. )
  34. # 3. 准备对话历史
  35. print("3. 准备对话历史...")
  36. conversation_history = [
  37. Message(content="我正在开发一个数据分析工具", role="user", timestamp=datetime.now()),
  38. Message(content="很好!数据分析工具通常需要处理大量数据。您计划使用什么技术栈?", role="assistant", timestamp=datetime.now()),
  39. Message(content="我打算使用Python和Pandas,已经完成了CSV读取模块", role="user", timestamp=datetime.now()),
  40. Message(content="不错的选择!Pandas在数据处理方面非常强大。接下来您可能需要考虑数据清洗和转换。", role="assistant", timestamp=datetime.now()),
  41. ]
  42. # 4. 添加一些记忆
  43. print("4. 添加记忆...")
  44. # memory_tool.execute(
  45. # "add",
  46. # content="用户正在开发数据分析工具,使用Python和Pandas",
  47. # memory_type="semantic",
  48. # importance=0.8
  49. # )
  50. # memory_tool.execute(
  51. # "add",
  52. # content="已完成CSV读取模块的开发",
  53. # memory_type="episodic",
  54. # importance=0.7
  55. # )
  56. # 5. 构建上下文
  57. print("5. 构建上下文...\n")
  58. context_str = builder.build(
  59. user_query="如何优化Pandas的内存占用?",
  60. conversation_history=conversation_history,
  61. system_instructions="你是一位资深的Python数据工程顾问。你的回答需要:1) 提供具体可行的建议 2) 解释技术原理 3) 给出代码示例"
  62. )
  63. print("=" * 80)
  64. print("构建的上下文 (结构化字符串):")
  65. print("=" * 80)
  66. print(context_str)
  67. print("=" * 80)
  68. print()
  69. # 6. 将上下文字符串转换为消息格式供 LLM 使用
  70. print("6. 将上下文传给 LLM...")
  71. messages = [
  72. {"role": "system", "content": context_str},
  73. {"role": "user", "content": "请回答"}
  74. ]
  75. from hello_agents.core.llm import HelloAgentsLLM
  76. llm = HelloAgentsLLM(
  77. model="ZhipuAI/GLM-4.6",
  78. api_key="6ff5219e-410a-4293-8772-0c948bfa691c",
  79. base_url="https://api-inference.modelscope.cn/v1/",
  80. provider="modelscope"
  81. )
  82. # 注意: 实际使用时需要配置 LLM
  83. response = llm.invoke(messages)
  84. print(f"LLM 回答: {response}")
  85. print("✅ ContextBuilder 演示完成!")
  86. print("\n提示: ContextBuilder 返回的是结构化的上下文字符串,")
  87. print(" 可以直接作为 system message 传给 LLM。")
  88. if __name__ == "__main__":
  89. main()