Spaces:
Sleeping
Sleeping
add
Browse filesFiles changed (2)
- src/config/prompts.py+65-31
- src/core/core_classes.py+149-18
1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647481 unmodified line# ===== CLASSIFIERS =====SYSTEM_PROMPT_ENTRY_CLASSIFIER = """You are a message classification specialist for a medical chat system with lifestyle coaching capabilities.TASK:Classify the current patient message to determine the appropriate system mode. Focus ONLY on the message content, completely ignoring patient's medical history.CLASSIFICATION MODES:- **ON**: Lifestyle, exercise, nutrition, rehabilitation requests- **OFF**: Medical complaints, symptoms, greetings, general questions- **HYBRID**: Messages containing BOTH lifestyle requests AND current medical complaintsAGGRESSIVE LIFESTYLE DETECTION:If the message contains ANY of these terms, classify as ON regardless of medical history:- Keywords: exercise, workout, training, fitness, sport, rehabilitation, nutrition, diet, physical, activity, movement, therapyDECISION LOGIC:1. **Scan for lifestyle keywords** → If found without medical complaints → ON2. **Check for medical symptoms** → If found without lifestyle content → OFF3. **Both present** → HYBRID4. **Neither present** (greetings, social) → OFFCLEAR EXAMPLES:✅ "I want to start exercising" → ON (sports request)✅ "Let's do some exercises" → ON (exercise request)✅ "What exercises are suitable for me" → ON (exercise inquiry)✅ "Let's talk about rehabilitation" → ON (rehabilitation)✅ "want to start working out" → ON (fitness motivation)❌ "I have a headache" → OFF (medical symptom)❌ "hello" → OFF (greeting)⚡ "I want to exercise but my back hurts" → HYBRID (both)CRITICAL RULES:- IGNORE patient's medical history completely- Focus ONLY on current message content- Be aggressive in detecting lifestyle intent- Medical history does NOT override lifestyle classificationOUTPUT FORMAT (JSON only):{"K": "Lifestyle Mode","V": "on|off|hybrid","T": "YYYY-MM-DDTHH:MM:SSZ"}"""SYSTEM_PROMPT_TRIAGE_EXIT_CLASSIFIER = """You are a clinical triage specialist evaluating patient readiness for lifestyle coaching after medical assessment.1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified line# ===== CLASSIFIERS =====SYSTEM_PROMPT_ENTRY_CLASSIFIER = """You are a message classification specialist for a medical chat system with lifestyle coaching and spiritual health assessment capabilities.TASK:Classify the current patient message to determine the appropriate system mode(s). Analyze the message for medical concerns (K), lifestyle needs (L), and spiritual distress indicators (S).CLASSIFICATION DIMENSIONS:**K (Koncern - Medical):**- "none": No medical concerns- "minor": Minor medical questions or stable conditions- "urgent": Active symptoms, pain, or medical issues requiring attention**L (Lifestyle):**- "off": No lifestyle/exercise/nutrition requests- "on": Lifestyle, exercise, nutrition, rehabilitation requests**S (Spiritual):**- "off": No spiritual distress indicators- "on": Spiritual/emotional distress, existential concerns, meaning/purpose questions**T (Triage - Urgency):**- "routine": Normal conversation, no urgency- "urgent": Requires prompt attention but not emergency- "emergency": Immediate medical attention neededLIFESTYLE DETECTION KEYWORDS:exercise, workout, training, fitness, sport, rehabilitation, nutrition, diet, physical, activity, movement, therapySPIRITUAL DISTRESS INDICATORS:**Emotional Markers:**- Anger, rage, frustration, irritability- Sadness, depression, crying, grief- Hopelessness, helplessness, despair- Anxiety, fear, worry, panic- Guilt, shame, regret- Loneliness, isolation, abandonment**Spiritual Markers:**- Questions about meaning, purpose, "why me?"- Loss of faith, questioning beliefs- Feeling abandoned by God/higher power- Existential concerns, life/death questions- Moral distress, ethical dilemmas- Loss of hope, future orientation- Disconnection from spiritual community- Inability to find peace or comfortDECISION LOGIC:1. Scan for medical symptoms → Set K level2. Scan for lifestyle keywords → Set L (on/off)3. Scan for emotional/spiritual markers → Set S (on/off)4. Assess overall urgency → Set T levelEXAMPLES:✅ "I want to start exercising" → K:none, L:on, S:off, T:routine✅ "I have a headache" → K:minor, L:off, S:off, T:routine✅ "Why is this happening to me? I feel so hopeless" → K:none, L:off, S:on, T:urgent✅ "I want to exercise but feel so depressed" → K:none, L:on, S:on, T:routine✅ "Severe chest pain" → K:urgent, L:off, S:off, T:emergency✅ "I can't find meaning in life anymore" → K:none, L:off, S:on, T:urgentCRITICAL RULES:- Focus ONLY on current message content- Be sensitive to subtle emotional/spiritual cues- Medical safety is paramount (K and T take priority)- Multiple dimensions can be active simultaneouslyOUTPUT FORMAT (JSON only):{"K": "none|minor|urgent","L": "off|on","S": "off|on","T": "routine|urgent|emergency","reasoning": "Brief explanation of classification"}"""SYSTEM_PROMPT_TRIAGE_EXIT_CLASSIFIER = """You are a clinical triage specialist evaluating patient readiness for lifestyle coaching after medical assessment.
18 unmodified lines1920212223242526272851 unmodified lines80818283848587 unmodified lines1731741751761771781791801811821831841851861871881892 unmodified lines192193194195196197985 unmodified lines11831184118511861187118811898 unmodified lines1198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122318 unmodified linesfrom datetime import datetimefrom dataclasses import dataclass, asdictfrom typing import Dict, List, Optional, Any, Union, Tuple, Callable, TypeVar, Type, TYPE_CHECKING# Import AIClientManager for type hintsif TYPE_CHECKING:from src.core.ai_client import AIClientManagerimport re51 unmodified lines# ===== ENHANCED DATA STRUCTURES =====@dataclassclass ClinicalBackground:"""Enhanced clinical background with composition context tracking"""87 unmodified lines@dataclassclass SessionState:"""Enhanced session state with dynamic prompt context"""current_mode: stris_active_session: boolsession_start_time: Optional[str]last_controller_decision: Dict# Lifecycle managementlifestyle_session_length: int = 0last_triage_summary: str = ""entry_classification: Dict = None# NEW: Dynamic prompt composition statecurrent_prompt_composition_id: Optional[str] = Nonecomposition_analytics: Dict = None2 unmodified linesself.entry_classification = {}if self.composition_analytics is None:self.composition_analytics = {}# ===== ENHANCED LIFESTYLE ASSISTANT WITH DYNAMIC PROMPTS =====985 unmodified linesself.api = apidef classify(self, user_message: str, clinical_background: ClinicalBackground) -> Dict:"""Класифікує повідомлення та повертає K/V/T формат"""system_prompt = SYSTEM_PROMPT_ENTRY_CLASSIFIERuser_prompt = PROMPT_ENTRY_CLASSIFIER(clinical_background, user_message)8 unmodified linestry:classification = _extract_json_object(response)# Валідація формату K/V/Tif not all(key in classification for key in ["K", "V", "T"]):raise ValueError("Missing K/V/T keys")if classification["V"] not in ["on", "off", "hybrid"]:classification["V"] = "off" # fallback# Переважно підставляємо серверний timestamp (UTC), ігноруючи T з LLMfrom datetime import datetime, timezoneclassification["T"] = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")return classificationexcept:from datetime import datetimereturn {"K": "Lifestyle Mode","V": "off",# Використовуємо UTC timestamp у fallback"T": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")}class TriageExitClassifier:"""Preserved Legacy Class - Triage Exit Assessment"""18 unmodified lines19202122232425262728293051 unmodified lines82838485868788899091929394959697989910010110210310410510687 unmodified lines1941951961971981992002012022032042052062072082092102112122132142152162172182192202 unmodified lines223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269985 unmodified lines1255125612571258125912601261126212631264126512661267126812691270127112728 unmodified lines1281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135418 unmodified linesfrom datetime import datetimefrom dataclasses import dataclass, asdictfrom typing import Dict, List, Optional, Any, Union, Tuple, Callable, TypeVar, Type, TYPE_CHECKINGfrom enum import Enum# Import AIClientManager for type hintsif TYPE_CHECKING:from src.core.ai_client import AIClientManagerfrom src.core.spiritual_classes import DistressClassification, ReferralMessageimport re51 unmodified lines# ===== ENHANCED DATA STRUCTURES =====# ===== ASSISTANT MODE ENUM =====class AssistantMode(Enum):"""Режими роботи асистента.Визначає доступні режими для обробки повідомлень користувача:- NONE: Режим не визначено- MEDICAL: Медичний режим для обробки медичних питань- LIFESTYLE: Режим lifestyle рекомендацій- SPIRITUAL: Режим оцінки духовного дистресу- COMBINED: Комбінований режим (Lifestyle + Spiritual)"""NONE = "none"MEDICAL = "medical"LIFESTYLE = "lifestyle"SPIRITUAL = "spiritual"COMBINED = "combined"@dataclassclass ClinicalBackground:"""Enhanced clinical background with composition context tracking"""87 unmodified lines@dataclassclass SessionState:"""Enhanced session state with dynamic prompt context and multi-mode support"""current_mode: 'AssistantMode' # Changed from str to AssistantMode enumis_active_session: boolsession_start_time: Optional[str]last_controller_decision: Dict# Lifecycle managementlifestyle_session_length: int = 0last_triage_summary: str = ""entry_classification: Dict = None# Spiritual state (NEW)spiritual_assessment: Optional['DistressClassification'] = Nonespiritual_referral: Optional['ReferralMessage'] = Nonespiritual_questions: List[str] = None# Combined mode state (NEW)combined_results: Dict[str, Any] = Noneactive_assistants: List[str] = None# Dynamic prompt composition statecurrent_prompt_composition_id: Optional[str] = Nonecomposition_analytics: Dict = None2 unmodified linesself.entry_classification = {}if self.composition_analytics is None:self.composition_analytics = {}if self.spiritual_questions is None:self.spiritual_questions = []if self.combined_results is None:self.combined_results = {}if self.active_assistants is None:self.active_assistants = []def reset(self):"""Скидає стан сесії, очищуючи всі поля"""self.is_active_session = Falseself.session_start_time = Noneself.last_controller_decision = {}self.lifestyle_session_length = 0self.last_triage_summary = ""self.entry_classification = {}self.spiritual_assessment = Noneself.spiritual_referral = Noneself.spiritual_questions = []self.combined_results = {}self.active_assistants = []self.current_prompt_composition_id = Noneself.composition_analytics = {}def update_mode(self, new_mode: 'AssistantMode'):"""Оновлює поточний режим роботи"""self.current_mode = new_mode# Оновлюємо список активних асистентівif new_mode == AssistantMode.COMBINED:self.active_assistants = ["lifestyle", "spiritual"]elif new_mode == AssistantMode.LIFESTYLE:self.active_assistants = ["lifestyle"]elif new_mode == AssistantMode.SPIRITUAL:self.active_assistants = ["spiritual"]elif new_mode == AssistantMode.MEDICAL:self.active_assistants = ["medical"]else:self.active_assistants = []def get_active_assistants(self) -> List[str]:"""Повертає список активних асистентів"""return self.active_assistants.copy()# ===== ENHANCED LIFESTYLE ASSISTANT WITH DYNAMIC PROMPTS =====985 unmodified linesself.api = apidef classify(self, user_message: str, clinical_background: ClinicalBackground) -> Dict:"""Класифікує повідомлення та повертає K/L/S/T формат.Returns:Dict з полями:- K: "none" | "minor" | "urgent" (медичні індикатори)- L: "off" | "on" (lifestyle інди��атори)- S: "off" | "on" (spiritual індикатори)- T: "routine" | "urgent" | "emergency" (терміновість)- reasoning: str (пояснення класифікації)- recommended_mode: Optional[str] (рекомендований режим)"""system_prompt = SYSTEM_PROMPT_ENTRY_CLASSIFIERuser_prompt = PROMPT_ENTRY_CLASSIFIER(clinical_background, user_message)8 unmodified linestry:classification = _extract_json_object(response)# Валідація формату K/L/S/Tif not all(key in classification for key in ["K", "L", "S", "T"]):raise ValueError("Missing K/L/S/T keys")# Валідація значень Kif classification["K"] not in ["none", "minor", "urgent"]:classification["K"] = "none" # fallback# Валідація значень Lif classification["L"] not in ["on", "off"]:classification["L"] = "off" # fallback# Валідація значень Sif classification["S"] not in ["on", "off"]:classification["S"] = "off" # fallback# Валідація значень Tif classification["T"] not in ["routine", "urgent", "emergency"]:classification["T"] = "routine" # fallback# Додаємо reasoning якщо немаєif "reasoning" not in classification:classification["reasoning"] = "Classification completed"# Визначаємо рекомендований режимclassification["recommended_mode"] = self._determine_recommended_mode(classification)return classificationexcept Exception as e:# Fallback при помилці парсингуreturn {"K": "none","L": "off","S": "off","T": "routine","reasoning": f"Classification error: {str(e)}. Using safe defaults.","recommended_mode": "medical"}def _determine_recommended_mode(self, classification: Dict) -> str:"""Визначає рекомендований режим на основі класифікації.Логіка:- K="urgent" → medical (пріоритет медичним питанням)- L="on" AND S="on" → combined (обидва типи підтримки)- L="on" AND S="off" → lifestyle- L="off" AND S="on" → spiritual- Інакше → medical (за замовчуванням)"""# Медичні питання мають найвищий пріоритетif classification.get("K") == "urgent":return "medical"# Комбінований режим коли потрібні обидва типи підтримкиif classification.get("L") == "on" and classification.get("S") == "on":return "combined"# Окремі режимиif classification.get("L") == "on":return "lifestyle"if classification.get("S") == "on":return "spiritual"# За замовчуванням медичний режимreturn "medical"class TriageExitClassifier:"""Preserved Legacy Class - Triage Exit Assessment"""
src/config/prompts.py+65-31
src/core/core_classes.py+149-18