From f3b9b49ac5dc3d3a0ecb1f8413e2a389f8510f18 Mon Sep 17 00:00:00 2001 From: Afloat Date: Tue, 17 Nov 2026 12:15:35 +0800 Subject: [PATCH] feat(weather): disambiguate city lookup with a country filter --- atomic-forge/tools/weather/README.md | 9 ++ .../weather/tests/test_country_filter.py | 106 ++++++++++++++++++ atomic-forge/tools/weather/tool/weather.py | 13 ++- 3 files changed, 126 insertions(+), 2 deletions(-) create mode 100644 atomic-forge/tools/weather/tests/test_country_filter.py diff --git a/atomic-forge/tools/weather/README.md b/atomic-forge/tools/weather/README.md index 8843b12f..e46717e8 100644 --- a/atomic-forge/tools/weather/README.md +++ b/atomic-forge/tools/weather/README.md @@ -17,6 +17,7 @@ Looks up current conditions and a daily/hourly forecast for any location using t ### Input Schema - `location` (str): city name, `'City, Region'`, or `'lat,lon'`. +- `country_code` (str, optional): two-letter ISO 3166-1 country code for city lookup, such as `GB` or `US`. Case-insensitive; omitted by default. Coordinates bypass geocoding, so the filter does not apply to `lat,lon`. - `units` (str): `metric` (Celsius / km/h / mm) or `imperial` (Fahrenheit / mph / inches). Default `metric`. - `forecast_days` (int): 1–16, default 3. - `include_hourly` (bool): include hourly forecast data, default `False`. @@ -46,6 +47,14 @@ else: print(day.date, day.temperature_min, "→", day.temperature_max, day.weather_description) ``` +For an ambiguous city name, use an explicit country filter: + +```python +out = tool.run(WeatherToolInputSchema(location="London", country_code="GB")) +``` + +The filter uses Open-Meteo's [`countryCode` parameter](https://open-meteo.com/en/docs/geocoding-api). If no city matches in that country, the tool returns a lookup error without fetching a forecast for another country. + ## Notes - Weather codes are translated to human-readable descriptions via the WMO interpretation table (Open-Meteo). - The tool fails gracefully and returns `error` set on the output rather than raising. diff --git a/atomic-forge/tools/weather/tests/test_country_filter.py b/atomic-forge/tools/weather/tests/test_country_filter.py new file mode 100644 index 00000000..7e3c7b07 --- /dev/null +++ b/atomic-forge/tools/weather/tests/test_country_filter.py @@ -0,0 +1,106 @@ +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlsplit + +import pytest +from pydantic import ValidationError + +from tool.weather import WeatherTool, WeatherToolConfig, WeatherToolInputSchema + + +@pytest.fixture +def service(): + requests = [] + locations = { + "GB": {"name": "London", "country": "United Kingdom", "latitude": 51.5085, "longitude": -0.1257}, + "US": {"name": "London", "country": "United States", "latitude": 39.8865, "longitude": -83.4483}, + } + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + url = urlsplit(self.path) + params = parse_qs(url.query) + requests.append((url.path, params)) + if url.path == "/geocode": + location = locations.get(params.get("countryCode", ["US"])[0]) + body = {"results": [location] if location else []} + else: + body = {"current": {"time": "2026-01-01T00:00", "temperature_2m": 12.5}} + encoded = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) + thread.start() + origin = f"http://127.0.0.1:{server.server_port}" + tool = WeatherTool(WeatherToolConfig(geocoding_url=origin + "/geocode", forecast_url=origin + "/forecast")) + try: + yield tool, requests, locations + finally: + tool._session.close() + server.shutdown() + thread.join() + server.server_close() + + +@pytest.mark.parametrize("country_code", ["gb", "GB", "US"]) +def test_ambiguous_city_uses_requested_country_coordinates_for_forecast(service, country_code): + tool, requests, locations = service + result = tool.run(WeatherToolInputSchema(location="London", country_code=country_code, language="fr")) + expected = locations[country_code.upper()] + + assert result.error is None + assert result.country == expected["country"] + assert (result.latitude, result.longitude) == (expected["latitude"], expected["longitude"]) + assert result.current.temperature == 12.5 + assert requests[0] == ( + "/geocode", + {"name": ["London"], "count": ["1"], "language": ["fr"], "format": ["json"], "countryCode": [country_code.upper()]}, + ) + assert requests[1][0] == "/forecast" + assert requests[1][1]["latitude"] == [str(expected["latitude"])] + assert requests[1][1]["longitude"] == [str(expected["longitude"])] + assert "countryCode" not in requests[1][1] + + +def test_omitting_country_keeps_unfiltered_geocoding(service): + tool, requests, _ = service + result = tool.run(WeatherToolInputSchema(location="London")) + + assert result.error is None + assert result.country == "United States" + assert "countryCode" not in requests[0][1] + + +def test_country_without_a_matching_city_does_not_fetch_another_countrys_forecast(service): + tool, requests, _ = service + result = tool.run(WeatherToolInputSchema(location="London", country_code="JP")) + + assert result.error == "Location 'London' not found." + assert result.current is None + assert [path for path, _ in requests] == ["/geocode"] + + +def test_explicit_coordinates_bypass_country_geocoding(service): + tool, requests, _ = service + result = tool.run(WeatherToolInputSchema(location="48.8566,2.3522", country_code="GB")) + + assert result.error is None + assert (result.latitude, result.longitude) == (48.8566, 2.3522) + assert result.country is None + assert [path for path, _ in requests] == ["/forecast"] + assert "countryCode" not in requests[0][1] + + +@pytest.mark.parametrize("country_code", ["", "G", "GBR", "G1", " GB", "GB ", "éé", "US,GB"]) +def test_malformed_country_filters_are_rejected_before_lookup(country_code): + with pytest.raises(ValidationError, match="country_code"): + WeatherToolInputSchema(location="London", country_code=country_code) diff --git a/atomic-forge/tools/weather/tool/weather.py b/atomic-forge/tools/weather/tool/weather.py index bd10d5c4..4da7d741 100644 --- a/atomic-forge/tools/weather/tool/weather.py +++ b/atomic-forge/tools/weather/tool/weather.py @@ -65,6 +65,13 @@ class WeatherToolInputSchema(BaseIOSchema): " IL'`), or a `lat,lon` pair (e.g. `'48.8566,2.3522'`)." ), ) + country_code: Optional[str] = Field( + default=None, + min_length=2, + max_length=2, + pattern=r"^[A-Za-z]{2}$", + description="Optional ISO 3166-1 alpha-2 country filter for city lookup (e.g. GB). Ignored for lat,lon input.", + ) units: Literal["metric", "imperial"] = Field( default="metric", description="'metric' uses Celsius and km/h; 'imperial' uses Fahrenheit and mph.", @@ -188,8 +195,10 @@ def parse_latlon(cls, value: str) -> Optional[Tuple[float, float]]: return None return lat, lon - def _geocode(self, query: str, language: str) -> dict: + def _geocode(self, query: str, language: str, country_code: Optional[str] = None) -> dict: params = {"name": query, "count": "1", "language": language, "format": "json"} + if country_code is not None: + params["countryCode"] = country_code.upper() response = self._session.get(self.geocoding_url, params=params, timeout=self.timeout) response.raise_for_status() data = response.json() @@ -326,7 +335,7 @@ def run(self, params: WeatherToolInputSchema) -> WeatherToolOutputSchema: location_name = f"{latitude:.4f}, {longitude:.4f}" country = None else: - geocoded = self._geocode(params.location, params.language) + geocoded = self._geocode(params.location, params.language, params.country_code) latitude = geocoded["latitude"] longitude = geocoded["longitude"] location_name = geocoded.get("name", params.location)