Ferocious0xide commited on
Commit
b443ecf
·
verified ·
1 Parent(s): ad7dafa

Update app.py

Browse files

resetting app.py back to original setting

Files changed (1) hide show
  1. app.py +14 -211
app.py CHANGED
@@ -1,208 +1,36 @@
1
- # Import required libraries
2
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
3
  import datetime
4
  import requests
5
  import pytz
6
  import yaml
7
  from tools.final_answer import FinalAnswerTool
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:
15
- geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={city}&count=1&language=en&format=json"
16
- response = requests.get(geocoding_url, timeout=10)
17
-
18
- if response.status_code == 200:
19
- data = response.json()
20
- if data.get("results"):
21
- result = data["results"][0]
22
- return (result["latitude"], result["longitude"])
23
- return None
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.
31
-
32
- Args:
33
- city: Name of any city in the world
34
-
35
- Returns:
36
- str: Weather information including temperature and conditions
37
- """
38
- try:
39
- coords = get_coordinates(city)
40
- if not coords:
41
- return f"Sorry, couldn't find coordinates for {city}. Please check the city name and try again."
42
-
43
- lat, lon = coords
44
-
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 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,36 +38,13 @@ model = HfApiModel(
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,
238
- get_bike_trails,
239
- check_biking_conditions,
240
- get_current_time_in_timezone,
241
- image_generation_tool
242
- ],
243
  max_steps=6,
244
  verbosity_level=1,
245
  grammar=None,
@@ -249,6 +54,4 @@ agent = CodeAgent(
249
  prompt_templates=prompt_templates
250
  )
251
 
252
- # Launch Gradio UI
253
- if __name__ == "__main__":
254
- 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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  @tool
9
+ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
10
+ #Keep this format for the description / args / args description but feel free to modify the tool
11
+ """A tool that does nothing yet
12
  Args:
13
+ arg1: the first argument
14
+ arg2: the second argument
 
 
15
  """
16
+ return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
 
18
  @tool
19
  def get_current_time_in_timezone(timezone: str) -> str:
20
  """A tool that fetches the current local time in a specified timezone.
 
21
  Args:
22
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
23
  """
24
  try:
25
+ # Create timezone object
26
  tz = pytz.timezone(timezone)
27
+ # Get current time in that timezone
28
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
29
  return f"The current local time in {timezone} is: {local_time}"
30
  except Exception as e:
31
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
32
 
33
+ final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  model = HfApiModel(
35
  max_tokens=2096,
36
  temperature=0.5,
 
38
  custom_role_conversions=None,
39
  )
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  with open("prompts.yaml", 'r') as stream:
42
  prompt_templates = yaml.safe_load(stream)
43
+
44
+ # We're creating our CodeAgent
45
  agent = CodeAgent(
46
  model=model,
47
+ tools=[final_answer], ## add your tools here (don't remove final answer)
 
 
 
 
 
 
 
48
  max_steps=6,
49
  verbosity_level=1,
50
  grammar=None,
 
54
  prompt_templates=prompt_templates
55
  )
56
 
57
+ GradioUI(agent).launch()