repl.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # cli/repl.py
  2. """REPL 循环实现"""
  3. from hello_agents import HelloAgentsLLM
  4. from core.main_agent import MainAgent
  5. from core.file_manager import FileManager
  6. from utils.logger import setup_logger
  7. def print_welcome():
  8. """打印欢迎信息"""
  9. print(
  10. """
  11. ╔══════════════════════════════════════════════════════════╗
  12. ║ ║
  13. ║ 🤖 Welcome to LearningAgent! ║
  14. ║ ║
  15. ║ Your AI Learning Companion ║
  16. ║ ║
  17. ╚══════════════════════════════════════════════════════════╝
  18. 输入 /help 查看可用命令
  19. """
  20. )
  21. def print_goodbye():
  22. """打印告别信息"""
  23. print(
  24. """
  25. ╔══════════════════════════════════════════════════════════╗
  26. ║ ║
  27. ║ 👋 Goodbye! ║
  28. ║ ║
  29. ║ Keep Learning, Keep Growing! ║
  30. ║ ║
  31. ╚══════════════════════════════════════════════════════════╝
  32. """
  33. )
  34. def start_repl():
  35. """
  36. 启动 REPL 循环
  37. """
  38. # 设置日志
  39. logger = setup_logger("learning_agent")
  40. logger.info("LearningAgent started")
  41. # 初始化组件
  42. try:
  43. llm = HelloAgentsLLM()
  44. file_manager = FileManager()
  45. # REPL 始终是交互式环境,启用流式输出
  46. agent = MainAgent(llm, file_manager, streaming=True)
  47. except Exception as e:
  48. print(f"❌ 初始化失败:{e}")
  49. print("请检查配置文件(.env)和 API Key")
  50. return
  51. # 显示欢迎信息
  52. print_welcome()
  53. # REPL 循环
  54. while True:
  55. try:
  56. # 获取用户输入
  57. user_input = input("\n> ").strip()
  58. # 空输入跳过
  59. if not user_input:
  60. continue
  61. # 处理命令
  62. result = agent.process_command(user_input)
  63. # 检查是否退出
  64. if result == "EXIT":
  65. print_goodbye()
  66. logger.info("LearningAgent exited normally")
  67. break
  68. # 显示结果
  69. # 注意:如果 agent.streaming=True,流式输出已经打印到 stdout
  70. # 这里只打印非流式的结果(如帮助信息、错误消息等)
  71. if not agent.streaming:
  72. print(result)
  73. except KeyboardInterrupt:
  74. print("\n\n👋 操作已取消")
  75. continue
  76. except Exception as e:
  77. logger.error(f"Error in REPL: {e}", exc_info=True)
  78. print(f"❌ 发生错误:{e}")
  79. print("输入 /help 查看帮助,或 /exit 退出")
  80. if __name__ == "__main__":
  81. start_repl()