Spaces:
Sleeping
Sleeping
Update app.py
Browse filesupdating the weather api to use an open spec and added funcitonality.
app.py
CHANGED
@@ -1,72 +1,202 @@
|
|
1 |
-
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
|
2 |
import datetime
|
3 |
import requests
|
4 |
import pytz
|
5 |
import yaml
|
6 |
from tools.final_answer import FinalAnswerTool
|
7 |
-
|
8 |
from Gradio_UI import GradioUI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
11 |
@tool
|
12 |
-
def
|
13 |
-
|
14 |
-
|
15 |
Args:
|
16 |
-
|
17 |
-
|
|
|
|
|
18 |
"""
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
@tool
|
22 |
-
def
|
23 |
-
"""
|
|
|
24 |
Args:
|
25 |
-
|
|
|
|
|
|
|
26 |
"""
|
27 |
try:
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
except Exception as e:
|
34 |
-
return f"Error
|
35 |
-
@tool
|
36 |
-
def get_weather(city):
|
37 |
-
import requests
|
38 |
-
api_url = f"https://api.weather.com/v1/location/{city}?apiKey=YOUR_API_KEY"
|
39 |
-
response = requests.get(api_url)
|
40 |
-
if response.status_code == 200:
|
41 |
-
data = response.json()
|
42 |
-
return data.get("weather", "No weather information available")
|
43 |
-
else:
|
44 |
-
return "Error: Unable to fetch weather data."
|
45 |
-
|
46 |
-
# Execute the function and prepare the final answer
|
47 |
-
|
48 |
-
result = get_weather("New York")
|
49 |
-
final_answer = f"The current weather in New York is: {result}"
|
50 |
-
print(final_answer)
|
51 |
-
|
52 |
-
final_answer = FinalAnswerTool()
|
53 |
-
model = HfApiModel(
|
54 |
-
max_tokens=2096,
|
55 |
-
temperature=0.5,
|
56 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
|
57 |
-
custom_role_conversions=None,
|
58 |
-
)
|
59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
|
|
64 |
with open("prompts.yaml", 'r') as stream:
|
65 |
prompt_templates = yaml.safe_load(stream)
|
66 |
-
|
67 |
agent = CodeAgent(
|
68 |
model=model,
|
69 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
max_steps=6,
|
71 |
verbosity_level=1,
|
72 |
grammar=None,
|
@@ -76,5 +206,5 @@ agent = CodeAgent(
|
|
76 |
prompt_templates=prompt_templates
|
77 |
)
|
78 |
|
79 |
-
|
80 |
GradioUI(agent).launch()
|
|
|
1 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
|
2 |
import datetime
|
3 |
import requests
|
4 |
import pytz
|
5 |
import yaml
|
6 |
from tools.final_answer import FinalAnswerTool
|
|
|
7 |
from Gradio_UI import GradioUI
|
8 |
+
from typing import Dict, Tuple, Optional
|
9 |
+
|
10 |
+
def get_coordinates(city: str) -> Optional[Tuple[float, float]]:
|
11 |
+
"""Get coordinates for any city using Open-Meteo Geocoding API."""
|
12 |
+
try:
|
13 |
+
# Using Open-Meteo's free geocoding API
|
14 |
+
geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&language=en&format=json"
|
15 |
+
response = requests.get(geocoding_url, timeout=10)
|
16 |
+
|
17 |
+
if response.status_code == 200:
|
18 |
+
data = response.json()
|
19 |
+
if data.get("results"):
|
20 |
+
result = data["results"][0]
|
21 |
+
return (result["latitude"], result["longitude"])
|
22 |
+
return None
|
23 |
+
except Exception:
|
24 |
+
return None
|
25 |
|
|
|
26 |
@tool
|
27 |
+
def get_weather(city: str) -> str:
|
28 |
+
"""Get current weather information for a specified city.
|
29 |
+
|
30 |
Args:
|
31 |
+
city: Name of any city in the world
|
32 |
+
|
33 |
+
Returns:
|
34 |
+
str: Weather information including temperature and conditions
|
35 |
"""
|
36 |
+
try:
|
37 |
+
# First get the coordinates for the city
|
38 |
+
coords = get_coordinates(city)
|
39 |
+
if not coords:
|
40 |
+
return f"Sorry, couldn't find coordinates for {city}. Please check the city name and try again."
|
41 |
+
|
42 |
+
lat, lon = coords
|
43 |
+
|
44 |
+
# Get weather using Open-Meteo API
|
45 |
+
api_url = "https://api.open-meteo.com/v1/forecast"
|
46 |
+
params = {
|
47 |
+
"latitude": lat,
|
48 |
+
"longitude": lon,
|
49 |
+
"current": "temperature_2m,wind_speed_10m,relative_humidity_2m",
|
50 |
+
"hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
|
51 |
+
}
|
52 |
+
|
53 |
+
response = requests.get(api_url, params=params, timeout=10)
|
54 |
+
|
55 |
+
if response.status_code == 200:
|
56 |
+
data = response.json()
|
57 |
+
current = data["current"]
|
58 |
+
|
59 |
+
weather_report = (
|
60 |
+
f"Current weather in {city}:\n"
|
61 |
+
f"🌡️ Temperature: {current['temperature_2m']}°C\n"
|
62 |
+
f"💨 Wind Speed: {current['wind_speed_10m']} km/h\n"
|
63 |
+
f"💧 Humidity: {current.get('relative_humidity_2m', 'N/A')}%\n"
|
64 |
+
f"\nWould you like to check local bike trails? Use get_bike_trails('{city}')"
|
65 |
+
)
|
66 |
+
|
67 |
+
return weather_report
|
68 |
+
else:
|
69 |
+
return f"Error fetching weather data. Status code: {response.status_code}"
|
70 |
+
|
71 |
+
except Exception as e:
|
72 |
+
return f"Error fetching weather data: {str(e)}"
|
73 |
|
74 |
@tool
|
75 |
+
def check_biking_conditions(city: str) -> str:
|
76 |
+
"""Check if current weather conditions are good for biking in specified city.
|
77 |
+
|
78 |
Args:
|
79 |
+
city: Name of any city in the world
|
80 |
+
|
81 |
+
Returns:
|
82 |
+
str: Assessment of biking conditions based on weather
|
83 |
"""
|
84 |
try:
|
85 |
+
coords = get_coordinates(city)
|
86 |
+
if not coords:
|
87 |
+
return f"Sorry, couldn't find coordinates for {city}."
|
88 |
+
|
89 |
+
lat, lon = coords
|
90 |
+
|
91 |
+
api_url = "https://api.open-meteo.com/v1/forecast"
|
92 |
+
params = {
|
93 |
+
"latitude": lat,
|
94 |
+
"longitude": lon,
|
95 |
+
"current": "temperature_2m,wind_speed_10m",
|
96 |
+
"hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
|
97 |
+
}
|
98 |
+
|
99 |
+
response = requests.get(api_url, params=params, timeout=10)
|
100 |
+
|
101 |
+
if response.status_code == 200:
|
102 |
+
data = response.json()
|
103 |
+
current = data["current"]
|
104 |
+
temp = current['temperature_2m']
|
105 |
+
wind_speed = current['wind_speed_10m']
|
106 |
+
|
107 |
+
# Assess conditions for biking
|
108 |
+
conditions = []
|
109 |
+
|
110 |
+
if wind_speed > 20:
|
111 |
+
conditions.append(f"⚠️ Wind speeds are high ({wind_speed} km/h)")
|
112 |
+
if temp < 10:
|
113 |
+
conditions.append(f"🌡️ It's cold ({temp}°C) - dress warmly")
|
114 |
+
elif temp > 30:
|
115 |
+
conditions.append(f"🌡️ It's hot ({temp}°C) - stay hydrated")
|
116 |
+
|
117 |
+
if conditions:
|
118 |
+
return f"Biking conditions in {city}:\n" + "\n".join(conditions)
|
119 |
+
else:
|
120 |
+
return f"👍 Great conditions for biking in {city}! {temp}°C with moderate wind speeds."
|
121 |
+
|
122 |
+
else:
|
123 |
+
return f"Error checking conditions. Status code: {response.status_code}"
|
124 |
+
|
125 |
except Exception as e:
|
126 |
+
return f"Error checking biking conditions: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
|
128 |
+
# Keep mock trails data but make it more dynamic
|
129 |
+
MOCK_TRAILS = {
|
130 |
+
# Dynamic trail generation based on city characteristics
|
131 |
+
"default_trails": [
|
132 |
+
{
|
133 |
+
"name": "{city} Riverside Path",
|
134 |
+
"difficulty": "Easy",
|
135 |
+
"length": "5.5 miles",
|
136 |
+
"description": "Scenic waterfront trail perfect for casual rides",
|
137 |
+
"features": ["Waterfront views", "Paved path", "Family-friendly"]
|
138 |
+
},
|
139 |
+
{
|
140 |
+
"name": "{city} Urban Loop",
|
141 |
+
"difficulty": "Moderate",
|
142 |
+
"length": "8.2 miles",
|
143 |
+
"description": "Popular city loop with diverse urban scenery",
|
144 |
+
"features": ["City views", "Mixed terrain", "Cultural spots"]
|
145 |
+
}
|
146 |
+
]
|
147 |
+
}
|
148 |
|
149 |
+
@tool
|
150 |
+
def get_bike_trails(city: str) -> str:
|
151 |
+
"""Get information about bike trails in a specified city.
|
152 |
+
|
153 |
+
Args:
|
154 |
+
city: Name of any city in the world
|
155 |
+
|
156 |
+
Returns:
|
157 |
+
str: Information about available bike trails
|
158 |
+
"""
|
159 |
+
# Generate dynamic trails for any city
|
160 |
+
trails = []
|
161 |
+
for trail_template in MOCK_TRAILS["default_trails"]:
|
162 |
+
trail = {
|
163 |
+
"name": trail_template["name"].format(city=city),
|
164 |
+
"difficulty": trail_template["difficulty"],
|
165 |
+
"length": trail_template["length"],
|
166 |
+
"description": trail_template["description"],
|
167 |
+
"features": trail_template["features"]
|
168 |
+
}
|
169 |
+
trails.append(trail)
|
170 |
+
|
171 |
+
response = f"🚲 Suggested Bike Trails in {city}:\n\n"
|
172 |
+
|
173 |
+
for trail in trails:
|
174 |
+
response += (
|
175 |
+
f"📍 {trail['name']}\n"
|
176 |
+
f" • Difficulty: {trail['difficulty']}\n"
|
177 |
+
f" • Length: {trail['length']}\n"
|
178 |
+
f" • Description: {trail['description']}\n"
|
179 |
+
f" • Features: {', '.join(trail['features'])}\n\n"
|
180 |
+
)
|
181 |
+
|
182 |
+
response += "(Note: These are suggested routes based on typical city features. Always verify local trails and conditions.)"
|
183 |
+
|
184 |
+
return response
|
185 |
|
186 |
+
# Initialize agent with all tools
|
187 |
with open("prompts.yaml", 'r') as stream:
|
188 |
prompt_templates = yaml.safe_load(stream)
|
189 |
+
|
190 |
agent = CodeAgent(
|
191 |
model=model,
|
192 |
+
tools=[
|
193 |
+
final_answer,
|
194 |
+
get_weather,
|
195 |
+
get_bike_trails,
|
196 |
+
check_biking_conditions,
|
197 |
+
get_current_time_in_timezone,
|
198 |
+
image_generation_tool
|
199 |
+
],
|
200 |
max_steps=6,
|
201 |
verbosity_level=1,
|
202 |
grammar=None,
|
|
|
206 |
prompt_templates=prompt_templates
|
207 |
)
|
208 |
|
209 |
+
# Launch Gradio UI
|
210 |
GradioUI(agent).launch()
|