1
0

01_context_builder_basic.py 3.4 KB

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