14_weather_agent.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """在 Agent 中使用天气 MCP 服务器"""
  2. import os
  3. from dotenv import load_dotenv
  4. from hello_agents import SimpleAgent, HelloAgentsLLM
  5. from hello_agents.tools import MCPTool
  6. load_dotenv()
  7. def create_weather_assistant():
  8. """创建天气助手"""
  9. llm = HelloAgentsLLM()
  10. assistant = SimpleAgent(
  11. name="天气助手",
  12. llm=llm,
  13. system_prompt="""你是天气助手,可以查询城市天气。
  14. 使用 get_weather 工具查询天气,支持中文城市名。
  15. """
  16. )
  17. # 添加天气 MCP 工具
  18. server_script = os.path.join(os.path.dirname(__file__), "14_weather_mcp_server.py")
  19. weather_tool = MCPTool(server_command=["python", server_script])
  20. assistant.add_tool(weather_tool)
  21. return assistant
  22. def demo():
  23. """演示"""
  24. assistant = create_weather_assistant()
  25. print("\n查询北京天气:")
  26. response = assistant.run("北京今天天气怎么样?")
  27. print(f"回答: {response}\n")
  28. def interactive():
  29. """交互模式"""
  30. assistant = create_weather_assistant()
  31. while True:
  32. user_input = input("\n你: ").strip()
  33. if user_input.lower() in ['quit', 'exit']:
  34. break
  35. response = assistant.run(user_input)
  36. print(f"助手: {response}")
  37. if __name__ == "__main__":
  38. import sys
  39. if len(sys.argv) > 1 and sys.argv[1] == "demo":
  40. demo()
  41. else:
  42. interactive()