fix(weather): fall back to met.no when the open-meteo forecast does not answer

Live 2026-11-18 the open-meteo forecast timed out three times (geocoding
worked) and every weather question ended in 'service unavailable'. The
forecast now waits 6s instead of 10s and then asks met.no (no key),
mapping its symbol to the WMO code the Korean sentence uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-18 01:59:49 +09:00
parent c51e5b2f68
commit 680d4fbdc1
2 changed files with 105 additions and 5 deletions

View File

@@ -190,6 +190,56 @@ WMO_CODES_KO = {
}
_OPEN_METEO_TIMEOUT_SEC = 6
_MET_NO_URL = "https://api.met.no/weatherapi/locationforecast/2.0/compact"
# met.no's terms ask for an identifying User-Agent; it names the app, nothing about the user.
_MET_NO_HEADERS = {"User-Agent": "jarvis-voice-assistant/2 github.com/isair/jarvis"}
def _met_no_wmo(symbol: str) -> Optional[int]:
"""The WMO code closest to a met.no symbol code ('lightrainshowers_night' -> 80)."""
s = (symbol or "").split("_")[0]
if "thunder" in s:
return 95
plain = {"clearsky": 0, "fair": 1, "partlycloudy": 2, "cloudy": 3, "fog": 45}
if s in plain:
return plain[s]
level = 0 if s.startswith("light") else 2 if s.startswith("heavy") else 1
showers = "showers" in s
if "snow" in s:
return (85, 85, 86)[level] if showers else (71, 73, 75)[level]
if "sleet" in s:
return (66, 66, 67)[level]
if "rain" in s:
return (80, 81, 82)[level] if showers else (61, 63, 65)[level]
return None
def _met_no_current(lat: float, lon: float) -> Dict[str, Any]:
"""Current conditions from met.no (no key) in open-meteo's 'current' keys; {} on failure."""
try:
resp = requests.get(_MET_NO_URL, params={"lat": round(lat, 4), "lon": round(lon, 4)},
headers=_MET_NO_HEADERS, timeout=_OPEN_METEO_TIMEOUT_SEC)
resp.raise_for_status()
now = ((resp.json() or {}).get("properties") or {}).get("timeseries") or []
data = now[0].get("data") or {} if now else {}
details = (data.get("instant") or {}).get("details") or {}
if details.get("air_temperature") is None:
return {}
symbol = ((data.get("next_1_hours") or {}).get("summary") or {}).get("symbol_code", "")
wind = details.get("wind_speed")
return {
"temperature_2m": details.get("air_temperature"),
"apparent_temperature": None,
"relative_humidity_2m": details.get("relative_humidity"),
"weather_code": _met_no_wmo(symbol),
"wind_speed_10m": round(wind * 3.6, 1) if wind is not None else None,
}
except Exception as e:
debug_log(f"met.no failed ({type(e).__name__})", "tools")
return {}
class WeatherTool(Tool):
"""Tool for getting current weather using Open-Meteo API."""
@@ -424,11 +474,15 @@ class WeatherTool(Tool):
"timezone": "auto"
}
weather_response = requests.get(weather_url, params=weather_params, timeout=10)
weather_response.raise_for_status()
weather_data = weather_response.json()
current = weather_data.get("current", {})
try:
weather_response = requests.get(weather_url, params=weather_params,
timeout=_OPEN_METEO_TIMEOUT_SEC)
weather_response.raise_for_status()
current = (weather_response.json() or {}).get("current", {})
except requests.exceptions.RequestException as e:
# Live 2026-11-18: the forecast server stopped answering while geocoding worked.
debug_log(f"open-meteo forecast failed ({type(e).__name__}); trying met.no", "tools")
current = _met_no_current(lat, lon)
if not current:
return ToolExecutionResult(
success=False,

View File

@@ -404,6 +404,52 @@ class TestWeatherTool:
kw in result.reply_text.lower() for kw in ("location", "city")
)
@patch('requests.get')
def test_when_open_meteo_does_not_answer_met_no_gives_the_weather(self, mock_get):
"""Live 2026-11-18: the open-meteo forecast timed out (geocoding had worked) and the
answer was that the weather service was unavailable."""
geo = Mock(status_code=200, raise_for_status=Mock())
geo.json.return_value = {"results": [{"latitude": 37.57, "longitude": 126.98,
"name": "서울", "country": "대한민국"}]}
met = Mock(status_code=200, raise_for_status=Mock())
met.json.return_value = {"properties": {"timeseries": [{"data": {
"instant": {"details": {"air_temperature": 8.6, "relative_humidity": 96.0,
"wind_speed": 2.2}},
"next_1_hours": {"summary": {"symbol_code": "lightrainshowers_night"}}}}]}}
def get(url, *a, **k):
if "geocoding" in url:
return geo
if "open-meteo" in url:
raise requests.exceptions.Timeout("timed out")
assert "met.no" in url
return met
mock_get.side_effect = get
result = self.tool.run({"location": "서울"}, self.context)
assert result.success is True
assert "서울" in result.reply_text
assert WMO_CODES_KO[80] in result.reply_text
assert str(round(8.6)) in result.reply_text
@patch('requests.get')
def test_when_both_weather_services_fail_the_answer_says_so(self, mock_get):
geo = Mock(status_code=200, raise_for_status=Mock())
geo.json.return_value = {"results": [{"latitude": 37.57, "longitude": 126.98,
"name": "서울", "country": "대한민국"}]}
def get(url, *a, **k):
if "geocoding" in url:
return geo
raise requests.exceptions.Timeout("timed out")
mock_get.side_effect = get
result = self.tool.run({"location": "서울"}, self.context)
assert result.success is False
assert "unavailable" in result.reply_text.lower()
@patch('requests.get')
def test_run_network_timeout(self, mock_get):
"""Test weather with network timeout."""