aniketkno commited on
Commit
d5f7c74
·
verified ·
1 Parent(s): 75b6e74

Update tools/weather.py

Browse files
Files changed (1) hide show
  1. tools/weather.py +58 -43
tools/weather.py CHANGED
@@ -21,15 +21,14 @@ class WeatherForecast(Tool):
21
  return "## Search Results\n\n" + "\n\n".join(postprocessed_results)
22
 
23
 
24
- def get_weather_forecast(self, city_name: str) -> str:
25
- """A tool that fetches the current weather/temperature of a specified city.
26
- Args:
27
- city_name: A string representing a valid city (e.g., 'Bangalore').
28
- """
29
-
30
- latitude, longitude = self.get_coordinates(city_name)
31
-
32
- base_url = "https://api.open-meteo.com/v1/forecast" # No API key needed for this version
33
  params = {
34
  "latitude": latitude,
35
  "longitude": longitude,
@@ -38,54 +37,70 @@ class WeatherForecast(Tool):
38
  "forecast_days": 7,
39
  "timezone": "auto"
40
  }
41
-
42
  try:
43
- response = requests.get(base_url, params=params) # No headers needed
44
- response.raise_for_status()
45
- weatherJSON = response.json()
46
- cityName = weatherJSON.get('location').get('name')
47
- cityTemp = weatherJSON.get('hourly').get('temperature_2m')
48
- averageTemp = round(mean(cityTemp), 1)
49
- hourlyunits = weatherJSON.get('hourly_units').get('temperature_2m')
50
  return weather_data
51
- return f"The current Temperature in {cityName} is {averageTemp}{hourlyunits}!"
52
  except requests.exceptions.RequestException as e:
53
- print(f"Error fetching weather data: {e}")
54
- return None
55
- except json.JSONDecodeError as e:
56
- print(f"Error decoding JSON response: {e}")
57
  return None
 
 
 
 
 
 
58
 
59
- def get_coordinates(self, city_name: str) -> [float, float]:
60
- """Gets coordinates using OpenStreetMap's Nominatim (no API key, but with limitations)."""
 
 
 
 
 
 
 
 
61
 
62
- # This approach is less reliable and might have rate limits.
63
- # It's suitable for basic use cases but not for production.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  headers = {
65
- 'User-Agent': 'MyGeocodingApp/1.0 (youremail@example.com)'
66
  }
67
-
68
  city_name = city_name.replace(" ", "+")
69
  base_url = "https://nominatim.openstreetmap.org/search"
70
  full_url = f"{base_url}?q={requests.utils.quote(city_name)}&format=json&limit=5"
71
-
72
  try:
73
- response = requests.get(geocoding_url, headers=headers)
74
- response.raise_for_status()
75
- geocoding_data = response.json()
76
- print(geocoding_data)
77
- if geocoding_data: # Check if any results were found
78
- latitude = float(geocoding_data[0]["lat"])
79
- longitude = float(geocoding_data[0]["lon"])
80
  return latitude, longitude
81
  else:
82
- print(f"Could not find coordinates for {city_name}")
83
- return None, None
84
-
85
  except requests.exceptions.RequestException as e:
86
  print(f"Error during geocoding: {e}")
87
  return None, None
88
- except (KeyError, IndexError, ValueError) as e: # Handle more potential errors
89
- print(f"Error parsing geocoding response: {e}")
90
- return None, None
91
-
 
21
  return "## Search Results\n\n" + "\n\n".join(postprocessed_results)
22
 
23
 
24
+ def get_weather_forecast(self, city: str) -> str:
25
+ latitude, longitude = self.get_coordinates(city)
26
+
27
+ if latitude is None or longitude is None:
28
+ print(f"Could not get coordinates for {city}. Cannot retrieve weather forecast.")
29
+ return None # Or raise an exception if you prefer
30
+
31
+ base_url = "https://api.open-meteo.com/v1/forecast"
 
32
  params = {
33
  "latitude": latitude,
34
  "longitude": longitude,
 
37
  "forecast_days": 7,
38
  "timezone": "auto"
39
  }
40
+
41
  try:
42
+ response = requests.get(base_url, params=params)
43
+ response.raise_for_status() # Raise an exception for bad status codes
44
+ weather_data = response.json()
 
 
 
 
45
  return weather_data
46
+
47
  except requests.exceptions.RequestException as e:
48
+ print(f"Error getting weather forecast: {e}")
 
 
 
49
  return None
50
+
51
+ # def get_weather_forecast(self, city_name: str) -> str:
52
+ # """A tool that fetches the current weather/temperature of a specified city.
53
+ # Args:
54
+ # city_name: A string representing a valid city (e.g., 'Bangalore').
55
+ # """
56
 
57
+ # latitude, longitude = self.get_coordinates(city)
58
+ # base_url = "https://api.open-meteo.com/v1/forecast" # No API key needed for this version
59
+ # params = {
60
+ # "latitude": latitude,
61
+ # "longitude": longitude,
62
+ # "hourly": "temperature_2m,precipitation,wind_speed",
63
+ # "daily": "temperature_2m_max,temperature_2m_min,precipitation_sum",
64
+ # "forecast_days": 7,
65
+ # "timezone": "auto"
66
+ # }
67
 
68
+ # try:
69
+ # response = requests.get(base_url, params=params) # No headers needed
70
+ # response.raise_for_status()
71
+ # weatherJSON = response.json()
72
+ # cityName = weatherJSON.get('location').get('name')
73
+ # cityTemp = weatherJSON.get('hourly').get('temperature_2m')
74
+ # averageTemp = round(mean(cityTemp), 1)
75
+ # hourlyunits = weatherJSON.get('hourly_units').get('temperature_2m')
76
+ # return f"The current Temperature in {cityName} is {averageTemp}{hourlyunits}!"
77
+ # except requests.exceptions.RequestException as e:
78
+ # print(f"Error fetching weather data: {e}")
79
+ # return None
80
+ # except json.JSONDecodeError as e:
81
+ # print(f"Error decoding JSON response: {e}")
82
+ # return None
83
+
84
+ def get_coordinates(self, city_name: str) -> [float, float]:
85
  headers = {
86
+ 'User-Agent': 'MyGeocodingApp/1.0 (youremail@example.com)' # Replace with your actual email
87
  }
 
88
  city_name = city_name.replace(" ", "+")
89
  base_url = "https://nominatim.openstreetmap.org/search"
90
  full_url = f"{base_url}?q={requests.utils.quote(city_name)}&format=json&limit=5"
91
+
92
  try:
93
+ response = requests.get(full_url, headers=headers)
94
+ response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
95
+ data = response.json()
96
+
97
+ if data: # Check if the response contains any results
98
+ latitude = data[0]['lat']
99
+ longitude = data[0]['lon']
100
  return latitude, longitude
101
  else:
102
+ return None, None # Return None if no results are found
103
+
 
104
  except requests.exceptions.RequestException as e:
105
  print(f"Error during geocoding: {e}")
106
  return None, None