pythonprincess commited on
Commit
fffce8b
Β·
verified Β·
1 Parent(s): a95f5c0

Upload tool_agent.py

Browse files
Files changed (1) hide show
  1. app/tool_agent.py +893 -0
app/tool_agent.py ADDED
@@ -0,0 +1,893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/tool_agent.py
2
+ """
3
+ πŸ› οΈ PENNY Tool Agent - Civic Data & Services Handler
4
+
5
+ Routes requests to civic data sources (events, resources, transit, etc.)
6
+ and integrates with real-time weather information.
7
+
8
+ MISSION: Connect residents to local civic services by intelligently
9
+ processing their requests and returning relevant, actionable information.
10
+
11
+ FEATURES:
12
+ - Real-time weather integration with outfit recommendations
13
+ - Event discovery with weather-aware suggestions
14
+ - Resource lookup (trash, transit, emergency services)
15
+ - City-specific data routing
16
+ - Graceful fallback for missing data
17
+
18
+ ENHANCEMENTS (Phase 1):
19
+ - βœ… Structured logging with performance tracking
20
+ - βœ… Enhanced error handling with user-friendly messages
21
+ - βœ… Type hints for all functions
22
+ - βœ… Health check integration
23
+ - βœ… Service availability tracking
24
+ - βœ… Integration with enhanced modules
25
+ - βœ… Penny's friendly voice throughout
26
+ - βœ… Context-aware city detection (uses tenant_id from UI dropdown)
27
+ """
28
+
29
+ import logging
30
+ import time
31
+ from typing import Optional, Dict, Any
32
+
33
+ # --- ENHANCED MODULE IMPORTS ---
34
+ from app.logging_utils import log_interaction, sanitize_for_logging
35
+
36
+ # --- AGENT IMPORTS (with availability tracking) ---
37
+ try:
38
+ from app.weather_agent import (
39
+ get_weather_for_location,
40
+ weather_to_event_recommendations,
41
+ recommend_outfit,
42
+ format_weather_summary
43
+ )
44
+ WEATHER_AGENT_AVAILABLE = True
45
+ except ImportError as e:
46
+ logging.getLogger(__name__).warning(f"Weather agent not available: {e}")
47
+ WEATHER_AGENT_AVAILABLE = False
48
+
49
+ # --- UTILITY IMPORTS (with availability tracking) ---
50
+ try:
51
+ from app.location_utils import (
52
+ extract_city_name,
53
+ load_city_events,
54
+ load_city_resources,
55
+ get_city_coordinates,
56
+ extract_location_detailed,
57
+ SupportedCities,
58
+ LocationStatus
59
+ )
60
+ LOCATION_UTILS_AVAILABLE = True
61
+ except ImportError as e:
62
+ logging.getLogger(__name__).warning(f"Location utils not available: {e}")
63
+ LOCATION_UTILS_AVAILABLE = False
64
+
65
+ # --- LOGGING SETUP ---
66
+ logger = logging.getLogger(__name__)
67
+
68
+ # --- TRACKING COUNTERS ---
69
+ _tool_request_count = 0
70
+ _weather_request_count = 0
71
+ _event_request_count = 0
72
+ _resource_request_count = 0
73
+
74
+
75
+ # ============================================================
76
+ # CITY DETECTION FROM CONTEXT (NEW FUNCTION)
77
+ # ============================================================
78
+
79
+ def get_city_from_context(context: Dict[str, Any], user_input: str) -> tuple[str, str]:
80
+ """
81
+ πŸ™οΈ Extracts city name and tenant_id from context or message.
82
+
83
+ Priority order:
84
+ 1. tenant_id from context (from UI dropdown)
85
+ 2. location from context
86
+ 3. Extract from user message text
87
+
88
+ Args:
89
+ context: Request context dictionary
90
+ user_input: User's message text
91
+
92
+ Returns:
93
+ Tuple of (city_name, tenant_id)
94
+ Example: ("Atlanta", "atlanta_ga")
95
+ """
96
+ def _normalize_tenant_id(tenant_id: str) -> tuple[str, str]:
97
+ """
98
+ Normalizes tenant_id to proper format using city registry.
99
+ Returns (city_name, proper_tenant_id)
100
+ """
101
+ tenant_id_lower = tenant_id.lower()
102
+
103
+ # If already in proper format (has underscore), verify it exists
104
+ if "_" in tenant_id_lower:
105
+ city_info = SupportedCities.get_city_by_tenant_id(tenant_id_lower)
106
+ if city_info:
107
+ return city_info.full_name.split(",")[0], city_info.tenant_id
108
+
109
+ # Try to find city by partial match
110
+ for city in SupportedCities.get_all_cities():
111
+ # Check if tenant_id matches any alias
112
+ if tenant_id_lower in [alias.lower() for alias in city.aliases]:
113
+ return city.full_name.split(",")[0], city.tenant_id
114
+ # Check if tenant_id matches city name part
115
+ city_name_part = city.tenant_id.split("_")[0]
116
+ if tenant_id_lower == city_name_part:
117
+ return city.full_name.split(",")[0], city.tenant_id
118
+
119
+ # Fallback: return as-is (will be handled by caller)
120
+ return tenant_id.replace("_", " ").title(), tenant_id_lower
121
+
122
+ # Priority 1: Check tenant_id in context (from dropdown)
123
+ tenant_id = context.get("tenant_id", "").lower()
124
+ if tenant_id and tenant_id != "unknown":
125
+ city_name, proper_tenant_id = _normalize_tenant_id(tenant_id)
126
+ logger.info(f"βœ… City from context tenant_id: {city_name} ({proper_tenant_id})")
127
+ return city_name, proper_tenant_id
128
+
129
+ # Priority 2: Check location in context
130
+ location = context.get("location")
131
+ if location:
132
+ # Try to extract proper tenant_id from location string
133
+ location_result = extract_location_detailed(location)
134
+ if location_result.status == LocationStatus.FOUND and location_result.tenant_id:
135
+ city_name = location_result.city_info.full_name.split(",")[0] if location_result.city_info else location.title()
136
+ proper_tenant_id = location_result.tenant_id
137
+ logger.info(f"βœ… City from context location: {city_name} ({proper_tenant_id})")
138
+ return city_name, proper_tenant_id
139
+ else:
140
+ # Fallback to old method if extraction fails
141
+ city_name = location.title()
142
+ city_name, proper_tenant_id = _normalize_tenant_id(location.lower().replace(" ", "_"))
143
+ logger.info(f"βœ… City from context location (fallback): {city_name} ({proper_tenant_id})")
144
+ return city_name, proper_tenant_id
145
+
146
+ # Priority 3: Fall back to extracting from message
147
+ location_result = extract_location_detailed(user_input)
148
+ if location_result.status == LocationStatus.FOUND and location_result.tenant_id:
149
+ city_name = location_result.city_info.full_name.split(",")[0] if location_result.city_info else extract_city_name(user_input)
150
+ proper_tenant_id = location_result.tenant_id
151
+ logger.info(f"⚠️ City extracted from message: {city_name} ({proper_tenant_id})")
152
+ return city_name, proper_tenant_id
153
+ else:
154
+ # Fallback to old method
155
+ city_name = extract_city_name(user_input)
156
+ city_name, proper_tenant_id = _normalize_tenant_id(city_name.lower().replace(" ", "_"))
157
+ logger.info(f"⚠️ City extracted from message (fallback): {city_name} ({proper_tenant_id})")
158
+ return city_name, proper_tenant_id
159
+
160
+
161
+ # ============================================================
162
+ # MAIN TOOL REQUEST HANDLER (ENHANCED)
163
+ # ============================================================
164
+
165
+ async def handle_tool_request(
166
+ user_input: str,
167
+ role: str = "unknown",
168
+ lat: Optional[float] = None,
169
+ lon: Optional[float] = None,
170
+ context: Optional[Dict[str, Any]] = None
171
+ ) -> Dict[str, Any]:
172
+ """
173
+ πŸ› οΈ Handles tool-based actions for civic services.
174
+
175
+ Routes user requests to appropriate civic data sources and real-time
176
+ services, including weather, events, transit, trash, and emergency info.
177
+
178
+ Args:
179
+ user_input: User's request text
180
+ role: User's role (resident, official, etc.)
181
+ lat: Latitude coordinate (optional)
182
+ lon: Longitude coordinate (optional)
183
+ context: Request context with tenant_id, location, etc. (optional)
184
+
185
+ Returns:
186
+ Dictionary containing:
187
+ - tool: str (which tool was used)
188
+ - city: str (detected city name)
189
+ - response: str or dict (user-facing response)
190
+ - data: dict (optional, raw data)
191
+ - tenant_id: str (optional, standardized city identifier)
192
+
193
+ Example:
194
+ result = await handle_tool_request(
195
+ user_input="What's the weather in Atlanta?",
196
+ role="resident",
197
+ lat=33.7490,
198
+ lon=-84.3880,
199
+ context={"tenant_id": "atlanta"}
200
+ )
201
+ """
202
+ global _tool_request_count
203
+ _tool_request_count += 1
204
+
205
+ start_time = time.time()
206
+
207
+ # Initialize context if not provided
208
+ if context is None:
209
+ context = {}
210
+
211
+ # Sanitize input for logging (PII protection)
212
+ safe_input = sanitize_for_logging(user_input)
213
+ logger.info(f"πŸ› οΈ Tool request #{_tool_request_count}: '{safe_input[:50]}...'")
214
+ logger.info(f"πŸ“ Context: {context}")
215
+
216
+ try:
217
+ # Check if location utilities are available
218
+ if not LOCATION_UTILS_AVAILABLE:
219
+ logger.error("Location utilities not available")
220
+ return {
221
+ "tool": "error",
222
+ "response": (
223
+ "I'm having trouble accessing city data right now. "
224
+ "Try again in a moment! πŸ’›"
225
+ ),
226
+ "error": "Location utilities not loaded"
227
+ }
228
+
229
+ lowered = user_input.lower()
230
+
231
+ # πŸ”₯ NEW: Get city from context first, then fall back to message
232
+ city_name, tenant_id = get_city_from_context(context, user_input)
233
+
234
+ logger.info(f"πŸ™οΈ Detected city: {city_name} (tenant_id: {tenant_id})")
235
+
236
+ # Route to appropriate handler
237
+ result = None
238
+
239
+ # Weather queries
240
+ if any(keyword in lowered for keyword in ["weather", "forecast", "temperature", "rain", "sunny"]):
241
+ result = await _handle_weather_query(
242
+ user_input=user_input,
243
+ city_name=city_name,
244
+ tenant_id=tenant_id,
245
+ lat=lat,
246
+ lon=lon
247
+ )
248
+
249
+ # Event queries
250
+ elif any(keyword in lowered for keyword in ["events", "meetings", "city hall", "happening", "activities"]):
251
+ result = await _handle_events_query(
252
+ user_input=user_input,
253
+ city_name=city_name,
254
+ tenant_id=tenant_id,
255
+ lat=lat,
256
+ lon=lon
257
+ )
258
+
259
+ # Resource queries (trash, transit, emergency, food banks, libraries, shelters, etc.)
260
+ elif any(keyword in lowered for keyword in [
261
+ "trash", "recycling", "garbage", "waste",
262
+ "bus", "train", "transit", "transportation", "schedule",
263
+ "alert", "warning", "non emergency", "emergency",
264
+ "food bank", "foodbank", "food pantry", "pantry",
265
+ "library", "libraries", "shelter", "shelters",
266
+ "help center", "help center", "assistance", "resource",
267
+ "clinic", "hospital", "pharmacy", "health",
268
+ "housing", "utility", "water", "electric", "gas"
269
+ ]):
270
+ result = await _handle_resource_query(
271
+ user_input=user_input,
272
+ city_name=city_name,
273
+ tenant_id=tenant_id,
274
+ lowered=lowered
275
+ )
276
+
277
+ # Unknown/fallback
278
+ else:
279
+ result = _handle_unknown_query(city_name)
280
+
281
+ # Add metadata and log interaction
282
+ response_time = (time.time() - start_time) * 1000
283
+ result["response_time_ms"] = round(response_time, 2)
284
+ result["role"] = role
285
+
286
+ log_interaction(
287
+ tenant_id=tenant_id,
288
+ interaction_type="tool_request",
289
+ intent=result.get("tool", "unknown"),
290
+ response_time_ms=response_time,
291
+ success=result.get("error") is None,
292
+ metadata={
293
+ "city": city_name,
294
+ "tool": result.get("tool"),
295
+ "role": role,
296
+ "has_location": lat is not None and lon is not None
297
+ }
298
+ )
299
+
300
+ logger.info(
301
+ f"βœ… Tool request complete: {result.get('tool')} "
302
+ f"({response_time:.0f}ms)"
303
+ )
304
+
305
+ return result
306
+
307
+ except Exception as e:
308
+ response_time = (time.time() - start_time) * 1000
309
+ logger.error(f"❌ Tool agent error: {e}", exc_info=True)
310
+
311
+ log_interaction(
312
+ tenant_id="unknown",
313
+ interaction_type="tool_error",
314
+ intent="error",
315
+ response_time_ms=response_time,
316
+ success=False,
317
+ metadata={
318
+ "error": str(e),
319
+ "error_type": type(e).__name__
320
+ }
321
+ )
322
+
323
+ return {
324
+ "tool": "error",
325
+ "response": (
326
+ "I ran into trouble processing that request. "
327
+ "Could you try rephrasing? πŸ’›"
328
+ ),
329
+ "error": str(e),
330
+ "response_time_ms": round(response_time, 2)
331
+ }
332
+
333
+
334
+ # ============================================================
335
+ # WEATHER QUERY HANDLER (ENHANCED)
336
+ # ============================================================
337
+
338
+ async def _handle_weather_query(
339
+ user_input: str,
340
+ city_name: str,
341
+ tenant_id: str,
342
+ lat: Optional[float],
343
+ lon: Optional[float]
344
+ ) -> Dict[str, Any]:
345
+ """
346
+ 🌀️ Handles weather-related queries with outfit recommendations.
347
+ """
348
+ global _weather_request_count
349
+ _weather_request_count += 1
350
+
351
+ logger.info(f"🌀️ Weather query #{_weather_request_count} for {city_name}")
352
+
353
+ # Check weather agent availability
354
+ if not WEATHER_AGENT_AVAILABLE:
355
+ logger.warning("Weather agent not available")
356
+ return {
357
+ "tool": "weather",
358
+ "city": city_name,
359
+ "response": "Weather service isn't available right now. Try again soon! 🌀️"
360
+ }
361
+
362
+ # Get coordinates if not provided
363
+ if lat is None or lon is None:
364
+ coords = get_city_coordinates(tenant_id)
365
+ if coords:
366
+ lat, lon = coords["lat"], coords["lon"]
367
+ logger.info(f"Using city coordinates: {lat}, {lon}")
368
+
369
+ if lat is None or lon is None:
370
+ return {
371
+ "tool": "weather",
372
+ "city": city_name,
373
+ "response": (
374
+ f"To get weather for {city_name}, I need location coordinates. "
375
+ f"Can you share your location? πŸ“"
376
+ )
377
+ }
378
+
379
+ try:
380
+ # Fetch weather data
381
+ weather = await get_weather_for_location(lat, lon)
382
+
383
+ # Get weather-based event recommendations
384
+ recommendations = weather_to_event_recommendations(weather)
385
+
386
+ # Get outfit recommendation
387
+ temp = weather.get("temperature", {}).get("value", 70)
388
+ phrase = weather.get("phrase", "Clear")
389
+ outfit = recommend_outfit(temp, phrase)
390
+
391
+ # Format weather summary
392
+ weather_summary = format_weather_summary(weather)
393
+
394
+ # Build user-friendly response
395
+ response_text = (
396
+ f"🌀️ **Weather for {city_name}:**\n"
397
+ f"{weather_summary}\n\n"
398
+ f"πŸ‘• **What to wear:** {outfit}"
399
+ )
400
+
401
+ # Add event recommendations if available
402
+ if recommendations:
403
+ rec = recommendations[0] # Get top recommendation
404
+ response_text += f"\n\nπŸ“… **Activity suggestion:** {rec['reason']}"
405
+
406
+ return {
407
+ "tool": "weather",
408
+ "city": city_name,
409
+ "tenant_id": tenant_id,
410
+ "response": response_text,
411
+ "data": {
412
+ "weather": weather,
413
+ "recommendations": recommendations,
414
+ "outfit": outfit
415
+ }
416
+ }
417
+
418
+ except Exception as e:
419
+ logger.error(f"Weather query error: {e}", exc_info=True)
420
+ return {
421
+ "tool": "weather",
422
+ "city": city_name,
423
+ "response": (
424
+ f"I couldn't get the weather for {city_name} right now. "
425
+ f"Try again in a moment! 🌀️"
426
+ ),
427
+ "error": str(e)
428
+ }
429
+
430
+
431
+ # ============================================================
432
+ # EVENTS QUERY HANDLER (ENHANCED)
433
+ # ============================================================
434
+
435
+ async def _handle_events_query(
436
+ user_input: str,
437
+ city_name: str,
438
+ tenant_id: str,
439
+ lat: Optional[float],
440
+ lon: Optional[float]
441
+ ) -> Dict[str, Any]:
442
+ """
443
+ πŸ“… Handles event discovery queries.
444
+ """
445
+ global _event_request_count
446
+ _event_request_count += 1
447
+
448
+ logger.info(f"πŸ“… Event query #{_event_request_count} for {city_name}")
449
+
450
+ try:
451
+ # Load structured event data
452
+ event_data = load_city_events(tenant_id)
453
+ events = event_data.get("events", [])
454
+ num_events = len(events)
455
+
456
+ if num_events == 0:
457
+ return {
458
+ "tool": "civic_events",
459
+ "city": city_name,
460
+ "tenant_id": tenant_id,
461
+ "response": (
462
+ f"I don't have any upcoming events for {city_name} right now. "
463
+ f"Check back soon! πŸ“…"
464
+ )
465
+ }
466
+
467
+ # Get top event
468
+ top_event = events[0]
469
+ top_event_name = top_event.get("name", "Upcoming event")
470
+
471
+ # Build response
472
+ if num_events == 1:
473
+ response_text = (
474
+ f"πŸ“… **Upcoming event in {city_name}:**\n"
475
+ f"β€’ {top_event_name}\n\n"
476
+ f"Check the full details in the attached data!"
477
+ )
478
+ else:
479
+ response_text = (
480
+ f"πŸ“… **Found {num_events} upcoming events in {city_name}!**\n"
481
+ f"Top event: {top_event_name}\n\n"
482
+ f"Check the full list in the attached data!"
483
+ )
484
+
485
+ return {
486
+ "tool": "civic_events",
487
+ "city": city_name,
488
+ "tenant_id": tenant_id,
489
+ "response": response_text,
490
+ "data": event_data
491
+ }
492
+
493
+ except FileNotFoundError:
494
+ logger.warning(f"Event data file not found for {tenant_id}")
495
+ return {
496
+ "tool": "civic_events",
497
+ "city": city_name,
498
+ "response": (
499
+ f"Event data for {city_name} isn't available yet. "
500
+ f"I'm still learning about events in your area! πŸ“…"
501
+ ),
502
+ "error": "Event data file not found"
503
+ }
504
+
505
+ except Exception as e:
506
+ logger.error(f"Events query error: {e}", exc_info=True)
507
+ return {
508
+ "tool": "civic_events",
509
+ "city": city_name,
510
+ "response": (
511
+ f"I had trouble loading events for {city_name}. "
512
+ f"Try again soon! πŸ“…"
513
+ ),
514
+ "error": str(e)
515
+ }
516
+
517
+
518
+ # ============================================================
519
+ # RESOURCE QUERY HANDLER (ENHANCED)
520
+ # ============================================================
521
+
522
+ async def _handle_resource_query(
523
+ user_input: str,
524
+ city_name: str,
525
+ tenant_id: str,
526
+ lowered: str
527
+ ) -> Dict[str, Any]:
528
+ """
529
+ ♻️ Handles resource queries (trash, transit, emergency).
530
+ """
531
+ global _resource_request_count
532
+ _resource_request_count += 1
533
+
534
+ logger.info(f"♻️ Resource query #{_resource_request_count} for {city_name}")
535
+
536
+ # Map keywords to resource types
537
+ resource_query_map = {
538
+ # Trash & Recycling
539
+ "trash": "trash_and_recycling",
540
+ "recycling": "trash_and_recycling",
541
+ "garbage": "trash_and_recycling",
542
+ "waste": "trash_and_recycling",
543
+ # Transit
544
+ "bus": "transit",
545
+ "train": "transit",
546
+ "transit": "transit",
547
+ "transportation": "transit",
548
+ "schedule": "transit",
549
+ # Emergency
550
+ "alert": "emergency",
551
+ "warning": "emergency",
552
+ "non emergency": "emergency",
553
+ "emergency": "emergency",
554
+ # Food Assistance
555
+ "food bank": "food_assistance",
556
+ "foodbank": "food_assistance",
557
+ "food pantry": "food_assistance",
558
+ "pantry": "food_assistance",
559
+ # Libraries
560
+ "library": "libraries",
561
+ "libraries": "libraries",
562
+ # Shelters
563
+ "shelter": "shelters",
564
+ "shelters": "shelters",
565
+ # General Resources
566
+ "help center": "community_resources",
567
+ "help center": "community_resources",
568
+ "assistance": "community_resources",
569
+ "resource": "community_resources",
570
+ "resources": "community_resources",
571
+ # Health Services
572
+ "clinic": "health_services",
573
+ "hospital": "health_services",
574
+ "pharmacy": "health_services",
575
+ "health": "health_services",
576
+ # Housing & Utilities
577
+ "housing": "housing_utilities",
578
+ "utility": "housing_utilities",
579
+ "utilities": "housing_utilities",
580
+ "water": "housing_utilities",
581
+ "electric": "housing_utilities",
582
+ "gas": "housing_utilities"
583
+ }
584
+
585
+ # Find matching resource type (check longer phrases first for better specificity)
586
+ # Sort keys by length (longest first) to match "food bank" before "food" (if it existed)
587
+ sorted_keys = sorted(resource_query_map.keys(), key=len, reverse=True)
588
+ resource_key = next(
589
+ (resource_query_map[key] for key in sorted_keys if key in lowered),
590
+ None
591
+ )
592
+
593
+ if not resource_key:
594
+ return {
595
+ "tool": "unknown",
596
+ "city": city_name,
597
+ "response": (
598
+ "I'm not sure which resource you're asking about. "
599
+ "Try asking about trash, transit, food banks, libraries, shelters, "
600
+ "health services, or emergency services! πŸ’¬"
601
+ )
602
+ }
603
+
604
+ try:
605
+ # Load structured resource data
606
+ resource_data = load_city_resources(tenant_id)
607
+ service_info = resource_data["services"].get(resource_key, {})
608
+
609
+ if not service_info:
610
+ return {
611
+ "tool": resource_key,
612
+ "city": city_name,
613
+ "response": (
614
+ f"I don't have {resource_key.replace('_', ' ')} information "
615
+ f"for {city_name} yet. Check the city's official website! πŸ›οΈ"
616
+ )
617
+ }
618
+
619
+ # Build resource-specific response
620
+ if resource_key == "trash_and_recycling":
621
+ pickup_days = service_info.get('pickup_days', 'Varies by address')
622
+ response_text = (
623
+ f"♻️ **Trash & Recycling for {city_name}:**\n"
624
+ f"Pickup days: {pickup_days}\n\n"
625
+ f"Check the official link for your specific schedule!"
626
+ )
627
+
628
+ elif resource_key == "transit":
629
+ provider = service_info.get('provider', 'The local transit authority')
630
+ response_text = (
631
+ f"🚌 **Transit for {city_name}:**\n"
632
+ f"Provider: {provider}\n\n"
633
+ f"Use the provided links to find routes and schedules!"
634
+ )
635
+
636
+ elif resource_key == "emergency":
637
+ non_emergency = service_info.get('non_emergency_phone', 'N/A')
638
+ response_text = (
639
+ f"🚨 **Emergency Info for {city_name}:**\n"
640
+ f"Non-emergency: {non_emergency}\n\n"
641
+ f"**For life-threatening emergencies, always call 911.**"
642
+ )
643
+
644
+ elif resource_key == "food_assistance":
645
+ locations = service_info.get('locations', [])
646
+ if locations:
647
+ response_text = (
648
+ f"🍽️ **Food Assistance in {city_name}:**\n"
649
+ f"Found {len(locations)} food bank(s) or pantry(ies).\n\n"
650
+ f"Check the attached data for locations, hours, and contact information!"
651
+ )
652
+ else:
653
+ response_text = (
654
+ f"🍽️ **Food Assistance in {city_name}:**\n"
655
+ f"Food assistance information is available. Check the attached data for details!"
656
+ )
657
+
658
+ elif resource_key == "libraries":
659
+ locations = service_info.get('locations', [])
660
+ if locations:
661
+ response_text = (
662
+ f"πŸ“š **Libraries in {city_name}:**\n"
663
+ f"Found {len(locations)} library(ies).\n\n"
664
+ f"Check the attached data for locations, hours, and services!"
665
+ )
666
+ else:
667
+ response_text = (
668
+ f"πŸ“š **Libraries in {city_name}:**\n"
669
+ f"Library information is available. Check the attached data for details!"
670
+ )
671
+
672
+ elif resource_key == "shelters":
673
+ locations = service_info.get('locations', [])
674
+ if locations:
675
+ response_text = (
676
+ f"🏠 **Shelters in {city_name}:**\n"
677
+ f"Found {len(locations)} shelter(s).\n\n"
678
+ f"Check the attached data for locations, availability, and contact information!"
679
+ )
680
+ else:
681
+ response_text = (
682
+ f"🏠 **Shelters in {city_name}:**\n"
683
+ f"Shelter information is available. Check the attached data for details!"
684
+ )
685
+
686
+ elif resource_key == "community_resources":
687
+ resources = service_info.get('resources', [])
688
+ if resources:
689
+ response_text = (
690
+ f"πŸ›οΈ **Community Resources in {city_name}:**\n"
691
+ f"Found {len(resources)} resource(s).\n\n"
692
+ f"Check the attached data for available services and contact information!"
693
+ )
694
+ else:
695
+ response_text = (
696
+ f"πŸ›οΈ **Community Resources in {city_name}:**\n"
697
+ f"Community resource information is available. Check the attached data for details!"
698
+ )
699
+
700
+ elif resource_key == "health_services":
701
+ locations = service_info.get('locations', [])
702
+ if locations:
703
+ response_text = (
704
+ f"πŸ₯ **Health Services in {city_name}:**\n"
705
+ f"Found {len(locations)} health service location(s).\n\n"
706
+ f"Check the attached data for clinics, hospitals, and pharmacies!"
707
+ )
708
+ else:
709
+ response_text = (
710
+ f"πŸ₯ **Health Services in {city_name}:**\n"
711
+ f"Health service information is available. Check the attached data for details!"
712
+ )
713
+
714
+ elif resource_key == "housing_utilities":
715
+ response_text = (
716
+ f"🏘️ **Housing & Utilities in {city_name}:**\n"
717
+ f"Housing and utility information is available.\n\n"
718
+ f"Check the attached data for housing assistance and utility services!"
719
+ )
720
+
721
+ else:
722
+ response_text = f"Information found for {resource_key.replace('_', ' ')}, but details aren't available yet."
723
+
724
+ return {
725
+ "tool": resource_key,
726
+ "city": city_name,
727
+ "tenant_id": tenant_id,
728
+ "response": response_text,
729
+ "data": service_info
730
+ }
731
+
732
+ except FileNotFoundError:
733
+ logger.warning(f"Resource data file not found for {tenant_id}")
734
+ return {
735
+ "tool": "resource_loader",
736
+ "city": city_name,
737
+ "response": (
738
+ f"Resource data for {city_name} isn't available yet. "
739
+ f"Check back soon! πŸ›οΈ"
740
+ ),
741
+ "error": "Resource data file not found"
742
+ }
743
+
744
+ except Exception as e:
745
+ logger.error(f"Resource query error: {e}", exc_info=True)
746
+ return {
747
+ "tool": "resource_loader",
748
+ "city": city_name,
749
+ "response": (
750
+ f"I had trouble loading resource data for {city_name}. "
751
+ f"Try again soon! πŸ›οΈ"
752
+ ),
753
+ "error": str(e)
754
+ }
755
+
756
+
757
+ # ============================================================
758
+ # UNKNOWN QUERY HANDLER
759
+ # ============================================================
760
+
761
+ def _handle_unknown_query(city_name: str) -> Dict[str, Any]:
762
+ """
763
+ ❓ Fallback for queries that don't match any tool.
764
+ """
765
+ logger.info(f"❓ Unknown query for {city_name}")
766
+
767
+ return {
768
+ "tool": "unknown",
769
+ "city": city_name,
770
+ "response": (
771
+ "I'm not sure which civic service you're asking about. "
772
+ "Try asking about weather, events, trash, or transit! πŸ’¬"
773
+ )
774
+ }
775
+
776
+
777
+ # ============================================================
778
+ # HEALTH CHECK & DIAGNOSTICS
779
+ # ============================================================
780
+
781
+ def get_tool_agent_health() -> Dict[str, Any]:
782
+ """
783
+ πŸ“Š Returns tool agent health status.
784
+
785
+ Used by the main application health check endpoint.
786
+ """
787
+ return {
788
+ "status": "operational",
789
+ "service_availability": {
790
+ "weather_agent": WEATHER_AGENT_AVAILABLE,
791
+ "location_utils": LOCATION_UTILS_AVAILABLE
792
+ },
793
+ "statistics": {
794
+ "total_requests": _tool_request_count,
795
+ "weather_requests": _weather_request_count,
796
+ "event_requests": _event_request_count,
797
+ "resource_requests": _resource_request_count
798
+ },
799
+ "supported_queries": [
800
+ "weather",
801
+ "events",
802
+ "trash_and_recycling",
803
+ "transit",
804
+ "emergency"
805
+ ]
806
+ }
807
+
808
+
809
+ # ============================================================
810
+ # TESTING
811
+ # ============================================================
812
+
813
+ if __name__ == "__main__":
814
+ """πŸ§ͺ Test tool agent functionality"""
815
+ import asyncio
816
+
817
+ print("=" * 60)
818
+ print("πŸ§ͺ Testing Tool Agent")
819
+ print("=" * 60)
820
+
821
+ # Display service availability
822
+ print("\nπŸ“Š Service Availability:")
823
+ print(f" Weather Agent: {'βœ…' if WEATHER_AGENT_AVAILABLE else '❌'}")
824
+ print(f" Location Utils: {'βœ…' if LOCATION_UTILS_AVAILABLE else '❌'}")
825
+
826
+ print("\n" + "=" * 60)
827
+
828
+ test_queries = [
829
+ {
830
+ "name": "Weather query with context",
831
+ "input": "What's the weather?",
832
+ "lat": 33.7490,
833
+ "lon": -84.3880,
834
+ "context": {"tenant_id": "atlanta"}
835
+ },
836
+ {
837
+ "name": "Events query with context",
838
+ "input": "show me local events",
839
+ "lat": None,
840
+ "lon": None,
841
+ "context": {"tenant_id": "atlanta"}
842
+ },
843
+ {
844
+ "name": "Trash query with context",
845
+ "input": "When is trash pickup?",
846
+ "lat": None,
847
+ "lon": None,
848
+ "context": {"tenant_id": "atlanta"}
849
+ }
850
+ ]
851
+
852
+ async def run_tests():
853
+ for i, query in enumerate(test_queries, 1):
854
+ print(f"\n--- Test {i}: {query['name']} ---")
855
+ print(f"Query: {query['input']}")
856
+ print(f"Context: {query.get('context', {})}")
857
+
858
+ try:
859
+ result = await handle_tool_request(
860
+ user_input=query["input"],
861
+ role="test_user",
862
+ lat=query.get("lat"),
863
+ lon=query.get("lon"),
864
+ context=query.get("context", {})
865
+ )
866
+
867
+ print(f"Tool: {result.get('tool')}")
868
+ print(f"City: {result.get('city')}")
869
+ print(f"Tenant ID: {result.get('tenant_id')}")
870
+
871
+ response = result.get('response')
872
+ if isinstance(response, str):
873
+ print(f"Response: {response[:150]}...")
874
+ else:
875
+ print(f"Response: [Dict with {len(response)} keys]")
876
+
877
+ if result.get('response_time_ms'):
878
+ print(f"Response time: {result['response_time_ms']:.0f}ms")
879
+
880
+ except Exception as e:
881
+ print(f"❌ Error: {e}")
882
+
883
+ asyncio.run(run_tests())
884
+
885
+ print("\n" + "=" * 60)
886
+ print("πŸ“Š Final Statistics:")
887
+ health = get_tool_agent_health()
888
+ for key, value in health["statistics"].items():
889
+ print(f" {key}: {value}")
890
+
891
+ print("\n" + "=" * 60)
892
+ print("βœ… Tests complete")
893
+ print("=" * 60)