Spaces:
Sleeping
feat: Task 6 - Add comprehensive error handling and fallback
Browse files- Add handle_assistant_error() with fallback to Medical mode
- Add _retry_with_backoff() for temporary errors (timeout, connection)
- Add error handling to _handle_spiritual_mode()
- Add error handling to _handle_combined_mode()
- Add error handling to _handle_entry_classification() with last-known-mode fallback
- Update CombinedAssistant._combine_responses() with partial failure notifications
- Log all errors with traceback for debugging
Error handling strategy:
- Timeout/Connection errors: Retry with exponential backoff (max 3 attempts)
- Assistant errors: Fallback to Medical mode with clear user notification
- Entry Classifier errors: Use last known mode or default to Medical
- Partial failures in Combined mode: Show available assistant + error message
Requirements: 11.1, 11.2, 11.3, 11.4, 11.5
Files changed (2)
- lifestyle_app.py+204-20
- src/core/combined_assistant.py+43-1
384 unmodified lines385386387388389390391392393394395135 unmodified lines53153253353453553653753853954054154254354432 unmodified lines577578579580581582583584585586587588589590591592304 unmodified lines897898899900901902384 unmodified lines- L=on, S=on → Combined mode- L=off, S=off → Medical modeRequirements: 4.1, 4.2, 4.3, 4.5"""# Classify message (Requirement: 4.1, 4.2, 4.3, 4.4)classification = self.entry_classifier.classify(message, self.clinical_background)self.session_state.entry_classification = classification# Extract indicatorsK = classification.get("K", "none")135 unmodified lines- Yellow flags: Continue with clarifying questions- No flags: Continue with supportive responseRequirements: 1.2, 3.1"""# Process message through Spiritual Assistantresult = self.spiritual_assistant.process_message(message,self.chat_history,self.clinical_background)# Store spiritual assessment in session state (Requirement: 7.3)self.session_state.spiritual_assessment = result.get("classification")32 unmodified lines- Determines priority based on results- Handles escalation if spiritual red flag detectedRequirements: 2.1, 2.3"""# Process message through Combined Assistant (Requirement: 2.1)result = self.combined_assistant.process_message(message,self.chat_history,self.clinical_background,self.lifestyle_profile,self.session_state.lifestyle_session_length)# Store combined results in session state (Requirement: 7.4)self.session_state.combined_results = {304 unmodified lines# Spiritual assessment already stored in session_statedef reset_session(self) -> Tuple[List, str]:"""Session reset with new logic"""# Close current session before reset384 unmodified lines385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426135 unmodified lines56256356456556656756856957057157257357457557657757857932 unmodified lines612613614615616617618619620621622623624625626627628629630631304 unmodified lines936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086384 unmodified lines- L=on, S=on → Combined mode- L=off, S=off → Medical modeRequirements: 4.1, 4.2, 4.3, 4.5, 11.3"""try:# Classify message (Requirement: 4.1, 4.2, 4.3, 4.4)classification = self.entry_classifier.classify(message, self.clinical_background)self.session_state.entry_classification = classificationexcept Exception as e:# Entry Classifier error - use last known mode or default to Medical (Requirement: 11.3)import logginglogger = logging.getLogger(__name__)logger.error(f"Entry Classifier error: {e}")# Try to use last known modeif self.session_state.current_mode != AssistantMode.NONE:fallback_mode = self.session_state.current_modelogger.info(f"Using last known mode: {fallback_mode.value}")else:fallback_mode = AssistantMode.MEDICALlogger.info("No last known mode, defaulting to Medical")# Generate fallback responsefallback_message = f"""⚠️ **Classification Service Unavailable**Unable to automatically determine the best support mode. Using {fallback_mode.value} mode.Please continue with your question, or manually select a different mode if needed."""try:medical_response = self.soft_medical_triage.conduct_triage(message,self.clinical_background,self.chat_history)return f"{fallback_message}\n\n---\n\n{medical_response}", fallback_modeexcept Exception:return f"{fallback_message}\n\nHow can I help you?", fallback_mode# Extract indicatorsK = classification.get("K", "none")135 unmodified lines- Yellow flags: Continue with clarifying questions- No flags: Continue with supportive responseRequirements: 1.2, 3.1, 11.1"""try:# Process message through Spiritual Assistantresult = self.spiritual_assistant.process_message(message,self.chat_history,self.clinical_background)except Exception as e:# Handle spiritual assistant error (Requirement: 11.1)return self.handle_assistant_error(e, AssistantMode.SPIRITUAL, message)# Store spiritual assessment in session state (Requirement: 7.3)self.session_state.spiritual_assessment = result.get("classification")32 unmodified lines- Determines priority based on results- Handles escalation if spiritual red flag detectedRequirements: 2.1, 2.3, 11.1"""try:# Process message through Combined Assistant (Requirement: 2.1)result = self.combined_assistant.process_message(message,self.chat_history,self.clinical_background,self.lifestyle_profile,self.session_state.lifestyle_session_length)except Exception as e:# Handle combined assistant error (Requirement: 11.1)return self.handle_assistant_error(e, AssistantMode.COMBINED, message)# Store combined results in session state (Requirement: 7.4)self.session_state.combined_results = {304 unmodified lines# Spiritual assessment already stored in session_statedef _retry_with_backoff(self,func,*args,max_retries: int = 3,initial_delay: float = 1.0,**kwargs):"""Retry function with exponential backoff for temporary errors.Requirements: 11.5"""import logginglogger = logging.getLogger(__name__)delay = initial_delaylast_error = Nonefor attempt in range(max_retries):try:return func(*args, **kwargs)except (TimeoutError, ConnectionError) as e:last_error = eif attempt < max_retries - 1:logger.warning(f"Attempt {attempt + 1} failed: {e}. Retrying in {delay}s...")time.sleep(delay)delay *= 2 # Exponential backoffelse:logger.error(f"All {max_retries} attempts failed")raise last_errorexcept Exception as e:# Non-temporary error - don't retryraise eraise last_errordef handle_assistant_error(self,error: Exception,current_mode: AssistantMode,message: str) -> Tuple[str, AssistantMode]:"""Handle assistant errors with fallback logic.Fallback strategy:- Spiritual error → Medical mode- Lifestyle error → Medical mode- Combined error → Medical mode- Medical error → Soft medical triage- Entry Classifier error → Use last known mode or MedicalRequirements: 11.1, 11.4"""import loggingimport tracebacklogger = logging.getLogger(__name__)logger.error(f"Assistant error in {current_mode.value} mode: {error}")logger.error(traceback.format_exc())# Determine error type and appropriate fallbackerror_type = type(error).__name__# Timeout errors - temporary issue (Requirement: 11.5)if isinstance(error, TimeoutError):fallback_mode = AssistantMode.MEDICALuser_message = f"""⚠️ **Service Temporarily Unavailable**The {current_mode.value} assistant is experiencing delays. Switching to medical support mode.Please try again in a moment, or continue with medical assistance."""# Try medical assistanttry:medical_response = self.soft_medical_triage.conduct_triage(message,self.clinical_background,self.chat_history)return f"{user_message}\n\n---\n\n{medical_response}", fallback_modeexcept Exception as e:logger.error(f"Medical fallback also failed: {e}")return f"{user_message}\n\nPlease try again or contact support.", fallback_mode# Connection errors - temporary issueelif isinstance(error, ConnectionError):fallback_mode = AssistantMode.MEDICALuser_message = f"""⚠️ **Connection Issue**Unable to connect to the {current_mode.value} assistant. Switching to medical support mode.Your data is safe. Please try again."""try:medical_response = self.soft_medical_triage.conduct_triage(message,self.clinical_background,self.chat_history)return f"{user_message}\n\n---\n\n{medical_response}", fallback_modeexcept Exception:return f"{user_message}\n\nPlease refresh and try again.", fallback_mode# Value errors - invalid inputelif isinstance(error, ValueError):fallback_mode = AssistantMode.MEDICALuser_message = f"""⚠️ **Input Processing Error**There was an issue processing your request in {current_mode.value} mode. Switching to safe medical mode.Please rephrase your message or try a different approach."""try:medical_response = self.soft_medical_triage.conduct_triage(message,self.clinical_background,self.chat_history)return f"{user_message}\n\n---\n\n{medical_response}", fallback_modeexcept Exception:return f"{user_message}\n\nHow can I help you today?", fallback_mode# Generic errors - fallback to medicalelse:fallback_mode = AssistantMode.MEDICALuser_message = f"""⚠️ **Unexpected Error**An unexpected error occurred in {current_mode.value} mode. For your safety, switching to medical support mode.Error type: {error_type}Please try again or contact support if the issue persists."""try:medical_response = self.soft_medical_triage.conduct_triage(message,self.clinical_background,self.chat_history)return f"{user_message}\n\n---\n\n{medical_response}", fallback_modeexcept Exception:return f"{user_message}\n\nHow can I help you with your health today?", fallback_modedef reset_session(self) -> Tuple[List, str]:"""Session reset with new logic"""# Close current session before reset
266 unmodified lines267268269270271272273274275276277266 unmodified lines- lifestyle priority: Lifestyle first (prominent), then spiritual- balanced: Both equally prominentRequirements: 2.2, 2.5, 6.4"""lifestyle_msg = lifestyle_result.get("message", "")spiritual_msg = spiritual_result.get("message", "")if priority == "spiritual":# Spiritual takes precedence (Requirement 2.4)return f"""{spiritual_msg}266 unmodified lines267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319266 unmodified lines- lifestyle priority: Lifestyle first (prominent), then spiritual- balanced: Both equally prominentHandles partial failures with user notifications.Requirements: 2.2, 2.5, 6.4, 11.1"""lifestyle_msg = lifestyle_result.get("message", "")spiritual_msg = spiritual_result.get("message", "")# Check for errors (Requirement: 11.1)lifestyle_error = lifestyle_result.get("error", False)spiritual_error = spiritual_result.get("error", False)# Both failedif lifestyle_error and spiritual_error:return f"""⚠️ **Combined Support Temporarily Unavailable**Both lifestyle and spiritual assistants are experiencing issues.💚 **Lifestyle:** {lifestyle_msg}🕊️ **Spiritual:** {spiritual_msg}Please try again or switch to Medical mode for immediate assistance."""# Only lifestyle failedif lifestyle_error:return f"""🕊️ **Spiritual Assessment (Lifestyle Temporarily Unavailable)**{spiritual_msg}---⚠️ **Lifestyle Support:** {lifestyle_msg}Spiritual assessment is available. Lifestyle support will return shortly."""# Only spiritual failedif spiritual_error:return f"""💚 **Lifestyle Coaching (Spiritual Temporarily Unavailable)**{lifestyle_msg}---⚠️ **Spiritual Support:** {spiritual_msg}Lifestyle coaching is available. Spiritual assessment will return shortly."""if priority == "spiritual":# Spiritual takes precedence (Requirement 2.4)return f"""{spiritual_msg}