Spaces:
Sleeping
Sleeping
feat: Add XML-style tags to prompts for better structure
Browse filesPrompts updated with XML-like tags:
- <system_role> - defines the AI's role
- <classification_categories> - defines categories
- <category> - individual category definitions
- <critical_rules> - important rules
- <guidelines> - behavioral guidelines
- <examples> - example outputs
- <output_format> - expected format
- <scratchpad> - thinking process
- <outcome_categories> - possible outcomes
- <evaluation_process> - step-by-step process
HTML formatter updated to:
- Highlight XML tags in blue/purple
- Highlight attributes in green/orange
- Preserve code-like appearance with monospace font
- Better visual hierarchy
Files changed (3)
24 unmodified lines2526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727324 unmodified lines# System prompt for generating triage questionsSYSTEM_PROMPT_TRIAGE_QUESTION = """You are a compassionate healthcare assistant conducting a gentle wellness check.The patient may be experiencing some emotional or spiritual distress. Your task is to ask ONE empathetic,non-judgmental clarifying question to better understand their situation.GUIDELINES:1. Be warm and supportive, not clinical or interrogating2. Ask open-ended questions that invite sharing3. Acknowledge their feelings without making assumptions4. Keep the question natural, like a caring conversation5. CRITICAL: Respond in the SAME LANGUAGE as the patient's messageEXAMPLES of good questions:- "It sounds like you're going through a difficult time. Would you like to tell me more about what's on your mind?"- "I hear that things feel heavy right now. What would be most helpful for you to talk about?"- "Thank you for sharing that with me. How have you been coping with these feelings?"Respond with ONLY the question text, no JSON or formatting. Match the patient's language."""# System prompt for evaluating triage responsesSYSTEM_PROMPT_TRIAGE_EVALUATE = """You are evaluating a patient's response during a gentle wellness check.Based on the patient's response, determine the appropriate outcome:RESOLVED_GREEN: Patient is coping well, has support systems, or the concern was minor- Signs: mentions coping strategies, support from others, temporary stress, feeling better- Example: "I'm just having a bad day, but I have my family to talk to"ESCALATE_RED: Patient shows significant distress that needs professional support- Signs: persistent hopelessness, isolation, inability to cope, worsening symptoms- Example: "I feel completely alone and nothing helps anymore"CONTINUE: Need more information to make a determination- Signs: vague response, unclear situation, patient deflecting- Example: "I don't know, it's complicated"Respond ONLY with valid JSON:{"outcome": "resolved_green" | "escalate_red" | "continue","reasoning": "Brief explanation","confidence": 0.0-1.0}"""class SoftTriageManager:24 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013124 unmodified lines# System prompt for generating triage questionsSYSTEM_PROMPT_TRIAGE_QUESTION = """<system_role>You are a compassionate healthcare assistant conducting a gentle wellness check. The patient may be experiencing some emotional or spiritual distress. Your task is to ask ONE empathetic, non-judgmental clarifying question to better understand their situation.</system_role><guidelines><guideline priority="high">Be warm and supportive, not clinical or interrogating</guideline><guideline priority="high">Ask open-ended questions that invite sharing</guideline><guideline priority="medium">Acknowledge their feelings without making assumptions</guideline><guideline priority="medium">Keep the question natural, like a caring conversation</guideline><guideline priority="critical">CRITICAL: Respond in the SAME LANGUAGE as the patient's message</guideline></guidelines><examples><example language="english">"It sounds like you're going through a difficult time. Would you like to tell me more about what's on your mind?"</example><example language="english">"I hear that things feel heavy right now. What would be most helpful for you to talk about?"</example><example language="english">"Thank you for sharing that with me. How have you been coping with these feelings?"</example><example language="ukrainian">"Здається, ви переживаєте важкий час. Чи хотіли б ви розповісти більше про те, що вас турбує?"</example><example language="ukrainian">"Я розумію, що зараз вам важко. Про що б вам найбільше хотілося поговорити?"</example></examples><output_format>Respond with ONLY the question text, no JSON or formatting. Match the patient's language.</output_format>"""# System prompt for evaluating triage responsesSYSTEM_PROMPT_TRIAGE_EVALUATE = """<system_role>You are evaluating a patient's response during a gentle wellness check. Based on the patient's response, determine the appropriate outcome to guide next steps.</system_role><outcome_categories><outcome name="RESOLVED_GREEN" action="return_to_medical"><description>Patient is coping well, has support systems, or the concern was minor</description><indicators>- Mentions coping strategies or support from others- Describes temporary stress that is manageable- Reports feeling better or having resources- Shows resilience or positive outlook</indicators><example>"I'm just having a bad day, but I have my family to talk to"</example><example>"It's been tough, but I'm managing with my therapist's help"</example></outcome><outcome name="ESCALATE_RED" action="generate_referral"><description>Patient shows significant distress that needs professional support</description><indicators>- Persistent hopelessness without relief- Complete isolation with no support system- Inability to cope or function- Worsening symptoms or deterioration- Continued crisis language</indicators><example>"I feel completely alone and nothing helps anymore"</example><example>"Every day is worse, I can't see a way forward"</example></outcome><outcome name="CONTINUE" action="ask_another_question"><description>Need more information to make a determination</description><indicators>- Vague or unclear response- Patient deflecting or avoiding- Ambiguous situation requiring clarification- Mixed signals that need exploration</indicators><example>"I don't know, it's complicated"</example><example>"Maybe, I'm not sure"</example></outcome></outcome_categories><evaluation_process><step>Review the patient's response carefully</step><step>Identify specific indicators present in their words</step><step>Match indicators to outcome categories</step><step>Consider the overall tone and context</step><step>Assess confidence in your determination</step></evaluation_process><output_format>Respond ONLY with valid JSON in this exact format:{"outcome": "resolved_green" | "escalate_red" | "continue","reasoning": "Brief explanation of why you chose this outcome","confidence": 0.0-1.0}Do not include any text before or after the JSON object.</output_format>"""class SoftTriageManager:
61 unmodified lines62636465666768697071727374757677787980818283848586878889909161 unmodified lines# System prompt for spiritual classificationSYSTEM_PROMPT_SPIRITUAL_MONITOR = """You are a background spiritual distress classifier for a medical chatbot.Your task is to analyze patient messages and classify them into one of three categories:- GREEN: No spiritual/emotional distress indicators. Normal medical conversation.- YELLOW: Potential distress indicators present. May need gentle follow-up.- RED: Severe distress indicators. Immediate support needed.CLASSIFICATION RULES:1. RED (immediate): Suicidal ideation, death wishes, severe hopelessness, crisis language2. YELLOW (potential): Sadness, anxiety, spiritual questions, grief, existential concerns, loneliness3. GREEN (none): Medical symptoms only, routine questions, no emotional contentIMPORTANT:- When uncertain between GREEN and YELLOW, choose YELLOW (conservative approach)- Any mention of suicide, self-harm, or wanting to die is ALWAYS RED- Spiritual questions (about God, faith, meaning) are YELLOW unless combined with crisis languageRespond ONLY with valid JSON in this exact format:{"state": "green" | "yellow" | "red","indicators": ["indicator1", "indicator2"],"confidence": 0.0-1.0,"reasoning": "Brief explanation"}"""class SpiritualMonitor:61 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713861 unmodified lines# System prompt for spiritual classificationSYSTEM_PROMPT_SPIRITUAL_MONITOR = """<system_role>You are a background spiritual distress classifier for a medical chatbot. Your task is to analyze patient messages and classify their level of spiritual or emotional distress to help route them to appropriate support.</system_role><classification_categories>You must classify this message into exactly ONE of the following three categories:<category name="GREEN" severity="no_distress">The message contains only medical symptoms, routine questions, appointment scheduling, medication inquiries, or other standard healthcare topics. There are no indicators of emotional or spiritual distress.</category><category name="YELLOW" severity="potential_distress">The message contains indicators of mild to moderate distress, including:- Expressions of sadness, worry, or anxiety- Spiritual or existential questions (about God, faith, life's meaning, purpose)- Grief or loss (not acute crisis)- Loneliness or isolation- Feeling overwhelmed or stressed- Questions about suffering or "why me"- Mild hopelessness that doesn't involve crisis language</category><category name="RED" severity="severe_distress">The message contains indicators of severe distress or crisis, including:- ANY mention of suicide, suicidal thoughts, or suicidal ideation- Self-harm thoughts or behaviors- Explicit wishes to die or not wake up- Severe hopelessness combined with crisis language- Statements like "I can't go on," "I want to end it," "no reason to live"- Active crisis or emergency language</category></classification_categories><critical_rules>1. ANY mention of suicide, self-harm, death wishes, or wanting to die is ALWAYS classified as RED, regardless of other content2. When uncertain between GREEN and YELLOW, always choose YELLOW (err on the side of caution)3. When uncertain between YELLOW and RED, carefully evaluate for active crisis language - if present, choose RED4. Spiritual questions alone (without crisis indicators) are YELLOW, not RED5. Multiple YELLOW indicators together still remain YELLOW unless crisis language is present6. Physical pain or medical symptoms alone are GREEN unless accompanied by emotional/spiritual distress language</critical_rules><analysis_process>Before providing your classification, use the scratchpad to think through your analysis:<scratchpad>- Identify any distress indicators present in the message- Note the severity level of each indicator- Consider whether crisis language is present- Determine which category best fits- Assess your confidence level</scratchpad></analysis_process><output_format>After your analysis, provide your classification in valid JSON format with the following structure:- "state": Must be exactly "green", "yellow", or "red" (lowercase)- "indicators": An array of specific distress indicators found (empty array [] if none)- "confidence": A number between 0.0 and 1.0 representing your confidence in the classification- "reasoning": A brief 1-2 sentence explanation of why you chose this classificationYour response must be ONLY valid JSON in this exact format:{"state": "green" | "yellow" | "red","indicators": ["indicator1", "indicator2"],"confidence": 0.0-1.0,"reasoning": "Brief explanation"}Do not include any text before or after the JSON object.</output_format>"""class SpiritualMonitor:
260 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892901 unmodified line2922932942952962972981 unmodified line3003013023033043053066 unmodified lines313314315316317318319320321322323324260 unmodified linesdef format_prompt_with_html(prompt_text: str) -> str:"""Format prompt with HTML tags for better visualization."""import re# Add HTML structureformatted = prompt_text# Highlight sections (UPPERCASE headers)formatted = re.sub(r'^([A-Z][A-Z\s]+:)$',r'<h3 style="color: #2563eb; margin-top: 1em; margin-bottom: 0.5em;">\1</h3>',formatted,flags=re.MULTILINE)# Highlight subsections (Title Case headers)formatted = re.sub(r'^([A-Z][a-zA-Z\s]+:)$',r'<h4 style="color: #7c3aed; margin-top: 0.8em; margin-bottom: 0.3em;">\1</h4>',formatted,flags=re.MULTILINE)# Highlight bullet pointsformatted = re.sub(r'^([-•]\s+.+)$',r'<li style="margin-left: 1.5em; color: #059669;">\1</li>',formatted,flags=re.MULTILINE)1 unmodified line# Highlight numbered listsformatted = re.sub(r'^(\d+\.\s+.+)$',r'<li style="margin-left: 1.5em; color: #dc2626;">\1</li>',formatted,flags=re.MULTILINE)1 unmodified line# Highlight important keywordskeywords = ['IMPORTANT', 'CRITICAL', 'REQUIRED', 'MUST', 'SHALL','WARNING', 'NOTE', 'TASK', 'GOAL', 'OUTPUT']for keyword in keywords:formatted = re.sub(6 unmodified lines# Highlight JSON/code blocksformatted = re.sub(r'(\{[^}]+\})',r'<code style="background-color: #f3f4f6; padding: 2px 6px; border-radius: 3px; font-family: monospace;">\1</code>',formatted)# Wrap in containerformatted = f'<div style="font-family: system-ui; line-height: 1.6; padding: 1em;">{formatted}</div>'return formatted260 unmodified lines2612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982991 unmodified line3013023033043053063071 unmodified line3093103113123133143156 unmodified lines322323324325326327328329330331332333334335336260 unmodified linesdef format_prompt_with_html(prompt_text: str) -> str:"""Format prompt with HTML tags for better visualization."""import reimport html# Escape HTML first to prevent injectionformatted = html.escape(prompt_text)# Highlight XML-like opening tagsformatted = re.sub(r'<([a-z_]+)(?:\s+[^>]*)?>',r'<span style="color: #2563eb; font-weight: 600;"><\1></span>',formatted,flags=re.IGNORECASE)# Highlight XML-like closing tagsformatted = re.sub(r'</([a-z_]+)>',r'<span style="color: #7c3aed; font-weight: 600;"></\1></span>',formatted,flags=re.IGNORECASE)# Highlight XML attributesformatted = re.sub(r'([a-z_]+)="([^"]+)"',r'<span style="color: #059669;">\1</span>=<span style="color: #d97706;">"\2"</span>',formatted,flags=re.IGNORECASE)# Highlight bullet pointsformatted = re.sub(r'^([-•]\s+.+)$',r'<div style="margin-left: 1.5em; color: #059669;">\1</div>',formatted,flags=re.MULTILINE)1 unmodified line# Highlight numbered listsformatted = re.sub(r'^(\d+\.\s+.+)$',r'<div style="margin-left: 1.5em; color: #dc2626;">\1</div>',formatted,flags=re.MULTILINE)1 unmodified line# Highlight important keywordskeywords = ['IMPORTANT', 'CRITICAL', 'REQUIRED', 'MUST', 'SHALL','WARNING', 'NOTE', 'TASK', 'GOAL', 'OUTPUT', 'ANY']for keyword in keywords:formatted = re.sub(6 unmodified lines# Highlight JSON/code blocksformatted = re.sub(r'(\{[^}]+\})',r'<code style="background-color: #f3f4f6; padding: 2px 6px; border-radius: 3px; font-family: monospace; font-size: 0.9em;">\1</code>',formatted)# Convert newlines to <br> for proper displayformatted = formatted.replace('\n', '<br>')# Wrap in container with monospace font for code-like appearanceformatted = f'<div style="font-family: \'Courier New\', monospace; line-height: 1.8; padding: 1em; background-color: #f9fafb; border-radius: 8px; overflow-x: auto;">{formatted}</div>'return formatted
src/core/soft_triage_manager.py+86-28
src/core/spiritual_monitor.py+62-15
src/interface/simplified_gradio_app.py+28-16