The source line (KMA, open-meteo or met.no for now; KMA and open-meteo day counts for a forecast) only went to debug_log, which is off by default and muted while the worker's brain answers, so a live answer such as "흐림" could not be traced to its service. It now goes to the llm log tab without the place or the key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
958 lines
46 KiB
Python
958 lines
46 KiB
Python
"""Weather tool: KMA inside Korea when the app gives a key, else Open-Meteo (no key), then met.no."""
|
|
|
|
import math
|
|
import os
|
|
from collections import Counter
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import requests
|
|
from typing import Dict, Any, Optional
|
|
from ...debug import debug_log, notice
|
|
from ...utils.location import get_location_info
|
|
from ..base import Tool, ToolContext
|
|
from ..types import ToolExecutionResult
|
|
|
|
|
|
# Sentinel strings an LLM extractor may emit to mean "no place mentioned".
|
|
# Matched case-insensitively as whole-value comparisons, not substrings.
|
|
_NO_PLACE_SENTINELS = frozenset({
|
|
"none", "null", "no", "no place", "no location",
|
|
"n/a", "na", "unknown", "unspecified",
|
|
})
|
|
|
|
|
|
def _extract_place_from_user_text(text: str, cfg) -> Optional[str]:
|
|
"""Ask a small LLM to pull a place name out of the user's utterance.
|
|
|
|
Used as a last-ditch fallback when the tool-calling LLM didn't fill the
|
|
``location`` argument AND GeoIP auto-detect is unavailable. Small chat
|
|
models (e.g. gemma4:e2b) regularly fail to propagate a city into tool
|
|
args even when the user literally just said one — pulling the place
|
|
straight from the user's text sidesteps that weakness so the user
|
|
doesn't have to keep repeating themselves.
|
|
|
|
Returns ``None`` when no place is named, the call fails, or the
|
|
extractor gives back something that doesn't look like a place.
|
|
"""
|
|
if not isinstance(text, str) or not text.strip():
|
|
return None
|
|
if cfg is None:
|
|
return None
|
|
|
|
model = (
|
|
getattr(cfg, "tool_router_model", "")
|
|
or getattr(cfg, "intent_judge_model", "")
|
|
or getattr(cfg, "ollama_chat_model", "")
|
|
)
|
|
base_url = getattr(cfg, "ollama_base_url", "")
|
|
if not model or not base_url:
|
|
return None
|
|
|
|
try:
|
|
from ...llm import call_llm_direct
|
|
except Exception:
|
|
return None
|
|
|
|
sys_prompt = (
|
|
"You extract a single place name from a user's utterance so a weather "
|
|
"tool can look it up. Reply with ONLY the place name (city, town, or "
|
|
"country), with no punctuation, quotes, or explanation. If the user "
|
|
"did not name any place, reply with exactly: none"
|
|
)
|
|
user_prompt = f"User utterance: {text}\n\nPlace:"
|
|
|
|
try:
|
|
resp = call_llm_direct(
|
|
base_url, model, sys_prompt, user_prompt,
|
|
timeout_sec=float(getattr(cfg, "llm_tools_timeout_sec", 8.0)),
|
|
)
|
|
except Exception as e:
|
|
debug_log(f" ⚠️ place extraction failed: {e}", "tools")
|
|
return None
|
|
|
|
if not resp or not isinstance(resp, str):
|
|
return None
|
|
|
|
# Strip punctuation and quotes the extractor might wrap around the name.
|
|
place = resp.strip().strip("'\"`*.,:;!?()[]{}<>").split("\n", 1)[0].strip()
|
|
if not place:
|
|
return None
|
|
if place.lower() in _NO_PLACE_SENTINELS:
|
|
return None
|
|
# Reject multi-sentence or overly long replies — those are almost always
|
|
# the model explaining ("the user did not name a place") instead of
|
|
# answering. Place names are at most a handful of words (e.g. "New York",
|
|
# "Stratford-upon-Avon", "São Paulo"), so 5 words is a generous cap.
|
|
if len(place) > 60 or "." in place or len(place.split()) > 5:
|
|
return None
|
|
return place
|
|
|
|
|
|
def _romanise_place(name: str, cfg) -> Optional[str]:
|
|
"""Romanise a non-Latin place name for the geocoder.
|
|
|
|
Open-Meteo's geocoding API only matches Latin/English spellings, so a
|
|
Korean (or other non-Latin) city name like ``서울`` returns zero results
|
|
even though the place plainly exists. When OUTPUT_LANGUAGE locks replies to
|
|
Korean the tool-calling model naturally fills ``location`` with the Korean
|
|
name, which would otherwise dead-end. Ask the (already warm) small model for
|
|
the common English exonym so geocoding can succeed on a retry.
|
|
|
|
Returns the romanised name, or ``None`` if it is unavailable, unchanged, or
|
|
doesn't look like a place.
|
|
"""
|
|
if not isinstance(name, str) or not name.strip() or name.isascii():
|
|
return None
|
|
if cfg is None:
|
|
return None
|
|
|
|
model = (
|
|
getattr(cfg, "tool_router_model", "")
|
|
or getattr(cfg, "intent_judge_model", "")
|
|
or getattr(cfg, "ollama_chat_model", "")
|
|
)
|
|
base_url = getattr(cfg, "ollama_base_url", "")
|
|
if not model or not base_url:
|
|
return None
|
|
|
|
try:
|
|
from ...llm import call_llm_direct
|
|
except Exception:
|
|
return None
|
|
|
|
sys_prompt = (
|
|
"You romanise place names for a geocoding API that only understands "
|
|
"English/Latin spellings. Reply with ONLY the common English name of "
|
|
"the place, no punctuation, quotes, or explanation. "
|
|
"Examples: 서울 -> Seoul, 도쿄 -> Tokyo, 뮌헨 -> Munich."
|
|
)
|
|
user_prompt = f"Place: {name}\n\nEnglish name:"
|
|
|
|
try:
|
|
resp = call_llm_direct(
|
|
base_url, model, sys_prompt, user_prompt,
|
|
timeout_sec=float(getattr(cfg, "llm_tools_timeout_sec", 8.0)),
|
|
)
|
|
except Exception as e:
|
|
debug_log(f" ⚠️ place romanisation failed: {e}", "tools")
|
|
return None
|
|
|
|
if not resp or not isinstance(resp, str):
|
|
return None
|
|
out = resp.strip().strip("'\"`*.,:;!?()[]{}<>").split("\n", 1)[0].strip()
|
|
if not out or out.lower() in _NO_PLACE_SENTINELS:
|
|
return None
|
|
if len(out) > 60 or len(out.split()) > 5 or out == name:
|
|
return None
|
|
return out
|
|
|
|
|
|
# WMO Weather interpretation codes
|
|
# https://open-meteo.com/en/docs
|
|
WMO_CODES = {
|
|
0: "Clear sky",
|
|
1: "Mainly clear",
|
|
2: "Partly cloudy",
|
|
3: "Overcast",
|
|
45: "Foggy",
|
|
48: "Depositing rime fog",
|
|
51: "Light drizzle",
|
|
53: "Moderate drizzle",
|
|
55: "Dense drizzle",
|
|
56: "Light freezing drizzle",
|
|
57: "Dense freezing drizzle",
|
|
61: "Slight rain",
|
|
63: "Moderate rain",
|
|
65: "Heavy rain",
|
|
66: "Light freezing rain",
|
|
67: "Heavy freezing rain",
|
|
# 68/69 and 83/84 (rain and snow mixed, i.e. sleet) are WMO 4677 codes open-meteo does not
|
|
# send; met.no's sleet maps to them.
|
|
68: "Slight sleet",
|
|
69: "Sleet",
|
|
71: "Slight snow",
|
|
73: "Moderate snow",
|
|
75: "Heavy snow",
|
|
77: "Snow grains",
|
|
80: "Slight rain showers",
|
|
81: "Moderate rain showers",
|
|
82: "Violent rain showers",
|
|
83: "Slight sleet showers",
|
|
84: "Sleet showers",
|
|
85: "Slight snow showers",
|
|
86: "Heavy snow showers",
|
|
95: "Thunderstorm",
|
|
96: "Thunderstorm with slight hail",
|
|
99: "Thunderstorm with heavy hail",
|
|
}
|
|
|
|
# Korean conditions for the concise spoken reply.
|
|
WMO_CODES_KO = {
|
|
0: "맑음", 1: "대체로 맑음", 2: "구름 조금", 3: "흐림",
|
|
45: "안개", 48: "서리 안개",
|
|
51: "약한 이슬비", 53: "이슬비", 55: "강한 이슬비",
|
|
56: "약한 어는 이슬비", 57: "강한 어는 이슬비",
|
|
61: "약한 비", 63: "비", 65: "강한 비",
|
|
66: "약한 어는 비", 67: "강한 어는 비", 68: "약한 진눈깨비", 69: "진눈깨비",
|
|
71: "약한 눈", 73: "눈", 75: "강한 눈", 77: "싸락눈",
|
|
80: "약한 소나기", 81: "소나기", 82: "강한 소나기", 83: "약한 진눈깨비 소나기", 84: "진눈깨비 소나기",
|
|
85: "약한 눈소나기", 86: "강한 눈소나기",
|
|
95: "천둥번개", 96: "우박 동반 천둥번개", 99: "강한 우박 천둥번개",
|
|
}
|
|
|
|
|
|
_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"}
|
|
|
|
|
|
# OpenStreetMap's place search: any language, down to districts (부산 연제구), which open-meteo's
|
|
# geocoder (cities, Latin spellings) does not know. Its policy asks for an identifying User-Agent.
|
|
_NOMINATIM_URL = "https://nominatim.openstreetmap.org/search"
|
|
|
|
|
|
def _osm_place(name: str) -> Optional[Dict[str, Any]]:
|
|
"""The place OpenStreetMap finds for a name: {'lat', 'lon', 'country_code'}; None if none or on failure."""
|
|
try:
|
|
resp = requests.get(_NOMINATIM_URL, headers=_MET_NO_HEADERS, timeout=_OPEN_METEO_TIMEOUT_SEC,
|
|
params={"q": name, "format": "jsonv2", "limit": 1, "addressdetails": 1})
|
|
resp.raise_for_status()
|
|
found = resp.json()
|
|
if not isinstance(found, list) or not found:
|
|
return None
|
|
place = found[0]
|
|
code = ((place.get("address") or {}).get("country_code") or "").upper() or None
|
|
return {"lat": float(place["lat"]), "lon": float(place["lon"]), "country_code": code}
|
|
except Exception as e:
|
|
debug_log(f" ⚠️ OpenStreetMap place search failed ({type(e).__name__})", "tools")
|
|
return None
|
|
|
|
|
|
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 (83, 84, 84)[level] if showers else (68, 69, 69)[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 {}
|
|
|
|
|
|
# KMA (기상청 API허브): current weather inside Korea when the app gives a key (admin.spec.md).
|
|
KMA_KEY_ENV = "JARVIS_KMA_API_KEY"
|
|
_KMA_API = "https://apihub.kma.go.kr/api/typ02/openApi/"
|
|
_KMA_URL = _KMA_API + "VilageFcstInfoService_2.0/"
|
|
_KMA_MID_URL = _KMA_API + "MidFcstInfoService/"
|
|
_KMA_TIMEOUT_SEC = 5
|
|
_KST = timezone(timedelta(hours=9))
|
|
# KMA's own words: PTY (precipitation type, 0 = none) wins over SKY (sky state).
|
|
# 4 (소나기) is in 단기예보 only, 5 to 7 in 초단기실황/초단기예보 only.
|
|
_KMA_PTY_KO = {1: "비", 2: "비나 눈", 3: "눈", 4: "소나기", 5: "빗방울", 6: "빗방울과 눈날림", 7: "눈날림"}
|
|
_KMA_PTY_WMO = {1: 63, 2: 69, 3: 73, 4: 81, 5: 51, 6: 68, 7: 71}
|
|
_KMA_SKY_KO = {1: "맑음", 3: "구름 많음", 4: "흐림"}
|
|
_KMA_SKY_WMO = {1: 0, 3: 2, 4: 3}
|
|
_kma_key = ""
|
|
# 중기예보 places: (getMidTa city, lat, lon); getMidLandFcst's region comes from the city's code.
|
|
# Every code checked live against KMA on 2026-11-18.
|
|
_KMA_MID_CITIES = (
|
|
("11B10101", 37.5665, 126.9780), ("11B20201", 37.4563, 126.7052), ("11B20601", 37.2636, 127.0286),
|
|
("11B20305", 37.7599, 126.7800), ("11B20701", 37.2720, 127.4350), ("11B20606", 36.9921, 127.1129),
|
|
("11D10301", 37.8813, 127.7298), ("11D10401", 37.3422, 127.9202), ("11D20501", 37.7519, 128.8761),
|
|
("11D20401", 38.2070, 128.5918), ("11C20401", 36.3504, 127.3845), ("11C20404", 36.4800, 127.2890),
|
|
("11C20104", 36.6013, 126.6608), ("11C20101", 36.7845, 126.4503), ("11C20301", 36.8151, 127.1139),
|
|
("11C10301", 36.6424, 127.4890), ("11C10101", 36.9910, 127.9259), ("11F10201", 35.8242, 127.1480),
|
|
("21F10501", 35.9676, 126.7369), ("11F20501", 35.1595, 126.8526), ("21F20801", 34.8118, 126.3922),
|
|
("11F20401", 34.7604, 127.6622), ("11F20405", 34.9507, 127.4872), ("11H10701", 35.8714, 128.6014),
|
|
("11H10501", 36.5684, 128.7294), ("11H10201", 36.0190, 129.3435), ("11H20201", 35.1796, 129.0756),
|
|
("11H20101", 35.5384, 129.3114), ("11H20301", 35.2280, 128.6811), ("11H20701", 35.1800, 128.1076),
|
|
("11G00201", 33.4996, 126.5312), ("11G00401", 33.2541, 126.5600),
|
|
)
|
|
_KMA_MID_REGIONS = {"11B": "11B00000", "11D1": "11D10000", "11D2": "11D20000", "11C1": "11C10000",
|
|
"11C2": "11C20000", "11F1": "11F10000", "11F2": "11F20000", "11H1": "11H10000",
|
|
"11H2": "11H20000", "11G": "11G00000"}
|
|
# A forecast goes this many days ahead (KMA 중기예보's last day).
|
|
MAX_DAYS_AHEAD = 10
|
|
_WEEKDAYS_KO = "월화수목금토일"
|
|
_DAY_NAMES_KO = {0: "오늘", 1: "내일", 2: "모레"}
|
|
|
|
|
|
def _now() -> datetime:
|
|
return datetime.now(_KST)
|
|
|
|
|
|
def take_kma_key() -> None:
|
|
"""Keep the app's KMA key here and take it out of the environment, so no child process
|
|
(MCP servers, MeloTTS) inherits it. Without a call the environment is read on each request."""
|
|
global _kma_key
|
|
_kma_key = os.environ.pop(KMA_KEY_ENV, "").strip()
|
|
|
|
|
|
def _kma_key_now() -> str:
|
|
return _kma_key or os.environ.get(KMA_KEY_ENV, "").strip()
|
|
|
|
|
|
def _kma_grid(lat: float, lon: float) -> tuple:
|
|
"""KMA's 5 km forecast grid point (nx, ny) for a place (the Lambert conformal conic of KMA's guide)."""
|
|
re_, grid = 6371.00877 / 5.0, math.radians(1)
|
|
slat1, slat2, olon, olat = 30 * grid, 60 * grid, 126 * grid, 38 * grid
|
|
sn = math.log(math.cos(slat1) / math.cos(slat2)) / math.log(
|
|
math.tan(math.pi / 4 + slat2 / 2) / math.tan(math.pi / 4 + slat1 / 2))
|
|
sf = math.tan(math.pi / 4 + slat1 / 2) ** sn * math.cos(slat1) / sn
|
|
ro = re_ * sf / math.tan(math.pi / 4 + olat / 2) ** sn
|
|
ra = re_ * sf / math.tan(math.pi / 4 + lat * grid / 2) ** sn
|
|
theta = lon * grid - olon
|
|
theta = (theta + math.pi) % (2 * math.pi) - math.pi
|
|
theta *= sn
|
|
return int(ra * math.sin(theta) + 43 + 0.5), int(ro - ra * math.cos(theta) + 136 + 0.5)
|
|
|
|
|
|
def _kma_get(url: str, key: str, params: Dict[str, Any]) -> list:
|
|
"""One KMA call's items; raises on any failure. The key is in the URL: never log the error text."""
|
|
resp = requests.get(url, timeout=_KMA_TIMEOUT_SEC, params={
|
|
"pageNo": 1, "numOfRows": 100, "dataType": "JSON", **params, "authKey": key})
|
|
resp.raise_for_status()
|
|
body = (resp.json() or {}).get("response") or {}
|
|
code = (body.get("header") or {}).get("resultCode")
|
|
if code != "00":
|
|
raise ValueError(f"KMA result code {code}")
|
|
return ((body.get("body") or {}).get("items") or {}).get("item") or []
|
|
|
|
|
|
def _kma_items(service: str, key: str, base: datetime, nx: int, ny: int, rows: int = 100) -> list:
|
|
return _kma_get(_KMA_URL + service, key, {"numOfRows": rows, "base_date": base.strftime("%Y%m%d"),
|
|
"base_time": base.strftime("%H%M"), "nx": nx, "ny": ny})
|
|
|
|
|
|
def _kma_failed(what: str, e: Exception) -> None:
|
|
why = str(e) if isinstance(e, (ValueError, KeyError)) else type(e).__name__
|
|
debug_log(f"KMA {what} failed ({why}); using open-meteo", "tools")
|
|
|
|
|
|
def _kma_half(cats: Dict[str, Dict[str, str]], pm: bool) -> Optional[str]:
|
|
"""Half a day's weather from 단기예보's hours: the commonest precipitation if any, else the commonest
|
|
(on a tie the cloudier) sky. None when the forecast has no hour of that half left."""
|
|
times = [t for t in cats.get("SKY", {}) if (t >= "1200") == pm]
|
|
if not times:
|
|
return None
|
|
wet = [p for p in (int(float(cats.get("PTY", {}).get(t, 0))) for t in times) if p in _KMA_PTY_KO]
|
|
if wet:
|
|
return _KMA_PTY_KO[Counter(wet).most_common(1)[0][0]]
|
|
skies = Counter(int(float(cats["SKY"][t])) for t in times)
|
|
return _KMA_SKY_KO.get(max(skies, key=lambda v: (skies[v], v)))
|
|
|
|
|
|
def _kma_short_days(lat: float, lon: float, key: str, now: datetime, offsets: list) -> Dict[int, Dict[str, Any]]:
|
|
"""단기예보 (out about 10 minutes after 02, 05, ..., 23 h) for the days it covers: today to 3 days ahead."""
|
|
t = now - timedelta(minutes=15)
|
|
hours = [h for h in (2, 5, 8, 11, 14, 17, 20, 23) if h <= t.hour]
|
|
base = (t.replace(hour=hours[-1]) if hours else (t - timedelta(days=1)).replace(hour=23)).replace(
|
|
minute=0, second=0, microsecond=0)
|
|
nx, ny = _kma_grid(lat, lon)
|
|
by_date: Dict[str, Dict[str, Dict[str, str]]] = {}
|
|
for i in _kma_items("getVilageFcst", key, base, nx, ny, rows=1500):
|
|
by_date.setdefault(i.get("fcstDate"), {}).setdefault(i.get("category"), {})[i.get("fcstTime")] = i.get("fcstValue")
|
|
out = {}
|
|
for off in offsets:
|
|
date = now.date() + timedelta(days=off)
|
|
cats = by_date.get(date.strftime("%Y%m%d")) or {}
|
|
if not (cats.get("TMN") or cats.get("TMX")): # a day the forecast does not (fully) cover
|
|
continue
|
|
temps = [float(v) for v in cats.get("TMP", {}).values()]
|
|
lo = float(next(iter(cats["TMN"].values()))) if cats.get("TMN") else min(temps, default=None)
|
|
hi = float(next(iter(cats["TMX"].values()))) if cats.get("TMX") else max(temps, default=None)
|
|
reh = [float(v) for v in cats.get("REH", {}).values()]
|
|
out[off] = {"date": date, "am": _kma_half(cats, False), "pm": _kma_half(cats, True), "min": lo,
|
|
"max": hi, "pop": max((int(float(v)) for v in cats.get("POP", {}).values()), default=None),
|
|
"humidity": sum(reh) / len(reh) if reh else None,
|
|
"wind_ms": max((float(v) for v in cats.get("WSD", {}).values()), default=None)}
|
|
return out
|
|
|
|
|
|
def _kma_mid_days(lat: float, lon: float, key: str, now: datetime, offsets: list) -> Dict[int, Dict[str, Any]]:
|
|
"""중기예보 (out about 30 minutes after 06 and 18 h) for the nearest KMA city and its region; its days
|
|
are counted from the day it came out, up to 10 days ahead."""
|
|
t = now - timedelta(minutes=30)
|
|
base = (t.replace(hour=18) if t.hour >= 18 else t.replace(hour=6) if t.hour >= 6
|
|
else (t - timedelta(days=1)).replace(hour=18)).replace(minute=0, second=0, microsecond=0)
|
|
city = min(_KMA_MID_CITIES, key=lambda c: (c[1] - lat) ** 2 + ((c[2] - lon) * math.cos(math.radians(lat))) ** 2)[0]
|
|
region = _KMA_MID_REGIONS.get(city[:3]) or _KMA_MID_REGIONS["11" + city[2:4]]
|
|
tm_fc = base.strftime("%Y%m%d%H%M")
|
|
ta = _kma_get(_KMA_MID_URL + "getMidTa", key, {"regId": city, "tmFc": tm_fc})[0]
|
|
land = _kma_get(_KMA_MID_URL + "getMidLandFcst", key, {"regId": region, "tmFc": tm_fc})[0]
|
|
out = {}
|
|
for off in offsets:
|
|
date = now.date() + timedelta(days=off)
|
|
n = (date - base.date()).days
|
|
am = land.get(f"wf{n}Am") or land.get(f"wf{n}")
|
|
pops = [p for p in (land.get(f"rnSt{n}Am"), land.get(f"rnSt{n}Pm"), land.get(f"rnSt{n}")) if p is not None]
|
|
if am is None and ta.get(f"taMax{n}") is None:
|
|
continue
|
|
out[off] = {"date": date, "am": am, "pm": land.get(f"wf{n}Pm") or am, "min": ta.get(f"taMin{n}"),
|
|
"max": ta.get(f"taMax{n}"), "pop": max(pops) if pops else None}
|
|
return out
|
|
|
|
|
|
def _kma_days(lat: float, lon: float, key: str, offsets: list) -> Dict[int, Dict[str, Any]]:
|
|
"""KMA's forecast for each day it has: 단기예보 first, 중기예보 for the rest; {} on failure."""
|
|
now = _now().astimezone(_KST)
|
|
out: Dict[int, Dict[str, Any]] = {}
|
|
if any(off <= 3 for off in offsets):
|
|
try:
|
|
out.update(_kma_short_days(lat, lon, key, now, offsets))
|
|
except Exception as e:
|
|
_kma_failed("short-term forecast", e)
|
|
rest = [off for off in offsets if off not in out]
|
|
if any(off >= 3 for off in rest):
|
|
try:
|
|
out.update(_kma_mid_days(lat, lon, key, now, rest))
|
|
except Exception as e:
|
|
_kma_failed("mid-term forecast", e)
|
|
return out
|
|
|
|
|
|
def _open_meteo_days(lat: float, lon: float, offsets: list) -> Dict[int, Dict[str, Any]]:
|
|
"""open-meteo's daily forecast (the place's own days) for the given days; {} on failure."""
|
|
try:
|
|
resp = requests.get("https://api.open-meteo.com/v1/forecast", timeout=_OPEN_METEO_TIMEOUT_SEC, params={
|
|
"latitude": lat, "longitude": lon, "timezone": "auto", "forecast_days": max(offsets) + 1,
|
|
"daily": "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,"
|
|
"wind_speed_10m_max,precipitation_sum"})
|
|
resp.raise_for_status()
|
|
daily = (resp.json() or {}).get("daily") or {}
|
|
except Exception as e:
|
|
debug_log(f"open-meteo daily forecast failed ({type(e).__name__})", "tools")
|
|
return {}
|
|
|
|
def at(name: str, off: int):
|
|
values = daily.get(name) or []
|
|
return values[off] if off < len(values) else None
|
|
|
|
out = {}
|
|
for off in offsets:
|
|
code, date = at("weather_code", off), at("time", off)
|
|
if date is None or (code is None and at("temperature_2m_max", off) is None):
|
|
continue
|
|
ko = WMO_CODES_KO.get(code) if code is not None else None
|
|
out[off] = {"date": datetime.fromisoformat(date).date(), "am": ko, "pm": ko,
|
|
"min": at("temperature_2m_min", off), "max": at("temperature_2m_max", off),
|
|
"pop": at("precipitation_probability_max", off),
|
|
"wind_ms": _ms(at("wind_speed_10m_max", off)), "rain_mm": at("precipitation_sum", off)}
|
|
return out
|
|
|
|
|
|
def _ms(kmh: Optional[float]) -> Optional[float]:
|
|
return kmh / 3.6 if kmh is not None else None
|
|
|
|
|
|
def _detail_parts(humidity, wind_ms, rain_mm, wind_word: str, rain_word: str) -> list:
|
|
"""습도 / 바람 / 강수량 for an answer asked in detail; a dry spell's 0 mm is left out."""
|
|
parts = []
|
|
if humidity is not None:
|
|
parts.append(f"습도 {round(float(humidity))}%")
|
|
if wind_ms is not None:
|
|
parts.append(f"{wind_word} 초속 {round(float(wind_ms), 1):g}미터")
|
|
if rain_mm is not None and float(rain_mm) > 0:
|
|
parts.append(f"{rain_word} {round(float(rain_mm), 1):g}mm")
|
|
return parts
|
|
|
|
|
|
def _weekday_offsets() -> str:
|
|
"""The days_ahead of each coming weekday, so the model need not count them (a small model
|
|
counted 'this weekend' from a Wednesday as 2)."""
|
|
today = datetime.now()
|
|
days = ", ".join(f"{(today + timedelta(days=n)).strftime('%A')} {n}" for n in range(1, 8))
|
|
return f"From today, {today.strftime('%A')}: {days}."
|
|
|
|
|
|
def _day_span(args: Optional[Dict[str, Any]]) -> tuple:
|
|
"""(first, last) day asked for, counted from today: (0, 0) is the weather now."""
|
|
def num(name: str, default: int) -> int:
|
|
try:
|
|
return int(float((args or {}).get(name)))
|
|
except (TypeError, ValueError):
|
|
return default
|
|
first = min(max(num("days_ahead", 0), 0), MAX_DAYS_AHEAD)
|
|
return first, min(first + max(num("days", 1), 1) - 1, MAX_DAYS_AHEAD)
|
|
|
|
|
|
def _day_sentence(off: int, day: Dict[str, Any], place: str, detail: bool = False) -> str:
|
|
"""'내일(11월 19일 목요일) 서울 날씨는 오전 맑음, 오후 비, 최저 -1도, 최고 4도, 강수확률 60%입니다.'"""
|
|
d = day["date"]
|
|
when = f"{d.month}월 {d.day}일 {_WEEKDAYS_KO[d.weekday()]}요일"
|
|
if off in _DAY_NAMES_KO:
|
|
when = f"{_DAY_NAMES_KO[off]}({when})"
|
|
am, pm = day.get("am"), day.get("pm")
|
|
parts = [f"오전 {am}, 오후 {pm}" if am and pm and am != pm else am or pm]
|
|
if day.get("min") is not None:
|
|
parts.append(f"최저 {round(float(day['min']))}도")
|
|
if day.get("max") is not None:
|
|
parts.append(f"최고 {round(float(day['max']))}도")
|
|
if day.get("pop") is not None:
|
|
parts.append(f"강수확률 {round(float(day['pop']))}%")
|
|
if detail:
|
|
parts += _detail_parts(day.get("humidity"), day.get("wind_ms"), day.get("rain_mm"), "최대 바람", "강수량")
|
|
return f"{when} {place} 날씨는 " + ", ".join(p for p in parts if p) + "입니다."
|
|
|
|
|
|
def _kma_current(lat: float, lon: float, key: str, now: Optional[datetime] = None) -> Dict[str, Any]:
|
|
"""Current weather from KMA in open-meteo's 'current' keys plus 'condition_ko'; {} on failure.
|
|
|
|
초단기실황 (each hour's observation, out at about :40) gives the temperature, humidity, wind and
|
|
precipitation; it has no sky state, so 초단기예보 (out at about :45) gives the coming hour's SKY.
|
|
"""
|
|
now = (now or datetime.now(_KST)).astimezone(_KST)
|
|
nx, ny = _kma_grid(lat, lon)
|
|
try:
|
|
obs_base = (now - timedelta(minutes=40)).replace(minute=0, second=0, microsecond=0)
|
|
obs = {i.get("category"): i.get("obsrValue") for i in _kma_items("getUltraSrtNcst", key, obs_base, nx, ny)}
|
|
fc_base = (now - timedelta(minutes=45)).replace(minute=30, second=0, microsecond=0)
|
|
sky = sorted((i.get("fcstDate", "") + i.get("fcstTime", ""), i.get("fcstValue"))
|
|
for i in _kma_items("getUltraSrtFcst", key, fc_base, nx, ny) if i.get("category") == "SKY")
|
|
temp, pty, sky_v = float(obs["T1H"]), int(float(obs.get("PTY") or 0)), int(sky[0][1]) if sky else None
|
|
if pty in _KMA_PTY_KO:
|
|
ko, wmo = _KMA_PTY_KO[pty], _KMA_PTY_WMO[pty]
|
|
elif sky_v in _KMA_SKY_KO:
|
|
ko, wmo = _KMA_SKY_KO[sky_v], _KMA_SKY_WMO[sky_v]
|
|
else:
|
|
raise ValueError("KMA gave no sky state")
|
|
wind = obs.get("WSD")
|
|
return {
|
|
"temperature_2m": temp,
|
|
"apparent_temperature": None,
|
|
"relative_humidity_2m": float(obs["REH"]) if obs.get("REH") is not None else None,
|
|
"weather_code": wmo,
|
|
"condition_ko": ko,
|
|
"wind_speed_10m": round(float(wind) * 3.6, 1) if wind is not None else None,
|
|
"precipitation": float(obs["RN1"]) if obs.get("RN1") is not None else None,
|
|
}
|
|
except Exception as e:
|
|
why = str(e) if isinstance(e, (ValueError, KeyError)) else type(e).__name__
|
|
debug_log(f"KMA failed ({why}); using open-meteo", "tools")
|
|
return {}
|
|
|
|
|
|
class WeatherTool(Tool):
|
|
"""Tool for getting current weather using Open-Meteo API."""
|
|
|
|
@property
|
|
def name(self) -> str:
|
|
return "getWeather"
|
|
|
|
@property
|
|
def description(self) -> str:
|
|
return (
|
|
"Weather only (current + forecast). NOT for time-of-day, date, or "
|
|
"location questions — those are already in the assistant's context. "
|
|
"Use for ANY weather question: now, later today, tomorrow, this week. "
|
|
"For another day set days_ahead, the days from today's date in the "
|
|
"context to that day (tomorrow 1, up to 10), and days for more than one "
|
|
"day: a weekend is days_ahead to the coming Saturday with days 2, a week "
|
|
"is days 7. "
|
|
"Set location to the place the user asked about. If they named none, "
|
|
"set it to where the user has said they are, from the conversation or "
|
|
"what you remember about them. Otherwise leave it empty: the tool "
|
|
"auto-detects the user's location (do not copy the detected location "
|
|
"into it). Do NOT ask the user where they are; just call this tool."
|
|
)
|
|
|
|
@property
|
|
def inputSchema(self) -> Dict[str, Any]:
|
|
return {
|
|
"type": "object",
|
|
"properties": {
|
|
"location": {
|
|
"type": "string",
|
|
"description": "City name or location (e.g., 'London', 'New York', 'Tokyo'): the place the user asked about, or else where the user has said they are (the conversation or your memory of them). Omit otherwise; the tool then auto-detects the user's location. Never ask the user for this argument."
|
|
},
|
|
"days_ahead": {
|
|
"type": "integer",
|
|
"description": "Days from today to the day asked about: omit or 0 for now, 1 for tomorrow, 2 for the day after, up to 10. " + _weekday_offsets()
|
|
},
|
|
"days": {
|
|
"type": "integer",
|
|
"description": "How many days from days_ahead on (default 1): 2 for a weekend (Saturday and Sunday), 7 for a week."
|
|
},
|
|
"detail": {
|
|
"type": "boolean",
|
|
"description": "true only when the user asks for more detail: the answer then also has the humidity, the wind and the rain amount."
|
|
}
|
|
},
|
|
"required": []
|
|
}
|
|
|
|
def _get_user_location(self, context: ToolContext) -> Optional[Dict[str, Any]]:
|
|
"""Get user's current location from config/auto-detection.
|
|
|
|
Returns dict with 'lat', 'lon', and 'display_name' keys, or None if unavailable.
|
|
"""
|
|
try:
|
|
location_info = get_location_info(
|
|
config_ip=getattr(context.cfg, 'location_ip_address', None),
|
|
auto_detect=getattr(context.cfg, 'location_auto_detect', True),
|
|
resolve_cgnat_public_ip=getattr(context.cfg, 'location_cgnat_resolve_public_ip', True),
|
|
location_cache_minutes=getattr(context.cfg, 'location_cache_minutes', 60),
|
|
)
|
|
|
|
if "error" in location_info:
|
|
debug_log(f" ⚠️ location detection failed: {location_info.get('error')}", "tools")
|
|
return None
|
|
|
|
# Use coordinates directly (avoids geocoding issues with district names)
|
|
lat = location_info.get("latitude")
|
|
lon = location_info.get("longitude")
|
|
if lat is None or lon is None:
|
|
return None
|
|
|
|
# Build display name from available fields (handle None values)
|
|
city = location_info.get("city") or ""
|
|
region = location_info.get("region") or ""
|
|
country = location_info.get("country") or ""
|
|
|
|
# Prefer city, but fall back to region if city is a district
|
|
display_parts = []
|
|
if city:
|
|
display_parts.append(city)
|
|
if region and region != city:
|
|
display_parts.append(region)
|
|
if country:
|
|
display_parts.append(country)
|
|
|
|
display_name = ", ".join(display_parts) if display_parts else "your location"
|
|
|
|
return {"lat": lat, "lon": lon, "display_name": display_name,
|
|
"country_code": location_info.get("country_code")}
|
|
except Exception as e:
|
|
debug_log(f" ⚠️ location detection error: {e}", "tools")
|
|
return None
|
|
|
|
@staticmethod
|
|
def _forecast_lines(lat: float, lon: float, country_code: Optional[str], first: int, last: int,
|
|
location_display: str, detail: bool = False) -> list:
|
|
"""A sentence for each day from first to last that a forecast has: KMA inside Korea with the
|
|
app's key, open-meteo for the days KMA does not give."""
|
|
offsets = list(range(first, last + 1))
|
|
days: Dict[int, Dict[str, Any]] = {}
|
|
kma_key = _kma_key_now()
|
|
if kma_key and country_code == "KR":
|
|
days = _kma_days(lat, lon, kma_key, offsets)
|
|
from_kma = len(days)
|
|
rest = [off for off in offsets if off not in days]
|
|
if rest:
|
|
days.update(_open_meteo_days(lat, lon, rest))
|
|
# Which service gave the answer, in the app's log (no place: it comes from the question).
|
|
notice(f"weather days {first}-{last}: {from_kma} from KMA, {len(days) - from_kma} from open-meteo", "llm")
|
|
place = location_display.split(",")[0].strip() or location_display
|
|
return [_day_sentence(off, days[off], place, detail) for off in offsets if off in days]
|
|
|
|
def run(self, args: Optional[Dict[str, Any]], context: ToolContext) -> ToolExecutionResult:
|
|
"""Get the weather now, or the forecast for the days asked about, for a location."""
|
|
context.user_print("🌤️ Checking weather...")
|
|
|
|
try:
|
|
# Get location from args, or fall back to user's detected location
|
|
location_str = ""
|
|
if args and isinstance(args, dict):
|
|
raw_location = args.get("location")
|
|
# Handle None values (LLM may pass location: null/None)
|
|
location_str = str(raw_location).strip() if raw_location else ""
|
|
|
|
# Determine coordinates and display name
|
|
lat: Optional[float] = None
|
|
lon: Optional[float] = None
|
|
location_display: str = ""
|
|
country_code: Optional[str] = None
|
|
|
|
# Track whether we inferred the place name from the user's text
|
|
# rather than receiving it from the caller — used only for the
|
|
# debug log, doesn't change behaviour downstream.
|
|
place_from_fallback = False
|
|
|
|
set_place = getattr(getattr(context, "cfg", None), "location_name", None)
|
|
set_place = set_place.strip() if isinstance(set_place, str) else ""
|
|
if not location_str and set_place:
|
|
# No place asked for: the place the user set in the settings (location.spec.md).
|
|
location_str = set_place
|
|
debug_log(" 📍 using the location set in the settings", "tools")
|
|
|
|
if not location_str:
|
|
# No location provided - try auto-detected coordinates first.
|
|
user_loc = self._get_user_location(context)
|
|
if user_loc:
|
|
lat = user_loc["lat"]
|
|
lon = user_loc["lon"]
|
|
location_display = user_loc["display_name"]
|
|
country_code = user_loc.get("country_code")
|
|
debug_log(
|
|
f" 📍 using detected location: {location_display} ({lat}, {lon})",
|
|
"tools",
|
|
)
|
|
else:
|
|
# Auto-detect failed. Last resort: scrape a place name from
|
|
# the user's current utterance. Small tool-calling models
|
|
# often drop the city from tool args even when the user
|
|
# just said one, so doing this on the tool side stops the
|
|
# "I need it for London" → "please tell me which city"
|
|
# ping-pong loop.
|
|
user_text = getattr(context, "redacted_text", "") or ""
|
|
cfg = getattr(context, "cfg", None)
|
|
extracted = _extract_place_from_user_text(user_text, cfg)
|
|
if extracted:
|
|
debug_log(
|
|
f" 📍 auto-detect unavailable; extracted place from user text: '{extracted}'",
|
|
"tools",
|
|
)
|
|
location_str = extracted
|
|
place_from_fallback = True
|
|
else:
|
|
# Auto-detect genuinely failed and the user didn't name
|
|
# a place in this utterance. Asking is the right move.
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text=(
|
|
"I couldn't auto-detect your location. "
|
|
"Please tell me which city to check the weather for."
|
|
),
|
|
)
|
|
|
|
if location_str:
|
|
# User specified a location (or we pulled one from their text) — geocode it.
|
|
debug_log(
|
|
f" 🌤️ geocoding location: '{location_str}'"
|
|
+ (" (from user text fallback)" if place_from_fallback else ""),
|
|
"tools",
|
|
)
|
|
|
|
geocode_url = "https://geocoding-api.open-meteo.com/v1/search"
|
|
# Intentionally English — tool results are processed by the LLM,
|
|
# not shown to the user. All models handle English data well.
|
|
geocode_params = {
|
|
"name": location_str,
|
|
"count": 1,
|
|
"language": "en",
|
|
"format": "json"
|
|
}
|
|
|
|
# Open-Meteo knows cities only, in Latin spellings, and matches a
|
|
# non-Latin name loosely (live 2026-11-18: "부산" gave a village
|
|
# called Pusan 140 km away). A non-Latin name, and a Latin one
|
|
# open-meteo does not know (a district), is looked up on
|
|
# OpenStreetMap in the words the user used.
|
|
geo_data: Dict[str, Any] = {}
|
|
if location_str.isascii():
|
|
geo_response = requests.get(geocode_url, params=geocode_params, timeout=10)
|
|
geo_response.raise_for_status()
|
|
geo_data = geo_response.json()
|
|
osm = None if geo_data.get("results") else _osm_place(location_str)
|
|
if osm:
|
|
debug_log(" 📍 found on OpenStreetMap", "tools")
|
|
geo_data = {"results": [{"latitude": osm["lat"], "longitude": osm["lon"],
|
|
"name": location_str, "country_code": osm["country_code"]}]}
|
|
|
|
# Not on OpenStreetMap either (or it failed): retry open-meteo
|
|
# once with an LLM-romanised name before giving up.
|
|
if not geo_data.get("results"):
|
|
romanised = _romanise_place(location_str, getattr(context, "cfg", None))
|
|
if romanised:
|
|
debug_log(
|
|
f" 🌤️ geocode empty for '{location_str}'; retrying romanised '{romanised}'",
|
|
"tools",
|
|
)
|
|
geocode_params["name"] = romanised
|
|
geo_response = requests.get(geocode_url, params=geocode_params, timeout=10)
|
|
geo_response.raise_for_status()
|
|
geo_data = geo_response.json()
|
|
if geo_data.get("results"):
|
|
location_str = romanised
|
|
|
|
# A "district, city, country" name (often the detected location
|
|
# copied from the context) may not match as a whole. Retry
|
|
# without the leading parts, narrowest area first.
|
|
parts = [p.strip() for p in location_str.split(",") if p.strip()]
|
|
for i in range(1, len(parts)):
|
|
if geo_data.get("results"):
|
|
break
|
|
wider = ", ".join(parts[i:])
|
|
debug_log(f" 🌤️ geocode empty; retrying wider area '{wider}'", "tools")
|
|
geocode_params["name"] = wider
|
|
geo_response = requests.get(geocode_url, params=geocode_params, timeout=10)
|
|
geo_response.raise_for_status()
|
|
geo_data = geo_response.json()
|
|
|
|
if not geo_data.get("results"):
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text=f"Could not find location '{location_str}'. Try a different city name or spelling."
|
|
)
|
|
|
|
place = geo_data["results"][0]
|
|
lat = place["latitude"]
|
|
lon = place["longitude"]
|
|
place_name = place.get("name", location_str)
|
|
country = place.get("country", "")
|
|
admin1 = place.get("admin1", "") # State/region
|
|
country_code = place.get("country_code")
|
|
|
|
# Build display name
|
|
location_display = place_name
|
|
if admin1 and admin1 != place_name:
|
|
location_display += f", {admin1}"
|
|
if country:
|
|
location_display += f", {country}"
|
|
|
|
debug_log(f" 📍 resolved to {location_display} ({lat}, {lon})", "tools")
|
|
|
|
first, last = _day_span(args)
|
|
detail = (args or {}).get("detail") is True or str((args or {}).get("detail")).lower() == "true"
|
|
if first > 0:
|
|
lines = self._forecast_lines(lat, lon, country_code, first, last, location_display, detail)
|
|
if not lines:
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text=f"Weather forecast temporarily unavailable for {location_display}."
|
|
)
|
|
context.user_print(f"✅ Forecast for {location_display.split(',')[0].strip()}")
|
|
return ToolExecutionResult(success=True, reply_text="\n".join(lines))
|
|
|
|
# Step 2: Get current weather + forecast
|
|
weather_url = "https://api.open-meteo.com/v1/forecast"
|
|
weather_params = {
|
|
"latitude": lat,
|
|
"longitude": lon,
|
|
"current": "temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m,wind_gusts_10m,precipitation",
|
|
"hourly": "temperature_2m,weather_code",
|
|
"daily": "weather_code,temperature_2m_max,temperature_2m_min",
|
|
"forecast_days": 7,
|
|
"temperature_unit": "celsius",
|
|
"wind_speed_unit": "kmh",
|
|
"timezone": "auto"
|
|
}
|
|
|
|
current: Dict[str, Any] = {}
|
|
source = "KMA"
|
|
kma_key = _kma_key_now()
|
|
if kma_key and country_code == "KR":
|
|
current = _kma_current(lat, lon, kma_key)
|
|
if not current:
|
|
source = "open-meteo"
|
|
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 Exception 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")
|
|
source = "met.no"
|
|
current = _met_no_current(lat, lon)
|
|
if not current:
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text=f"Weather data temporarily unavailable for {location_display}."
|
|
)
|
|
notice(f"weather now: {source}", "llm")
|
|
|
|
# Extract current weather values
|
|
temp_c = current.get("temperature_2m")
|
|
feels_like_c = current.get("apparent_temperature")
|
|
humidity = current.get("relative_humidity_2m")
|
|
weather_code = current.get("weather_code", 0)
|
|
wind_speed = current.get("wind_speed_10m")
|
|
wind_gusts = current.get("wind_gusts_10m")
|
|
|
|
# Convert to Fahrenheit as well
|
|
temp_f = round(temp_c * 9/5 + 32, 1) if temp_c is not None else None
|
|
feels_like_f = round(feels_like_c * 9/5 + 32, 1) if feels_like_c is not None else None
|
|
|
|
# Get weather description
|
|
weather_desc = WMO_CODES.get(weather_code, "Unknown conditions")
|
|
|
|
# Concise, ready-to-speak Korean one-liner for the voice path. The
|
|
# tool result is normally re-synthesised by the LLM, but a small
|
|
# model rambles and leaks °F / CJK fragments, so we hand it a clean
|
|
# Korean sentence it can echo verbatim (one-sentence system rule).
|
|
_ko = current.get("condition_ko") or WMO_CODES_KO.get(weather_code, weather_desc)
|
|
_short_loc = location_display.split(",")[0].strip() or location_display
|
|
_ko_parts = [f"지금 {_short_loc} 날씨는 {_ko}"]
|
|
if temp_c is not None:
|
|
_t = f"기온 {round(temp_c)}도"
|
|
if feels_like_c is not None and round(feels_like_c) != round(temp_c):
|
|
_t += f"(체감 {round(feels_like_c)}도)"
|
|
_ko_parts.append(_t)
|
|
if detail:
|
|
_ko_parts += _detail_parts(humidity, _ms(wind_speed), current.get("precipitation"),
|
|
"바람", "지난 1시간 강수량")
|
|
ko_sentence = ", ".join(_ko_parts) + "입니다."
|
|
|
|
# The reply is the clean Korean sentence ONLY — no English/°C source
|
|
# for the model to echo ("25도 Celsius"), no forecast firehose to
|
|
# ramble over. The model just echoes this one sentence.
|
|
lines = [ko_sentence]
|
|
if last > 0: # "this week": now, then each day
|
|
lines += self._forecast_lines(lat, lon, country_code, 0, last, location_display, detail)
|
|
|
|
reply_text = "\n".join(lines)
|
|
|
|
debug_log(f" ✅ weather retrieved: {weather_desc}, {temp_c}°C", "tools")
|
|
# Use first part of location_display for concise output
|
|
short_name = location_display.split(",")[0].strip()
|
|
context.user_print(f"✅ Weather for {short_name}: {weather_desc}, {temp_c}°C")
|
|
|
|
return ToolExecutionResult(success=True, reply_text=reply_text)
|
|
|
|
except requests.exceptions.Timeout:
|
|
debug_log("weather request timed out", "tools")
|
|
context.user_print("⚠️ Weather service timeout.")
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text="Weather service is taking too long to respond. Please try again."
|
|
)
|
|
except requests.exceptions.RequestException as e:
|
|
debug_log(f"weather request failed: {e}", "tools")
|
|
context.user_print("⚠️ Weather service unavailable.")
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text="Weather service is temporarily unavailable. Please try again later."
|
|
)
|
|
except Exception as e:
|
|
debug_log(f"weather error: {e}", "tools")
|
|
context.user_print("⚠️ Error getting weather.")
|
|
return ToolExecutionResult(
|
|
success=False,
|
|
reply_text=f"Error getting weather: {e}"
|
|
)
|