pythonprincess commited on
Commit
bc2a262
Β·
verified Β·
1 Parent(s): 40bd7d6

Upload tool_agent.py

Browse files
Files changed (1) hide show
  1. tool_agent.py +768 -0
tool_agent.py ADDED
@@ -0,0 +1,768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
260
+ elif any(keyword in lowered for keyword in ["trash", "recycling", "garbage", "bus", "train", "schedule", "alert", "warning", "non emergency"]):
261
+ result = await _handle_resource_query(
262
+ user_input=user_input,
263
+ city_name=city_name,
264
+ tenant_id=tenant_id,
265
+ lowered=lowered
266
+ )
267
+
268
+ # Unknown/fallback
269
+ else:
270
+ result = _handle_unknown_query(city_name)
271
+
272
+ # Add metadata and log interaction
273
+ response_time = (time.time() - start_time) * 1000
274
+ result["response_time_ms"] = round(response_time, 2)
275
+ result["role"] = role
276
+
277
+ log_interaction(
278
+ tenant_id=tenant_id,
279
+ interaction_type="tool_request",
280
+ intent=result.get("tool", "unknown"),
281
+ response_time_ms=response_time,
282
+ success=result.get("error") is None,
283
+ metadata={
284
+ "city": city_name,
285
+ "tool": result.get("tool"),
286
+ "role": role,
287
+ "has_location": lat is not None and lon is not None
288
+ }
289
+ )
290
+
291
+ logger.info(
292
+ f"βœ… Tool request complete: {result.get('tool')} "
293
+ f"({response_time:.0f}ms)"
294
+ )
295
+
296
+ return result
297
+
298
+ except Exception as e:
299
+ response_time = (time.time() - start_time) * 1000
300
+ logger.error(f"❌ Tool agent error: {e}", exc_info=True)
301
+
302
+ log_interaction(
303
+ tenant_id="unknown",
304
+ interaction_type="tool_error",
305
+ intent="error",
306
+ response_time_ms=response_time,
307
+ success=False,
308
+ metadata={
309
+ "error": str(e),
310
+ "error_type": type(e).__name__
311
+ }
312
+ )
313
+
314
+ return {
315
+ "tool": "error",
316
+ "response": (
317
+ "I ran into trouble processing that request. "
318
+ "Could you try rephrasing? πŸ’›"
319
+ ),
320
+ "error": str(e),
321
+ "response_time_ms": round(response_time, 2)
322
+ }
323
+
324
+
325
+ # ============================================================
326
+ # WEATHER QUERY HANDLER (ENHANCED)
327
+ # ============================================================
328
+
329
+ async def _handle_weather_query(
330
+ user_input: str,
331
+ city_name: str,
332
+ tenant_id: str,
333
+ lat: Optional[float],
334
+ lon: Optional[float]
335
+ ) -> Dict[str, Any]:
336
+ """
337
+ 🌀️ Handles weather-related queries with outfit recommendations.
338
+ """
339
+ global _weather_request_count
340
+ _weather_request_count += 1
341
+
342
+ logger.info(f"🌀️ Weather query #{_weather_request_count} for {city_name}")
343
+
344
+ # Check weather agent availability
345
+ if not WEATHER_AGENT_AVAILABLE:
346
+ logger.warning("Weather agent not available")
347
+ return {
348
+ "tool": "weather",
349
+ "city": city_name,
350
+ "response": "Weather service isn't available right now. Try again soon! 🌀️"
351
+ }
352
+
353
+ # Get coordinates if not provided
354
+ if lat is None or lon is None:
355
+ coords = get_city_coordinates(tenant_id)
356
+ if coords:
357
+ lat, lon = coords["lat"], coords["lon"]
358
+ logger.info(f"Using city coordinates: {lat}, {lon}")
359
+
360
+ if lat is None or lon is None:
361
+ return {
362
+ "tool": "weather",
363
+ "city": city_name,
364
+ "response": (
365
+ f"To get weather for {city_name}, I need location coordinates. "
366
+ f"Can you share your location? πŸ“"
367
+ )
368
+ }
369
+
370
+ try:
371
+ # Fetch weather data
372
+ weather = await get_weather_for_location(lat, lon)
373
+
374
+ # Get weather-based event recommendations
375
+ recommendations = weather_to_event_recommendations(weather)
376
+
377
+ # Get outfit recommendation
378
+ temp = weather.get("temperature", {}).get("value", 70)
379
+ phrase = weather.get("phrase", "Clear")
380
+ outfit = recommend_outfit(temp, phrase)
381
+
382
+ # Format weather summary
383
+ weather_summary = format_weather_summary(weather)
384
+
385
+ # Build user-friendly response
386
+ response_text = (
387
+ f"🌀️ **Weather for {city_name}:**\n"
388
+ f"{weather_summary}\n\n"
389
+ f"πŸ‘• **What to wear:** {outfit}"
390
+ )
391
+
392
+ # Add event recommendations if available
393
+ if recommendations:
394
+ rec = recommendations[0] # Get top recommendation
395
+ response_text += f"\n\nπŸ“… **Activity suggestion:** {rec['reason']}"
396
+
397
+ return {
398
+ "tool": "weather",
399
+ "city": city_name,
400
+ "tenant_id": tenant_id,
401
+ "response": response_text,
402
+ "data": {
403
+ "weather": weather,
404
+ "recommendations": recommendations,
405
+ "outfit": outfit
406
+ }
407
+ }
408
+
409
+ except Exception as e:
410
+ logger.error(f"Weather query error: {e}", exc_info=True)
411
+ return {
412
+ "tool": "weather",
413
+ "city": city_name,
414
+ "response": (
415
+ f"I couldn't get the weather for {city_name} right now. "
416
+ f"Try again in a moment! 🌀️"
417
+ ),
418
+ "error": str(e)
419
+ }
420
+
421
+
422
+ # ============================================================
423
+ # EVENTS QUERY HANDLER (ENHANCED)
424
+ # ============================================================
425
+
426
+ async def _handle_events_query(
427
+ user_input: str,
428
+ city_name: str,
429
+ tenant_id: str,
430
+ lat: Optional[float],
431
+ lon: Optional[float]
432
+ ) -> Dict[str, Any]:
433
+ """
434
+ πŸ“… Handles event discovery queries.
435
+ """
436
+ global _event_request_count
437
+ _event_request_count += 1
438
+
439
+ logger.info(f"πŸ“… Event query #{_event_request_count} for {city_name}")
440
+
441
+ try:
442
+ # Load structured event data
443
+ event_data = load_city_events(tenant_id)
444
+ events = event_data.get("events", [])
445
+ num_events = len(events)
446
+
447
+ if num_events == 0:
448
+ return {
449
+ "tool": "civic_events",
450
+ "city": city_name,
451
+ "tenant_id": tenant_id,
452
+ "response": (
453
+ f"I don't have any upcoming events for {city_name} right now. "
454
+ f"Check back soon! πŸ“…"
455
+ )
456
+ }
457
+
458
+ # Get top event
459
+ top_event = events[0]
460
+ top_event_name = top_event.get("name", "Upcoming event")
461
+
462
+ # Build response
463
+ if num_events == 1:
464
+ response_text = (
465
+ f"πŸ“… **Upcoming event in {city_name}:**\n"
466
+ f"β€’ {top_event_name}\n\n"
467
+ f"Check the full details in the attached data!"
468
+ )
469
+ else:
470
+ response_text = (
471
+ f"πŸ“… **Found {num_events} upcoming events in {city_name}!**\n"
472
+ f"Top event: {top_event_name}\n\n"
473
+ f"Check the full list in the attached data!"
474
+ )
475
+
476
+ return {
477
+ "tool": "civic_events",
478
+ "city": city_name,
479
+ "tenant_id": tenant_id,
480
+ "response": response_text,
481
+ "data": event_data
482
+ }
483
+
484
+ except FileNotFoundError:
485
+ logger.warning(f"Event data file not found for {tenant_id}")
486
+ return {
487
+ "tool": "civic_events",
488
+ "city": city_name,
489
+ "response": (
490
+ f"Event data for {city_name} isn't available yet. "
491
+ f"I'm still learning about events in your area! πŸ“…"
492
+ ),
493
+ "error": "Event data file not found"
494
+ }
495
+
496
+ except Exception as e:
497
+ logger.error(f"Events query error: {e}", exc_info=True)
498
+ return {
499
+ "tool": "civic_events",
500
+ "city": city_name,
501
+ "response": (
502
+ f"I had trouble loading events for {city_name}. "
503
+ f"Try again soon! πŸ“…"
504
+ ),
505
+ "error": str(e)
506
+ }
507
+
508
+
509
+ # ============================================================
510
+ # RESOURCE QUERY HANDLER (ENHANCED)
511
+ # ============================================================
512
+
513
+ async def _handle_resource_query(
514
+ user_input: str,
515
+ city_name: str,
516
+ tenant_id: str,
517
+ lowered: str
518
+ ) -> Dict[str, Any]:
519
+ """
520
+ ♻️ Handles resource queries (trash, transit, emergency).
521
+ """
522
+ global _resource_request_count
523
+ _resource_request_count += 1
524
+
525
+ logger.info(f"♻️ Resource query #{_resource_request_count} for {city_name}")
526
+
527
+ # Map keywords to resource types
528
+ resource_query_map = {
529
+ "trash": "trash_and_recycling",
530
+ "recycling": "trash_and_recycling",
531
+ "garbage": "trash_and_recycling",
532
+ "bus": "transit",
533
+ "train": "transit",
534
+ "schedule": "transit",
535
+ "alert": "emergency",
536
+ "warning": "emergency",
537
+ "non emergency": "emergency"
538
+ }
539
+
540
+ # Find matching resource type
541
+ resource_key = next(
542
+ (resource_query_map[key] for key in resource_query_map if key in lowered),
543
+ None
544
+ )
545
+
546
+ if not resource_key:
547
+ return {
548
+ "tool": "unknown",
549
+ "city": city_name,
550
+ "response": (
551
+ "I'm not sure which resource you're asking about. "
552
+ "Try asking about trash, transit, or emergency services! πŸ’¬"
553
+ )
554
+ }
555
+
556
+ try:
557
+ # Load structured resource data
558
+ resource_data = load_city_resources(tenant_id)
559
+ service_info = resource_data["services"].get(resource_key, {})
560
+
561
+ if not service_info:
562
+ return {
563
+ "tool": resource_key,
564
+ "city": city_name,
565
+ "response": (
566
+ f"I don't have {resource_key.replace('_', ' ')} information "
567
+ f"for {city_name} yet. Check the city's official website! πŸ›οΈ"
568
+ )
569
+ }
570
+
571
+ # Build resource-specific response
572
+ if resource_key == "trash_and_recycling":
573
+ pickup_days = service_info.get('pickup_days', 'Varies by address')
574
+ response_text = (
575
+ f"♻️ **Trash & Recycling for {city_name}:**\n"
576
+ f"Pickup days: {pickup_days}\n\n"
577
+ f"Check the official link for your specific schedule!"
578
+ )
579
+
580
+ elif resource_key == "transit":
581
+ provider = service_info.get('provider', 'The local transit authority')
582
+ response_text = (
583
+ f"🚌 **Transit for {city_name}:**\n"
584
+ f"Provider: {provider}\n\n"
585
+ f"Use the provided links to find routes and schedules!"
586
+ )
587
+
588
+ elif resource_key == "emergency":
589
+ non_emergency = service_info.get('non_emergency_phone', 'N/A')
590
+ response_text = (
591
+ f"🚨 **Emergency Info for {city_name}:**\n"
592
+ f"Non-emergency: {non_emergency}\n\n"
593
+ f"**For life-threatening emergencies, always call 911.**"
594
+ )
595
+
596
+ else:
597
+ response_text = f"Information found for {resource_key.replace('_', ' ')}, but details aren't available yet."
598
+
599
+ return {
600
+ "tool": resource_key,
601
+ "city": city_name,
602
+ "tenant_id": tenant_id,
603
+ "response": response_text,
604
+ "data": service_info
605
+ }
606
+
607
+ except FileNotFoundError:
608
+ logger.warning(f"Resource data file not found for {tenant_id}")
609
+ return {
610
+ "tool": "resource_loader",
611
+ "city": city_name,
612
+ "response": (
613
+ f"Resource data for {city_name} isn't available yet. "
614
+ f"Check back soon! πŸ›οΈ"
615
+ ),
616
+ "error": "Resource data file not found"
617
+ }
618
+
619
+ except Exception as e:
620
+ logger.error(f"Resource query error: {e}", exc_info=True)
621
+ return {
622
+ "tool": "resource_loader",
623
+ "city": city_name,
624
+ "response": (
625
+ f"I had trouble loading resource data for {city_name}. "
626
+ f"Try again soon! πŸ›οΈ"
627
+ ),
628
+ "error": str(e)
629
+ }
630
+
631
+
632
+ # ============================================================
633
+ # UNKNOWN QUERY HANDLER
634
+ # ============================================================
635
+
636
+ def _handle_unknown_query(city_name: str) -> Dict[str, Any]:
637
+ """
638
+ ❓ Fallback for queries that don't match any tool.
639
+ """
640
+ logger.info(f"❓ Unknown query for {city_name}")
641
+
642
+ return {
643
+ "tool": "unknown",
644
+ "city": city_name,
645
+ "response": (
646
+ "I'm not sure which civic service you're asking about. "
647
+ "Try asking about weather, events, trash, or transit! πŸ’¬"
648
+ )
649
+ }
650
+
651
+
652
+ # ============================================================
653
+ # HEALTH CHECK & DIAGNOSTICS
654
+ # ============================================================
655
+
656
+ def get_tool_agent_health() -> Dict[str, Any]:
657
+ """
658
+ πŸ“Š Returns tool agent health status.
659
+
660
+ Used by the main application health check endpoint.
661
+ """
662
+ return {
663
+ "status": "operational",
664
+ "service_availability": {
665
+ "weather_agent": WEATHER_AGENT_AVAILABLE,
666
+ "location_utils": LOCATION_UTILS_AVAILABLE
667
+ },
668
+ "statistics": {
669
+ "total_requests": _tool_request_count,
670
+ "weather_requests": _weather_request_count,
671
+ "event_requests": _event_request_count,
672
+ "resource_requests": _resource_request_count
673
+ },
674
+ "supported_queries": [
675
+ "weather",
676
+ "events",
677
+ "trash_and_recycling",
678
+ "transit",
679
+ "emergency"
680
+ ]
681
+ }
682
+
683
+
684
+ # ============================================================
685
+ # TESTING
686
+ # ============================================================
687
+
688
+ if __name__ == "__main__":
689
+ """πŸ§ͺ Test tool agent functionality"""
690
+ import asyncio
691
+
692
+ print("=" * 60)
693
+ print("πŸ§ͺ Testing Tool Agent")
694
+ print("=" * 60)
695
+
696
+ # Display service availability
697
+ print("\nπŸ“Š Service Availability:")
698
+ print(f" Weather Agent: {'βœ…' if WEATHER_AGENT_AVAILABLE else '❌'}")
699
+ print(f" Location Utils: {'βœ…' if LOCATION_UTILS_AVAILABLE else '❌'}")
700
+
701
+ print("\n" + "=" * 60)
702
+
703
+ test_queries = [
704
+ {
705
+ "name": "Weather query with context",
706
+ "input": "What's the weather?",
707
+ "lat": 33.7490,
708
+ "lon": -84.3880,
709
+ "context": {"tenant_id": "atlanta"}
710
+ },
711
+ {
712
+ "name": "Events query with context",
713
+ "input": "show me local events",
714
+ "lat": None,
715
+ "lon": None,
716
+ "context": {"tenant_id": "atlanta"}
717
+ },
718
+ {
719
+ "name": "Trash query with context",
720
+ "input": "When is trash pickup?",
721
+ "lat": None,
722
+ "lon": None,
723
+ "context": {"tenant_id": "atlanta"}
724
+ }
725
+ ]
726
+
727
+ async def run_tests():
728
+ for i, query in enumerate(test_queries, 1):
729
+ print(f"\n--- Test {i}: {query['name']} ---")
730
+ print(f"Query: {query['input']}")
731
+ print(f"Context: {query.get('context', {})}")
732
+
733
+ try:
734
+ result = await handle_tool_request(
735
+ user_input=query["input"],
736
+ role="test_user",
737
+ lat=query.get("lat"),
738
+ lon=query.get("lon"),
739
+ context=query.get("context", {})
740
+ )
741
+
742
+ print(f"Tool: {result.get('tool')}")
743
+ print(f"City: {result.get('city')}")
744
+ print(f"Tenant ID: {result.get('tenant_id')}")
745
+
746
+ response = result.get('response')
747
+ if isinstance(response, str):
748
+ print(f"Response: {response[:150]}...")
749
+ else:
750
+ print(f"Response: [Dict with {len(response)} keys]")
751
+
752
+ if result.get('response_time_ms'):
753
+ print(f"Response time: {result['response_time_ms']:.0f}ms")
754
+
755
+ except Exception as e:
756
+ print(f"❌ Error: {e}")
757
+
758
+ asyncio.run(run_tests())
759
+
760
+ print("\n" + "=" * 60)
761
+ print("πŸ“Š Final Statistics:")
762
+ health = get_tool_agent_health()
763
+ for key, value in health["statistics"].items():
764
+ print(f" {key}: {value}")
765
+
766
+ print("\n" + "=" * 60)
767
+ print("βœ… Tests complete")
768
+ print("=" * 60)