diet_recommendation_final.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from hello_agents import SimpleAgent, HelloAgentsLLM
  2. from hello_agents.tools import MCPTool
  3. from dotenv import load_dotenv
  4. import os
  5. import json
  6. from datetime import datetime
  7. load_dotenv()
  8. os.makedirs("recipes", exist_ok=True)
  9. def parse_response(response):
  10. try:
  11. if "```json" in response:
  12. json_start = response.find("```json") + 7
  13. json_end = response.find("```", json_start)
  14. json_str = response[json_start:json_end].strip()
  15. elif "```" in response:
  16. json_start = response.find("```") + 3
  17. json_end = response.find("```", json_start)
  18. json_str = response[json_start:json_end].strip()
  19. elif "{" in response and "}" in response:
  20. json_start = response.find("{")
  21. json_end = response.rfind("}") + 1
  22. json_str = response[json_start:json_end]
  23. else:
  24. raise ValueError("响应中未找到JSON数据")
  25. data = json.loads(json_str)
  26. return data
  27. except Exception as e:
  28. print(f"⚠️ 解析响应失败: {str(e)}")
  29. return None
  30. def write_content_to_file(content):
  31. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # 例: 20260428_143022
  32. filename = f"recipes/recipes_{timestamp}.md"
  33. with open(filename, "w", encoding="utf-8") as wf:
  34. wf.write(content)
  35. print(f"✅ 菜谱已创建: {filename}")
  36. web_search_tool = MCPTool(name="web_research", server_command=["npx", "-y", "@mzxrai/mcp-webresearch@latest"])
  37. # ===================================== 菜谱搜索助手 =====================================
  38. caipu_search_agent = SimpleAgent(
  39. name="caipu_search_agent",
  40. llm=HelloAgentsLLM(),
  41. system_prompt="""
  42. 你是菜谱搜索专家。你的任务是根据用户的需求和用户偏好搜索合适的菜谱。
  43. **重要提示:**
  44. 你必须使用工具来搜索菜谱!不要自己编造菜谱信息!返回的内容至少包括菜名和菜谱链接!可以包括菜品特点,便于后续筛选!
  45. **工具调用格式:**
  46. 使用visit_page工具时,必须严格按照以下格式:
  47. `[TOOL_CALL:visit_page:url=https://www.xiangha.com/so/?q=caipu&s=菜谱]`
  48. `[TOOL_CALL:visit_page:url=https://www.xiangha.com/so/?q=caipu&s=食材]`
  49. **示例:**
  50. 用户: "搜索五花肉的做法"
  51. 你的回复: [TOOL_CALL:visit_page:url=https://www.xiangha.com/so/?q=caipu&s=五花肉]
  52. 用户: "搜索和鱼有关的菜谱"
  53. 你的回复: [TOOL_CALL:visit_page:url=https://www.xiangha.com/so/?q=caipu&s=鱼]
  54. **注意:**
  55. 1. 必须使用工具,不要直接回答
  56. 2. 格式必须完全正确,包括方括号和冒号
  57. 3. 参数用逗号分隔
  58. """
  59. )
  60. caipu_search_agent.add_tool(web_search_tool)
  61. def build_caipu_search_prompts(user_input):
  62. return f"调用visit_page工具, 用户需求: {user_input}"
  63. # ===================================== 饮食专家助手 =====================================
  64. caipu_select_agent = SimpleAgent(
  65. name="caipu_select_agent",
  66. llm=HelloAgentsLLM(),
  67. system_prompt="""
  68. 你是饮食专家。你的任务是根据用户需求和推荐的菜谱列表,为用户选择一个最合适的菜谱,并给出推荐理由。
  69. **重要提示:**
  70. 你必须从推荐的菜谱列表中选择,不能凭空产生新的菜名和菜谱链接。
  71. 请严格按照以下JSON格式返回推荐菜谱:
  72. ```json
  73. {
  74. "name": "红烧鲫鱼",
  75. "url": "https://www.xiangha.com/caipu/102880489.html",
  76. "reason": "**推荐理由:**
  77. - 🐟 **清蒸烹饪** - 最清淡的烹饪方式,少油少盐
  78. - 🔥 **适合降火** - 清蒸做法不辛辣、不油腻,不会加重上火症状
  79. - 💪 **营养丰富** - 石斑鱼富含优质蛋白,肉质细嫩鲜美
  80. "
  81. }
  82. ```
  83. 如果没有合适的推荐结果,请返回空的json数据,格式如下:
  84. ```json
  85. {
  86. }
  87. ```
  88. """
  89. )
  90. def build_caipu_select_prompts(user_input, caipu_list):
  91. return f"用户需求: {user_input},推荐的菜谱列表: {caipu_list}"
  92. # ===================================== 网页内容提取助手 =====================================
  93. output_agent = SimpleAgent(
  94. name="demand_analyzer",
  95. llm=HelloAgentsLLM(),
  96. system_prompt="""
  97. 你是网页内容提取专家。你的任务是根据用户选择的菜名和菜谱链接,返回最终完整的的菜谱。
  98. **重要提示:**
  99. 你必须使用工具来获取菜谱信息!不要自己编造菜谱信息!
  100. **工具调用格式:**
  101. 使用visit_page工具时,必须严格按照以下格式:
  102. `[TOOL_CALL:visit_page:url=菜谱链接]`
  103. **示例:**
  104. 用户: 菜名: 红烧鲫鱼,菜谱链接: https://www.xiangha.com/caipu/102880489.html
  105. 你的回复: [TOOL_CALL:visit_page:url=https://www.xiangha.com/caipu/102880489.html]
  106. **注意:**
  107. 1. 必须使用工具,不要直接回答
  108. 2. 格式必须完全正确,包括方括号和冒号
  109. 3. 参数用逗号分隔
  110. """
  111. )
  112. output_agent.add_tool(web_search_tool)
  113. def build_output_prompts(caipu_json):
  114. return f"菜名: {caipu_json['name']}, 菜谱链接: {caipu_json['url']}"
  115. # ===================================== 完整流程 =====================================
  116. user_input = input("请输入菜谱需求(例如:我想吃小龙虾) >>> ")
  117. print("\n\n正在搜索菜谱...")
  118. search_caipu_result = caipu_search_agent.run(build_caipu_search_prompts(user_input=user_input))
  119. print(search_caipu_result)
  120. print("\n\n正在筛选菜谱...")
  121. caipu_select_result = caipu_select_agent.run(build_caipu_select_prompts(user_input=user_input, caipu_list=search_caipu_result))
  122. print(caipu_select_result)
  123. print("\n\n正在解析结果...")
  124. caipu_select_json = parse_response(caipu_select_result)
  125. print(caipu_select_json)
  126. if caipu_select_json:
  127. print("\n\n正在生成菜谱...")
  128. output_result = output_agent.run(build_output_prompts(caipu_select_json))
  129. print("\n\n正在保存菜谱...")
  130. print(f"菜名: {caipu_select_json['name']}\n推荐理由: {caipu_select_json['reason']}")
  131. write_content_to_file(output_result)
  132. else:
  133. print("\n\n未找到合适的菜谱")