Ferocious0xide commited on
Commit
5591fd4
·
verified ·
1 Parent(s): c6f8024

Update app.py

Browse files

fixing the weather agent request.

Files changed (1) hide show
  1. app.py +148 -6
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
@@ -7,6 +8,7 @@ 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:
@@ -22,6 +24,7 @@ def get_coordinates(city: str) -> Optional[Tuple[float, float]]:
22
  except Exception:
23
  return None
24
 
 
25
  @tool
26
  def get_weather(city: str) -> str:
27
  """Get current weather information for a specified city.
@@ -68,12 +71,138 @@ def get_weather(city: str) -> str:
68
  except Exception as e:
69
  return f"Error fetching weather data: {str(e)}"
70
 
71
- [... previous tool definitions remain the same ...]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
- # Initialize final answer tool
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  final_answer = FinalAnswerTool()
75
 
76
- # Initialize the model properly
77
  model = HfApiModel(
78
  max_tokens=2096,
79
  temperature=0.5,
@@ -81,16 +210,28 @@ model = HfApiModel(
81
  custom_role_conversions=None,
82
  )
83
 
84
- # Import tool from Hub if needed
85
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
86
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  # Load prompt templates
88
  with open("prompts.yaml", 'r') as stream:
89
  prompt_templates = yaml.safe_load(stream)
90
 
91
  # Initialize agent with all tools
92
  agent = CodeAgent(
93
- model=model, # Now model is properly defined
94
  tools=[
95
  final_answer,
96
  get_weather,
@@ -109,4 +250,5 @@ agent = CodeAgent(
109
  )
110
 
111
  # Launch Gradio UI
112
- GradioUI(agent).launch()
 
 
1
+ # Import required libraries
2
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
3
  import datetime
4
  import requests
 
8
  from Gradio_UI import GradioUI
9
  from typing import Dict, Tuple, Optional
10
 
11
+ # Utility function for geocoding
12
  def get_coordinates(city: str) -> Optional[Tuple[float, float]]:
13
  """Get coordinates for any city using Open-Meteo Geocoding API."""
14
  try:
 
24
  except Exception:
25
  return None
26
 
27
+ # Tool 1: Weather Information
28
  @tool
29
  def get_weather(city: str) -> str:
30
  """Get current weather information for a specified city.
 
71
  except Exception as e:
72
  return f"Error fetching weather data: {str(e)}"
73
 
74
+ # Tool 2: Biking Conditions
75
+ @tool
76
+ def check_biking_conditions(city: str) -> str:
77
+ """Check if current weather conditions are good for biking in specified city.
78
+
79
+ Args:
80
+ city: Name of any city in the world
81
+
82
+ Returns:
83
+ str: Assessment of biking conditions based on weather
84
+ """
85
+ try:
86
+ coords = get_coordinates(city)
87
+ if not coords:
88
+ return f"Sorry, couldn't find coordinates for {city}."
89
+
90
+ lat, lon = coords
91
+
92
+ api_url = "https://api.open-meteo.com/v1/forecast"
93
+ params = {
94
+ "latitude": lat,
95
+ "longitude": lon,
96
+ "current": "temperature_2m,wind_speed_10m",
97
+ "hourly": "temperature_2m,relative_humidity_2m,wind_speed_10m"
98
+ }
99
+
100
+ response = requests.get(api_url, params=params, timeout=10)
101
+
102
+ if response.status_code == 200:
103
+ data = response.json()
104
+ current = data["current"]
105
+ temp = current['temperature_2m']
106
+ wind_speed = current['wind_speed_10m']
107
+
108
+ # Assess conditions for biking
109
+ conditions = []
110
+
111
+ if wind_speed > 20:
112
+ conditions.append(f"⚠️ Wind speeds are high ({wind_speed} km/h)")
113
+ if temp < 10:
114
+ conditions.append(f"🌡️ It's cold ({temp}°C) - dress warmly")
115
+ elif temp > 30:
116
+ conditions.append(f"🌡️ It's hot ({temp}°C) - stay hydrated")
117
+
118
+ if conditions:
119
+ return f"Biking conditions in {city}:\n" + "\n".join(conditions)
120
+ else:
121
+ return f"👍 Great conditions for biking in {city}! {temp}°C with moderate wind speeds."
122
+
123
+ else:
124
+ return f"Error checking conditions. Status code: {response.status_code}"
125
+
126
+ except Exception as e:
127
+ return f"Error checking biking conditions: {str(e)}"
128
+
129
+ # Tool 3: Current Time in Timezone
130
+ @tool
131
+ def get_current_time_in_timezone(timezone: str) -> str:
132
+ """A tool that fetches the current local time in a specified timezone.
133
+
134
+ Args:
135
+ timezone: A string representing a valid timezone (e.g., 'America/New_York')
136
+ """
137
+ try:
138
+ tz = pytz.timezone(timezone)
139
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
140
+ return f"The current local time in {timezone} is: {local_time}"
141
+ except Exception as e:
142
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
143
 
144
+ # Mock trails data for dynamic trail suggestions
145
+ MOCK_TRAILS = {
146
+ "default_trails": [
147
+ {
148
+ "name": "{city} Riverside Path",
149
+ "difficulty": "Easy",
150
+ "length": "5.5 miles",
151
+ "description": "Scenic waterfront trail perfect for casual rides",
152
+ "features": ["Waterfront views", "Paved path", "Family-friendly"]
153
+ },
154
+ {
155
+ "name": "{city} Urban Loop",
156
+ "difficulty": "Moderate",
157
+ "length": "8.2 miles",
158
+ "description": "Popular city loop with diverse urban scenery",
159
+ "features": ["City views", "Mixed terrain", "Cultural spots"]
160
+ }
161
+ ]
162
+ }
163
+
164
+ # Tool 4: Bike Trails
165
+ @tool
166
+ def get_bike_trails(city: str) -> str:
167
+ """Get information about bike trails in a specified city.
168
+
169
+ Args:
170
+ city: Name of any city in the world
171
+
172
+ Returns:
173
+ str: Information about available bike trails
174
+ """
175
+ # Generate dynamic trails for any city
176
+ trails = []
177
+ for trail_template in MOCK_TRAILS["default_trails"]:
178
+ trail = {
179
+ "name": trail_template["name"].format(city=city),
180
+ "difficulty": trail_template["difficulty"],
181
+ "length": trail_template["length"],
182
+ "description": trail_template["description"],
183
+ "features": trail_template["features"]
184
+ }
185
+ trails.append(trail)
186
+
187
+ response = f"🚲 Suggested Bike Trails in {city}:\n\n"
188
+
189
+ for trail in trails:
190
+ response += (
191
+ f"📍 {trail['name']}\n"
192
+ f" • Difficulty: {trail['difficulty']}\n"
193
+ f" • Length: {trail['length']}\n"
194
+ f" • Description: {trail['description']}\n"
195
+ f" • Features: {', '.join(trail['features'])}\n\n"
196
+ )
197
+
198
+ response += "(Note: These are suggested routes based on typical city features. Always verify local trails and conditions.)"
199
+
200
+ return response
201
+
202
+ # Initialize components
203
  final_answer = FinalAnswerTool()
204
 
205
+ # Initialize the model
206
  model = HfApiModel(
207
  max_tokens=2096,
208
  temperature=0.5,
 
210
  custom_role_conversions=None,
211
  )
212
 
213
+ # Import image generation tool from Hub
214
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
215
 
216
+ # Example prompts.yaml content - save this in a file named prompts.yaml
217
+ PROMPT_TEMPLATES = """
218
+ default: |
219
+ You are a helpful assistant that provides weather information and local activity suggestions.
220
+ When someone asks about the weather, also consider suggesting bike trails and checking biking conditions.
221
+ Always provide helpful context about weather conditions for outdoor activities.
222
+ """
223
+
224
+ # Save prompts to file
225
+ with open("prompts.yaml", 'w') as f:
226
+ f.write(PROMPT_TEMPLATES)
227
+
228
  # Load prompt templates
229
  with open("prompts.yaml", 'r') as stream:
230
  prompt_templates = yaml.safe_load(stream)
231
 
232
  # Initialize agent with all tools
233
  agent = CodeAgent(
234
+ model=model,
235
  tools=[
236
  final_answer,
237
  get_weather,
 
250
  )
251
 
252
  # Launch Gradio UI
253
+ if __name__ == "__main__":
254
+ GradioUI(agent).launch()