pythonprincess commited on
Commit
441c9e7
·
verified ·
1 Parent(s): f14688e

Delete app/orchestrator.py

Browse files
Files changed (1) hide show
  1. app/orchestrator.py +0 -1358
app/orchestrator.py DELETED
@@ -1,1358 +0,0 @@
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
- # === ENHANCED LOCATION RESOLUTION ===
783
- # Try multiple strategies to get coordinates
784
-
785
- # Strategy 1: Use provided coordinates
786
- if lat is not None and lon is not None:
787
- logger.info(f"Using provided coordinates: {lat}, {lon}")
788
-
789
- # Strategy 2: Get coordinates from tenant_id (try multiple formats)
790
- elif tenant_id:
791
- # Try tenant_id as-is first
792
- coords = get_city_coordinates(tenant_id)
793
-
794
- # If that fails and tenant_id doesn't have state suffix, try adding common suffixes
795
- if not coords and "_" not in tenant_id:
796
- # Try common state abbreviations for known cities
797
- state_suffixes = ["_va", "_ga", "_al", "_tx", "_ri", "_wa"]
798
- for suffix in state_suffixes:
799
- test_tenant_id = tenant_id + suffix
800
- coords = get_city_coordinates(test_tenant_id)
801
- if coords:
802
- tenant_id = test_tenant_id # Update tenant_id to normalized form
803
- logger.info(f"Normalized tenant_id to {tenant_id}")
804
- break
805
-
806
- if coords:
807
- lat, lon = coords["lat"], coords["lon"]
808
- logger.info(f"✅ Using city coordinates for {tenant_id}: {lat}, {lon}")
809
-
810
- # Strategy 3: Extract location from message if still no coordinates
811
- if lat is None or lon is None:
812
- logger.info("No coordinates from tenant_id, trying to extract from message")
813
- location_result = extract_location_detailed(message)
814
-
815
- if location_result.status == LocationStatus.FOUND:
816
- extracted_tenant_id = location_result.tenant_id
817
- logger.info(f"📍 Location extracted from message: {extracted_tenant_id}")
818
-
819
- # Update tenant_id if we extracted a better one
820
- if not tenant_id or tenant_id != extracted_tenant_id:
821
- tenant_id = extracted_tenant_id
822
- logger.info(f"Updated tenant_id to {tenant_id}")
823
-
824
- # Get coordinates for extracted location
825
- coords = get_city_coordinates(tenant_id)
826
- if coords:
827
- lat, lon = coords["lat"], coords["lon"]
828
- logger.info(f"✅ Coordinates found from message extraction: {lat}, {lon}")
829
-
830
- # Final check: if still no coordinates, return error
831
- if lat is None or lon is None:
832
- logger.warning(f"❌ No coordinates available for weather request (tenant_id: {tenant_id})")
833
- return OrchestrationResult(
834
- intent=IntentType.WEATHER.value,
835
- reply=(
836
- "I need to know your location to check the weather! 📍 "
837
- "You can tell me your city, or share your location."
838
- ),
839
- success=False,
840
- error="Location required"
841
- )
842
-
843
- try:
844
- # Use combined weather + events if compound intent detected
845
- if is_compound and tenant_id and EVENT_WEATHER_AVAILABLE:
846
- logger.info("Using weather+events combined handler")
847
- result = await get_event_recommendations_with_weather(tenant_id, lat, lon)
848
-
849
- # Build response
850
- weather = result.get("weather", {})
851
- weather_summary = result.get("weather_summary", "Weather unavailable")
852
- suggestions = result.get("suggestions", [])
853
-
854
- reply_lines = [f"🌤️ **Weather Update:**\n{weather_summary}\n"]
855
-
856
- if suggestions:
857
- reply_lines.append("\n📅 **Event Suggestions Based on Weather:**")
858
- for suggestion in suggestions[:5]: # Top 5 suggestions
859
- reply_lines.append(f"• {suggestion}")
860
-
861
- reply = "\n".join(reply_lines)
862
-
863
- return OrchestrationResult(
864
- intent=IntentType.WEATHER.value,
865
- reply=reply,
866
- success=True,
867
- data=result,
868
- model_id="weather_events_combined"
869
- )
870
-
871
- else:
872
- # Simple weather query using enhanced weather_agent
873
- weather = await get_weather_for_location(lat, lon)
874
-
875
- # Use enhanced weather_agent's format_weather_summary
876
- if format_weather_summary:
877
- weather_text = format_weather_summary(weather)
878
- else:
879
- # Fallback formatting
880
- temp = weather.get("temperature", {}).get("value")
881
- phrase = weather.get("phrase", "Conditions unavailable")
882
- if temp:
883
- weather_text = f"{phrase}, {int(temp)}°F"
884
- else:
885
- weather_text = phrase
886
-
887
- # Get outfit recommendation from enhanced weather_agent
888
- if recommend_outfit:
889
- temp = weather.get("temperature", {}).get("value", 70)
890
- condition = weather.get("phrase", "Clear")
891
- outfit = recommend_outfit(temp, condition)
892
- reply = f"🌤️ {weather_text}\n\n👕 {outfit}"
893
- else:
894
- reply = f"🌤️ {weather_text}"
895
-
896
- return OrchestrationResult(
897
- intent=IntentType.WEATHER.value,
898
- reply=reply,
899
- success=True,
900
- data=weather,
901
- model_id="azure-maps-weather"
902
- )
903
-
904
- except Exception as e:
905
- logger.error(f"Weather error: {e}", exc_info=True)
906
- return OrchestrationResult(
907
- intent=IntentType.WEATHER.value,
908
- reply=(
909
- "I'm having trouble getting weather data right now. "
910
- "Can I help you with something else? 💛"
911
- ),
912
- success=False,
913
- error=str(e),
914
- fallback_used=True
915
- )
916
-
917
-
918
- async def _handle_events(
919
- message: str,
920
- context: Dict[str, Any],
921
- tenant_id: Optional[str],
922
- lat: Optional[float],
923
- lon: Optional[float],
924
- intent_result: IntentMatch
925
- ) -> OrchestrationResult:
926
- """
927
- 📅 Events handler.
928
-
929
- Routes event queries to tool_agent with proper error handling
930
- and graceful degradation.
931
- """
932
- logger.info("📅 Processing events request")
933
-
934
- if not tenant_id:
935
- return OrchestrationResult(
936
- intent=IntentType.EVENTS.value,
937
- reply=(
938
- "I'd love to help you find events! 📅 "
939
- "Which city are you interested in? "
940
- "I have information for Atlanta, Birmingham, Chesterfield, "
941
- "El Paso, Providence, and Seattle."
942
- ),
943
- success=False,
944
- error="City required"
945
- )
946
-
947
- # Check tool agent availability
948
- if not TOOL_AGENT_AVAILABLE:
949
- logger.warning("Tool agent not available")
950
- return OrchestrationResult(
951
- intent=IntentType.EVENTS.value,
952
- reply=(
953
- "Event information isn't available right now. "
954
- "Try again soon! 📅"
955
- ),
956
- success=False,
957
- error="Tool agent not loaded",
958
- fallback_used=True
959
- )
960
-
961
- try:
962
- # FIXED: Add role parameter (compatibility fix)
963
- tool_response = await handle_tool_request(
964
- user_input=message,
965
- role=context.get("role", "resident"), # ← ADDED
966
- lat=lat,
967
- lon=lon,
968
- context=context
969
- )
970
-
971
- reply = tool_response.get("response", "Events information retrieved.")
972
-
973
- return OrchestrationResult(
974
- intent=IntentType.EVENTS.value,
975
- reply=reply,
976
- success=True,
977
- data=tool_response,
978
- model_id="events_tool"
979
- )
980
-
981
- except Exception as e:
982
- logger.error(f"Events error: {e}", exc_info=True)
983
- return OrchestrationResult(
984
- intent=IntentType.EVENTS.value,
985
- reply=(
986
- "I'm having trouble loading event information right now. "
987
- "Check back soon! 📅"
988
- ),
989
- success=False,
990
- error=str(e),
991
- fallback_used=True
992
- )
993
-
994
- async def _handle_local_resources(
995
- message: str,
996
- context: Dict[str, Any],
997
- tenant_id: Optional[str],
998
- lat: Optional[float],
999
- lon: Optional[float]
1000
- ) -> OrchestrationResult:
1001
- """
1002
- 🏛️ Local resources handler (shelters, libraries, food banks, etc.).
1003
-
1004
- Routes resource queries to tool_agent with proper error handling.
1005
- """
1006
- logger.info("🏛️ Processing local resources request")
1007
-
1008
- if not tenant_id:
1009
- return OrchestrationResult(
1010
- intent=IntentType.LOCAL_RESOURCES.value,
1011
- reply=(
1012
- "I can help you find local resources! 🏛️ "
1013
- "Which city do you need help in? "
1014
- "I cover Atlanta, Birmingham, Chesterfield, El Paso, "
1015
- "Providence, and Seattle."
1016
- ),
1017
- success=False,
1018
- error="City required"
1019
- )
1020
-
1021
- # Check tool agent availability
1022
- if not TOOL_AGENT_AVAILABLE:
1023
- logger.warning("Tool agent not available")
1024
- return OrchestrationResult(
1025
- intent=IntentType.LOCAL_RESOURCES.value,
1026
- reply=(
1027
- "Resource information isn't available right now. "
1028
- "Try again soon! 🏛️"
1029
- ),
1030
- success=False,
1031
- error="Tool agent not loaded",
1032
- fallback_used=True
1033
- )
1034
-
1035
- try:
1036
- # FIXED: Add role parameter (compatibility fix)
1037
- tool_response = await handle_tool_request(
1038
- user_input=message,
1039
- role=context.get("role", "resident"), # ← ADDED
1040
- lat=lat,
1041
- lon=lon,
1042
- context=context
1043
- )
1044
-
1045
- reply = tool_response.get("response", "Resource information retrieved.")
1046
-
1047
- return OrchestrationResult(
1048
- intent=IntentType.LOCAL_RESOURCES.value,
1049
- reply=reply,
1050
- success=True,
1051
- data=tool_response,
1052
- model_id="resources_tool"
1053
- )
1054
-
1055
- except Exception as e:
1056
- logger.error(f"Resources error: {e}", exc_info=True)
1057
- return OrchestrationResult(
1058
- intent=IntentType.LOCAL_RESOURCES.value,
1059
- reply=(
1060
- "I'm having trouble finding resource information right now. "
1061
- "Would you like to try a different search? 💛"
1062
- ),
1063
- success=False,
1064
- error=str(e),
1065
- fallback_used=True
1066
- )
1067
-
1068
-
1069
- async def _handle_conversational(
1070
- message: str,
1071
- intent: IntentType,
1072
- context: Dict[str, Any]
1073
- ) -> OrchestrationResult:
1074
- """
1075
- 💬 Handles conversational intents (greeting, help, unknown).
1076
- Uses Penny's core LLM for natural responses with graceful fallback.
1077
- """
1078
- logger.info(f"💬 Processing conversational intent: {intent.value}")
1079
-
1080
- # Check LLM availability
1081
- use_llm = LLM_AVAILABLE
1082
-
1083
- try:
1084
- if use_llm:
1085
- # Build prompt based on intent
1086
- if intent == IntentType.GREETING:
1087
- prompt = (
1088
- f"The user greeted you with: '{message}'\n\n"
1089
- "Respond warmly as Penny, introduce yourself briefly, "
1090
- "and ask how you can help them with civic services today."
1091
- )
1092
-
1093
- elif intent == IntentType.HELP:
1094
- prompt = (
1095
- f"The user asked for help: '{message}'\n\n"
1096
- "Explain Penny's main features:\n"
1097
- "- Finding local resources (shelters, libraries, food banks)\n"
1098
- "- Community events and activities\n"
1099
- "- Weather information\n"
1100
- "- 27-language translation\n"
1101
- "- Document processing help\n\n"
1102
- "Ask which city they need assistance in."
1103
- )
1104
-
1105
- else: # UNKNOWN
1106
- prompt = (
1107
- f"The user said: '{message}'\n\n"
1108
- "You're not sure what they need help with. "
1109
- "Respond kindly, acknowledge their request, and ask them to "
1110
- "clarify or rephrase. Mention a few things you can help with."
1111
- )
1112
-
1113
- # Call Penny's core LLM
1114
- llm_result = await generate_response(prompt=prompt, max_new_tokens=200)
1115
-
1116
- # Use compatibility helper to check result
1117
- success, error = _check_result_success(llm_result, ["response"])
1118
-
1119
- if success:
1120
- reply = llm_result.get("response", "")
1121
-
1122
- return OrchestrationResult(
1123
- intent=intent.value,
1124
- reply=reply,
1125
- success=True,
1126
- data=llm_result,
1127
- model_id=CORE_MODEL_ID
1128
- )
1129
- else:
1130
- raise Exception(error or "LLM generation failed")
1131
-
1132
- else:
1133
- # LLM not available, use fallback directly
1134
- logger.info("LLM not available, using fallback responses")
1135
- raise Exception("LLM service not loaded")
1136
-
1137
- except Exception as e:
1138
- logger.warning(f"Conversational handler using fallback: {e}")
1139
-
1140
- # Hardcoded fallback responses (Penny's friendly voice)
1141
- fallback_replies = {
1142
- IntentType.GREETING: (
1143
- "Hi there! 👋 I'm Penny, your civic assistant. "
1144
- "I can help you find local resources, events, weather, and more. "
1145
- "What city are you in?"
1146
- ),
1147
- IntentType.HELP: (
1148
- "I'm Penny! 💛 I can help you with:\n\n"
1149
- "🏛️ Local resources (shelters, libraries, food banks)\n"
1150
- "📅 Community events\n"
1151
- "🌤️ Weather updates\n"
1152
- "🌍 Translation (27 languages)\n"
1153
- "📄 Document help\n\n"
1154
- "What would you like to know about?"
1155
- ),
1156
- IntentType.UNKNOWN: (
1157
- "I'm not sure I understood that. Could you rephrase? "
1158
- "I'm best at helping with local services, events, weather, "
1159
- "and translation! 💬"
1160
- )
1161
- }
1162
-
1163
- return OrchestrationResult(
1164
- intent=intent.value,
1165
- reply=fallback_replies.get(intent, "How can I help you today? 💛"),
1166
- success=True,
1167
- model_id="fallback",
1168
- fallback_used=True
1169
- )
1170
-
1171
-
1172
- async def _handle_fallback(
1173
- message: str,
1174
- intent: IntentType,
1175
- context: Dict[str, Any]
1176
- ) -> OrchestrationResult:
1177
- """
1178
- 🆘 Ultimate fallback handler for unhandled intents.
1179
-
1180
- This is a safety net that should rarely trigger, but ensures
1181
- users always get a helpful response.
1182
- """
1183
- logger.warning(f"⚠️ Fallback triggered for intent: {intent.value}")
1184
-
1185
- reply = (
1186
- "I've processed your request, but I'm not sure how to help with that yet. "
1187
- "I'm still learning! 🤖\n\n"
1188
- "I'm best at:\n"
1189
- "🏛️ Finding local resources\n"
1190
- "📅 Community events\n"
1191
- "🌤️ Weather updates\n"
1192
- "🌍 Translation\n\n"
1193
- "Could you rephrase your question? 💛"
1194
- )
1195
-
1196
- return OrchestrationResult(
1197
- intent=intent.value,
1198
- reply=reply,
1199
- success=False,
1200
- error="Unhandled intent",
1201
- fallback_used=True
1202
- )
1203
-
1204
-
1205
- # ============================================================
1206
- # HEALTH CHECK & DIAGNOSTICS (ENHANCED)
1207
- # ============================================================
1208
-
1209
- def get_orchestrator_health() -> Dict[str, Any]:
1210
- """
1211
- 📊 Returns comprehensive orchestrator health status.
1212
-
1213
- Used by the main application health check endpoint to monitor
1214
- the orchestrator and all its service dependencies.
1215
-
1216
- Returns:
1217
- Dictionary with health information including:
1218
- - status: operational/degraded
1219
- - service_availability: which services are loaded
1220
- - statistics: orchestration counts
1221
- - supported_intents: list of all intent types
1222
- - features: available orchestrator features
1223
- """
1224
- # Get service availability
1225
- services = get_service_availability()
1226
-
1227
- # Determine overall status
1228
- # Orchestrator is operational even if some services are down (graceful degradation)
1229
- critical_services = ["weather", "tool_agent"] # Must have these
1230
- critical_available = all(services.get(svc, False) for svc in critical_services)
1231
-
1232
- status = "operational" if critical_available else "degraded"
1233
-
1234
- return {
1235
- "status": status,
1236
- "core_model": CORE_MODEL_ID,
1237
- "max_response_time_ms": MAX_RESPONSE_TIME_MS,
1238
- "statistics": {
1239
- "total_orchestrations": _orchestration_count,
1240
- "emergency_interactions": _emergency_count
1241
- },
1242
- "service_availability": services,
1243
- "supported_intents": [intent.value for intent in IntentType],
1244
- "features": {
1245
- "emergency_routing": True,
1246
- "compound_intents": True,
1247
- "fallback_handling": True,
1248
- "performance_tracking": True,
1249
- "context_aware": True,
1250
- "multi_language": TRANSLATION_AVAILABLE,
1251
- "sentiment_analysis": SENTIMENT_AVAILABLE,
1252
- "bias_detection": BIAS_AVAILABLE,
1253
- "weather_integration": WEATHER_AGENT_AVAILABLE,
1254
- "event_recommendations": EVENT_WEATHER_AVAILABLE
1255
- }
1256
- }
1257
-
1258
-
1259
- def get_orchestrator_stats() -> Dict[str, Any]:
1260
- """
1261
- 📈 Returns orchestrator statistics.
1262
-
1263
- Useful for monitoring and analytics.
1264
- """
1265
- return {
1266
- "total_orchestrations": _orchestration_count,
1267
- "emergency_interactions": _emergency_count,
1268
- "services_available": sum(1 for v in get_service_availability().values() if v),
1269
- "services_total": len(get_service_availability())
1270
- }
1271
-
1272
-
1273
- # ============================================================
1274
- # TESTING & DEBUGGING (ENHANCED)
1275
- # ============================================================
1276
-
1277
- if __name__ == "__main__":
1278
- """
1279
- 🧪 Test the orchestrator with sample queries.
1280
- Run with: python -m app.orchestrator
1281
- """
1282
- import asyncio
1283
-
1284
- print("=" * 60)
1285
- print("🧪 Testing Penny's Orchestrator")
1286
- print("=" * 60)
1287
-
1288
- # Display service availability first
1289
- print("\n📊 Service Availability Check:")
1290
- services = get_service_availability()
1291
- for service, available in services.items():
1292
- status = "✅" if available else "❌"
1293
- print(f" {status} {service}: {'Available' if available else 'Not loaded'}")
1294
-
1295
- print("\n" + "=" * 60)
1296
-
1297
- test_queries = [
1298
- {
1299
- "name": "Greeting",
1300
- "message": "Hi Penny!",
1301
- "context": {}
1302
- },
1303
- {
1304
- "name": "Weather with location",
1305
- "message": "What's the weather?",
1306
- "context": {"lat": 33.7490, "lon": -84.3880}
1307
- },
1308
- {
1309
- "name": "Events in city",
1310
- "message": "Events in Atlanta",
1311
- "context": {"tenant_id": "atlanta_ga"}
1312
- },
1313
- {
1314
- "name": "Help request",
1315
- "message": "I need help",
1316
- "context": {}
1317
- },
1318
- {
1319
- "name": "Translation",
1320
- "message": "Translate hello",
1321
- "context": {"source_lang": "eng_Latn", "target_lang": "spa_Latn"}
1322
- }
1323
- ]
1324
-
1325
- async def run_tests():
1326
- for i, query in enumerate(test_queries, 1):
1327
- print(f"\n--- Test {i}: {query['name']} ---")
1328
- print(f"Query: {query['message']}")
1329
-
1330
- try:
1331
- result = await run_orchestrator(query["message"], query["context"])
1332
- print(f"Intent: {result['intent']}")
1333
- print(f"Success: {result['success']}")
1334
- print(f"Fallback: {result.get('fallback_used', False)}")
1335
-
1336
- # Truncate long replies
1337
- reply = result['reply']
1338
- if len(reply) > 150:
1339
- reply = reply[:150] + "..."
1340
- print(f"Reply: {reply}")
1341
-
1342
- if result.get('response_time_ms'):
1343
- print(f"Response time: {result['response_time_ms']:.0f}ms")
1344
-
1345
- except Exception as e:
1346
- print(f"❌ Error: {e}")
1347
-
1348
- asyncio.run(run_tests())
1349
-
1350
- print("\n" + "=" * 60)
1351
- print("📊 Final Statistics:")
1352
- stats = get_orchestrator_stats()
1353
- for key, value in stats.items():
1354
- print(f" {key}: {value}")
1355
-
1356
- print("\n" + "=" * 60)
1357
- print("✅ Tests complete")
1358
- print("=" * 60)