pythonprincess commited on
Commit
4511eb0
Β·
verified Β·
1 Parent(s): 37a2956

Upload orchestrator.py

Browse files
Files changed (1) hide show
  1. app/orchestrator.py +1317 -0
app/orchestrator.py ADDED
@@ -0,0 +1,1317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
558
+ source_lang = context.get("source_lang", "eng_Latn")
559
+ target_lang = context.get("target_lang", "spa_Latn")
560
+
561
+ # TODO: Parse languages from message when enhanced
562
+ # Example: "Translate 'hello' to Spanish"
563
+
564
+ result = await translate_text(message, source_lang, target_lang)
565
+
566
+ # Use compatibility helper to check result
567
+ success, error = _check_result_success(result, ["translated_text"])
568
+
569
+ if success:
570
+ translated = result.get("translated_text", "")
571
+ reply = (
572
+ f"Here's the translation:\n\n"
573
+ f"**{translated}**\n\n"
574
+ f"(Translated from {source_lang} to {target_lang})"
575
+ )
576
+
577
+ return OrchestrationResult(
578
+ intent=IntentType.TRANSLATION.value,
579
+ reply=reply,
580
+ success=True,
581
+ data=result,
582
+ model_id="penny-translate-agent"
583
+ )
584
+ else:
585
+ raise Exception(error or "Translation failed")
586
+
587
+ except Exception as e:
588
+ logger.error(f"Translation error: {e}", exc_info=True)
589
+ return OrchestrationResult(
590
+ intent=IntentType.TRANSLATION.value,
591
+ reply=(
592
+ "I had trouble translating that. Could you rephrase? πŸ’¬"
593
+ ),
594
+ success=False,
595
+ error=str(e),
596
+ fallback_used=True
597
+ )
598
+
599
+
600
+ async def _handle_sentiment(
601
+ message: str,
602
+ context: Dict[str, Any]
603
+ ) -> OrchestrationResult:
604
+ """
605
+ 😊 Sentiment analysis handler.
606
+
607
+ Analyzes the emotional tone of text with graceful fallback
608
+ if service is unavailable.
609
+ """
610
+ logger.info("😊 Processing sentiment analysis")
611
+
612
+ # Check service availability first
613
+ if not SENTIMENT_AVAILABLE:
614
+ logger.warning("Sentiment service not available")
615
+ return OrchestrationResult(
616
+ intent=IntentType.SENTIMENT_ANALYSIS.value,
617
+ reply="Sentiment analysis isn't available right now. Try again soon! 😊",
618
+ success=False,
619
+ error="Service not loaded",
620
+ fallback_used=True
621
+ )
622
+
623
+ try:
624
+ result = await get_sentiment_analysis(message)
625
+
626
+ # Use compatibility helper to check result
627
+ success, error = _check_result_success(result, ["label", "score"])
628
+
629
+ if success:
630
+ sentiment = result.get("label", "neutral")
631
+ confidence = result.get("score", 0.0)
632
+
633
+ reply = (
634
+ f"The overall sentiment detected is: **{sentiment}**\n"
635
+ f"Confidence: {confidence:.1%}"
636
+ )
637
+
638
+ return OrchestrationResult(
639
+ intent=IntentType.SENTIMENT_ANALYSIS.value,
640
+ reply=reply,
641
+ success=True,
642
+ data=result,
643
+ model_id="penny-sentiment-agent"
644
+ )
645
+ else:
646
+ raise Exception(error or "Sentiment analysis failed")
647
+
648
+ except Exception as e:
649
+ logger.error(f"Sentiment analysis error: {e}", exc_info=True)
650
+ return OrchestrationResult(
651
+ intent=IntentType.SENTIMENT_ANALYSIS.value,
652
+ reply="I couldn't analyze the sentiment right now. Try again? 😊",
653
+ success=False,
654
+ error=str(e),
655
+ fallback_used=True
656
+ )
657
+
658
+ async def _handle_bias(
659
+ message: str,
660
+ context: Dict[str, Any]
661
+ ) -> OrchestrationResult:
662
+ """
663
+ βš–οΈ Bias detection handler.
664
+
665
+ Analyzes text for potential bias patterns with graceful fallback
666
+ if service is unavailable.
667
+ """
668
+ logger.info("βš–οΈ Processing bias detection")
669
+
670
+ # Check service availability first
671
+ if not BIAS_AVAILABLE:
672
+ logger.warning("Bias detection service not available")
673
+ return OrchestrationResult(
674
+ intent=IntentType.BIAS_DETECTION.value,
675
+ reply="Bias detection isn't available right now. Try again soon! βš–οΈ",
676
+ success=False,
677
+ error="Service not loaded",
678
+ fallback_used=True
679
+ )
680
+
681
+ try:
682
+ result = await check_bias(message)
683
+
684
+ # Use compatibility helper to check result
685
+ success, error = _check_result_success(result, ["analysis"])
686
+
687
+ if success:
688
+ analysis = result.get("analysis", [])
689
+
690
+ if analysis:
691
+ top_result = analysis[0]
692
+ label = top_result.get("label", "unknown")
693
+ score = top_result.get("score", 0.0)
694
+
695
+ reply = (
696
+ f"Bias analysis complete:\n\n"
697
+ f"**Most likely category:** {label}\n"
698
+ f"**Confidence:** {score:.1%}"
699
+ )
700
+ else:
701
+ reply = "The text appears relatively neutral. βš–οΈ"
702
+
703
+ return OrchestrationResult(
704
+ intent=IntentType.BIAS_DETECTION.value,
705
+ reply=reply,
706
+ success=True,
707
+ data=result,
708
+ model_id="penny-bias-checker"
709
+ )
710
+ else:
711
+ raise Exception(error or "Bias detection failed")
712
+
713
+ except Exception as e:
714
+ logger.error(f"Bias detection error: {e}", exc_info=True)
715
+ return OrchestrationResult(
716
+ intent=IntentType.BIAS_DETECTION.value,
717
+ reply="I couldn't check for bias right now. Try again? βš–οΈ",
718
+ success=False,
719
+ error=str(e),
720
+ fallback_used=True
721
+ )
722
+
723
+
724
+ async def _handle_document(
725
+ message: str,
726
+ context: Dict[str, Any]
727
+ ) -> OrchestrationResult:
728
+ """
729
+ πŸ“„ Document processing handler.
730
+
731
+ Note: Actual file upload happens in router.py via FastAPI.
732
+ This handler just provides instructions.
733
+ """
734
+ logger.info("πŸ“„ Document processing requested")
735
+
736
+ reply = (
737
+ "I can help you process documents! πŸ“„\n\n"
738
+ "Please upload your document (PDF or image) using the "
739
+ "`/upload-document` endpoint. I can extract text, analyze forms, "
740
+ "and help you understand civic documents.\n\n"
741
+ "What kind of document do you need help with?"
742
+ )
743
+
744
+ return OrchestrationResult(
745
+ intent=IntentType.DOCUMENT_PROCESSING.value,
746
+ reply=reply,
747
+ success=True,
748
+ model_id="document_router"
749
+ )
750
+
751
+
752
+ async def _handle_weather(
753
+ message: str,
754
+ context: Dict[str, Any],
755
+ tenant_id: Optional[str],
756
+ lat: Optional[float],
757
+ lon: Optional[float],
758
+ intent_result: IntentMatch
759
+ ) -> OrchestrationResult:
760
+ """
761
+ 🌀️ Weather handler with compound intent support.
762
+
763
+ Handles both simple weather queries and compound weather+events queries.
764
+ Uses enhanced weather_agent.py with caching and performance tracking.
765
+ """
766
+ logger.info("🌀️ Processing weather request")
767
+
768
+ # Check service availability first
769
+ if not WEATHER_AGENT_AVAILABLE:
770
+ logger.warning("Weather agent not available")
771
+ return OrchestrationResult(
772
+ intent=IntentType.WEATHER.value,
773
+ reply="Weather service isn't available right now. Try again soon! 🌀️",
774
+ success=False,
775
+ error="Weather agent not loaded",
776
+ fallback_used=True
777
+ )
778
+
779
+ # Check for compound intent (weather + events)
780
+ is_compound = intent_result.is_compound or IntentType.EVENTS in intent_result.secondary_intents
781
+
782
+ # Validate location
783
+ if lat is None or lon is None:
784
+ # Try to get coordinates from tenant_id
785
+ if tenant_id:
786
+ coords = get_city_coordinates(tenant_id)
787
+ if coords and lat is None and lon is None:
788
+ lat, lon = coords["lat"], coords["lon"]
789
+ logger.info(f"Using city coordinates for {tenant_id}: {lat}, {lon}")
790
+
791
+ if lat is None or lon is None:
792
+ return OrchestrationResult(
793
+ intent=IntentType.WEATHER.value,
794
+ reply=(
795
+ "I need to know your location to check the weather! πŸ“ "
796
+ "You can tell me your city, or share your location."
797
+ ),
798
+ success=False,
799
+ error="Location required"
800
+ )
801
+
802
+ try:
803
+ # Use combined weather + events if compound intent detected
804
+ if is_compound and tenant_id and EVENT_WEATHER_AVAILABLE:
805
+ logger.info("Using weather+events combined handler")
806
+ result = await get_event_recommendations_with_weather(tenant_id, lat, lon)
807
+
808
+ # Build response
809
+ weather = result.get("weather", {})
810
+ weather_summary = result.get("weather_summary", "Weather unavailable")
811
+ suggestions = result.get("suggestions", [])
812
+
813
+ reply_lines = [f"🌀️ **Weather Update:**\n{weather_summary}\n"]
814
+
815
+ if suggestions:
816
+ reply_lines.append("\nπŸ“… **Event Suggestions Based on Weather:**")
817
+ for suggestion in suggestions[:5]: # Top 5 suggestions
818
+ reply_lines.append(f"β€’ {suggestion}")
819
+
820
+ reply = "\n".join(reply_lines)
821
+
822
+ return OrchestrationResult(
823
+ intent=IntentType.WEATHER.value,
824
+ reply=reply,
825
+ success=True,
826
+ data=result,
827
+ model_id="weather_events_combined"
828
+ )
829
+
830
+ else:
831
+ # Simple weather query using enhanced weather_agent
832
+ weather = await get_weather_for_location(lat, lon)
833
+
834
+ # Use enhanced weather_agent's format_weather_summary
835
+ if format_weather_summary:
836
+ weather_text = format_weather_summary(weather)
837
+ else:
838
+ # Fallback formatting
839
+ temp = weather.get("temperature", {}).get("value")
840
+ phrase = weather.get("phrase", "Conditions unavailable")
841
+ if temp:
842
+ weather_text = f"{phrase}, {int(temp)}Β°F"
843
+ else:
844
+ weather_text = phrase
845
+
846
+ # Get outfit recommendation from enhanced weather_agent
847
+ if recommend_outfit:
848
+ temp = weather.get("temperature", {}).get("value", 70)
849
+ condition = weather.get("phrase", "Clear")
850
+ outfit = recommend_outfit(temp, condition)
851
+ reply = f"🌀️ {weather_text}\n\nπŸ‘• {outfit}"
852
+ else:
853
+ reply = f"🌀️ {weather_text}"
854
+
855
+ return OrchestrationResult(
856
+ intent=IntentType.WEATHER.value,
857
+ reply=reply,
858
+ success=True,
859
+ data=weather,
860
+ model_id="azure-maps-weather"
861
+ )
862
+
863
+ except Exception as e:
864
+ logger.error(f"Weather error: {e}", exc_info=True)
865
+ return OrchestrationResult(
866
+ intent=IntentType.WEATHER.value,
867
+ reply=(
868
+ "I'm having trouble getting weather data right now. "
869
+ "Can I help you with something else? πŸ’›"
870
+ ),
871
+ success=False,
872
+ error=str(e),
873
+ fallback_used=True
874
+ )
875
+
876
+
877
+ async def _handle_events(
878
+ message: str,
879
+ context: Dict[str, Any],
880
+ tenant_id: Optional[str],
881
+ lat: Optional[float],
882
+ lon: Optional[float],
883
+ intent_result: IntentMatch
884
+ ) -> OrchestrationResult:
885
+ """
886
+ πŸ“… Events handler.
887
+
888
+ Routes event queries to tool_agent with proper error handling
889
+ and graceful degradation.
890
+ """
891
+ logger.info("πŸ“… Processing events request")
892
+
893
+ if not tenant_id:
894
+ return OrchestrationResult(
895
+ intent=IntentType.EVENTS.value,
896
+ reply=(
897
+ "I'd love to help you find events! πŸ“… "
898
+ "Which city are you interested in? "
899
+ "I have information for Atlanta, Birmingham, Chesterfield, "
900
+ "El Paso, Providence, and Seattle."
901
+ ),
902
+ success=False,
903
+ error="City required"
904
+ )
905
+
906
+ # Check tool agent availability
907
+ if not TOOL_AGENT_AVAILABLE:
908
+ logger.warning("Tool agent not available")
909
+ return OrchestrationResult(
910
+ intent=IntentType.EVENTS.value,
911
+ reply=(
912
+ "Event information isn't available right now. "
913
+ "Try again soon! πŸ“…"
914
+ ),
915
+ success=False,
916
+ error="Tool agent not loaded",
917
+ fallback_used=True
918
+ )
919
+
920
+ try:
921
+ # FIXED: Add role parameter (compatibility fix)
922
+ tool_response = await handle_tool_request(
923
+ user_input=message,
924
+ role=context.get("role", "resident"), # ← ADDED
925
+ lat=lat,
926
+ lon=lon,
927
+ context=context
928
+ )
929
+
930
+ reply = tool_response.get("response", "Events information retrieved.")
931
+
932
+ return OrchestrationResult(
933
+ intent=IntentType.EVENTS.value,
934
+ reply=reply,
935
+ success=True,
936
+ data=tool_response,
937
+ model_id="events_tool"
938
+ )
939
+
940
+ except Exception as e:
941
+ logger.error(f"Events error: {e}", exc_info=True)
942
+ return OrchestrationResult(
943
+ intent=IntentType.EVENTS.value,
944
+ reply=(
945
+ "I'm having trouble loading event information right now. "
946
+ "Check back soon! πŸ“…"
947
+ ),
948
+ success=False,
949
+ error=str(e),
950
+ fallback_used=True
951
+ )
952
+
953
+ async def _handle_local_resources(
954
+ message: str,
955
+ context: Dict[str, Any],
956
+ tenant_id: Optional[str],
957
+ lat: Optional[float],
958
+ lon: Optional[float]
959
+ ) -> OrchestrationResult:
960
+ """
961
+ πŸ›οΈ Local resources handler (shelters, libraries, food banks, etc.).
962
+
963
+ Routes resource queries to tool_agent with proper error handling.
964
+ """
965
+ logger.info("πŸ›οΈ Processing local resources request")
966
+
967
+ if not tenant_id:
968
+ return OrchestrationResult(
969
+ intent=IntentType.LOCAL_RESOURCES.value,
970
+ reply=(
971
+ "I can help you find local resources! πŸ›οΈ "
972
+ "Which city do you need help in? "
973
+ "I cover Atlanta, Birmingham, Chesterfield, El Paso, "
974
+ "Providence, and Seattle."
975
+ ),
976
+ success=False,
977
+ error="City required"
978
+ )
979
+
980
+ # Check tool agent availability
981
+ if not TOOL_AGENT_AVAILABLE:
982
+ logger.warning("Tool agent not available")
983
+ return OrchestrationResult(
984
+ intent=IntentType.LOCAL_RESOURCES.value,
985
+ reply=(
986
+ "Resource information isn't available right now. "
987
+ "Try again soon! πŸ›οΈ"
988
+ ),
989
+ success=False,
990
+ error="Tool agent not loaded",
991
+ fallback_used=True
992
+ )
993
+
994
+ try:
995
+ # FIXED: Add role parameter (compatibility fix)
996
+ tool_response = await handle_tool_request(
997
+ user_input=message,
998
+ role=context.get("role", "resident"), # ← ADDED
999
+ lat=lat,
1000
+ lon=lon,
1001
+ context=context
1002
+ )
1003
+
1004
+ reply = tool_response.get("response", "Resource information retrieved.")
1005
+
1006
+ return OrchestrationResult(
1007
+ intent=IntentType.LOCAL_RESOURCES.value,
1008
+ reply=reply,
1009
+ success=True,
1010
+ data=tool_response,
1011
+ model_id="resources_tool"
1012
+ )
1013
+
1014
+ except Exception as e:
1015
+ logger.error(f"Resources error: {e}", exc_info=True)
1016
+ return OrchestrationResult(
1017
+ intent=IntentType.LOCAL_RESOURCES.value,
1018
+ reply=(
1019
+ "I'm having trouble finding resource information right now. "
1020
+ "Would you like to try a different search? πŸ’›"
1021
+ ),
1022
+ success=False,
1023
+ error=str(e),
1024
+ fallback_used=True
1025
+ )
1026
+
1027
+
1028
+ async def _handle_conversational(
1029
+ message: str,
1030
+ intent: IntentType,
1031
+ context: Dict[str, Any]
1032
+ ) -> OrchestrationResult:
1033
+ """
1034
+ πŸ’¬ Handles conversational intents (greeting, help, unknown).
1035
+ Uses Penny's core LLM for natural responses with graceful fallback.
1036
+ """
1037
+ logger.info(f"πŸ’¬ Processing conversational intent: {intent.value}")
1038
+
1039
+ # Check LLM availability
1040
+ use_llm = LLM_AVAILABLE
1041
+
1042
+ try:
1043
+ if use_llm:
1044
+ # Build prompt based on intent
1045
+ if intent == IntentType.GREETING:
1046
+ prompt = (
1047
+ f"The user greeted you with: '{message}'\n\n"
1048
+ "Respond warmly as Penny, introduce yourself briefly, "
1049
+ "and ask how you can help them with civic services today."
1050
+ )
1051
+
1052
+ elif intent == IntentType.HELP:
1053
+ prompt = (
1054
+ f"The user asked for help: '{message}'\n\n"
1055
+ "Explain Penny's main features:\n"
1056
+ "- Finding local resources (shelters, libraries, food banks)\n"
1057
+ "- Community events and activities\n"
1058
+ "- Weather information\n"
1059
+ "- 27-language translation\n"
1060
+ "- Document processing help\n\n"
1061
+ "Ask which city they need assistance in."
1062
+ )
1063
+
1064
+ else: # UNKNOWN
1065
+ prompt = (
1066
+ f"The user said: '{message}'\n\n"
1067
+ "You're not sure what they need help with. "
1068
+ "Respond kindly, acknowledge their request, and ask them to "
1069
+ "clarify or rephrase. Mention a few things you can help with."
1070
+ )
1071
+
1072
+ # Call Penny's core LLM
1073
+ llm_result = await generate_response(prompt=prompt, max_new_tokens=200)
1074
+
1075
+ # Use compatibility helper to check result
1076
+ success, error = _check_result_success(llm_result, ["response"])
1077
+
1078
+ if success:
1079
+ reply = llm_result.get("response", "")
1080
+
1081
+ return OrchestrationResult(
1082
+ intent=intent.value,
1083
+ reply=reply,
1084
+ success=True,
1085
+ data=llm_result,
1086
+ model_id=CORE_MODEL_ID
1087
+ )
1088
+ else:
1089
+ raise Exception(error or "LLM generation failed")
1090
+
1091
+ else:
1092
+ # LLM not available, use fallback directly
1093
+ logger.info("LLM not available, using fallback responses")
1094
+ raise Exception("LLM service not loaded")
1095
+
1096
+ except Exception as e:
1097
+ logger.warning(f"Conversational handler using fallback: {e}")
1098
+
1099
+ # Hardcoded fallback responses (Penny's friendly voice)
1100
+ fallback_replies = {
1101
+ IntentType.GREETING: (
1102
+ "Hi there! πŸ‘‹ I'm Penny, your civic assistant. "
1103
+ "I can help you find local resources, events, weather, and more. "
1104
+ "What city are you in?"
1105
+ ),
1106
+ IntentType.HELP: (
1107
+ "I'm Penny! πŸ’› I can help you with:\n\n"
1108
+ "πŸ›οΈ Local resources (shelters, libraries, food banks)\n"
1109
+ "πŸ“… Community events\n"
1110
+ "🌀️ Weather updates\n"
1111
+ "🌍 Translation (27 languages)\n"
1112
+ "πŸ“„ Document help\n\n"
1113
+ "What would you like to know about?"
1114
+ ),
1115
+ IntentType.UNKNOWN: (
1116
+ "I'm not sure I understood that. Could you rephrase? "
1117
+ "I'm best at helping with local services, events, weather, "
1118
+ "and translation! πŸ’¬"
1119
+ )
1120
+ }
1121
+
1122
+ return OrchestrationResult(
1123
+ intent=intent.value,
1124
+ reply=fallback_replies.get(intent, "How can I help you today? πŸ’›"),
1125
+ success=True,
1126
+ model_id="fallback",
1127
+ fallback_used=True
1128
+ )
1129
+
1130
+
1131
+ async def _handle_fallback(
1132
+ message: str,
1133
+ intent: IntentType,
1134
+ context: Dict[str, Any]
1135
+ ) -> OrchestrationResult:
1136
+ """
1137
+ πŸ†˜ Ultimate fallback handler for unhandled intents.
1138
+
1139
+ This is a safety net that should rarely trigger, but ensures
1140
+ users always get a helpful response.
1141
+ """
1142
+ logger.warning(f"⚠️ Fallback triggered for intent: {intent.value}")
1143
+
1144
+ reply = (
1145
+ "I've processed your request, but I'm not sure how to help with that yet. "
1146
+ "I'm still learning! πŸ€–\n\n"
1147
+ "I'm best at:\n"
1148
+ "πŸ›οΈ Finding local resources\n"
1149
+ "πŸ“… Community events\n"
1150
+ "🌀️ Weather updates\n"
1151
+ "🌍 Translation\n\n"
1152
+ "Could you rephrase your question? πŸ’›"
1153
+ )
1154
+
1155
+ return OrchestrationResult(
1156
+ intent=intent.value,
1157
+ reply=reply,
1158
+ success=False,
1159
+ error="Unhandled intent",
1160
+ fallback_used=True
1161
+ )
1162
+
1163
+
1164
+ # ============================================================
1165
+ # HEALTH CHECK & DIAGNOSTICS (ENHANCED)
1166
+ # ============================================================
1167
+
1168
+ def get_orchestrator_health() -> Dict[str, Any]:
1169
+ """
1170
+ πŸ“Š Returns comprehensive orchestrator health status.
1171
+
1172
+ Used by the main application health check endpoint to monitor
1173
+ the orchestrator and all its service dependencies.
1174
+
1175
+ Returns:
1176
+ Dictionary with health information including:
1177
+ - status: operational/degraded
1178
+ - service_availability: which services are loaded
1179
+ - statistics: orchestration counts
1180
+ - supported_intents: list of all intent types
1181
+ - features: available orchestrator features
1182
+ """
1183
+ # Get service availability
1184
+ services = get_service_availability()
1185
+
1186
+ # Determine overall status
1187
+ # Orchestrator is operational even if some services are down (graceful degradation)
1188
+ critical_services = ["weather", "tool_agent"] # Must have these
1189
+ critical_available = all(services.get(svc, False) for svc in critical_services)
1190
+
1191
+ status = "operational" if critical_available else "degraded"
1192
+
1193
+ return {
1194
+ "status": status,
1195
+ "core_model": CORE_MODEL_ID,
1196
+ "max_response_time_ms": MAX_RESPONSE_TIME_MS,
1197
+ "statistics": {
1198
+ "total_orchestrations": _orchestration_count,
1199
+ "emergency_interactions": _emergency_count
1200
+ },
1201
+ "service_availability": services,
1202
+ "supported_intents": [intent.value for intent in IntentType],
1203
+ "features": {
1204
+ "emergency_routing": True,
1205
+ "compound_intents": True,
1206
+ "fallback_handling": True,
1207
+ "performance_tracking": True,
1208
+ "context_aware": True,
1209
+ "multi_language": TRANSLATION_AVAILABLE,
1210
+ "sentiment_analysis": SENTIMENT_AVAILABLE,
1211
+ "bias_detection": BIAS_AVAILABLE,
1212
+ "weather_integration": WEATHER_AGENT_AVAILABLE,
1213
+ "event_recommendations": EVENT_WEATHER_AVAILABLE
1214
+ }
1215
+ }
1216
+
1217
+
1218
+ def get_orchestrator_stats() -> Dict[str, Any]:
1219
+ """
1220
+ πŸ“ˆ Returns orchestrator statistics.
1221
+
1222
+ Useful for monitoring and analytics.
1223
+ """
1224
+ return {
1225
+ "total_orchestrations": _orchestration_count,
1226
+ "emergency_interactions": _emergency_count,
1227
+ "services_available": sum(1 for v in get_service_availability().values() if v),
1228
+ "services_total": len(get_service_availability())
1229
+ }
1230
+
1231
+
1232
+ # ============================================================
1233
+ # TESTING & DEBUGGING (ENHANCED)
1234
+ # ============================================================
1235
+
1236
+ if __name__ == "__main__":
1237
+ """
1238
+ πŸ§ͺ Test the orchestrator with sample queries.
1239
+ Run with: python -m app.orchestrator
1240
+ """
1241
+ import asyncio
1242
+
1243
+ print("=" * 60)
1244
+ print("πŸ§ͺ Testing Penny's Orchestrator")
1245
+ print("=" * 60)
1246
+
1247
+ # Display service availability first
1248
+ print("\nπŸ“Š Service Availability Check:")
1249
+ services = get_service_availability()
1250
+ for service, available in services.items():
1251
+ status = "βœ…" if available else "❌"
1252
+ print(f" {status} {service}: {'Available' if available else 'Not loaded'}")
1253
+
1254
+ print("\n" + "=" * 60)
1255
+
1256
+ test_queries = [
1257
+ {
1258
+ "name": "Greeting",
1259
+ "message": "Hi Penny!",
1260
+ "context": {}
1261
+ },
1262
+ {
1263
+ "name": "Weather with location",
1264
+ "message": "What's the weather?",
1265
+ "context": {"lat": 33.7490, "lon": -84.3880}
1266
+ },
1267
+ {
1268
+ "name": "Events in city",
1269
+ "message": "Events in Atlanta",
1270
+ "context": {"tenant_id": "atlanta_ga"}
1271
+ },
1272
+ {
1273
+ "name": "Help request",
1274
+ "message": "I need help",
1275
+ "context": {}
1276
+ },
1277
+ {
1278
+ "name": "Translation",
1279
+ "message": "Translate hello",
1280
+ "context": {"source_lang": "eng_Latn", "target_lang": "spa_Latn"}
1281
+ }
1282
+ ]
1283
+
1284
+ async def run_tests():
1285
+ for i, query in enumerate(test_queries, 1):
1286
+ print(f"\n--- Test {i}: {query['name']} ---")
1287
+ print(f"Query: {query['message']}")
1288
+
1289
+ try:
1290
+ result = await run_orchestrator(query["message"], query["context"])
1291
+ print(f"Intent: {result['intent']}")
1292
+ print(f"Success: {result['success']}")
1293
+ print(f"Fallback: {result.get('fallback_used', False)}")
1294
+
1295
+ # Truncate long replies
1296
+ reply = result['reply']
1297
+ if len(reply) > 150:
1298
+ reply = reply[:150] + "..."
1299
+ print(f"Reply: {reply}")
1300
+
1301
+ if result.get('response_time_ms'):
1302
+ print(f"Response time: {result['response_time_ms']:.0f}ms")
1303
+
1304
+ except Exception as e:
1305
+ print(f"❌ Error: {e}")
1306
+
1307
+ asyncio.run(run_tests())
1308
+
1309
+ print("\n" + "=" * 60)
1310
+ print("πŸ“Š Final Statistics:")
1311
+ stats = get_orchestrator_stats()
1312
+ for key, value in stats.items():
1313
+ print(f" {key}: {value}")
1314
+
1315
+ print("\n" + "=" * 60)
1316
+ print("βœ… Tests complete")
1317
+ print("=" * 60)