"""
Multi-day Weather Forecast Example
演示多日天氣預報功能
"""
import sys
from pathlib import Path
from datetime import datetime, timedelta
# Add src to path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
from weather_mcp import WeatherMCPClient, WeatherAgent
def example_1_tomorrow_weather():
"""範例 1:查詢明天的天氣"""
print("=" * 60)
print("範例 1:查詢明天東京的天氣")
print("=" * 60)
client = WeatherMCPClient()
# 計算明天日期
tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
print(f"明天日期:{tomorrow}\n")
# 查詢明天東京全天的天氣
result = client.get_city_weather(
city="Tokyo",
forecast_days=2, # 需要 2 天數據(今天 + 明天)
target_date=tomorrow # 指定明天日期
)
if "error" in result:
print(f"❌ 錯誤:{result['error']}")
return
# 取得天氣數據
weather = result.get("weather", {})
hourly = weather.get("hourly", {})
times = hourly.get("time", [])
temps = hourly.get("temperature_2m", [])
humidity = hourly.get("relative_humidity_2m", [])
rain_prob = hourly.get("precipitation_probability", [])
print(f"✅ 成功取得 {len(times)} 筆數據\n")
# 顯示早中晚的天氣
if len(times) >= 24:
print("明天天氣預報:")
print(f" 🌅 早上 (06:00): {temps[6]}°C, 濕度 {humidity[6]}%, 降雨 {rain_prob[6]}%")
print(f" ☀️ 中午 (12:00): {temps[12]}°C, 濕度 {humidity[12]}%, 降雨 {rain_prob[12]}%")
print(f" 🌙 晚上 (18:00): {temps[18]}°C, 濕度 {humidity[18]}%, 降雨 {rain_prob[18]}%")
print()
def example_2_week_forecast():
"""範例 2:查詢未來 7 天天氣"""
print("=" * 60)
print("範例 2:查詢未來 7 天倫敦的天氣")
print("=" * 60)
client = WeatherMCPClient()
# 查詢未來 7 天倫敦的天氣
result = client.get_city_weather(
city="London",
forecast_days=7, # 7 天預報
hours=24 # 取前 24 小時(向後兼容)
)
if "error" in result:
print(f"❌ 錯誤:{result['error']}")
return
weather = result.get("weather", {})
hourly = weather.get("hourly", {})
times = hourly.get("time", [])[:24]
temps = hourly.get("temperature_2m", [])[:24]
print(f"✅ 成功取得未來 7 天數據(顯示前 24 小時)\n")
# 顯示今天的最高最低溫
if temps:
max_temp = max(temps)
min_temp = min(temps)
avg_temp = sum(temps) / len(temps)
print(f"今天倫敦天氣:")
print(f" 🌡️ 最高溫:{max_temp}°C")
print(f" 🌡️ 最低溫:{min_temp}°C")
print(f" 📊 平均溫:{avg_temp:.1f}°C")
print()
def example_3_agent_natural_language():
"""範例 3:使用 Agent 自然語言查詢"""
print("=" * 60)
print("範例 3:使用 Agent 自然語言查詢天氣")
print("=" * 60)
import os
# 檢查 API key
if not os.getenv("GOOGLE_API_KEY"):
print("⚠️ 未設定 GOOGLE_API_KEY,跳過 Agent 範例")
print(" 請設定環境變數:export GOOGLE_API_KEY='your-key'")
print()
return
agent = WeatherAgent()
# Agent 會自動理解時間並計算日期
questions = [
"明天東京天氣如何?",
"未來 3 天台北的天氣",
]
for question in questions:
print(f"\n❓ 問題:{question}")
try:
answer = agent.ask_weather(question, verbose=False)
print(f"💬 回答:{answer}")
except Exception as e:
print(f"❌ 錯誤:{repr(e)}")
print()
def example_4_compare_cities():
"""範例 4:比較多個城市的天氣"""
print("=" * 60)
print("範例 4:比較多個城市明天的天氣")
print("=" * 60)
client = WeatherMCPClient()
tomorrow = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
cities = ["Tokyo", "London", "New York"]
print(f"比較日期:{tomorrow}\n")
for city in cities:
result = client.get_city_weather(
city=city,
forecast_days=2,
target_date=tomorrow
)
if "error" in result:
print(f" {city}: ❌ {result['error']}")
continue
weather = result.get("weather", {})
hourly = weather.get("hourly", {})
temps = hourly.get("temperature_2m", [])
if temps:
avg_temp = sum(temps) / len(temps)
max_temp = max(temps)
min_temp = min(temps)
print(f" {city:12} - 平均 {avg_temp:5.1f}°C (最高 {max_temp}°C, 最低 {min_temp}°C)")
print()
def main():
"""主程式"""
print("\n🌤️ 多日天氣預報功能演示\n")
# 自動載入 .env
try:
from dotenv import load_dotenv
env_path = Path(__file__).parent.parent / ".env"
if env_path.exists():
load_dotenv(env_path)
except ImportError:
pass
# 執行範例
example_1_tomorrow_weather()
example_2_week_forecast()
example_3_agent_natural_language()
example_4_compare_cities()
print("✅ 所有範例執行完畢!")
print("\n📚 更多資訊請參考:docs/MULTI_DAY_FORECAST.md")
if __name__ == "__main__":
main()