xomatic commited on
Commit
c10538b
·
verified ·
1 Parent(s): 8856e31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -232
app.py CHANGED
@@ -10,6 +10,15 @@ from Gradio_UI import GradioUI
10
  # -----------------------------
11
  # LOCATION + TIMEZONE TOOLS
12
  # -----------------------------
 
 
 
 
 
 
 
 
 
13
 
14
  @tool
15
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -26,250 +35,30 @@ def get_current_time_in_timezone(timezone: str) -> str:
26
  except Exception as e:
27
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
28
 
29
- @tool
30
- def get_location() -> dict:
31
- """Get user's approximate latitude and longitude."""
32
- try:
33
- res = requests.get("http://ip-api.com/json/")
34
- data = res.json()
35
- return {
36
- "latitude": data["lat"],
37
- "longitude": data["lon"]
38
- }
39
- except Exception as e:
40
- return {"error": str(e)}
41
-
42
- @tool
43
- def get_local_timezone() -> str:
44
- """Detects the user's local timezone based on IP."""
45
- try:
46
- res = requests.get("http://ip-api.com/json/")
47
- data = res.json()
48
- return data.get("timezone", "UTC")
49
- except Exception as e:
50
- return f"Error detecting timezone: {str(e)}"
51
-
52
-
53
- # -----------------------------
54
- # WEATHER TOOL (24H + UNCERTAINTY)
55
- # -----------------------------
56
-
57
- @tool
58
- def get_hourly_weather(latitude: float, longitude: float, timezone: str) -> list:
59
- """Fetch hourly weather forecast for next 24 hours including uncertainty bands.
60
- Args:
61
- latitude: The latitude of the location.
62
- longitude: The longitude of the location.
63
- timezone: The IANA timezone string (e.g., 'America/Los_Angeles').
64
-
65
- Returns:
66
- A list of hourly weather data points with temperature, precipitation,
67
- uncertainty bounds, and weather codes.
68
- """
69
- try:
70
- url = "https://api.open-meteo.com/v1/forecast"
71
-
72
- params = {
73
- "latitude": latitude,
74
- "longitude": longitude,
75
- "hourly": "temperature_2m,precipitation,weathercode",
76
- "forecast_days": 2,
77
- "timezone": timezone
78
- }
79
-
80
- res = requests.get(url, params=params)
81
- data = res.json()
82
-
83
- hourly = data["hourly"]
84
- tz = pytz.timezone(timezone)
85
- now = datetime.datetime.now(tz)
86
-
87
- result = []
88
-
89
- for t, temp, precip, code in zip(
90
- hourly["time"],
91
- hourly["temperature_2m"],
92
- hourly["precipitation"],
93
- hourly["weathercode"]
94
- ):
95
- dt = datetime.datetime.fromisoformat(t)
96
-
97
- if dt >= now and len(result) < 24:
98
- # simple synthetic uncertainty band (±2°C)
99
- result.append({
100
- "time": t,
101
- "temperature": temp,
102
- "temp_min": temp - 2,
103
- "temp_max": temp + 2,
104
- "precipitation": precip,
105
- "weathercode": code
106
- })
107
-
108
- return result
109
-
110
- except Exception as e:
111
- return [{"error": str(e)}]
112
-
113
-
114
- # -----------------------------
115
- # WEATHER CODE → ICON
116
- # -----------------------------
117
-
118
- def weather_icon(code):
119
- if code == 0:
120
- return "☀️"
121
- elif code in [1, 2, 3]:
122
- return "⛅"
123
- elif code in [45, 48]:
124
- return "🌫"
125
- elif code in [51, 53, 55, 61, 63, 65]:
126
- return "🌧"
127
- elif code in [71, 73, 75]:
128
- return "❄️"
129
- elif code in [95]:
130
- return "⛈"
131
- else:
132
- return "🌈"
133
-
134
-
135
- # -----------------------------
136
- # PLOT TOOL (ICONS + BANDS)
137
- # -----------------------------
138
- @tool
139
- def plot_weather(weather_data: list) -> str:
140
- """Generate an SVG weather visualization with icons and uncertainty bands.
141
-
142
- Args:
143
- weather_data: A list of dictionaries containing hourly weather data. Each dict
144
- should have 'time', 'temperature', 'temp_min', 'temp_max',
145
- 'precipitation', and 'weathercode'.
146
-
147
- Returns:
148
- A string file path to the generated SVG image.
149
- """
150
- import datetime
151
- from xml.etree.ElementTree import Element, SubElement, ElementTree, tostring
152
-
153
- # Helper: map weather code to icon
154
- def weather_icon(code):
155
- if code == 0:
156
- return "☀️"
157
- elif code in [1,2,3]:
158
- return "⛅"
159
- elif code in [45,48]:
160
- return "🌫"
161
- elif code in [51,53,55,61,63,65]:
162
- return "🌧"
163
- elif code in [71,73,75]:
164
- return "❄️"
165
- elif code in [95]:
166
- return "⛈"
167
- else:
168
- return "🌈"
169
-
170
- # SVG canvas size
171
- width = 1200
172
- height = 400
173
- margin = 50
174
-
175
- # Compute min/max for scaling
176
- temps = [entry["temperature"] for entry in weather_data]
177
- temp_min_vals = [entry["temp_min"] for entry in weather_data]
178
- temp_max_vals = [entry["temp_max"] for entry in weather_data]
179
- overall_min = min(temp_min_vals) - 2
180
- overall_max = max(temp_max_vals) + 2
181
-
182
- n = len(weather_data)
183
- step_x = (width - 2*margin) / (n-1) if n > 1 else 1
184
-
185
- def y_scale(temp):
186
- # invert y axis (SVG 0,0 is top-left)
187
- return height - margin - (temp - overall_min)/(overall_max - overall_min)*(height - 2*margin)
188
-
189
- # Create root SVG
190
- svg = Element('svg', width=str(width), height=str(height), xmlns="http://www.w3.org/2000/svg")
191
-
192
- # Draw uncertainty band
193
- points = []
194
- for i, entry in enumerate(weather_data):
195
- x = margin + i*step_x
196
- y = y_scale(entry["temp_max"])
197
- points.append(f"{x},{y}")
198
- for i, entry in reversed(list(enumerate(weather_data))):
199
- x = margin + i*step_x
200
- y = y_scale(entry["temp_min"])
201
- points.append(f"{x},{y}")
202
- band = SubElement(svg, "polygon", points=" ".join(points), fill="#a0c4ff", opacity="0.3")
203
-
204
- # Draw temperature line
205
- temp_line_points = []
206
- for i, entry in enumerate(weather_data):
207
- x = margin + i*step_x
208
- y = y_scale(entry["temperature"])
209
- temp_line_points.append(f"{x},{y}")
210
- SubElement(svg, "polyline", points=" ".join(temp_line_points),
211
- fill="none", stroke="#0077b6", stroke_width="2")
212
-
213
- # Draw precipitation bars
214
- max_precip = max([entry["precipitation"] for entry in weather_data] + [1])
215
- for i, entry in enumerate(weather_data):
216
- x = margin + i*step_x - step_x*0.2
217
- y = y_scale(overall_min) - (entry["precipitation"]/max_precip)*(height - 2*margin)
218
- bar_height = (entry["precipitation"]/max_precip)*(height - 2*margin)
219
- SubElement(svg, "rect", x=str(x), y=str(y), width=str(step_x*0.4),
220
- height=str(bar_height), fill="#00b4d8", opacity="0.4")
221
-
222
- # Draw icons and x-axis labels
223
- for i, entry in enumerate(weather_data):
224
- x = margin + i*step_x
225
- y_temp = y_scale(entry["temperature"])
226
- # icon above temp
227
- text = SubElement(svg, "text", x=str(x), y=str(y_temp - 10),
228
- font_size="20", text_anchor="middle")
229
- text.text = weather_icon(entry["weathercode"])
230
- # time label below
231
- t_label = SubElement(svg, "text", x=str(x), y=str(height - margin + 20),
232
- font_size="12", text_anchor="middle")
233
- t_label.text = entry["time"][11:16]
234
-
235
- # Save SVG
236
- file_path = "/mnt/data/weather_visual.svg"
237
- tree = ElementTree(svg)
238
- tree.write(file_path)
239
-
240
- return file_path
241
-
242
-
243
-
244
- # -----------------------------
245
- # AGENT SETUP
246
- # -----------------------------
247
-
248
  final_answer = FinalAnswerTool()
249
-
250
- model = HfApiModel(
251
  max_tokens=2096,
252
  temperature=0.5,
253
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
 
254
  )
255
 
256
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
257
-
258
  with open("prompts.yaml", 'r') as stream:
259
  prompt_templates = yaml.safe_load(stream)
260
-
 
261
  agent = CodeAgent(
262
  model=model,
263
- tools=[
264
- final_answer,
265
- get_location,
266
- get_local_timezone,
267
- get_hourly_weather,
268
- plot_weather
269
- ],
270
  max_steps=6,
271
  verbosity_level=1,
 
 
 
 
272
  prompt_templates=prompt_templates
273
  )
274
 
275
- GradioUI(agent).launch
 
 
 
10
  # -----------------------------
11
  # LOCATION + TIMEZONE TOOLS
12
  # -----------------------------
13
+ @tool
14
+ def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type
15
+ # Keep this format for the tool description / args description but feel free to modify the tool
16
+ """A tool that does nothing yet
17
+ Args:
18
+ arg1: the first argument
19
+ arg2: the second argument
20
+ """
21
+ return "What magic will you build ?"
22
 
23
  @tool
24
  def get_current_time_in_timezone(timezone: str) -> str:
 
35
  except Exception as e:
36
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  final_answer = FinalAnswerTool()
39
+ model = InferenceClientModel(
 
40
  max_tokens=2096,
41
  temperature=0.5,
42
  model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
43
+ custom_role_conversions=None,
44
  )
45
 
 
 
46
  with open("prompts.yaml", 'r') as stream:
47
  prompt_templates = yaml.safe_load(stream)
48
+
49
+ # We're creating our CodeAgent
50
  agent = CodeAgent(
51
  model=model,
52
+ tools=[final_answer], # add your tools here (don't remove final_answer)
 
 
 
 
 
 
53
  max_steps=6,
54
  verbosity_level=1,
55
+ grammar=None,
56
+ planning_interval=None,
57
+ name=None,
58
+ description=None,
59
  prompt_templates=prompt_templates
60
  )
61
 
62
+ GradioUI(agent).launch()
63
+
64
+