pythonprincess commited on
Commit
6fcb9f3
Β·
verified Β·
1 Parent(s): 38c70dd

Upload orchestrator.py

Browse files
Files changed (1) hide show
  1. app/orchestrator.py +1404 -0
app/orchestrator.py ADDED
@@ -0,0 +1,1404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 🎭 PENNY Orchestrator - Request Routing & Coordination Engine
3
+
4
+ This is Penny's decision-making brain. She analyzes each request, determines
5
+ the best way to help, and coordinates between her specialized AI models and
6
+ civic data tools.
7
+
8
+ MISSION: Route every resident request to the right resource while maintaining
9
+ Penny's warm, helpful personality and ensuring fast, accurate responses.
10
+
11
+ FEATURES:
12
+ - Enhanced intent classification with confidence scoring
13
+ - Compound intent handling (weather + events)
14
+ - Graceful fallbacks when services are unavailable
15
+ - Performance tracking for all operations
16
+ - Context-aware responses
17
+ - Emergency routing with immediate escalation
18
+
19
+ ENHANCEMENTS (Phase 1):
20
+ - βœ… Structured logging with performance tracking
21
+ - βœ… Safe imports with availability flags
22
+ - βœ… Result format checking helper
23
+ - βœ… Enhanced error handling patterns
24
+ - βœ… Service availability tracking
25
+ - βœ… Fixed function signature mismatches
26
+ - βœ… Integration with enhanced modules
27
+ """
28
+
29
+ import logging
30
+ import time
31
+ from typing import Dict, Any, Optional, List, Tuple
32
+ from datetime import datetime
33
+ from dataclasses import dataclass, field
34
+ from enum import Enum
35
+
36
+ # --- ENHANCED MODULE IMPORTS ---
37
+ from app.intents import classify_intent_detailed, IntentType, IntentMatch
38
+ from app.location_utils import (
39
+ extract_location_detailed,
40
+ LocationMatch,
41
+ LocationStatus,
42
+ get_city_coordinates
43
+ )
44
+ from app.logging_utils import (
45
+ log_interaction,
46
+ sanitize_for_logging,
47
+ LogLevel
48
+ )
49
+
50
+ # --- AGENT IMPORTS (with availability tracking) ---
51
+ try:
52
+ from app.weather_agent import (
53
+ get_weather_for_location,
54
+ recommend_outfit,
55
+ weather_to_event_recommendations,
56
+ format_weather_summary
57
+ )
58
+ WEATHER_AGENT_AVAILABLE = True
59
+ except ImportError as e:
60
+ logger = logging.getLogger(__name__)
61
+ logger.warning(f"Weather agent not available: {e}")
62
+ WEATHER_AGENT_AVAILABLE = False
63
+
64
+ try:
65
+ from app.event_weather import get_event_recommendations_with_weather
66
+ EVENT_WEATHER_AVAILABLE = True
67
+ except ImportError as e:
68
+ logger = logging.getLogger(__name__)
69
+ logger.warning(f"Event weather integration not available: {e}")
70
+ EVENT_WEATHER_AVAILABLE = False
71
+
72
+ try:
73
+ from app.tool_agent import handle_tool_request
74
+ TOOL_AGENT_AVAILABLE = True
75
+ except ImportError as e:
76
+ logger = logging.getLogger(__name__)
77
+ logger.warning(f"Tool agent not available: {e}")
78
+ TOOL_AGENT_AVAILABLE = False
79
+
80
+ # --- MODEL IMPORTS (with availability tracking) ---
81
+ try:
82
+ from models.translation.translation_utils import translate_text
83
+ TRANSLATION_AVAILABLE = True
84
+ except ImportError as e:
85
+ logger = logging.getLogger(__name__)
86
+ logger.warning(f"Translation service not available: {e}")
87
+ TRANSLATION_AVAILABLE = False
88
+
89
+ try:
90
+ from models.sentiment.sentiment_utils import get_sentiment_analysis
91
+ SENTIMENT_AVAILABLE = True
92
+ except ImportError as e:
93
+ logger = logging.getLogger(__name__)
94
+ logger.warning(f"Sentiment service not available: {e}")
95
+ SENTIMENT_AVAILABLE = False
96
+
97
+ try:
98
+ from models.bias.bias_utils import check_bias
99
+ BIAS_AVAILABLE = True
100
+ except ImportError as e:
101
+ logger = logging.getLogger(__name__)
102
+ logger.warning(f"Bias detection service not available: {e}")
103
+ BIAS_AVAILABLE = False
104
+
105
+ try:
106
+ from models.gemma.gemma_utils import generate_response
107
+ LLM_AVAILABLE = True
108
+ except ImportError as e:
109
+ logger = logging.getLogger(__name__)
110
+ logger.warning(f"LLM service not available: {e}")
111
+ LLM_AVAILABLE = False
112
+
113
+ # --- LOGGING SETUP ---
114
+ logger = logging.getLogger(__name__)
115
+
116
+ # --- CONFIGURATION ---
117
+ CORE_MODEL_ID = "penny-core-agent"
118
+ MAX_RESPONSE_TIME_MS = 5000 # 5 seconds - log if exceeded
119
+
120
+ # --- TRACKING COUNTERS ---
121
+ _orchestration_count = 0
122
+ _emergency_count = 0
123
+
124
+
125
+ # ============================================================
126
+ # COMPATIBILITY HELPER - Result Format Checking
127
+ # ============================================================
128
+
129
+ def _check_result_success(
130
+ result: Dict[str, Any],
131
+ expected_keys: List[str]
132
+ ) -> Tuple[bool, Optional[str]]:
133
+ """
134
+ βœ… Check if a utility function result indicates success.
135
+
136
+ Handles multiple return format patterns:
137
+ - Explicit "success" key (preferred)
138
+ - Presence of expected data keys (implicit success)
139
+ - Presence of "error" key (explicit failure)
140
+
141
+ This helper fixes compatibility issues where different utility
142
+ functions return different result formats.
143
+
144
+ Args:
145
+ result: Dictionary returned from utility function
146
+ expected_keys: List of keys that indicate successful data
147
+
148
+ Returns:
149
+ Tuple of (is_success, error_message)
150
+
151
+ Example:
152
+ result = await translate_text(message, "en", "es")
153
+ success, error = _check_result_success(result, ["translated_text"])
154
+ if success:
155
+ text = result.get("translated_text")
156
+ """
157
+ # Check for explicit success key
158
+ if "success" in result:
159
+ return result["success"], result.get("error")
160
+
161
+ # Check for explicit error (presence = failure)
162
+ if "error" in result and result["error"]:
163
+ return False, result["error"]
164
+
165
+ # Check for expected data keys (implicit success)
166
+ has_data = any(key in result for key in expected_keys)
167
+ if has_data:
168
+ return True, None
169
+
170
+ # Unknown format - assume failure
171
+ return False, "Unexpected response format"
172
+
173
+
174
+ # ============================================================
175
+ # SERVICE AVAILABILITY CHECK
176
+ # ============================================================
177
+
178
+ def get_service_availability() -> Dict[str, bool]:
179
+ """
180
+ πŸ“Š Returns which services are currently available.
181
+
182
+ Used for health checks, debugging, and deciding whether
183
+ to attempt service calls or use fallbacks.
184
+
185
+ Returns:
186
+ Dictionary mapping service names to availability status
187
+ """
188
+ return {
189
+ "translation": TRANSLATION_AVAILABLE,
190
+ "sentiment": SENTIMENT_AVAILABLE,
191
+ "bias_detection": BIAS_AVAILABLE,
192
+ "llm": LLM_AVAILABLE,
193
+ "tool_agent": TOOL_AGENT_AVAILABLE,
194
+ "weather": WEATHER_AGENT_AVAILABLE,
195
+ "event_weather": EVENT_WEATHER_AVAILABLE
196
+ }
197
+
198
+
199
+ # ============================================================
200
+ # ORCHESTRATION RESULT STRUCTURE
201
+ # ============================================================
202
+
203
+ @dataclass
204
+ class OrchestrationResult:
205
+ """
206
+ πŸ“¦ Structured result from orchestration pipeline.
207
+
208
+ This format is used throughout the system for consistency
209
+ and makes it easy to track what happened during request processing.
210
+ """
211
+ intent: str # Detected intent
212
+ reply: str # User-facing response
213
+ success: bool # Whether request succeeded
214
+ tenant_id: Optional[str] = None # City/location identifier
215
+ data: Optional[Dict[str, Any]] = None # Raw data from services
216
+ model_id: Optional[str] = None # Which model/service was used
217
+ error: Optional[str] = None # Error message if failed
218
+ response_time_ms: Optional[float] = None
219
+ confidence: Optional[float] = None # Intent confidence score
220
+ fallback_used: bool = False # True if fallback logic triggered
221
+
222
+ def to_dict(self) -> Dict[str, Any]:
223
+ """Converts to dictionary for API responses."""
224
+ return {
225
+ "intent": self.intent,
226
+ "reply": self.reply,
227
+ "success": self.success,
228
+ "tenant_id": self.tenant_id,
229
+ "data": self.data,
230
+ "model_id": self.model_id,
231
+ "error": self.error,
232
+ "response_time_ms": self.response_time_ms,
233
+ "confidence": self.confidence,
234
+ "fallback_used": self.fallback_used
235
+ }
236
+
237
+
238
+ # ============================================================
239
+ # MAIN ORCHESTRATOR FUNCTION (ENHANCED)
240
+ # ============================================================
241
+
242
+ async def run_orchestrator(
243
+ message: str,
244
+ context: Dict[str, Any] = None
245
+ ) -> Dict[str, Any]:
246
+ """
247
+ 🧠 Main decision-making brain of Penny.
248
+
249
+ This function:
250
+ 1. Analyzes the user's message to determine intent
251
+ 2. Extracts location/city information
252
+ 3. Routes to the appropriate specialized service
253
+ 4. Handles errors gracefully with helpful fallbacks
254
+ 5. Tracks performance and logs the interaction
255
+
256
+ Args:
257
+ message: User's input text
258
+ context: Additional context (tenant_id, lat, lon, session_id, etc.)
259
+
260
+ Returns:
261
+ Dictionary with response and metadata
262
+
263
+ Example:
264
+ result = await run_orchestrator(
265
+ message="What's the weather in Atlanta?",
266
+ context={"lat": 33.7490, "lon": -84.3880}
267
+ )
268
+ """
269
+ global _orchestration_count
270
+ _orchestration_count += 1
271
+
272
+ start_time = time.time()
273
+
274
+ # Initialize context if not provided
275
+ if context is None:
276
+ context = {}
277
+
278
+ # Sanitize message for logging (PII protection)
279
+ safe_message = sanitize_for_logging(message)
280
+ logger.info(f"🎭 Orchestrator processing: '{safe_message[:50]}...'")
281
+
282
+ try:
283
+ # === STEP 1: CLASSIFY INTENT (Enhanced) ===
284
+ intent_result = classify_intent_detailed(message)
285
+ intent = intent_result.intent
286
+ confidence = intent_result.confidence
287
+
288
+ logger.info(
289
+ f"Intent detected: {intent.value} "
290
+ f"(confidence: {confidence:.2f})"
291
+ )
292
+
293
+ # === STEP 2: EXTRACT LOCATION ===
294
+ tenant_id = context.get("tenant_id")
295
+ lat = context.get("lat")
296
+ lon = context.get("lon")
297
+
298
+ # If tenant_id not provided, try to extract from message
299
+ if not tenant_id or tenant_id == "unknown":
300
+ location_result = extract_location_detailed(message)
301
+
302
+ if location_result.status == LocationStatus.FOUND:
303
+ tenant_id = location_result.tenant_id
304
+ logger.info(f"Location extracted: {tenant_id}")
305
+
306
+ # Get coordinates for this tenant if available
307
+ coords = get_city_coordinates(tenant_id)
308
+ if coords and lat is None and lon is None:
309
+ lat, lon = coords["lat"], coords["lon"]
310
+ logger.info(f"Coordinates loaded: {lat}, {lon}")
311
+
312
+ elif location_result.status == LocationStatus.USER_LOCATION_NEEDED:
313
+ logger.info("User location services needed")
314
+ else:
315
+ logger.info(f"No location detected: {location_result.status}")
316
+
317
+ # === STEP 3: HANDLE EMERGENCY INTENTS (CRITICAL) ===
318
+ if intent == IntentType.EMERGENCY:
319
+ return await _handle_emergency(
320
+ message=message,
321
+ context=context,
322
+ start_time=start_time
323
+ )
324
+
325
+ # === STEP 4: ROUTE TO APPROPRIATE HANDLER ===
326
+
327
+ # Translation
328
+ if intent == IntentType.TRANSLATION:
329
+ result = await _handle_translation(message, context)
330
+
331
+ # Sentiment Analysis
332
+ elif intent == IntentType.SENTIMENT_ANALYSIS:
333
+ result = await _handle_sentiment(message, context)
334
+
335
+ # Bias Detection
336
+ elif intent == IntentType.BIAS_DETECTION:
337
+ result = await _handle_bias(message, context)
338
+
339
+ # Document Processing
340
+ elif intent == IntentType.DOCUMENT_PROCESSING:
341
+ result = await _handle_document(message, context)
342
+
343
+ # Weather (includes compound weather+events handling)
344
+ elif intent == IntentType.WEATHER:
345
+ result = await _handle_weather(
346
+ message=message,
347
+ context=context,
348
+ tenant_id=tenant_id,
349
+ lat=lat,
350
+ lon=lon,
351
+ intent_result=intent_result
352
+ )
353
+
354
+ # Events
355
+ elif intent == IntentType.EVENTS:
356
+ result = await _handle_events(
357
+ message=message,
358
+ context=context,
359
+ tenant_id=tenant_id,
360
+ lat=lat,
361
+ lon=lon,
362
+ intent_result=intent_result
363
+ )
364
+
365
+ # Local Resources
366
+ elif intent == IntentType.LOCAL_RESOURCES:
367
+ result = await _handle_local_resources(
368
+ message=message,
369
+ context=context,
370
+ tenant_id=tenant_id,
371
+ lat=lat,
372
+ lon=lon
373
+ )
374
+
375
+ # Greeting, Help, Unknown
376
+ elif intent in [IntentType.GREETING, IntentType.HELP, IntentType.UNKNOWN]:
377
+ result = await _handle_conversational(
378
+ message=message,
379
+ intent=intent,
380
+ context=context
381
+ )
382
+
383
+ else:
384
+ # Unhandled intent type (shouldn't happen, but safety net)
385
+ result = await _handle_fallback(message, intent, context)
386
+
387
+ # === STEP 5: ADD METADATA & LOG INTERACTION ===
388
+ response_time = (time.time() - start_time) * 1000
389
+ result.response_time_ms = round(response_time, 2)
390
+ result.confidence = confidence
391
+ result.tenant_id = tenant_id
392
+
393
+ # Log the interaction with structured logging
394
+ log_interaction(
395
+ tenant_id=tenant_id or "unknown",
396
+ interaction_type="orchestration",
397
+ intent=intent.value,
398
+ response_time_ms=response_time,
399
+ success=result.success,
400
+ metadata={
401
+ "confidence": confidence,
402
+ "fallback_used": result.fallback_used,
403
+ "model_id": result.model_id,
404
+ "orchestration_count": _orchestration_count
405
+ }
406
+ )
407
+
408
+ # Log slow responses
409
+ if response_time > MAX_RESPONSE_TIME_MS:
410
+ logger.warning(
411
+ f"⚠️ Slow response: {response_time:.0f}ms "
412
+ f"(intent: {intent.value})"
413
+ )
414
+
415
+ logger.info(
416
+ f"βœ… Orchestration complete: {intent.value} "
417
+ f"({response_time:.0f}ms)"
418
+ )
419
+
420
+ return result.to_dict()
421
+
422
+ except Exception as e:
423
+ # === CATASTROPHIC FAILURE HANDLER ===
424
+ response_time = (time.time() - start_time) * 1000
425
+ logger.error(
426
+ f"❌ Orchestrator error: {e} "
427
+ f"(response_time: {response_time:.0f}ms)",
428
+ exc_info=True
429
+ )
430
+
431
+ # Log failed interaction
432
+ log_interaction(
433
+ tenant_id=context.get("tenant_id", "unknown"),
434
+ interaction_type="orchestration_error",
435
+ intent="error",
436
+ response_time_ms=response_time,
437
+ success=False,
438
+ metadata={
439
+ "error": str(e),
440
+ "error_type": type(e).__name__
441
+ }
442
+ )
443
+
444
+ error_result = OrchestrationResult(
445
+ intent="error",
446
+ reply=(
447
+ "I'm having trouble processing your request right now. "
448
+ "Please try again in a moment, or let me know if you need "
449
+ "immediate assistance! πŸ’›"
450
+ ),
451
+ success=False,
452
+ error=str(e),
453
+ model_id="orchestrator",
454
+ fallback_used=True,
455
+ response_time_ms=round(response_time, 2)
456
+ )
457
+
458
+ return error_result.to_dict()
459
+
460
+
461
+ # ============================================================
462
+ # SPECIALIZED INTENT HANDLERS (ENHANCED)
463
+ # ============================================================
464
+
465
+ async def _handle_emergency(
466
+ message: str,
467
+ context: Dict[str, Any],
468
+ start_time: float
469
+ ) -> OrchestrationResult:
470
+ """
471
+ 🚨 CRITICAL: Emergency intent handler.
472
+
473
+ This function handles crisis situations with immediate routing
474
+ to appropriate services. All emergency interactions are logged
475
+ for compliance and safety tracking.
476
+
477
+ IMPORTANT: This is a compliance-critical function. All emergency
478
+ interactions must be logged and handled with priority.
479
+ """
480
+ global _emergency_count
481
+ _emergency_count += 1
482
+
483
+ # Sanitize message for logging (but keep full context for safety review)
484
+ safe_message = sanitize_for_logging(message)
485
+ logger.warning(f"🚨 EMERGENCY INTENT DETECTED (#{_emergency_count}): {safe_message[:100]}")
486
+
487
+ # TODO: Integrate with safety_utils.py when enhanced
488
+ # from app.safety_utils import route_emergency
489
+ # result = await route_emergency(message, context)
490
+
491
+ # For now, provide crisis resources
492
+ reply = (
493
+ "🚨 **If this is a life-threatening emergency, please call 911 immediately.**\n\n"
494
+ "For crisis support:\n"
495
+ "- **National Suicide Prevention Lifeline:** 988\n"
496
+ "- **Crisis Text Line:** Text HOME to 741741\n"
497
+ "- **National Domestic Violence Hotline:** 1-800-799-7233\n\n"
498
+ "I'm here to help connect you with local resources. "
499
+ "What kind of support do you need right now?"
500
+ )
501
+
502
+ # Log emergency interaction for compliance (CRITICAL)
503
+ response_time = (time.time() - start_time) * 1000
504
+ log_interaction(
505
+ tenant_id=context.get("tenant_id", "emergency"),
506
+ interaction_type="emergency",
507
+ intent=IntentType.EMERGENCY.value,
508
+ response_time_ms=response_time,
509
+ success=True,
510
+ metadata={
511
+ "emergency_number": _emergency_count,
512
+ "message_length": len(message),
513
+ "timestamp": datetime.now().isoformat(),
514
+ "action": "crisis_resources_provided"
515
+ }
516
+ )
517
+
518
+ logger.critical(
519
+ f"EMERGENCY LOG #{_emergency_count}: Resources provided "
520
+ f"({response_time:.0f}ms)"
521
+ )
522
+
523
+ return OrchestrationResult(
524
+ intent=IntentType.EMERGENCY.value,
525
+ reply=reply,
526
+ success=True,
527
+ model_id="emergency_router",
528
+ data={"crisis_resources_provided": True},
529
+ response_time_ms=round(response_time, 2)
530
+ )
531
+
532
+
533
+ async def _handle_translation(
534
+ message: str,
535
+ context: Dict[str, Any]
536
+ ) -> OrchestrationResult:
537
+ """
538
+ 🌍 Translation handler - 27 languages supported.
539
+
540
+ Handles translation requests with graceful fallback if service
541
+ is unavailable.
542
+ """
543
+ logger.info("🌍 Processing translation request")
544
+
545
+ # Check service availability first
546
+ if not TRANSLATION_AVAILABLE:
547
+ logger.warning("Translation service not available")
548
+ return OrchestrationResult(
549
+ intent=IntentType.TRANSLATION.value,
550
+ reply="Translation isn't available right now. Try again soon! 🌍",
551
+ success=False,
552
+ error="Service not loaded",
553
+ fallback_used=True
554
+ )
555
+
556
+ try:
557
+ # Extract language parameters from context or parse from message
558
+ source_lang = context.get("source_lang", "eng_Latn")
559
+ target_lang = context.get("target_lang", "spa_Latn")
560
+
561
+ # Parse target language from message if present
562
+ # Examples: "translate to Spanish", "in Spanish", "to Spanish"
563
+ message_lower = message.lower()
564
+ language_keywords = {
565
+ "spanish": "spa_Latn", "espaΓ±ol": "spa_Latn", "es": "spa_Latn",
566
+ "french": "fra_Latn", "franΓ§ais": "fra_Latn", "fr": "fra_Latn",
567
+ "chinese": "zho_Hans", "mandarin": "zho_Hans", "zh": "zho_Hans",
568
+ "arabic": "arb_Arab", "ar": "arb_Arab",
569
+ "hindi": "hin_Deva", "hi": "hin_Deva",
570
+ "portuguese": "por_Latn", "pt": "por_Latn",
571
+ "russian": "rus_Cyrl", "ru": "rus_Cyrl",
572
+ "german": "deu_Latn", "de": "deu_Latn",
573
+ "vietnamese": "vie_Latn", "vi": "vie_Latn",
574
+ "tagalog": "tgl_Latn", "tl": "tgl_Latn",
575
+ "urdu": "urd_Arab", "ur": "urd_Arab",
576
+ "swahili": "swh_Latn", "sw": "swh_Latn",
577
+ "english": "eng_Latn", "en": "eng_Latn"
578
+ }
579
+
580
+ # Check for "to [language]" or "in [language]" patterns
581
+ for lang_name, lang_code in language_keywords.items():
582
+ if f"to {lang_name}" in message_lower or f"in {lang_name}" in message_lower:
583
+ target_lang = lang_code
584
+ logger.info(f"🌍 Detected target language from message: {lang_name} -> {lang_code}")
585
+ break
586
+
587
+ result = await translate_text(message, source_lang, target_lang)
588
+
589
+ # Check if translation service was actually available
590
+ if not result.get("available", True):
591
+ error_msg = result.get("error", "Translation service is temporarily unavailable.")
592
+ logger.warning(f"Translation service unavailable: {error_msg}")
593
+ return OrchestrationResult(
594
+ intent=IntentType.TRANSLATION.value,
595
+ reply=(
596
+ "I'm having trouble accessing the translation service right now. "
597
+ "Please try again in a moment! 🌍"
598
+ ),
599
+ success=False,
600
+ error=error_msg,
601
+ fallback_used=True
602
+ )
603
+
604
+ # Use compatibility helper to check result
605
+ success, error = _check_result_success(result, ["translated_text"])
606
+
607
+ if success:
608
+ translated = result.get("translated_text", "")
609
+
610
+ # Check if translation was skipped (same source/target language)
611
+ if result.get("skipped", False):
612
+ reply = (
613
+ f"The text is already in {target_lang}. "
614
+ f"No translation needed! 🌍"
615
+ )
616
+ else:
617
+ reply = (
618
+ f"Here's the translation:\n\n"
619
+ f"**{translated}**\n\n"
620
+ f"(Translated from {source_lang} to {target_lang})"
621
+ )
622
+
623
+ return OrchestrationResult(
624
+ intent=IntentType.TRANSLATION.value,
625
+ reply=reply,
626
+ success=True,
627
+ data=result,
628
+ model_id="penny-translate-agent"
629
+ )
630
+ else:
631
+ raise Exception(error or "Translation failed")
632
+
633
+ except Exception as e:
634
+ logger.error(f"Translation error: {e}", exc_info=True)
635
+ return OrchestrationResult(
636
+ intent=IntentType.TRANSLATION.value,
637
+ reply=(
638
+ "I had trouble translating that. Could you rephrase? πŸ’¬"
639
+ ),
640
+ success=False,
641
+ error=str(e),
642
+ fallback_used=True
643
+ )
644
+
645
+
646
+ async def _handle_sentiment(
647
+ message: str,
648
+ context: Dict[str, Any]
649
+ ) -> OrchestrationResult:
650
+ """
651
+ 😊 Sentiment analysis handler.
652
+
653
+ Analyzes the emotional tone of text with graceful fallback
654
+ if service is unavailable.
655
+ """
656
+ logger.info("😊 Processing sentiment analysis")
657
+
658
+ # Check service availability first
659
+ if not SENTIMENT_AVAILABLE:
660
+ logger.warning("Sentiment service not available")
661
+ return OrchestrationResult(
662
+ intent=IntentType.SENTIMENT_ANALYSIS.value,
663
+ reply="Sentiment analysis isn't available right now. Try again soon! 😊",
664
+ success=False,
665
+ error="Service not loaded",
666
+ fallback_used=True
667
+ )
668
+
669
+ try:
670
+ result = await get_sentiment_analysis(message)
671
+
672
+ # Use compatibility helper to check result
673
+ success, error = _check_result_success(result, ["label", "score"])
674
+
675
+ if success:
676
+ sentiment = result.get("label", "neutral")
677
+ confidence = result.get("score", 0.0)
678
+
679
+ reply = (
680
+ f"The overall sentiment detected is: **{sentiment}**\n"
681
+ f"Confidence: {confidence:.1%}"
682
+ )
683
+
684
+ return OrchestrationResult(
685
+ intent=IntentType.SENTIMENT_ANALYSIS.value,
686
+ reply=reply,
687
+ success=True,
688
+ data=result,
689
+ model_id="penny-sentiment-agent"
690
+ )
691
+ else:
692
+ raise Exception(error or "Sentiment analysis failed")
693
+
694
+ except Exception as e:
695
+ logger.error(f"Sentiment analysis error: {e}", exc_info=True)
696
+ return OrchestrationResult(
697
+ intent=IntentType.SENTIMENT_ANALYSIS.value,
698
+ reply="I couldn't analyze the sentiment right now. Try again? 😊",
699
+ success=False,
700
+ error=str(e),
701
+ fallback_used=True
702
+ )
703
+
704
+ async def _handle_bias(
705
+ message: str,
706
+ context: Dict[str, Any]
707
+ ) -> OrchestrationResult:
708
+ """
709
+ βš–οΈ Bias detection handler.
710
+
711
+ Analyzes text for potential bias patterns with graceful fallback
712
+ if service is unavailable.
713
+ """
714
+ logger.info("βš–οΈ Processing bias detection")
715
+
716
+ # Check service availability first
717
+ if not BIAS_AVAILABLE:
718
+ logger.warning("Bias detection service not available")
719
+ return OrchestrationResult(
720
+ intent=IntentType.BIAS_DETECTION.value,
721
+ reply="Bias detection isn't available right now. Try again soon! βš–οΈ",
722
+ success=False,
723
+ error="Service not loaded",
724
+ fallback_used=True
725
+ )
726
+
727
+ try:
728
+ result = await check_bias(message)
729
+
730
+ # Use compatibility helper to check result
731
+ success, error = _check_result_success(result, ["analysis"])
732
+
733
+ if success:
734
+ analysis = result.get("analysis", [])
735
+
736
+ if analysis:
737
+ top_result = analysis[0]
738
+ label = top_result.get("label", "unknown")
739
+ score = top_result.get("score", 0.0)
740
+
741
+ reply = (
742
+ f"Bias analysis complete:\n\n"
743
+ f"**Most likely category:** {label}\n"
744
+ f"**Confidence:** {score:.1%}"
745
+ )
746
+ else:
747
+ reply = "The text appears relatively neutral. βš–οΈ"
748
+
749
+ return OrchestrationResult(
750
+ intent=IntentType.BIAS_DETECTION.value,
751
+ reply=reply,
752
+ success=True,
753
+ data=result,
754
+ model_id="penny-bias-checker"
755
+ )
756
+ else:
757
+ raise Exception(error or "Bias detection failed")
758
+
759
+ except Exception as e:
760
+ logger.error(f"Bias detection error: {e}", exc_info=True)
761
+ return OrchestrationResult(
762
+ intent=IntentType.BIAS_DETECTION.value,
763
+ reply="I couldn't check for bias right now. Try again? βš–οΈ",
764
+ success=False,
765
+ error=str(e),
766
+ fallback_used=True
767
+ )
768
+
769
+
770
+ async def _handle_document(
771
+ message: str,
772
+ context: Dict[str, Any]
773
+ ) -> OrchestrationResult:
774
+ """
775
+ πŸ“„ Document processing handler.
776
+
777
+ Note: Actual file upload happens in router.py via FastAPI.
778
+ This handler just provides instructions.
779
+ """
780
+ logger.info("πŸ“„ Document processing requested")
781
+
782
+ reply = (
783
+ "I can help you process documents! πŸ“„\n\n"
784
+ "Please upload your document (PDF or image) using the "
785
+ "`/upload-document` endpoint. I can extract text, analyze forms, "
786
+ "and help you understand civic documents.\n\n"
787
+ "What kind of document do you need help with?"
788
+ )
789
+
790
+ return OrchestrationResult(
791
+ intent=IntentType.DOCUMENT_PROCESSING.value,
792
+ reply=reply,
793
+ success=True,
794
+ model_id="document_router"
795
+ )
796
+
797
+
798
+ async def _handle_weather(
799
+ message: str,
800
+ context: Dict[str, Any],
801
+ tenant_id: Optional[str],
802
+ lat: Optional[float],
803
+ lon: Optional[float],
804
+ intent_result: IntentMatch
805
+ ) -> OrchestrationResult:
806
+ """
807
+ 🌀️ Weather handler with compound intent support.
808
+
809
+ Handles both simple weather queries and compound weather+events queries.
810
+ Uses enhanced weather_agent.py with caching and performance tracking.
811
+ """
812
+ logger.info("🌀️ Processing weather request")
813
+
814
+ # Check service availability first
815
+ if not WEATHER_AGENT_AVAILABLE:
816
+ logger.warning("Weather agent not available")
817
+ return OrchestrationResult(
818
+ intent=IntentType.WEATHER.value,
819
+ reply="Weather service isn't available right now. Try again soon! 🌀️",
820
+ success=False,
821
+ error="Weather agent not loaded",
822
+ fallback_used=True
823
+ )
824
+
825
+ # Check for compound intent (weather + events)
826
+ is_compound = intent_result.is_compound or IntentType.EVENTS in intent_result.secondary_intents
827
+
828
+ # === ENHANCED LOCATION RESOLUTION ===
829
+ # Try multiple strategies to get coordinates
830
+
831
+ # Strategy 1: Use provided coordinates
832
+ if lat is not None and lon is not None:
833
+ logger.info(f"Using provided coordinates: {lat}, {lon}")
834
+
835
+ # Strategy 2: Get coordinates from tenant_id (try multiple formats)
836
+ elif tenant_id:
837
+ # Try tenant_id as-is first
838
+ coords = get_city_coordinates(tenant_id)
839
+
840
+ # If that fails and tenant_id doesn't have state suffix, try adding common suffixes
841
+ if not coords and "_" not in tenant_id:
842
+ # Try common state abbreviations for known cities
843
+ state_suffixes = ["_va", "_ga", "_al", "_tx", "_ri", "_wa"]
844
+ for suffix in state_suffixes:
845
+ test_tenant_id = tenant_id + suffix
846
+ coords = get_city_coordinates(test_tenant_id)
847
+ if coords:
848
+ tenant_id = test_tenant_id # Update tenant_id to normalized form
849
+ logger.info(f"Normalized tenant_id to {tenant_id}")
850
+ break
851
+
852
+ if coords:
853
+ lat, lon = coords["lat"], coords["lon"]
854
+ logger.info(f"βœ… Using city coordinates for {tenant_id}: {lat}, {lon}")
855
+
856
+ # Strategy 3: Extract location from message if still no coordinates
857
+ if lat is None or lon is None:
858
+ logger.info("No coordinates from tenant_id, trying to extract from message")
859
+ location_result = extract_location_detailed(message)
860
+
861
+ if location_result.status == LocationStatus.FOUND:
862
+ extracted_tenant_id = location_result.tenant_id
863
+ logger.info(f"πŸ“ Location extracted from message: {extracted_tenant_id}")
864
+
865
+ # Update tenant_id if we extracted a better one
866
+ if not tenant_id or tenant_id != extracted_tenant_id:
867
+ tenant_id = extracted_tenant_id
868
+ logger.info(f"Updated tenant_id to {tenant_id}")
869
+
870
+ # Get coordinates for extracted location
871
+ coords = get_city_coordinates(tenant_id)
872
+ if coords:
873
+ lat, lon = coords["lat"], coords["lon"]
874
+ logger.info(f"βœ… Coordinates found from message extraction: {lat}, {lon}")
875
+
876
+ # Final check: if still no coordinates, return error
877
+ if lat is None or lon is None:
878
+ logger.warning(f"❌ No coordinates available for weather request (tenant_id: {tenant_id})")
879
+ return OrchestrationResult(
880
+ intent=IntentType.WEATHER.value,
881
+ reply=(
882
+ "I need to know your location to check the weather! πŸ“ "
883
+ "You can tell me your city, or share your location."
884
+ ),
885
+ success=False,
886
+ error="Location required"
887
+ )
888
+
889
+ try:
890
+ # Use combined weather + events if compound intent detected
891
+ if is_compound and tenant_id and EVENT_WEATHER_AVAILABLE:
892
+ logger.info("Using weather+events combined handler")
893
+ result = await get_event_recommendations_with_weather(tenant_id, lat, lon)
894
+
895
+ # Build response
896
+ weather = result.get("weather", {})
897
+ weather_summary = result.get("weather_summary", "Weather unavailable")
898
+ suggestions = result.get("suggestions", [])
899
+
900
+ reply_lines = [f"🌀️ **Weather Update:**\n{weather_summary}\n"]
901
+
902
+ if suggestions:
903
+ reply_lines.append("\nπŸ“… **Event Suggestions Based on Weather:**")
904
+ for suggestion in suggestions[:5]: # Top 5 suggestions
905
+ reply_lines.append(f"β€’ {suggestion}")
906
+
907
+ reply = "\n".join(reply_lines)
908
+
909
+ return OrchestrationResult(
910
+ intent=IntentType.WEATHER.value,
911
+ reply=reply,
912
+ success=True,
913
+ data=result,
914
+ model_id="weather_events_combined"
915
+ )
916
+
917
+ else:
918
+ # Simple weather query using enhanced weather_agent
919
+ weather = await get_weather_for_location(lat, lon)
920
+
921
+ # Use enhanced weather_agent's format_weather_summary
922
+ if format_weather_summary:
923
+ weather_text = format_weather_summary(weather)
924
+ else:
925
+ # Fallback formatting
926
+ temp = weather.get("temperature", {}).get("value")
927
+ phrase = weather.get("phrase", "Conditions unavailable")
928
+ if temp:
929
+ weather_text = f"{phrase}, {int(temp)}Β°F"
930
+ else:
931
+ weather_text = phrase
932
+
933
+ # Get outfit recommendation from enhanced weather_agent
934
+ if recommend_outfit:
935
+ temp = weather.get("temperature", {}).get("value", 70)
936
+ condition = weather.get("phrase", "Clear")
937
+ outfit = recommend_outfit(temp, condition)
938
+ reply = f"🌀️ {weather_text}\n\nπŸ‘• {outfit}"
939
+ else:
940
+ reply = f"🌀️ {weather_text}"
941
+
942
+ return OrchestrationResult(
943
+ intent=IntentType.WEATHER.value,
944
+ reply=reply,
945
+ success=True,
946
+ data=weather,
947
+ model_id="azure-maps-weather"
948
+ )
949
+
950
+ except Exception as e:
951
+ logger.error(f"Weather error: {e}", exc_info=True)
952
+ return OrchestrationResult(
953
+ intent=IntentType.WEATHER.value,
954
+ reply=(
955
+ "I'm having trouble getting weather data right now. "
956
+ "Can I help you with something else? πŸ’›"
957
+ ),
958
+ success=False,
959
+ error=str(e),
960
+ fallback_used=True
961
+ )
962
+
963
+
964
+ async def _handle_events(
965
+ message: str,
966
+ context: Dict[str, Any],
967
+ tenant_id: Optional[str],
968
+ lat: Optional[float],
969
+ lon: Optional[float],
970
+ intent_result: IntentMatch
971
+ ) -> OrchestrationResult:
972
+ """
973
+ πŸ“… Events handler.
974
+
975
+ Routes event queries to tool_agent with proper error handling
976
+ and graceful degradation.
977
+ """
978
+ logger.info("πŸ“… Processing events request")
979
+
980
+ if not tenant_id:
981
+ return OrchestrationResult(
982
+ intent=IntentType.EVENTS.value,
983
+ reply=(
984
+ "I'd love to help you find events! πŸ“… "
985
+ "Which city are you interested in? "
986
+ "I have information for Atlanta, Birmingham, Chesterfield, "
987
+ "El Paso, Providence, and Seattle."
988
+ ),
989
+ success=False,
990
+ error="City required"
991
+ )
992
+
993
+ # Check tool agent availability
994
+ if not TOOL_AGENT_AVAILABLE:
995
+ logger.warning("Tool agent not available")
996
+ return OrchestrationResult(
997
+ intent=IntentType.EVENTS.value,
998
+ reply=(
999
+ "Event information isn't available right now. "
1000
+ "Try again soon! πŸ“…"
1001
+ ),
1002
+ success=False,
1003
+ error="Tool agent not loaded",
1004
+ fallback_used=True
1005
+ )
1006
+
1007
+ try:
1008
+ # FIXED: Add role parameter (compatibility fix)
1009
+ tool_response = await handle_tool_request(
1010
+ user_input=message,
1011
+ role=context.get("role", "resident"), # ← ADDED
1012
+ lat=lat,
1013
+ lon=lon,
1014
+ context=context
1015
+ )
1016
+
1017
+ reply = tool_response.get("response", "Events information retrieved.")
1018
+
1019
+ return OrchestrationResult(
1020
+ intent=IntentType.EVENTS.value,
1021
+ reply=reply,
1022
+ success=True,
1023
+ data=tool_response,
1024
+ model_id="events_tool"
1025
+ )
1026
+
1027
+ except Exception as e:
1028
+ logger.error(f"Events error: {e}", exc_info=True)
1029
+ return OrchestrationResult(
1030
+ intent=IntentType.EVENTS.value,
1031
+ reply=(
1032
+ "I'm having trouble loading event information right now. "
1033
+ "Check back soon! πŸ“…"
1034
+ ),
1035
+ success=False,
1036
+ error=str(e),
1037
+ fallback_used=True
1038
+ )
1039
+
1040
+ async def _handle_local_resources(
1041
+ message: str,
1042
+ context: Dict[str, Any],
1043
+ tenant_id: Optional[str],
1044
+ lat: Optional[float],
1045
+ lon: Optional[float]
1046
+ ) -> OrchestrationResult:
1047
+ """
1048
+ πŸ›οΈ Local resources handler (shelters, libraries, food banks, etc.).
1049
+
1050
+ Routes resource queries to tool_agent with proper error handling.
1051
+ """
1052
+ logger.info("πŸ›οΈ Processing local resources request")
1053
+
1054
+ if not tenant_id:
1055
+ return OrchestrationResult(
1056
+ intent=IntentType.LOCAL_RESOURCES.value,
1057
+ reply=(
1058
+ "I can help you find local resources! πŸ›οΈ "
1059
+ "Which city do you need help in? "
1060
+ "I cover Atlanta, Birmingham, Chesterfield, El Paso, "
1061
+ "Providence, and Seattle."
1062
+ ),
1063
+ success=False,
1064
+ error="City required"
1065
+ )
1066
+
1067
+ # Check tool agent availability
1068
+ if not TOOL_AGENT_AVAILABLE:
1069
+ logger.warning("Tool agent not available")
1070
+ return OrchestrationResult(
1071
+ intent=IntentType.LOCAL_RESOURCES.value,
1072
+ reply=(
1073
+ "Resource information isn't available right now. "
1074
+ "Try again soon! πŸ›οΈ"
1075
+ ),
1076
+ success=False,
1077
+ error="Tool agent not loaded",
1078
+ fallback_used=True
1079
+ )
1080
+
1081
+ try:
1082
+ # FIXED: Add role parameter (compatibility fix)
1083
+ tool_response = await handle_tool_request(
1084
+ user_input=message,
1085
+ role=context.get("role", "resident"), # ← ADDED
1086
+ lat=lat,
1087
+ lon=lon,
1088
+ context=context
1089
+ )
1090
+
1091
+ reply = tool_response.get("response", "Resource information retrieved.")
1092
+
1093
+ return OrchestrationResult(
1094
+ intent=IntentType.LOCAL_RESOURCES.value,
1095
+ reply=reply,
1096
+ success=True,
1097
+ data=tool_response,
1098
+ model_id="resources_tool"
1099
+ )
1100
+
1101
+ except Exception as e:
1102
+ logger.error(f"Resources error: {e}", exc_info=True)
1103
+ return OrchestrationResult(
1104
+ intent=IntentType.LOCAL_RESOURCES.value,
1105
+ reply=(
1106
+ "I'm having trouble finding resource information right now. "
1107
+ "Would you like to try a different search? πŸ’›"
1108
+ ),
1109
+ success=False,
1110
+ error=str(e),
1111
+ fallback_used=True
1112
+ )
1113
+
1114
+
1115
+ async def _handle_conversational(
1116
+ message: str,
1117
+ intent: IntentType,
1118
+ context: Dict[str, Any]
1119
+ ) -> OrchestrationResult:
1120
+ """
1121
+ πŸ’¬ Handles conversational intents (greeting, help, unknown).
1122
+ Uses Penny's core LLM for natural responses with graceful fallback.
1123
+ """
1124
+ logger.info(f"πŸ’¬ Processing conversational intent: {intent.value}")
1125
+
1126
+ # Check LLM availability
1127
+ use_llm = LLM_AVAILABLE
1128
+
1129
+ try:
1130
+ if use_llm:
1131
+ # Build prompt based on intent
1132
+ if intent == IntentType.GREETING:
1133
+ prompt = (
1134
+ f"The user greeted you with: '{message}'\n\n"
1135
+ "Respond warmly as Penny, introduce yourself briefly, "
1136
+ "and ask how you can help them with civic services today."
1137
+ )
1138
+
1139
+ elif intent == IntentType.HELP:
1140
+ prompt = (
1141
+ f"The user asked for help: '{message}'\n\n"
1142
+ "Explain Penny's main features:\n"
1143
+ "- Finding local resources (shelters, libraries, food banks)\n"
1144
+ "- Community events and activities\n"
1145
+ "- Weather information\n"
1146
+ "- 27-language translation\n"
1147
+ "- Document processing help\n\n"
1148
+ "Ask which city they need assistance in."
1149
+ )
1150
+
1151
+ else: # UNKNOWN
1152
+ prompt = (
1153
+ f"The user said: '{message}'\n\n"
1154
+ "You're not sure what they need help with. "
1155
+ "Respond kindly, acknowledge their request, and ask them to "
1156
+ "clarify or rephrase. Mention a few things you can help with."
1157
+ )
1158
+
1159
+ # Call Penny's core LLM
1160
+ llm_result = await generate_response(prompt=prompt, max_new_tokens=200)
1161
+
1162
+ # Use compatibility helper to check result
1163
+ success, error = _check_result_success(llm_result, ["response"])
1164
+
1165
+ if success:
1166
+ reply = llm_result.get("response", "")
1167
+
1168
+ return OrchestrationResult(
1169
+ intent=intent.value,
1170
+ reply=reply,
1171
+ success=True,
1172
+ data=llm_result,
1173
+ model_id=CORE_MODEL_ID
1174
+ )
1175
+ else:
1176
+ raise Exception(error or "LLM generation failed")
1177
+
1178
+ else:
1179
+ # LLM not available, use fallback directly
1180
+ logger.info("LLM not available, using fallback responses")
1181
+ raise Exception("LLM service not loaded")
1182
+
1183
+ except Exception as e:
1184
+ logger.warning(f"Conversational handler using fallback: {e}")
1185
+
1186
+ # Hardcoded fallback responses (Penny's friendly voice)
1187
+ fallback_replies = {
1188
+ IntentType.GREETING: (
1189
+ "Hi there! πŸ‘‹ I'm Penny, your civic assistant. "
1190
+ "I can help you find local resources, events, weather, and more. "
1191
+ "What city are you in?"
1192
+ ),
1193
+ IntentType.HELP: (
1194
+ "I'm Penny! πŸ’› I can help you with:\n\n"
1195
+ "πŸ›οΈ Local resources (shelters, libraries, food banks)\n"
1196
+ "πŸ“… Community events\n"
1197
+ "🌀️ Weather updates\n"
1198
+ "🌍 Translation (27 languages)\n"
1199
+ "πŸ“„ Document help\n\n"
1200
+ "What would you like to know about?"
1201
+ ),
1202
+ IntentType.UNKNOWN: (
1203
+ "I'm not sure I understood that. Could you rephrase? "
1204
+ "I'm best at helping with local services, events, weather, "
1205
+ "and translation! πŸ’¬"
1206
+ )
1207
+ }
1208
+
1209
+ return OrchestrationResult(
1210
+ intent=intent.value,
1211
+ reply=fallback_replies.get(intent, "How can I help you today? πŸ’›"),
1212
+ success=True,
1213
+ model_id="fallback",
1214
+ fallback_used=True
1215
+ )
1216
+
1217
+
1218
+ async def _handle_fallback(
1219
+ message: str,
1220
+ intent: IntentType,
1221
+ context: Dict[str, Any]
1222
+ ) -> OrchestrationResult:
1223
+ """
1224
+ πŸ†˜ Ultimate fallback handler for unhandled intents.
1225
+
1226
+ This is a safety net that should rarely trigger, but ensures
1227
+ users always get a helpful response.
1228
+ """
1229
+ logger.warning(f"⚠️ Fallback triggered for intent: {intent.value}")
1230
+
1231
+ reply = (
1232
+ "I've processed your request, but I'm not sure how to help with that yet. "
1233
+ "I'm still learning! πŸ€–\n\n"
1234
+ "I'm best at:\n"
1235
+ "πŸ›οΈ Finding local resources\n"
1236
+ "πŸ“… Community events\n"
1237
+ "🌀️ Weather updates\n"
1238
+ "🌍 Translation\n\n"
1239
+ "Could you rephrase your question? πŸ’›"
1240
+ )
1241
+
1242
+ return OrchestrationResult(
1243
+ intent=intent.value,
1244
+ reply=reply,
1245
+ success=False,
1246
+ error="Unhandled intent",
1247
+ fallback_used=True
1248
+ )
1249
+
1250
+
1251
+ # ============================================================
1252
+ # HEALTH CHECK & DIAGNOSTICS (ENHANCED)
1253
+ # ============================================================
1254
+
1255
+ def get_orchestrator_health() -> Dict[str, Any]:
1256
+ """
1257
+ πŸ“Š Returns comprehensive orchestrator health status.
1258
+
1259
+ Used by the main application health check endpoint to monitor
1260
+ the orchestrator and all its service dependencies.
1261
+
1262
+ Returns:
1263
+ Dictionary with health information including:
1264
+ - status: operational/degraded
1265
+ - service_availability: which services are loaded
1266
+ - statistics: orchestration counts
1267
+ - supported_intents: list of all intent types
1268
+ - features: available orchestrator features
1269
+ """
1270
+ # Get service availability
1271
+ services = get_service_availability()
1272
+
1273
+ # Determine overall status
1274
+ # Orchestrator is operational even if some services are down (graceful degradation)
1275
+ critical_services = ["weather", "tool_agent"] # Must have these
1276
+ critical_available = all(services.get(svc, False) for svc in critical_services)
1277
+
1278
+ status = "operational" if critical_available else "degraded"
1279
+
1280
+ return {
1281
+ "status": status,
1282
+ "core_model": CORE_MODEL_ID,
1283
+ "max_response_time_ms": MAX_RESPONSE_TIME_MS,
1284
+ "statistics": {
1285
+ "total_orchestrations": _orchestration_count,
1286
+ "emergency_interactions": _emergency_count
1287
+ },
1288
+ "service_availability": services,
1289
+ "supported_intents": [intent.value for intent in IntentType],
1290
+ "features": {
1291
+ "emergency_routing": True,
1292
+ "compound_intents": True,
1293
+ "fallback_handling": True,
1294
+ "performance_tracking": True,
1295
+ "context_aware": True,
1296
+ "multi_language": TRANSLATION_AVAILABLE,
1297
+ "sentiment_analysis": SENTIMENT_AVAILABLE,
1298
+ "bias_detection": BIAS_AVAILABLE,
1299
+ "weather_integration": WEATHER_AGENT_AVAILABLE,
1300
+ "event_recommendations": EVENT_WEATHER_AVAILABLE
1301
+ }
1302
+ }
1303
+
1304
+
1305
+ def get_orchestrator_stats() -> Dict[str, Any]:
1306
+ """
1307
+ πŸ“ˆ Returns orchestrator statistics.
1308
+
1309
+ Useful for monitoring and analytics.
1310
+ """
1311
+ return {
1312
+ "total_orchestrations": _orchestration_count,
1313
+ "emergency_interactions": _emergency_count,
1314
+ "services_available": sum(1 for v in get_service_availability().values() if v),
1315
+ "services_total": len(get_service_availability())
1316
+ }
1317
+
1318
+
1319
+ # ============================================================
1320
+ # TESTING & DEBUGGING (ENHANCED)
1321
+ # ============================================================
1322
+
1323
+ if __name__ == "__main__":
1324
+ """
1325
+ πŸ§ͺ Test the orchestrator with sample queries.
1326
+ Run with: python -m app.orchestrator
1327
+ """
1328
+ import asyncio
1329
+
1330
+ print("=" * 60)
1331
+ print("πŸ§ͺ Testing Penny's Orchestrator")
1332
+ print("=" * 60)
1333
+
1334
+ # Display service availability first
1335
+ print("\nπŸ“Š Service Availability Check:")
1336
+ services = get_service_availability()
1337
+ for service, available in services.items():
1338
+ status = "βœ…" if available else "❌"
1339
+ print(f" {status} {service}: {'Available' if available else 'Not loaded'}")
1340
+
1341
+ print("\n" + "=" * 60)
1342
+
1343
+ test_queries = [
1344
+ {
1345
+ "name": "Greeting",
1346
+ "message": "Hi Penny!",
1347
+ "context": {}
1348
+ },
1349
+ {
1350
+ "name": "Weather with location",
1351
+ "message": "What's the weather?",
1352
+ "context": {"lat": 33.7490, "lon": -84.3880}
1353
+ },
1354
+ {
1355
+ "name": "Events in city",
1356
+ "message": "Events in Atlanta",
1357
+ "context": {"tenant_id": "atlanta_ga"}
1358
+ },
1359
+ {
1360
+ "name": "Help request",
1361
+ "message": "I need help",
1362
+ "context": {}
1363
+ },
1364
+ {
1365
+ "name": "Translation",
1366
+ "message": "Translate hello",
1367
+ "context": {"source_lang": "eng_Latn", "target_lang": "spa_Latn"}
1368
+ }
1369
+ ]
1370
+
1371
+ async def run_tests():
1372
+ for i, query in enumerate(test_queries, 1):
1373
+ print(f"\n--- Test {i}: {query['name']} ---")
1374
+ print(f"Query: {query['message']}")
1375
+
1376
+ try:
1377
+ result = await run_orchestrator(query["message"], query["context"])
1378
+ print(f"Intent: {result['intent']}")
1379
+ print(f"Success: {result['success']}")
1380
+ print(f"Fallback: {result.get('fallback_used', False)}")
1381
+
1382
+ # Truncate long replies
1383
+ reply = result['reply']
1384
+ if len(reply) > 150:
1385
+ reply = reply[:150] + "..."
1386
+ print(f"Reply: {reply}")
1387
+
1388
+ if result.get('response_time_ms'):
1389
+ print(f"Response time: {result['response_time_ms']:.0f}ms")
1390
+
1391
+ except Exception as e:
1392
+ print(f"❌ Error: {e}")
1393
+
1394
+ asyncio.run(run_tests())
1395
+
1396
+ print("\n" + "=" * 60)
1397
+ print("πŸ“Š Final Statistics:")
1398
+ stats = get_orchestrator_stats()
1399
+ for key, value in stats.items():
1400
+ print(f" {key}: {value}")
1401
+
1402
+ print("\n" + "=" * 60)
1403
+ print("βœ… Tests complete")
1404
+ print("=" * 60)