From 1e5e11affa5ef1b243e8b5c865d867f7c85de996 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 25 Nov 2025 15:19:23 +0000 Subject: [PATCH 01/25] Transform LLM Council into Wellness Council - Multidisciplinary AI Wellness Tool MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit transforms the LLM Council architecture into a specialized wellness reflection tool with 5 healthcare professional perspectives and comprehensive safety features. ## Major Changes ### Backend Transformations - **5 Specialized Roles**: Therapist, Psychiatrist, Personal Trainer, Doctor (GP), Psychologist - **Role-Specific System Prompts**: Each model receives detailed professional persona - **Crisis Detection System**: Automatic keyword scanning for crisis situations - **Medical Disclaimers**: Integrated throughout all prompts and responses - **Wellness-Focused Prompts**: Updated all 3 stages for healthcare context ### Frontend Enhancements - **Professional Role Badges**: Visual indicators showing each professional's specialty - **Medical Disclaimer Component**: Prominent warnings throughout interface - **Crisis Resources Component**: Auto-displays when crisis keywords detected - **Wellness Branding**: Updated all text from "LLM Council" to "Wellness Council" - **Professional Role Display**: Tabs and labels show role names (e.g., "Therapist") - **Enhanced Descriptions**: Stage-specific descriptions explain the wellness process ### Safety & Ethics - **Crisis Keyword Detection**: Monitors for suicide, self-harm, eating disorders, abuse, etc. - **Crisis Resource Links**: 988 Lifeline, Crisis Text Line, emergency services - **Medical Disclaimers**: Clear warnings this is NOT medical advice - **Transparent Reasoning**: All peer evaluations visible for scrutiny ### Documentation - **WELLNESS_COUNCIL.md**: Comprehensive 400+ line documentation covering: - Medical disclaimers and ethics - How the system works (3 stages) - Use cases and example scenarios - Configuration and customization - Limitations and safety considerations - Installation and development guide ## File Changes - backend/config.py: 5 models with role prompts, crisis keywords, medical disclaimer - backend/council.py: Role-specific queries, crisis detection, wellness prompts - frontend/index.html: Updated title and meta description - frontend/src/components/ChatInterface.jsx: Medical disclaimers, crisis resources - frontend/src/components/Stage1.jsx: Professional role badges and headers - frontend/src/components/Stage3.jsx: "Integrative Wellness Coordinator" branding - NEW: MedicalDisclaimer component with styling - NEW: CrisisResources component with 24/7 helpline information - NEW: WELLNESS_COUNCIL.md comprehensive documentation ## Key Features ✅ Anonymous peer review prevents professional hierarchy bias ✅ Crisis detection with immediate resource display ✅ Medical disclaimers on every screen ✅ Transparent reasoning - all evaluations visible ✅ Professional role specialization with detailed personas ✅ Integrative synthesis combining all perspectives ## Use Cases - Self-reflection before healthcare appointments - Understanding multidisciplinary perspectives on wellness - Educational tool for learning about different therapeutic approaches - Organizing thoughts and questions for real professionals **CRITICAL**: This is an educational/reflection tool, NOT medical advice, therapy, or professional healthcare. Always consult licensed professionals. --- WELLNESS_COUNCIL.md | 382 ++++++++++++++++++ backend/config.py | 106 ++++- backend/council.py | 168 +++++--- frontend/index.html | 3 +- frontend/src/components/ChatInterface.jsx | 115 +++--- frontend/src/components/CrisisResources.css | 83 ++++ frontend/src/components/CrisisResources.jsx | 37 ++ frontend/src/components/MedicalDisclaimer.css | 33 ++ frontend/src/components/MedicalDisclaimer.jsx | 17 + frontend/src/components/Stage1.css | 32 +- frontend/src/components/Stage1.jsx | 12 +- frontend/src/components/Stage3.jsx | 7 +- 12 files changed, 878 insertions(+), 117 deletions(-) create mode 100644 WELLNESS_COUNCIL.md create mode 100644 frontend/src/components/CrisisResources.css create mode 100644 frontend/src/components/CrisisResources.jsx create mode 100644 frontend/src/components/MedicalDisclaimer.css create mode 100644 frontend/src/components/MedicalDisclaimer.jsx diff --git a/WELLNESS_COUNCIL.md b/WELLNESS_COUNCIL.md new file mode 100644 index 000000000..2d7cc4727 --- /dev/null +++ b/WELLNESS_COUNCIL.md @@ -0,0 +1,382 @@ +# Wellness Council + +**A Multidisciplinary AI Wellness Reflection Tool** + +## ⚠️ CRITICAL DISCLAIMER + +**THIS IS NOT MEDICAL ADVICE, THERAPY, OR PROFESSIONAL HEALTHCARE.** + +Wellness Council is an AI-powered educational and self-exploration tool designed to help you reflect on wellness concerns from multiple professional perspectives. It is: + +- ✅ For educational purposes and personal reflection +- ✅ A tool to organize your thoughts before seeing professionals +- ✅ A way to explore different wellness perspectives +- ❌ NOT a replacement for licensed healthcare professionals +- ❌ NOT medical, psychiatric, or psychological diagnosis or treatment +- ❌ NOT emergency services + +**Always consult licensed healthcare professionals for medical, mental health, or wellness concerns.** + +### Crisis Resources + +If you're experiencing a mental health crisis or thoughts of self-harm: + +- **988 Suicide & Crisis Lifeline:** Call or text **988** (24/7) +- **Crisis Text Line:** Text HOME to **741741** (24/7) +- **Emergency Services:** Call **911** or go to your nearest emergency room +- **International:** Find resources at [FindAHelpline.com](https://findahelpline.com) + +--- + +## What is Wellness Council? + +Wellness Council is a 3-stage deliberation system where multiple AI models, each given a specific healthcare professional role, collaboratively provide perspectives on wellness questions. The system combines: + +- **Therapist** - CBT, emotional processing, talk therapy approaches +- **Psychiatrist** - Clinical assessment, medical perspectives, pharmacology +- **Personal Trainer** - Physical fitness, nutrition, body wellness +- **Doctor (GP)** - General health screening, lifestyle medicine, physical health +- **Psychologist** - Evidence-based interventions, behavioral science, research + +### Key Innovation: Anonymous Peer Review + +In **Stage 2**, each professional perspective anonymously evaluates all other perspectives, preventing bias and ensuring objective assessment of advice quality—just like real multidisciplinary healthcare teams. + +--- + +## How It Works + +### Stage 1: Professional Perspectives +Each AI "professional" independently responds to your wellness concern based on their specialized expertise. You can view each perspective individually through tabs. + +**Example Question:** *"I feel that I am fat but everybody still thinks that I am skinny, how can I improve how I see myself, especially mentally?"* + +**Responses:** +- **Therapist:** Explores cognitive distortions about body image, emotional processing +- **Psychiatrist:** Considers body dysmorphic disorder screening, clinical assessment +- **Personal Trainer:** Discusses body composition vs. weight, realistic fitness goals +- **Doctor:** Rules out thyroid/metabolic issues, nutritional deficiencies +- **Psychologist:** Applies evidence-based research on body image interventions + +### Stage 2: Anonymous Peer Review +Each professional evaluates all responses (labeled as "Response A", "Response B", etc.) without knowing who wrote what. They assess: + +- Appropriateness and safety of advice +- Medical/psychological factors considered +- Evidence-based quality +- Compassion and person-centered approach + +The system calculates **aggregate rankings** showing which perspectives received the highest peer evaluations. + +**Why This Matters:** Just like in real healthcare, different professionals catch each other's blind spots. The psychiatrist might recognize when the personal trainer's advice could reinforce dysmorphic thinking. The doctor might note medical factors the therapist hadn't considered. + +### Stage 3: Integrative Wellness Recommendation +An **Integrative Wellness Coordinator** synthesizes all perspectives and peer reviews into a holistic recommendation that: + +- Prioritizes safety (flags any red flags) +- Combines physical, mental, emotional dimensions +- Provides actionable next steps +- Emphasizes when to seek professional help +- Highlights where professionals agree (strong signal) + +--- + +## Features + +### Crisis Detection +The system automatically detects crisis keywords (suicide, self-harm, eating disorders, abuse, etc.) and displays prominent crisis resources at the top of responses. + +### Medical Disclaimers +Prominent disclaimers appear throughout the interface to ensure users understand this is a reflection tool, not medical care. + +### Transparent Reasoning +All raw professional evaluations are visible. You can see: +- Each professional's full response +- Each peer evaluation with extracted rankings +- How aggregate rankings were calculated + +This transparency builds trust and allows you to validate the system's interpretation. + +### Professional Role Badges +Each response is clearly labeled with the professional role, making it easy to understand the lens through which advice is given. + +--- + +## Use Cases + +### 1. Self-Reflection Before Appointments +Use Wellness Council to organize your thoughts and understand different perspectives before seeing actual healthcare providers. This can help you: +- Articulate concerns more clearly +- Know which type of professional to see first +- Prepare questions for your appointments + +### 2. Understanding Multidisciplinary Perspectives +Wellness concerns often span multiple domains (mental, physical, behavioral). Wellness Council helps you see how different professionals would approach the same issue. + +### 3. Exploring Options +When you're unsure whether a concern is primarily physical, mental, or behavioral, seeing multiple perspectives can help you understand the full picture. + +### 4. Educational Tool +Learn about different therapeutic approaches, evidence-based interventions, and how healthcare professionals think about wellness. + +--- + +## Example Scenarios + +### Scenario 1: Body Image Concerns +**Question:** *"I feel that I am fat but everybody still thinks that I am skinny, how can I improve how I see myself, especially mentally?"* + +**What You Get:** +- Therapist identifies cognitive distortions, suggests journaling/CBT techniques +- Psychiatrist screens for body dysmorphic disorder, discusses when clinical intervention helps +- Personal Trainer explains body composition vs. weight, promotes body-positive fitness +- Doctor rules out medical causes (thyroid, etc.), discusses nutrition's role in mental health +- Psychologist provides research-backed interventions for body image + +**Peer Review Shows:** Therapist and Psychologist perspectives ranked highest for addressing core cognitive/behavioral issues. Doctor's medical screening noted as important preliminary step. + +**Integrative Recommendation:** Combines cognitive restructuring (therapy), medical screening (doctor), evidence-based techniques (psychologist), and healthy relationship with fitness (trainer). + +### Scenario 2: Relationship Anxiety +**Question:** *"I have a feeling that my boyfriend doesn't like me anymore, how can I find out without asking him directly?"* + +**What You Get:** +- Therapist explores attachment styles, communication patterns, fear of vulnerability +- Psychiatrist considers anxiety disorders, relationship anxiety symptoms +- Personal Trainer discusses physical intimacy and shared activities +- Doctor asks about hormonal changes that might affect mood/perception +- Psychologist explains confirmation bias, provides reality-testing techniques + +**Peer Review Shows:** Psychologist and Therapist perspectives ranked highest for addressing the cognitive and relational aspects. Doctor's hormonal consideration noted as worth exploring but likely secondary. + +**Integrative Recommendation:** Primary focus on anxiety/attachment (therapist + psychologist), with medical ruling out (doctor) and relationship-building activities (trainer). Challenges the premise—why not ask directly? Explores underlying fear of communication. + +--- + +## Technical Architecture + +### Backend (Python/FastAPI) +- **5 Council Models:** Each assigned a professional role via system prompts +- **Role-Specific Prompts:** Detailed personas defining expertise, focus areas, and approach +- **Crisis Detection:** Keyword scanning triggers crisis resource display +- **Anonymous Peer Review:** Stage 2 anonymizes responses as "Response A, B, C, etc." +- **Aggregate Ranking:** Calculates average position across all peer evaluations + +### Frontend (React) +- **Professional Role Badges:** Visual indication of each perspective's specialty +- **Tabbed Interface:** Easy navigation between professionals and peer reviews +- **Medical Disclaimers:** Prominent warnings throughout +- **Crisis Resources Component:** Auto-displays when crisis keywords detected +- **Transparent Evaluation:** Shows raw peer reviews and extracted rankings + +--- + +## Configuration + +### Customizing Professional Roles + +Edit `backend/config.py` to: +- Change which AI models represent each professional +- Modify role prompts to adjust professional personas +- Add/remove specialties +- Adjust crisis keywords + +### Changing the Council Composition + +Current setup: 5 professionals (Therapist, Psychiatrist, Personal Trainer, Doctor, Psychologist) + +You can modify this to include: +- Nutritionist +- Sleep specialist +- Social worker +- Couples counselor +- Addiction specialist +- etc. + +Simply update `COUNCIL_MODELS`, `ROLE_PROMPTS`, and `ROLE_NAMES` in `backend/config.py`. + +--- + +## Ethics & Safety + +### What We've Built In + +1. **Crisis Detection:** Automatic detection of crisis keywords with prominent resource display +2. **Medical Disclaimers:** Visible on every screen, can't be missed +3. **Non-Directive Framing:** "Wellness reflection tool" not "AI therapist" or "AI doctor" +4. **Professional Care Emphasis:** Stage 3 synthesis always includes when/why to seek real professionals +5. **Transparent Reasoning:** All evaluations visible for scrutiny + +### What You Must Add + +1. **Legal Review:** Have actual healthcare attorneys review disclaimers for your jurisdiction +2. **User Agreement:** Terms of service making it clear this is not medical care +3. **Age Restrictions:** Consider minimum age requirements +4. **Data Privacy:** HIPAA-compliant storage if handling health information +5. **Professional Oversight:** Consider having licensed professionals review system outputs + +### What This Is NOT + +- ❌ Telemed +icine or telehealth service +- ❌ Licensed therapy or counseling +- ❌ Medical diagnosis or treatment +- ❌ Prescription or medication management +- ❌ Emergency services +- ❌ Replacement for human healthcare providers + +--- + +## Limitations + +### AI Limitations +- AI cannot detect non-verbal cues, body language, or subtle indicators +- AI lacks human empathy and lived experience +- AI may hallucinate or provide inaccurate information +- AI cannot perform physical exams or diagnostic tests +- AI cannot legally prescribe or diagnose + +### Systemic Limitations +- No accountability or liability like licensed professionals have +- No continuity of care or long-term relationship +- No ability to hospitalize or intervene in emergencies +- No insurance coverage or treatment records +- No professional licensing or oversight + +### Use Case Limitations +- Not suitable for emergency situations +- Not suitable for complex psychiatric conditions +- Not suitable for medication management +- Not suitable for diagnosis of any condition +- Not suitable for legal/court-mandated treatment + +--- + +## Installation & Setup + +### Prerequisites +- Python 3.8+ +- Node.js 16+ +- OpenRouter API key + +### Backend Setup +```bash +cd backend +pip install -r requirements.txt +cp .env.example .env +# Add your OPENROUTER_API_KEY to .env +python -m backend.main +``` + +Backend runs on **http://localhost:8001** + +### Frontend Setup +```bash +cd frontend +npm install +npm run dev +``` + +Frontend runs on **http://localhost:5173** + +### Environment Variables +``` +OPENROUTER_API_KEY=your_key_here +``` + +--- + +## Future Enhancements + +### Potential Features +- **Follow-Up Questions:** Allow users to ask specific professionals follow-up questions +- **Conversation History Analysis:** Track patterns over time (with user consent) +- **Resource Library:** Links to vetted mental health resources, exercises, worksheets +- **Professional Referral Network:** Connect users with actual licensed professionals in their area +- **Multi-Language Support:** Serve diverse populations +- **Accessibility Features:** Screen reader optimization, high contrast modes +- **Export Functionality:** Save conversations for discussion with real healthcare providers + +### Research Opportunities +- Study whether multidisciplinary AI perspectives improve help-seeking behavior +- Measure if users feel more prepared for actual healthcare appointments +- Analyze which professional perspectives users find most valuable for different concerns +- Evaluate if peer review improves advice quality vs. single-model approaches + +--- + +## Development Notes + +### Adding a New Professional Role + +1. **Choose a model** in `backend/config.py`: + ```python + COUNCIL_MODELS = [ + # ... existing models + "anthropic/claude-sonnet-4.5", # New role + ] + ``` + +2. **Create role prompt**: + ```python + ROLE_PROMPTS = { + "anthropic/claude-sonnet-4.5": """You are a certified nutritionist... + + Focus on: + - Dietary patterns and nutrition + - Meal planning + - etc. + """ + } + ``` + +3. **Add role name**: + ```python + ROLE_NAMES = { + "anthropic/claude-sonnet-4.5": "Nutritionist" + } + ``` + +4. No frontend changes needed—it automatically displays the new role! + +### Testing Different Prompts + +Use the conversation history to A/B test different role prompts. Track which prompt variations: +- Receive higher peer review rankings +- Provide more actionable advice +- Better balance safety with empowerment + +--- + +## Contributing + +This is a sensitive application dealing with human wellbeing. If contributing: + +1. **Safety First:** Any PR must maintain or improve safety features +2. **Ethical Review:** Consider ethical implications of changes +3. **Medical Accuracy:** Consult healthcare professionals when appropriate +4. **Inclusive Design:** Consider diverse populations and needs +5. **Transparent Communication:** Never hide system limitations + +--- + +## License & Attribution + +Based on the LLM Council architecture. Adapted for wellness/healthcare education and reflection. + +**Remember:** This is a tool for exploration and reflection, not a replacement for human healthcare professionals. Always seek professional help for medical, mental health, or wellness concerns. + +--- + +## Support & Feedback + +If you're struggling with mental health, please reach out to: +- **988 Suicide & Crisis Lifeline:** Call or text **988** +- **SAMHSA National Helpline:** 1-800-662-4357 +- **Crisis Text Line:** Text HOME to 741741 + +For technical issues or feedback about this tool, please contact [your contact method]. + +--- + +**Built with care for human wellbeing. Used responsibly, this tool can help people organize their thoughts and explore wellness from multiple angles before seeking professional care.** diff --git a/backend/config.py b/backend/config.py index a9cf7c473..5d10e6321 100644 --- a/backend/config.py +++ b/backend/config.py @@ -1,4 +1,4 @@ -"""Configuration for the LLM Council.""" +"""Configuration for the Wellness Council.""" import os from dotenv import load_dotenv @@ -8,19 +8,109 @@ # OpenRouter API key OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") -# Council members - list of OpenRouter model identifiers +# Wellness council members - 5 specialized professional roles COUNCIL_MODELS = [ - "openai/gpt-5.1", - "google/gemini-3-pro-preview", - "anthropic/claude-sonnet-4.5", - "x-ai/grok-4", + "anthropic/claude-sonnet-4.5", # Therapist + "openai/gpt-5.1", # Psychiatrist + "google/gemini-3-pro-preview", # Personal Trainer + "x-ai/grok-4", # Doctor (GP) + "meta-llama/llama-3.1-70b-instruct", # Psychologist ] -# Chairman model - synthesizes final response -CHAIRMAN_MODEL = "google/gemini-3-pro-preview" +# Define professional roles for each model +ROLE_PROMPTS = { + "anthropic/claude-sonnet-4.5": """You are a licensed therapist specializing in cognitive-behavioral therapy (CBT), emotional processing, and talk therapy. + +Focus on: +- Identifying and reframing cognitive distortions and negative thought patterns +- Emotional validation and creating safe space for feelings +- Building healthy coping strategies and resilience +- Exploring relationship dynamics and communication patterns +- Therapeutic techniques like journaling, mindfulness, grounding exercises + +Approach: Compassionate, non-judgmental, focused on emotional insight and behavioral change through talk therapy.""", + + "openai/gpt-5.1": """You are a board-certified psychiatrist with expertise in mental health disorders, psychopharmacology, and clinical diagnosis. + +Focus on: +- Clinical assessment using DSM-5 criteria +- Differential diagnosis of mental health conditions +- Medication options and pharmacological interventions when appropriate +- Neurobiological and genetic factors in mental health +- Identifying when medical intervention is necessary +- Comorbidities and complex cases + +Approach: Medical/clinical lens with compassion, evidence-based medicine, risk assessment.""", + + "google/gemini-3-pro-preview": """You are a certified personal trainer and nutrition specialist with expertise in fitness, body composition, and physical wellness. + +Focus on: +- Exercise programming and movement for mental health +- Body composition, fitness goals, and realistic physical expectations +- Nutrition and its impact on mood and energy +- Building sustainable healthy habits around physical activity +- Body positivity and healthy relationship with exercise +- Physical activity as mental health intervention + +Approach: Encouraging, body-positive, focused on health over appearance, science-based fitness.""", + + "x-ai/grok-4": """You are a general practitioner (family medicine doctor) with holistic health expertise. + +Focus on: +- Ruling out underlying medical conditions (thyroid, hormonal, metabolic) +- Physical symptoms that may affect mental/emotional health +- Lifestyle factors: sleep, nutrition, substance use +- Preventive care and health screening +- When to refer to specialists +- Mind-body connection and physical health's impact on wellbeing + +Approach: Holistic, practical, focused on physical health screening and lifestyle medicine.""", + + "meta-llama/llama-3.1-70b-instruct": """You are a clinical psychologist with a PhD in behavioral science and research expertise. + +Focus on: +- Evidence-based psychological interventions (CBT, DBT, ACT, etc.) +- Behavioral analysis and reinforcement patterns +- Research-backed techniques for behavior change +- Psychological assessment and measurement +- Cognitive science and how thoughts shape experience +- Long-term behavior modification strategies + +Approach: Scientific, research-oriented, evidence-based practice, focused on measurable interventions.""" +} + +# Human-readable role names for UI display +ROLE_NAMES = { + "anthropic/claude-sonnet-4.5": "Therapist", + "openai/gpt-5.1": "Psychiatrist", + "google/gemini-3-pro-preview": "Personal Trainer", + "x-ai/grok-4": "Doctor (GP)", + "meta-llama/llama-3.1-70b-instruct": "Psychologist" +} + +# Chairman model - integrative wellness coordinator +CHAIRMAN_MODEL = "anthropic/claude-sonnet-4.5" # OpenRouter API endpoint OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions" # Data directory for conversation storage DATA_DIR = "data/conversations" + +# Crisis keywords for safety detection +CRISIS_KEYWORDS = [ + "suicide", "suicidal", "kill myself", "end my life", "want to die", + "self-harm", "cutting", "hurting myself", + "eating disorder", "anorexia", "bulimia", "starving", + "abuse", "being abused", "domestic violence", + "psychosis", "hearing voices", "hallucinations", + "overdose", "pills" +] + +# Medical disclaimer text +MEDICAL_DISCLAIMER = """⚠️ IMPORTANT MEDICAL DISCLAIMER: +This is an AI-powered wellness reflection tool for educational and self-exploration purposes only. +This is NOT medical advice, therapy, or professional healthcare. +Always consult licensed healthcare professionals for medical, mental health, or wellness concerns. +If you're in crisis, please contact emergency services or a crisis hotline immediately. +""" diff --git a/backend/council.py b/backend/council.py index 5069abec9..196cad53e 100644 --- a/backend/council.py +++ b/backend/council.py @@ -1,32 +1,70 @@ -"""3-stage LLM Council orchestration.""" +"""3-stage Wellness Council orchestration.""" from typing import List, Dict, Any, Tuple -from .openrouter import query_models_parallel, query_model -from .config import COUNCIL_MODELS, CHAIRMAN_MODEL +from .openrouter import query_model +from .config import ( + COUNCIL_MODELS, CHAIRMAN_MODEL, ROLE_PROMPTS, ROLE_NAMES, + MEDICAL_DISCLAIMER, CRISIS_KEYWORDS +) +import asyncio -async def stage1_collect_responses(user_query: str) -> List[Dict[str, Any]]: +def check_for_crisis(user_query: str) -> bool: """ - Stage 1: Collect individual responses from all council models. + Detect if query contains crisis indicators requiring immediate intervention. Args: user_query: The user's question Returns: - List of dicts with 'model' and 'response' keys + True if crisis keywords detected, False otherwise """ - messages = [{"role": "user", "content": user_query}] + query_lower = user_query.lower() + return any(keyword in query_lower for keyword in CRISIS_KEYWORDS) - # Query all models in parallel - responses = await query_models_parallel(COUNCIL_MODELS, messages) - # Format results +async def stage1_collect_responses(user_query: str) -> List[Dict[str, Any]]: + """ + Stage 1: Collect individual responses from wellness professionals. + + Args: + user_query: The user's wellness question/concern + + Returns: + List of dicts with 'model', 'response', and 'role' keys + """ + # Prepend disclaimer to user query + query_with_disclaimer = f"""{MEDICAL_DISCLAIMER} + +User's Question/Concern: +{user_query} + +Please provide your professional perspective on this concern.""" + stage1_results = [] - for model, response in responses.items(): + + # Query each model with its specific professional role + tasks = [] + for model in COUNCIL_MODELS: + role_context = ROLE_PROMPTS.get(model, "") + + messages = [ + {"role": "system", "content": role_context}, + {"role": "user", "content": query_with_disclaimer} + ] + + tasks.append(query_model(model, messages)) + + # Wait for all responses + responses = await asyncio.gather(*tasks) + + # Format results with role information + for model, response in zip(COUNCIL_MODELS, responses): if response is not None: # Only include successful responses stage1_results.append({ "model": model, - "response": response.get('content', '') + "response": response.get('content', ''), + "role": ROLE_NAMES.get(model, "Health Professional") }) return stage1_results @@ -61,17 +99,24 @@ async def stage2_collect_rankings( for label, result in zip(labels, stage1_results) ]) - ranking_prompt = f"""You are evaluating different responses to the following question: + ranking_prompt = f"""You are a healthcare professional conducting peer review of wellness recommendations. -Question: {user_query} +User's Concern: {user_query} -Here are the responses from different models (anonymized): +Here are responses from different healthcare professionals (anonymized for unbiased review): {responses_text} -Your task: -1. First, evaluate each response individually. For each response, explain what it does well and what it does poorly. -2. Then, at the very end of your response, provide a final ranking. +Your task as a healthcare professional: +1. First, evaluate each response individually. For each response, consider: + - Appropriateness and safety of the advice given + - Whether important medical/psychological factors were considered + - Potential risks, contraindications, or red flags + - Completeness of the professional perspective + - Evidence-based quality and practical applicability + - Compassion and person-centered approach + +2. Then, at the very end of your response, provide your FINAL RANKING of which responses would be most helpful and safe for this person. IMPORTANT: Your final ranking MUST be formatted EXACTLY as follows: - Start with the line "FINAL RANKING:" (all caps, with colon) @@ -79,34 +124,42 @@ async def stage2_collect_rankings( - Each line should be: number, period, space, then ONLY the response label (e.g., "1. Response A") - Do not add any other text or explanations in the ranking section -Example of the correct format for your ENTIRE response: +Example format: -Response A provides good detail on X but misses Y... -Response B is accurate but lacks depth on Z... -Response C offers the most comprehensive answer... +Response A provides compassionate insight into emotional factors but may miss underlying medical considerations... +Response B offers evidence-based interventions and appropriately addresses safety concerns... +Response C takes a holistic approach but could be more specific... FINAL RANKING: -1. Response C -2. Response A -3. Response B +1. Response B +2. Response C +3. Response A -Now provide your evaluation and ranking:""" +Now provide your peer evaluation and ranking:""" - messages = [{"role": "user", "content": ranking_prompt}] + # Get rankings from all council models in parallel, each with their professional role + tasks = [] + for model in COUNCIL_MODELS: + role_context = ROLE_PROMPTS.get(model, "") + messages = [ + {"role": "system", "content": role_context}, + {"role": "user", "content": ranking_prompt} + ] + tasks.append(query_model(model, messages)) - # Get rankings from all council models in parallel - responses = await query_models_parallel(COUNCIL_MODELS, messages) + responses = await asyncio.gather(*tasks) # Format results stage2_results = [] - for model, response in responses.items(): + for model, response in zip(COUNCIL_MODELS, responses): if response is not None: full_text = response.get('content', '') parsed = parse_ranking_from_text(full_text) stage2_results.append({ "model": model, "ranking": full_text, - "parsed_ranking": parsed + "parsed_ranking": parsed, + "role": ROLE_NAMES.get(model, "Health Professional") }) return stage2_results, label_to_model @@ -139,22 +192,37 @@ async def stage3_synthesize_final( for result in stage2_results ]) - chairman_prompt = f"""You are the Chairman of an LLM Council. Multiple AI models have provided responses to a user's question, and then ranked each other's responses. + chairman_prompt = f"""You are an Integrative Wellness Coordinator synthesizing input from a multidisciplinary healthcare team. + +{MEDICAL_DISCLAIMER} -Original Question: {user_query} +User's Concern: {user_query} -STAGE 1 - Individual Responses: +PROFESSIONAL PERSPECTIVES (Stage 1): {stage1_text} -STAGE 2 - Peer Rankings: +PEER EVALUATIONS (Stage 2): {stage2_text} -Your task as Chairman is to synthesize all of this information into a single, comprehensive, accurate answer to the user's original question. Consider: -- The individual responses and their insights -- The peer rankings and what they reveal about response quality -- Any patterns of agreement or disagreement +Your task as Integrative Wellness Coordinator: +Synthesize all professional perspectives into a holistic, compassionate wellness recommendation that: + +1. **Safety First**: Flag any medical red flags or concerns requiring immediate professional intervention +2. **Integrative Approach**: Combine physical, mental, emotional, and behavioral health dimensions +3. **Actionable Steps**: Provide clear, practical next steps the person can take +4. **Professional Care**: Emphasize when and why to seek specific professional help +5. **Evidence-Based**: Prioritize interventions with research support +6. **Person-Centered**: Be compassionate, non-judgmental, and empowering +7. **Patterns of Agreement**: Highlight where multiple professionals agree (strong signal) +8. **Balanced Perspective**: Address different viewpoints respectfully -Provide a clear, well-reasoned final answer that represents the council's collective wisdom:""" +Structure your response as: +- **Key Insights**: What the council collectively understands about this concern +- **Recommended Approach**: Integrated action plan combining perspectives +- **Important Considerations**: Safety concerns, when to seek professional help, what to monitor +- **Next Steps**: Specific, actionable recommendations + +Provide your integrative wellness recommendation:""" messages = [{"role": "user", "content": chairman_prompt}] @@ -295,31 +363,34 @@ async def generate_conversation_title(user_query: str) -> str: async def run_full_council(user_query: str) -> Tuple[List, List, Dict, Dict]: """ - Run the complete 3-stage council process. + Run the complete 3-stage wellness council process. Args: - user_query: The user's question + user_query: The user's wellness question/concern Returns: Tuple of (stage1_results, stage2_results, stage3_result, metadata) """ - # Stage 1: Collect individual responses + # Check for crisis keywords + is_crisis = check_for_crisis(user_query) + + # Stage 1: Collect individual responses from wellness professionals stage1_results = await stage1_collect_responses(user_query) # If no models responded successfully, return error if not stage1_results: return [], [], { "model": "error", - "response": "All models failed to respond. Please try again." - }, {} + "response": "All wellness professionals failed to respond. Please try again." + }, {"is_crisis": is_crisis} - # Stage 2: Collect rankings + # Stage 2: Collect peer rankings stage2_results, label_to_model = await stage2_collect_rankings(user_query, stage1_results) # Calculate aggregate rankings aggregate_rankings = calculate_aggregate_rankings(stage2_results, label_to_model) - # Stage 3: Synthesize final answer + # Stage 3: Synthesize final wellness recommendation stage3_result = await stage3_synthesize_final( user_query, stage1_results, @@ -329,7 +400,8 @@ async def run_full_council(user_query: str) -> Tuple[List, List, Dict, Dict]: # Prepare metadata metadata = { "label_to_model": label_to_model, - "aggregate_rankings": aggregate_rankings + "aggregate_rankings": aggregate_rankings, + "is_crisis": is_crisis } return stage1_results, stage2_results, stage3_result, metadata diff --git a/frontend/index.html b/frontend/index.html index c20fbd3a7..522138dd8 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,7 +4,8 @@ - frontend + + Wellness Council - Multidisciplinary AI Wellness Tool
diff --git a/frontend/src/components/ChatInterface.jsx b/frontend/src/components/ChatInterface.jsx index 3ae796caa..3c867fc56 100644 --- a/frontend/src/components/ChatInterface.jsx +++ b/frontend/src/components/ChatInterface.jsx @@ -3,6 +3,8 @@ import ReactMarkdown from 'react-markdown'; import Stage1 from './Stage1'; import Stage2 from './Stage2'; import Stage3 from './Stage3'; +import MedicalDisclaimer from './MedicalDisclaimer'; +import CrisisResources from './CrisisResources'; import './ChatInterface.css'; export default function ChatInterface({ @@ -41,8 +43,10 @@ export default function ChatInterface({ return (
-

Welcome to LLM Council

-

Create a new conversation to get started

+

Welcome to Wellness Council

+

A multidisciplinary AI wellness reflection tool

+ +

Create a new conversation to get started

); @@ -53,67 +57,74 @@ export default function ChatInterface({
{conversation.messages.length === 0 ? (
-

Start a conversation

-

Ask a question to consult the LLM Council

+

Wellness Council

+

Share your wellness concerns to receive multidisciplinary perspectives

+
) : ( - conversation.messages.map((msg, index) => ( -
- {msg.role === 'user' ? ( -
-
You
-
-
- {msg.content} + <> + + {conversation.messages.map((msg, index) => ( +
+ {msg.role === 'user' ? ( +
+
You
+
+
+ {msg.content} +
-
- ) : ( -
-
LLM Council
+ ) : ( +
+
Wellness Council
- {/* Stage 1 */} - {msg.loading?.stage1 && ( -
-
- Running Stage 1: Collecting individual responses... -
- )} - {msg.stage1 && } + {/* Crisis Resources */} + {msg.metadata?.is_crisis && } - {/* Stage 2 */} - {msg.loading?.stage2 && ( -
-
- Running Stage 2: Peer rankings... -
- )} - {msg.stage2 && ( - - )} + {/* Stage 1 */} + {msg.loading?.stage1 && ( +
+
+ Gathering professional perspectives... +
+ )} + {msg.stage1 && } - {/* Stage 3 */} - {msg.loading?.stage3 && ( -
-
- Running Stage 3: Final synthesis... -
- )} - {msg.stage3 && } -
- )} -
- )) + {/* Stage 2 */} + {msg.loading?.stage2 && ( +
+
+ Conducting peer review... +
+ )} + {msg.stage2 && ( + + )} + + {/* Stage 3 */} + {msg.loading?.stage3 && ( +
+
+ Synthesizing integrative recommendation... +
+ )} + {msg.stage3 && } +
+ )} +
+ ))} + )} {isLoading && (
- Consulting the council... + Consulting wellness professionals...
)} @@ -124,7 +135,7 @@ export default function ChatInterface({