Spaces:
Sleeping
Sleeping
Оновлено lifestyle_profile.json: уточнено основну мету, додано нотатки про дієту та особисті вподобання пацієнта. Оновлено підсумок останньої сесії з акцентом на новий симптом болю в нозі. Внесено зміни до формату виходу в prompts.py для покращення обробки даних. У класі MedicalSafetyValidator реалізовано кешування звітів про безпеку для підвищення ефективності перевірок.
Browse filesFiles changed (4)
8 unmodified lines91011121314151617181920212223242526272829303132333435363738398 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).","exercise_preferences": ["Swimming (doctor-approved, patient expresses continued desire for this activity)","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.","personal_preferences": "Patient is actively seeking immediate dietary guidance ('що порадиш?'). This indicates a readiness for practical, actionable advice in the dietary domain.","journey_summary": "...c history. | 05.09.2025: Serhii is highly motivated and has already initiated positive lifestyle changes (weight loss, swimmi... | 05.09.2025: Serhii is motivated and compliant with his current exercise regimen, showing initial weight loss. 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...","last_session_summary": "[16.09.2025] Patient inquired about lunch recommendations and expressed preferences for meat, cheese, and fish. No update on the medical evaluation of the leg pain from the previous session was provided, maintaining the critical safety concern as the immediate priority.","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 (unspecified frequency, 'позавчора' - the day before yesterday), 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.","academic_schedule": "semester-based, some flexibility for health priorities","current_weight": "118.0 kg (down from 120 kg)"}8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142438 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 lines91011121314152 unmodified lines181920212223242526278 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.","exercise_preferences": ["Swimming (doctor-approved, patient expresses continued desire for this activity)","Short evening walks (30 mins) without discomfort"2 unmodified lines"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": [],"personal_preferences": [],"journey_summary": "...c history. | 05.09.2025: Serhii is highly motivated and has already initiated positive lifestyle changes (weight loss, swimmi... | 05.09.2025: Serhii is motivated and compliant with his current exercise regimen, showing initial weight loss. 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...","last_session_summary": "[16.09.2025] Patient reported new leg pain after attempting squats, which is a serious medical concern given his DVT history. The session was automatically ended to prioritize immediate medical attention for this symptom. Prior to this, the patient mentioned swimming recently and taking short breaks during 8 hours of computer work.","next_check_in": "Immediate follow-up (1-3 days)","progress_metrics": {"baseline_weight": "120.0 kg (target: gradual reduction to 95-100 kg)",8 unmodified lines91011121314152 unmodified lines181920212223242526278 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).","exercise_preferences": ["Swimming (doctor-approved, patient expresses continued desire for this activity)","Short evening walks (30 mins) without discomfort"2 unmodified lines"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.","personal_preferences": "Patient is actively seeking immediate dietary guidance ('що порадиш?'). This indicates a readiness for practical, actionable advice in the dietary domain.","journey_summary": "...c history. | 05.09.2025: Serhii is highly motivated and has already initiated positive lifestyle changes (weight loss, swimmi... | 05.09.2025: Serhii is motivated and compliant with his current exercise regimen, showing initial weight loss. 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...","last_session_summary": "[16.09.2025] Patient inquired about lunch recommendations and expressed preferences for meat, cheese, and fish. No update on the medical evaluation of the leg pain from the previous session was provided, maintaining the critical safety concern as the immediate priority.","next_check_in": "Immediate follow-up (1-3 days)","progress_metrics": {"baseline_weight": "120.0 kg (target: gradual reduction to 95-100 kg)",
1352 unmodified lines13531354135513561357135813591360136113621363136413651366136713688 unmodified lines137713781379138013811382138313841385138613871388138913901391139234 unmodified lines1427142814291430143114321433143414351436143714381439144014411352 unmodified linesdef _apply_llm_updates(self, original_profile: LifestyleProfile, analysis: Dict) -> LifestyleProfile:"""Apply LLM analysis results to create updated profile"""# Create copy of original profileupdated_profile = LifestyleProfile(patient_name=original_profile.patient_name,patient_age=original_profile.patient_age,conditions=original_profile.conditions.copy(),primary_goal=original_profile.primary_goal,exercise_preferences=original_profile.exercise_preferences.copy(),exercise_limitations=original_profile.exercise_limitations.copy(),dietary_notes=original_profile.dietary_notes.copy(),personal_preferences=original_profile.personal_preferences.copy(),journey_summary=original_profile.journey_summary,last_session_summary=original_profile.last_session_summary,next_check_in=original_profile.next_check_in,8 unmodified linesupdated_fields = analysis.get("updated_fields", {})if "exercise_preferences" in updated_fields:updated_profile.exercise_preferences = updated_fields["exercise_preferences"]if "exercise_limitations" in updated_fields:updated_profile.exercise_limitations = updated_fields["exercise_limitations"]if "dietary_notes" in updated_fields:updated_profile.dietary_notes = updated_fields["dietary_notes"]if "personal_preferences" in updated_fields:updated_profile.personal_preferences = updated_fields["personal_preferences"]if "primary_goal" in updated_fields:updated_profile.primary_goal = updated_fields["primary_goal"]34 unmodified linessession_context: str) -> LifestyleProfile:"""Fallback simple profile update without LLM"""updated_profile = LifestyleProfile(patient_name=lifestyle_profile.patient_name,patient_age=lifestyle_profile.patient_age,conditions=lifestyle_profile.conditions.copy(),primary_goal=lifestyle_profile.primary_goal,exercise_preferences=lifestyle_profile.exercise_preferences.copy(),exercise_limitations=lifestyle_profile.exercise_limitations.copy(),dietary_notes=lifestyle_profile.dietary_notes.copy(),personal_preferences=lifestyle_profile.personal_preferences.copy(),journey_summary=lifestyle_profile.journey_summary,last_session_summary=lifestyle_profile.last_session_summary,next_check_in=lifestyle_profile.next_check_in,1352 unmodified lines13531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113928 unmodified lines140114021403140414051406140714081409141014111412141314141415141634 unmodified lines1451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771352 unmodified linesdef _apply_llm_updates(self, original_profile: LifestyleProfile, analysis: Dict) -> LifestyleProfile:"""Apply LLM analysis results to create updated profile"""def _clone_list(value):if isinstance(value, list):return value.copy()if value is None or value == "":return []if isinstance(value, str):return [value]try:return list(value)except TypeError:return [value]def _normalize_list(value):if value is None or value == "":return []if isinstance(value, list):return valueif isinstance(value, str):return [value]try:return list(value)except TypeError:return [value]# Create copy of original profileupdated_profile = LifestyleProfile(patient_name=original_profile.patient_name,patient_age=original_profile.patient_age,conditions=_clone_list(original_profile.conditions),primary_goal=original_profile.primary_goal,exercise_preferences=_clone_list(original_profile.exercise_preferences),exercise_limitations=_clone_list(original_profile.exercise_limitations),dietary_notes=_clone_list(original_profile.dietary_notes),personal_preferences=_clone_list(original_profile.personal_preferences),journey_summary=original_profile.journey_summary,last_session_summary=original_profile.last_session_summary,next_check_in=original_profile.next_check_in,8 unmodified linesupdated_fields = analysis.get("updated_fields", {})if "exercise_preferences" in updated_fields:updated_profile.exercise_preferences = _normalize_list(updated_fields["exercise_preferences"])if "exercise_limitations" in updated_fields:updated_profile.exercise_limitations = _normalize_list(updated_fields["exercise_limitations"])if "dietary_notes" in updated_fields:updated_profile.dietary_notes = _normalize_list(updated_fields["dietary_notes"])if "personal_preferences" in updated_fields:updated_profile.personal_preferences = _normalize_list(updated_fields["personal_preferences"])if "primary_goal" in updated_fields:updated_profile.primary_goal = updated_fields["primary_goal"]34 unmodified linessession_context: str) -> LifestyleProfile:"""Fallback simple profile update without LLM"""def _clone_list(value):if isinstance(value, list):return value.copy()if value is None or value == "":return []if isinstance(value, str):return [value]try:return list(value)except TypeError:return [value]updated_profile = LifestyleProfile(patient_name=lifestyle_profile.patient_name,patient_age=lifestyle_profile.patient_age,conditions=_clone_list(lifestyle_profile.conditions),primary_goal=lifestyle_profile.primary_goal,exercise_preferences=_clone_list(lifestyle_profile.exercise_preferences),exercise_limitations=_clone_list(lifestyle_profile.exercise_limitations),dietary_notes=_clone_list(lifestyle_profile.dietary_notes),personal_preferences=_clone_list(lifestyle_profile.personal_preferences),journey_summary=lifestyle_profile.journey_summary,last_session_summary=lifestyle_profile.last_session_summary,next_check_in=lifestyle_profile.next_check_in,
14 unmodified lines1516171819205 unmodified lines262728293031323310 unmodified lines44454647484950515253545556575853 unmodified lines11211311411511611711823 unmodified lines14214314414514614714830 unmodified lines179180181182183184185198 unmodified lines38438538638738838914 unmodified linesimport timeimport reimport jsonfrom src.prompts.types import (PromptComponent, PromptCompositionSpec, AssemblyResult, SafetyLevel,5 unmodified linesclass MedicalSafetyValidator:"""LLM-driven safety validator that replaces rigid keyword checks."""def __init__(self, api_client: Optional[AIClientManager] = None):self.api_client = api_client@dataclassclass _SafetyReport:10 unmodified lines) -> Tuple[bool, List[str], List[str]]:"""Use LLM safety reviewer when available, otherwise fallback to heuristic check."""if self.api_client is None:return self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)try:report = self._run_llm_review(prompt, components_used, clinical_background, classification_spec)return report.is_safe, report.violations, report.warningsexcept Exception as exc:print(f"⚠️ LLM safety review failed: {exc} — using heuristic fallback")return self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)def _run_llm_review(self,53 unmodified linescomponents_used: List[str],clinical_background: Optional[Dict[str, Any]] = None,classification_spec: Optional[PromptCompositionSpec] = None,) -> Tuple[bool, List[str], List[str]]:safety_violations: List[str] = []safety_warnings: List[str] = []prompt_lower = prompt.lower()23 unmodified linescond.lower() for cond in (clinical_background or {}).get('active_problems', [])]for condition, requirements in condition_requirements.items():if any(condition in ac for ac in active_conditions):missing = [req for req in requirements if req not in prompt_lower]if missing:safety_violations.extend([30 unmodified linesf"Critical alerts present but safety level is {classification_spec.safety_level.value}")return (len(safety_violations) == 0, safety_violations, safety_warnings)class PromptTemplateEngine:"""198 unmodified lines)if not is_safe:self.assembly_metrics['safety_validations_failed'] += 1# Attempt safety correctioncorrected_result = self._attempt_safety_correction(14 unmodified lines15161718192021225 unmodified lines2829303132333435363710 unmodified lines484950515253545556575859606162636465666768697071727374757677787980818253 unmodified lines13613713813914014114223 unmodified lines16616716816917017117217317417517617717830 unmodified lines209210211212213214215216217218219220221222223224225226227228229230231232233234235236237198 unmodified lines43643743843944044144214 unmodified linesimport timeimport reimport jsonimport hashlibfrom collections import OrderedDictfrom src.prompts.types import (PromptComponent, PromptCompositionSpec, AssemblyResult, SafetyLevel,5 unmodified linesclass MedicalSafetyValidator:"""LLM-driven safety validator that replaces rigid keyword checks."""def __init__(self, api_client: Optional[AIClientManager] = None, max_cache_entries: int = 32):self.api_client = api_clientself._cache: "OrderedDict[str, MedicalSafetyValidator._SafetyReport]" = OrderedDict()self._max_cache_entries = max_cache_entries@dataclassclass _SafetyReport:10 unmodified lines) -> Tuple[bool, List[str], List[str]]:"""Use LLM safety reviewer when available, otherwise fallback to heuristic check."""report = self._get_safety_report(prompt, components_used, clinical_background, classification_spec)return report.is_safe, report.violations, report.warningsdef _get_safety_report(self,prompt: str,components_used: List[str],clinical_background: Dict[str, Any],classification_spec: PromptCompositionSpec,) -> _SafetyReport:cache_key = self._build_cache_key(prompt, components_used, clinical_background, classification_spec)cached = self._cache.get(cache_key)if cached:self._cache.move_to_end(cache_key)return cachedif self.api_client is not None:try:report = self._run_llm_review(prompt, components_used, clinical_background, classification_spec)except Exception as exc:print(f"⚠️ LLM safety review failed: {exc} — using heuristic fallback")report = self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)else:report = self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)self._cache[cache_key] = reportif len(self._cache) > self._max_cache_entries:self._cache.popitem(last=False)return reportdef _run_llm_review(self,53 unmodified linescomponents_used: List[str],clinical_background: Optional[Dict[str, Any]] = None,classification_spec: Optional[PromptCompositionSpec] = None,) -> _SafetyReport:safety_violations: List[str] = []safety_warnings: List[str] = []prompt_lower = prompt.lower()23 unmodified linescond.lower() for cond in (clinical_background or {}).get('active_problems', [])]for condition, requirements in condition_requirements.items():condition_component = f"{condition}_management"if any(condition in ac for ac in active_conditions):if condition_component not in components_used and (not classification_spec or condition not in (classification_spec.medical_emphasis or [])):# Skip strict enforcement if condition-specific component wasn't part of assembly intentcontinuemissing = [req for req in requirements if req not in prompt_lower]if missing:safety_violations.extend([30 unmodified linesf"Critical alerts present but safety level is {classification_spec.safety_level.value}")return self._SafetyReport(is_safe=len(safety_violations) == 0,violations=safety_violations,warnings=safety_warnings,)def _build_cache_key(self,prompt: str,components_used: List[str],clinical_background: Dict[str, Any],classification_spec: PromptCompositionSpec,) -> str:payload = {"prompt_hash": hashlib.sha256(prompt.encode('utf-8')).hexdigest(),"components": sorted(components_used),"critical_alerts": sorted(clinical_background.get('critical_alerts', [])),"active_problems": sorted(clinical_background.get('active_problems', [])),"safety_level": classification_spec.safety_level.value if classification_spec else None,"session_focus": classification_spec.session_focus if classification_spec else None,"medical_emphasis": sorted(classification_spec.medical_emphasis or []) if classification_spec else [],}return json.dumps(payload, sort_keys=True)class PromptTemplateEngine:"""198 unmodified lines)if not is_safe:print(f"⚠️ Dynamic safety check failed. Components: {components_used}. Violations: {violations}")self.assembly_metrics['safety_validations_failed'] += 1# Attempt safety correctioncorrected_result = self._attempt_safety_correction(
lifestyle_profile.json+13-9
lifestyle_profile.json.backup+5-5
src/core/core_classes.py+50-14
src/prompts/assembler.py+64-11