main.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import os
  2. import json
  3. import shutil
  4. from hello_agents import HelloAgentsLLM, SimpleAgent
  5. from agents.react_agent import NewReActAgent
  6. from agents.agent_prompts import PLAN_AGENT_PROMPT, ANALYSIS_AGENT_PROMPT, REPORT_AGENT_PROMPT
  7. from tools.data_exploration import create_data_exploration_registry
  8. from tools.data_analysis import create_data_analysis_registry
  9. if __name__ == "__main__":
  10. # 清空 out 目录
  11. if os.path.exists("out"):
  12. shutil.rmtree("out")
  13. os.makedirs("out", exist_ok=True)
  14. os.makedirs("out/figures", exist_ok=True)
  15. llm = HelloAgentsLLM()
  16. registry = create_data_exploration_registry()
  17. planning_agent = NewReActAgent(
  18. name="PlanningAgent",
  19. llm=llm,
  20. custom_prompt=PLAN_AGENT_PROMPT,
  21. tool_registry=registry,
  22. max_steps=5
  23. )
  24. question = "请开始分析"
  25. try:
  26. plan_result = planning_agent.run(question)
  27. print(f"任务规划: {plan_result}")
  28. except Exception as e:
  29. print(f"执行过程中出现错误: {e}")
  30. # 检查 plan_result 是否符合 python 列表格式
  31. if not isinstance(plan_result, list):
  32. print("错误:任务规划结果格式不正确,预期为Python列表。")
  33. exit(1)
  34. registry = create_data_analysis_registry()
  35. analysis_agent = NewReActAgent(
  36. name="AnalysisAgent",
  37. llm=llm,
  38. custom_prompt=ANALYSIS_AGENT_PROMPT,
  39. tool_registry=registry,
  40. max_steps=5
  41. )
  42. task_result = []
  43. for task in plan_result:
  44. print(f"执行任务: {task}")
  45. try:
  46. answer = analysis_agent.run(task)
  47. task_result.append({ "task": task, "result": answer })
  48. print(f"任务结果: {answer}")
  49. except Exception as e:
  50. print(f"执行过程中出现错误: {e}")
  51. print(f"\n所有任务结果: {task_result}")
  52. report_agent = SimpleAgent(
  53. name="ReportAgent",
  54. system_prompt=REPORT_AGENT_PROMPT,
  55. llm=llm,
  56. enable_tool_calling=False
  57. )
  58. final_result = report_agent.run(json.dumps(task_result, ensure_ascii=False))
  59. # 清理报告内容,确保以"# 执行摘要"开头
  60. if "# 执行摘要" in final_result:
  61. start_idx = final_result.find("# 执行摘要")
  62. final_result = final_result[start_idx:]
  63. print(f"\n最终分析报告: \n{final_result}")
  64. # 保存报告到文件
  65. os.makedirs("out", exist_ok=True)
  66. with open("out/analysis_report.md", "w", encoding="utf-8") as f:
  67. f.write(final_result)