Spaces:
Sleeping
Sleeping
Оновлено lifestyle_profile.json: об'єднано нотатки про вподобання та обмеження в одне поле, уточнено підсумок останньої сесії з акцентом на бажання пацієнта займатися плаванням. Додано логування в класі MedicalSafetyValidator для покращення відстеження безпеки динамічних запитів.
Browse filesFiles changed (3)
10 unmodified lines1112131415161718192021222324252627282930315 unmodified lines3738394041424310 unmodified lines],"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)",5 unmodified lines"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)"}10 unmodified lines111213141516171819202122232425262728295 unmodified lines3536373839404110 unmodified lines],"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)",5 unmodified lines"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 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)"}
16 unmodified lines1718192021229 unmodified lines32333435363710 unmodified lines4849505152538 unmodified lines6263646566672 unmodified lines7071727374757677329 unmodified lines40740840941041141223 unmodified lines4364374384394404419 unmodified lines45145245345445545616 unmodified linesimport jsonimport hashlibfrom collections import OrderedDictfrom src.prompts.types import (PromptComponent, PromptCompositionSpec, AssemblyResult, SafetyLevel,9 unmodified linesself.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.warnings8 unmodified linescached = self._cache.get(cache_key)if cached:self._cache.move_to_end(cache_key)return cachedif self.api_client is not None:2 unmodified linesexcept 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:329 unmodified linesself.assembly_metrics['total_assemblies'] += 1assembly_notes = []try:# Step 1: Component selection based on classificationselected_components = self._select_and_validate_components(23 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 correction9 unmodified lines)self.assembly_metrics['safety_validations_passed'] += 1# Step 7: Performance tracking and result compilationassembly_time = (time.time() - start_time) * 100016 unmodified lines17181920212223249 unmodified lines34353637383940414243444510 unmodified lines56575859606162636465668 unmodified lines757677787980812 unmodified lines8485868788899091929394959697329 unmodified lines42742842943043143243343423 unmodified lines4584594604614624634644654664674684699 unmodified lines47948048148248348448516 unmodified linesimport jsonimport hashlibfrom collections import OrderedDictimport loggingimport osfrom src.prompts.types import (PromptComponent, PromptCompositionSpec, AssemblyResult, SafetyLevel,9 unmodified linesself.api_client = api_clientself._cache: "OrderedDict[str, MedicalSafetyValidator._SafetyReport]" = OrderedDict()self._max_cache_entries = max_cache_entriesself.logger = logging.getLogger("dynamic_prompts")if os.getenv("LOG_PROMPTS", "false").lower() == "true" and not self.logger.handlers:self.logger.setLevel(logging.INFO)handler = logging.FileHandler("dynamic_prompts.log", encoding="utf-8")handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))self.logger.addHandler(handler)@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:report = self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)self.logger.info("[DYNAMIC_PROMPT] safety_heuristic components=%s", components_used)return report.is_safe, report.violations, report.warningsreport = self._get_safety_report(prompt, components_used, clinical_background, classification_spec)return report.is_safe, report.violations, report.warnings8 unmodified linescached = self._cache.get(cache_key)if cached:self._cache.move_to_end(cache_key)self.logger.info("[DYNAMIC_PROMPT] cache_hit components=%s", components_used)return cachedif self.api_client is not None:2 unmodified linesexcept Exception as exc:print(f"⚠️ LLM safety review failed: {exc} — using heuristic fallback")report = self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)self.logger.info("[DYNAMIC_PROMPT] safety_fallback_due_to_error components=%s error=%s",components_used,exc,)else:report = self._heuristic_fallback(prompt, components_used, clinical_background, classification_spec)self.logger.info("[DYNAMIC_PROMPT] safety_heuristic components=%s", components_used)self._cache[cache_key] = reportif len(self._cache) > self._max_cache_entries:329 unmodified linesself.assembly_metrics['total_assemblies'] += 1assembly_notes = []logger = logging.getLogger("dynamic_prompts")try:# Step 1: Component selection based on classificationselected_components = self._select_and_validate_components(23 unmodified lines)if not is_safe:logger.info("[DYNAMIC_PROMPT] safety_failed components=%s violations=%s warnings=%s",components_used,violations,warnings,)print(f"⚠️ Dynamic safety check failed. Components: {components_used}. Violations: {violations}")self.assembly_metrics['safety_validations_failed'] += 1# Attempt safety correction9 unmodified lines)self.assembly_metrics['safety_validations_passed'] += 1logger.info("[DYNAMIC_PROMPT] components=%s", components_used)# Step 7: Performance tracking and result compilationassembly_time = (time.time() - start_time) * 1000
lifestyle_profile.json+6-8
lifestyle_profile.json.backup+13-9
src/prompts/assembler.py+29