-
Notifications
You must be signed in to change notification settings - Fork 134
/
tool.py
199 lines (191 loc) · 7.1 KB
/
tool.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
from __future__ import annotations
from griptape.artifacts import ListArtifact, TextArtifact, ErrorArtifact, InfoArtifact
from griptape.tools import BaseTool
from griptape.utils.decorators import activity
from schema import Schema, Literal
from typing import Optional
from attrs import define, field
import requests
import logging
@define
class OpenWeatherClient(BaseTool):
BASE_URL = "https://api.openweathermap.org/data/3.0/onecall"
GEOCODING_URL = "https://api.openweathermap.org/geo/1.0/direct"
US_STATE_CODES = [
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY",
]
api_key: str = field(kw_only=True)
units: str = field(default="imperial", kw_only=True)
@activity(
config={
"description": "Can be used to fetch the latitude and longitude for a given location.",
"schema": Schema(
{
Literal(
"location",
description="Location to fetch coordinates for. "
"For US cities, use the format 'city_name, state_code'. "
"For non-US cities, use 'city_name, country_code'. "
"For cities without specifying state or country, simply use 'city_name'.",
): str
}
),
}
)
def get_coordinates_by_location(self, params: dict) -> InfoArtifact | ErrorArtifact:
location = params["values"].get("location")
coordinates = self._fetch_coordinates(location)
if coordinates:
lat, lon = coordinates
return InfoArtifact(f"Coordinates for {location}: Latitude: {lat}, Longitude: {lon}")
else:
return ErrorArtifact(f"Error fetching coordinates for location: {location}")
def _fetch_coordinates(self, location: str) -> Optional[tuple[float, Optional[float]]]:
parts = location.split(",")
if len(parts) == 2 and parts[1].strip() in self.US_STATE_CODES:
location += ", US"
request_params = {"q": location, "limit": 1, "appid": self.api_key}
try:
response = requests.get(self.GEOCODING_URL, params=request_params)
if response.status_code == 200:
data = response.json()
if data and isinstance(data, list):
return data[0]["lat"], data[0]["lon"]
else:
logging.error(
f"Error fetching coordinates. HTTP Status Code: {response.status_code}. Response: {response.text}"
)
except Exception as e:
logging.error(f"Error fetching coordinates: {e}")
return None
@activity(
config={
"description": "Can be used to fetch current weather data for a given location. "
"Temperatures are returned in {{ _self.units }} by default.",
"schema": Schema({Literal("location", description="Location to fetch weather data for."): str}),
}
)
def get_current_weather_by_location(self, params: dict) -> ListArtifact | TextArtifact | ErrorArtifact:
location = params["values"].get("location")
coordinates = self._fetch_coordinates(location)
if coordinates:
lat, lon = coordinates
request_params = {
"lat": lat,
"lon": lon,
"exclude": "minutely,hourly,daily,alerts",
"appid": self.api_key,
"units": self.units,
}
return self._fetch_weather_data(request_params)
else:
return ErrorArtifact(f"Error fetching coordinates for location: {location}")
@activity(
config={
"description": "Can be used to fetch hourly forecast for a given location up to 48 hours ahead. "
"Temperatures are returned in {{ _self.units }} by default.",
"schema": Schema({Literal("location", description="Location to fetch hourly forecast for."): str}),
}
)
def get_hourly_forecast_by_location(self, params: dict) -> ListArtifact | TextArtifact | ErrorArtifact:
location = params["values"].get("location")
coordinates = self._fetch_coordinates(location)
if coordinates:
lat, lon = coordinates
request_params = {
"lat": lat,
"lon": lon,
"exclude": "minutely,current,daily,alerts",
"appid": self.api_key,
"units": self.units,
}
return self._fetch_weather_data(request_params)
else:
return ErrorArtifact(f"Error fetching coordinates for location: {location}")
@activity(
config={
"description": "Can be used to fetch daily forecast for a given location up to 8 days ahead. "
"Temperatures are returned in {{ _self.units }} by default.",
"schema": Schema({Literal("location", description="Location to fetch daily forecast for."): str}),
}
)
def get_daily_forecast_by_location(self, params: dict) -> ListArtifact | TextArtifact | ErrorArtifact:
location = params["values"].get("location")
coordinates = self._fetch_coordinates(location)
if coordinates:
lat, lon = coordinates
request_params = {
"lat": lat,
"lon": lon,
"exclude": "minutely,hourly,current,alerts",
"appid": self.api_key,
"units": self.units,
}
return self._fetch_weather_data(request_params)
else:
return ErrorArtifact(f"Error fetching coordinates for location: {location}")
def _fetch_weather_data(self, request_params: dict) -> ListArtifact | TextArtifact | ErrorArtifact:
try:
response = requests.get(self.BASE_URL, params=request_params)
if response.status_code == 200:
data = response.json()
if isinstance(data, list):
wrapped_data = [InfoArtifact(item) for item in data]
return ListArtifact(wrapped_data)
else:
return TextArtifact(str(data))
else:
logging.error(f"Error fetching weather data. HTTP Status Code: {response.status_code}")
return ErrorArtifact("Error fetching weather data from OpenWeather API")
except Exception as e:
logging.error(f"Error fetching weather data: {e}")
return ErrorArtifact(f"Error fetching weather data: {e}")