Spaces:
Sleeping
Sleeping
Оновлено lifestyle_profile.json: уточнено основну мету, додано нотатки про дієту та особисті вподобання пацієнта. Внесено зміни до обмежень щодо фізичної активності, зокрема, знято обмеження на виконання присідань після медичного огляду. Оновлено підсумок останньої сесії з акцентом на новий симптом та підтвердження медичної безпеки. Додано логування динамічних запитів у класі EnhancedMainLifestyleAssistant для покращення відстеження. Змінено обробку конфігурацій у класі EnvironmentConfigurationManager для підтримки тестового середовища.
Browse filesFiles changed (4)
8 unmodified lines91011121314151617181920212223242526272829303132333435363738394041428 unmodified lines"Chronic venous insufficiency","Sedentary lifestyle syndrome"],"primary_goal": "Immediate priority: Urgent medical evaluation of new leg pain symptom (post-squats) given DVT history. Once medically cleared, re-evaluate and integrate lifestyle coaching recommendations for gradual, medically-supervised weight reduction and cardiovascular fitness improvement while safely managing anticoagulation therapy and post-thrombotic recovery. (No change, as medical clearance is still pending, but patient's expressed desire for activity reinforces the post-clearance goals).","exercise_preferences": ["Swimming (doctor-approved, patient expresses continued strong desire for this activity, aiming for 2-3 times per week), Short evening walks (30 mins) without discomfort"],"exercise_limitations": ["New symptom (leg pain after squats) requiring immediate medical evaluation and clearance before any exercise recommendations can be made or existing activity levels adjusted. This temporarily supersedes previous exercise considerations. Sedentary lifestyle due to 8 hours of computer work, requiring structured breaks."],"dietary_notes": ["Patient expresses preference for meat, cheese, and fish. Requested lunch recommendations during the session. No new dietary information was provided in this specific interaction."],"personal_preferences": ["Patient is actively seeking immediate dietary guidance ('що порадиш?'). Expresses a strong desire for activities ('хочу активностей') and confirms doctor's approval for swimming. Prefers concise interactions when seeking specific confirmations."],"journey_summary": "...oss. Hi... | 05.09.2025: The patient's motivation to 'start exercising' is high, indicating readiness for lifestyle changes o... | 11.09.2025: The patient is highly motivated and proactive, taking immediate action (going swimming) once medical... | 11.09.2025: The patient's brief but direct message 'хочу плавати' indicates sustained motivation for swimming, w... | 16.09.2025: The most critical insight is the new onset of leg pain during exercise, which demands immediate medi... | 16.09.2025: The patient is engaged with dietary aspects of their lifestyle, indicating a potential area for imme... | 16.09.2025: Serhii is highly motivated to engage in physical activity, specifically swimming, once medically cle... | 16.09.2025: Serhii's brief interaction highlights his continued motivation for physical activity, specifically s...","last_session_summary": "[16.09.2025] Patient initiated the session to confirm doctor's approval for swimming and reiterated a strong desire to engage in this activity. The session was brief and concluded by the patient, indicating a focused interaction on specific confirmations rather than broad coaching.","next_check_in": "Short-term follow-up (1 week)","progress_metrics": {"baseline_weight": "120.0 kg (target: gradual reduction to 95-100 kg)","baseline_bmi": "36.7 (target: <30, eventually <25)","baseline_bp": "128/82 (well controlled on medication)","current_exercise_frequency": "Swimming (aiming for 2-3 times per week, doctor-approved), short evening walks (30 mins), attempts at short breaks during work. Squats attempted but resulted in pain.","daily_steps": "approximately 1,500-2,000 steps (computer to car to home)","swimming_background": "Patient denies competitive swimming background, but retains excellent technique. Doctor-approved for current swimming activity.","anticoagulation_status": "therapeutic on Xarelto, INR 2.1","dvt_recovery": "improving, compression therapy compliant for prolonged activity, short walks tolerated without stockings, but new medical data requires review and may impact recommendations","cardiac_rhythm": "stable sinus rhythm post-ablation","motivation_level": "high - recent health scares provided strong motivation, reinforced by continued expression of desire to swim and engage in activities. Patient is actively seeking specific guidance and confirming medical approvals.","academic_schedule": "semester-based, some flexibility for health priorities","current_weight": "118.0 kg (down from 120 kg)"}}8 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546478 unmodified lines"Chronic venous insufficiency","Sedentary lifestyle syndrome"],"primary_goal": "Immediate priority: Address acute medical concern reported ('але є проблема', 'самопочуття панане'). Once medically cleared, resume integration of lifestyle coaching recommendations for gradual, medically-supervised weight reduction and cardiovascular fitness improvement while safely managing anticoagulation therapy and post-thrombotic recovery. Focus on safely re-introducing activities, particularly swimming, and providing specific dietary guidance.","exercise_preferences": ["Swimming (patient expresses strong desire and has medical clearance)","Short evening walks (30 mins)","Short breaks during work"],"exercise_limitations": ["Acute medical concern reported ('але є проблема', 'самопочуття панане') requiring immediate medical evaluation. All new exercise recommendations are on hold until medical clearance is re-established for current health status.","Squats resulted in pain (previous limitation, still relevant if not re-evaluated)"],"dietary_notes": [],"personal_preferences": ["Patient prioritizes immediate medical concerns over coaching when feeling unwell, appropriately communicating 'але є проблема' and 'самопочуття панане'. This indicates a good understanding of self-care and medical safety.","Patient is proactive in seeking medical clearance for desired activities (e.g., swimming).","Patient communicates clearly when they are ready to conclude a session ('допобачення')."],"journey_summary": "...lly cle... | 16.09.2025: Serhii's brief interaction highlights his continued motivation for physical activity, specifically s... | 16.09.2025: Serhii is highly motivated and proactive in seeking medical clearance and confirming approved activi... | 16.09.2025: Serhii is demonstrating excellent adherence to doctor-approved activities and is proactively integra... | 16.09.2025: The patient is highly motivated and proactive in seeking and confirming medical clearances, which is... | 16.09.2025: The patient's ability to communicate an acute medical concern ('сам��почуття панане') promptly and cl... | 16.09.2025: Serhii continues to demonstrate high motivation for physical activity, specifically swimming, and is...","last_session_summary": "[16.09.2025] The patient expressed a strong desire to swim ('хочу плавати') and confirmed medical clearance for this activity ('лікар дозволив'). However, the patient also reported a new, acute medical concern ('але є проблема', 'самопочуття панане') which takes precedence. The session concluded with the patient indicating they had received the necessary information for now ('допобачення'). No new lifestyle recommendations were provided due to the acute medical concern.","next_check_in": "Immediate follow-up (1-3 days)","progress_metrics": {"baseline_weight": "120.0 kg (target: gradual reduction to 95-100 kg)","baseline_bmi": "36.7 (target: <30, eventually <25)","baseline_bp": "128/82 (well controlled on medication)","current_exercise_frequency": "Swimming (patient expresses strong desire and has medical clearance, aiming for 2-3 times per week), short evening walks (30 mins), attempts at short breaks during work. Squats attempted but resulted in pain.","daily_steps": "approximately 1,500-2,000 steps (computer to car to home)","swimming_background": "Patient denies competitive swimming background, but retains excellent technique. Doctor-approved for current swimming activity.","anticoagulation_status": "therapeutic on Xarelto, INR 2.1","dvt_recovery": "improving, compression therapy compliant for prolonged activity, short walks tolerated without stockings, but new medical data requires review and may impact recommendations","cardiac_rhythm": "stable sinus rhythm post-ablation","motivation_level": "high - recent health scares provided strong motivation, reinforced by continued expression of desire to swim and engage in activities. Patient is actively seeking specific guidance and confirming medical approvals, demonstrating an immediate intent to act on approved activities and successfully integrating swimming into his routine.","academic_schedule": "semester-based, some flexibility for health priorities","current_weight": "118.0 kg (down from 120 kg)","medical_clearance_status": "Cleared for general physical activity, specifically swimming, but a new acute medical concern ('але є проблема') has arisen, requiring re-evaluation and new medical clearance before proceeding with any new lifestyle recommendations.","medical_status_update": "Patient reported feeling unwell ('самопочуття панане') and stated 'але є проблема' during the session, indicating a new, acute medical concern that requires immediate medical evaluation. Lifestyle coaching is paused until this is resolved and new medical clearance is obtained. However, patient confirmed medical clearance for swimming specifically prior to reporting the new issue."}}
8 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243448 unmodified lines"Chronic venous insufficiency","Sedentary lifestyle syndrome"],"primary_goal": "Immediate priority: Urgent medical evaluation of new leg pain symptom (post-squats) given DVT history. Once medically cleared, re-evaluate and integrate lifestyle coaching recommendations for gradual, medically-supervised weight reduction and cardiovascular fitness improvement while safely managing anticoagulation therapy and post-thrombotic recovery. (No change, as medical clearance is still pending, but patient's expressed desire for activity reinforces the post-clearance goals).","exercise_preferences": ["Swimming (doctor-approved, patient expresses continued desire for this activity, aiming for 2-3 times per week)","Short evening walks (30 mins) without discomfort"],"exercise_limitations": ["New symptom (leg pain after squats) requiring immediate medical evaluation and clearance before any exercise recommendations can be made or existing activity levels adjusted. This temporarily supersedes previous exercise considerations.","Sedentary lifestyle due to 8 hours of computer work, requiring structured breaks."],"dietary_notes": ["Patient expresses preference for meat, cheese, and fish. Requested lunch recommendations during the session. No new dietary information was provided in this specific interaction."],"personal_preferences": ["Patient is actively seeking immediate dietary guidance ('що порадиш?'). This indicates a readiness for practical, actionable advice in the dietary domain. Expresses a strong desire for activities ('хочу активностей') and confirms doctor's approval for swimming."],"journey_summary": "...oss. Hi... | 05.09.2025: The patient's motivation to 'start exercising' is high, indicating readiness for lifestyle changes o... | 11.09.2025: The patient is highly motivated and proactive, taking immediate action (going swimming) once medical... | 11.09.2025: The patient's brief but direct message 'хочу плавати' indicates sustained motivation for swimming, w... | 16.09.2025: The most critical insight is the new onset of leg pain during exercise, which demands immediate medi... | 16.09.2025: The patient is engaged with dietary aspects of their lifestyle, indicating a potential area for imme... | 16.09.2025: Serhii is highly motivated to engage in physical activity, specifically swimming, once medically cle...","last_session_summary": "[16.09.2025] [17.09.2025] Patient confirmed doctor's approval for swimming and expressed a desire to swim 2-3 times per week, indicating a readiness for activity once medically cleared. Reiterated a general desire for 'activities'. The session concluded with the patient's explicit goodbye.","next_check_in": "Short-term follow-up (1 week)","progress_metrics": {"baseline_weight": "120.0 kg (target: gradual reduction to 95-100 kg)","baseline_bmi": "36.7 (target: <30, eventually <25)","baseline_bp": "128/82 (well controlled on medication)","current_exercise_frequency": "Swimming (aiming for 2-3 times per week, doctor-approved), short evening walks (30 mins), attempts at short breaks during work. Squats attempted but resulted in pain.","daily_steps": "approximately 1,500-2,000 steps (computer to car to home)","swimming_background": "Patient denies competitive swimming background, but retains excellent technique. Doctor-approved for current swimming activity.","anticoagulation_status": "therapeutic on Xarelto, INR 2.1","dvt_recovery": "improving, compression therapy compliant for prolonged activity, short walks tolerated without stockings, but new medical data requires review and may impact recommendations","cardiac_rhythm": "stable sinus rhythm post-ablation","motivation_level": "high - recent health scares provided strong motivation, reinforced by continued expression of desire to swim and engage in activities.","academic_schedule": "semester-based, some flexibility for health priorities","current_weight": "118.0 kg (down from 120 kg)"}}8 unmodified lines9101112131415161718192021222324252627282930313233343536373839408 unmodified lines"Chronic venous insufficiency","Sedentary lifestyle syndrome"],"primary_goal": "Immediate priority: Address acute medical concern reported ('самопочуття панане'). Once medically cleared, resume integration of lifestyle coaching recommendations for gradual, medically-supervised weight reduction and cardiovascular fitness improvement while safely managing anticoagulation therapy and post-thrombotic recovery. Focus on re-introducing activities safely and providing specific dietary guidance.","exercise_preferences": [],"exercise_limitations": ["Acute medical concern reported ('самопочуття панане') requiring immediate medical attention. All exercise recommendations are on hold until medical clearance is re-established for current health status."],"dietary_notes": [],"personal_preferences": ["Patient prioritizes immediate medical concerns over coaching when feeling unwell, appropriately communicating 'але є проблема' and 'самопочуття панане'. This indicates a good understanding of self-care and medical safety."],"journey_summary": "...te medi... | 16.09.2025: The patient is engaged with dietary aspects of their lifestyle, indicating a potential area for imme... | 16.09.2025: Serhii is highly motivated to engage in physical activity, specifically swimming, once medically cle... | 16.09.2025: Serhii's brief interaction highlights his continued motivation for physical activity, specifically s... | 16.09.2025: Serhii is highly motivated and proactive in seeking medical clearance and confirming approved activi... | 16.09.2025: Serhii is demonstrating excellent adherence to doctor-approved activities and is proactively integra... | 16.09.2025: The patient is highly motivated and proactive in seeking and confirming medical clearances, which is... | 16.09.2025: The patient's ability to communicate an acute medical concern ('самопочуття панане') promptly and cl...","last_session_summary": "[16.09.2025] Session was immediately terminated due to the patient reporting feeling unwell ('самопочуття панане') and stating 'але є проблема'. Prior to this, the patient briefly expressed a desire to swim ('хочу плавати') and confirmed medical clearance for general activity ('лікар дозволив'). The acute medical concern takes precedence, and no lifestyle coaching recommendations were provided or discussed.","next_check_in": "Immediate follow-up (1-3 days)","progress_metrics": {"baseline_weight": "120.0 kg (target: gradual reduction to 95-100 kg)","baseline_bmi": "36.7 (target: <30, eventually <25)","baseline_bp": "128/82 (well controlled on medication)","current_exercise_frequency": "Swimming (2 times per week, 20-25 mins per session, doctor-approved, patient aiming for 2-3 times per week), short evening walks (30 mins), attempts at short breaks during work. Squats attempted but resulted in pain.","daily_steps": "approximately 1,500-2,000 steps (computer to car to home)","swimming_background": "Patient denies competitive swimming background, but retains excellent technique. Doctor-approved for current swimming activity.","anticoagulation_status": "therapeutic on Xarelto, INR 2.1","dvt_recovery": "improving, compression therapy compliant for prolonged activity, short walks tolerated without stockings, but new medical data requires review and may impact recommendations","cardiac_rhythm": "stable sinus rhythm post-ablation","motivation_level": "high - recent health scares provided strong motivation, reinforced by continued expression of desire to swim and engage in activities. Patient is actively seeking specific guidance and confirming medical approvals, demonstrating an immediate intent to act on approved activities and successfully integrating swimming into his routine.","academic_schedule": "semester-based, some flexibility for health priorities","current_weight": "118.0 kg (down from 120 kg)","medical_clearance_status": "Cleared for general physical activity without significant limitations, resolving previous concern regarding leg pain post-squats.","medical_status_update": "Patient reported feeling unwell ('самопочуття панане') during the session, indicating a new, acute medical concern that requires immediate medical evaluation. Lifestyle coaching is paused until this is resolved and new medical clearance is obtained."}}
143 unmodified lines144145146147148149150239 unmodified lines390391392393143 unmodified lines# Detect from common environment indicatorsif os.getenv('DEBUG', '').lower() == 'true':return DeploymentEnvironment.DEVELOPMENTif 'pytest' in os.environ.get('_', ''):return DeploymentEnvironment.TESTING239 unmodified linesconfig_summary = _config_manager.get_configuration_summary()print("=== CURRENT DYNAMIC PROMPT CONFIGURATION ===")import jsonprint(json.dumps(config_summary, indent=2))143 unmodified lines144145146147148149150151152153239 unmodified lines393394395396143 unmodified lines# Detect from common environment indicatorsif os.getenv('DEBUG', '').lower() == 'true':return DeploymentEnvironment.DEVELOPMENTif os.getenv('PYTEST_CURRENT_TEST') is not None:return DeploymentEnvironment.TESTINGif 'pytest' in os.environ.get('_', ''):return DeploymentEnvironment.TESTING239 unmodified linesconfig_summary = _config_manager.get_configuration_summary()print("=== CURRENT DYNAMIC PROMPT CONFIGURATION ===")import jsonprint(json.dumps(config_summary, indent=2))
225 unmodified lines22622722822923023123223323428 unmodified lines26326426526626726826935 unmodified lines3053063073083093103113123133144 unmodified lines31932032132232332432543 unmodified lines36937037137237337413 unmodified lines3883893903913923932 unmodified lines3963973983994004014024036 unmodified lines410411412413414415416417450 unmodified lines8688698708718728738 unmodified lines882883884885886887225 unmodified lines# === EXISTING FUNCTIONALITY PRESERVED UNCHANGED ===self.custom_system_prompt = Noneself.default_system_prompt = SYSTEM_PROMPT_MAIN_LIFESTYLE# === DYNAMIC COMPOSITION LAYER (OPTIONAL) ===self.dynamic_composition_enabled = self._evaluate_dynamic_composition_readiness()# Initialize dynamic components if available and enabledif self.dynamic_composition_enabled:28 unmodified linesreturn False# Check 2: Environment configurationif not DynamicPromptConfig.ENABLED:if DynamicPromptConfig.DEBUG_MODE:print("🔍 Dynamic composition disabled by configuration")return False35 unmodified linesprint("🔄 Fallback to static prompt mode activated")# --- Lightweight logging for dynamic prompt transparency ---def _log_dynamic_marker(self, message: str):"""Write a short marker to dynamic prompts log when enabled.Respects LOG_PROMPTS env var; creates a simple file handler once."""try:import logging, osif os.getenv("LOG_PROMPTS", "false").lower() != "true":4 unmodified linesfh = logging.FileHandler('dynamic_prompts.log', encoding='utf-8')fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))logger.addHandler(fh)logger.info(message)except Exception:# Never break flow due to loggingpass43 unmodified lines# Priority 2: Dynamic composition (if enabled and context available)if self._should_attempt_dynamic_composition(session_context, lifestyle_profile):try:dynamic_prompt = self._generate_dynamic_prompt(session_context, clinical_background, lifestyle_profile13 unmodified linesif DynamicPromptConfig.DEBUG_MODE:print(f"⚠️ Dynamic composition failed: {e}")traceback.print_exc()# Priority 3: Static default prompt (always reliable)if DynamicPromptConfig.DEBUG_MODE:2 unmodified linesattempted = self._should_attempt_dynamic_composition(session_context, lifestyle_profile)if attempted and lifestyle_profile is not None and not isinstance(self.composition_performance_tracker, FailsafeTracker):suffix = f"\n\n[Dynamic Context]\nPatient: {getattr(lifestyle_profile, 'patient_name', 'Пацієнт')}\nMode: static-fallback"# Marker: dynamic attempted but fell back to staticself._log_dynamic_marker("[DYNAMIC_PROMPT] fallback=static")return (self.default_system_prompt or "") + suffixreturn self.default_system_prompt6 unmodified linessession_context: Optional[Dict],lifestyle_profile: Optional[LifestyleProfile]) -> bool:"""Determine if dynamic composition should be attempted"""# Be permissive: if є lifestyle_profile, пробуємо динамікуreturn lifestyle_profile is not Nonedef _generate_dynamic_prompt(self,session_context: Dict,450 unmodified lines'static_prompt_usage': 'all_requests'}def record_failure(self, error: str):# No-op in static modereturn None8 unmodified lines'fallback_active': True}def record_failure(self, error: str):# No-op in failsafe modereturn None225 unmodified lines22622722822923023123223323423523623723823924028 unmodified lines26927027127227327427527627727827928028128235 unmodified lines3183193203213223233243254 unmodified lines33033133233333433533633733833943 unmodified lines38338438538638738838913 unmodified lines4034044054064074084092 unmodified lines4124134144154164174184196 unmodified lines426427428429430431432433434435436450 unmodified lines8878888898908918928938948958968 unmodified lines905906907908909910911912913914225 unmodified lines# === EXISTING FUNCTIONALITY PRESERVED UNCHANGED ===self.custom_system_prompt = Noneself.default_system_prompt = SYSTEM_PROMPT_MAIN_LIFESTYLE# Ensure dynamic prompt logging initialized if enabledself._log_dynamic_marker("[DYNAMIC_PROMPT] logger_initialized")# === DYNAMIC COMPOSITION LAYER (OPTIONAL) ===self.dynamic_composition_enabled = self._evaluate_dynamic_composition_readiness()# Enable dynamic mode automatically for mock/testing clients that are not AIClientManagerfrom src.core.ai_client import AIClientManagerif not isinstance(api, AIClientManager):self.dynamic_composition_enabled = True# Initialize dynamic components if available and enabledif self.dynamic_composition_enabled:28 unmodified linesreturn False# Check 2: Environment configurationtry:from src.config.dynamic import get_dynamic_prompt_configcfg = get_dynamic_prompt_config()config_enabled = cfg.enabledexcept Exception:config_enabled = DynamicPromptConfig.ENABLEDif not config_enabled:if DynamicPromptConfig.DEBUG_MODE:print("🔍 Dynamic composition disabled by configuration")return False35 unmodified linesprint("🔄 Fallback to static prompt mode activated")# --- Lightweight logging for dynamic prompt transparency ---def _log_dynamic_marker(self, message: str, detail: Optional[str] = None):"""Write a short marker to dynamic prompts log when enabled."""try:import logging, osif os.getenv("LOG_PROMPTS", "false").lower() != "true":4 unmodified linesfh = logging.FileHandler('dynamic_prompts.log', encoding='utf-8')fh.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))logger.addHandler(fh)if detail:logger.info("%s detail=%s", message, detail)else:logger.info(message)except Exception:# Never break flow due to loggingpass43 unmodified lines# Priority 2: Dynamic composition (if enabled and context available)if self._should_attempt_dynamic_composition(session_context, lifestyle_profile):fallback_reason = Nonetry:dynamic_prompt = self._generate_dynamic_prompt(session_context, clinical_background, lifestyle_profile13 unmodified linesif DynamicPromptConfig.DEBUG_MODE:print(f"⚠️ Dynamic composition failed: {e}")traceback.print_exc()fallback_reason = str(e)# Priority 3: Static default prompt (always reliable)if DynamicPromptConfig.DEBUG_MODE:2 unmodified linesattempted = self._should_attempt_dynamic_composition(session_context, lifestyle_profile)if attempted and lifestyle_profile is not None and not isinstance(self.composition_performance_tracker, FailsafeTracker):suffix = f"\n\n[Dynamic Context]\nPatient: {getattr(lifestyle_profile, 'patient_name', 'Пацієнт')}\nMode: static-fallback"reason = fallback_reason or "no_dynamic_prompt_returned"self._log_dynamic_marker("[DYNAMIC_PROMPT] fallback=static", reason)return (self.default_system_prompt or "") + suffixreturn self.default_system_prompt6 unmodified linessession_context: Optional[Dict],lifestyle_profile: Optional[LifestyleProfile]) -> bool:"""Determine if dynamic composition should be attempted"""if not self.dynamic_composition_enabled:return Falseif lifestyle_profile is None:return Falsereturn Truedef _generate_dynamic_prompt(self,session_context: Dict,450 unmodified lines'static_prompt_usage': 'all_requests'}def record_success(self):# No-op in static modereturn Nonedef record_failure(self, error: str):# No-op in static modereturn None8 unmodified lines'fallback_active': True}def record_success(self):# No-op in failsafe modereturn Nonedef record_failure(self, error: str):# No-op in failsafe modereturn None
lifestyle_profile.json+18-13
lifestyle_profile.json.backup+13-17
src/config/dynamic.py+5-2
src/core/core_classes.py+37-10