From c3506d20288fc81259abacf88e736974b361b746 Mon Sep 17 00:00:00 2001 From: Tyrrnien81 Date: Wed, 9 Jul 2025 22:51:50 -0500 Subject: [PATCH] feat: Phase 4 Enhanced AI Coaching & Crisis Detection Documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✨ Phase 4 Features Documented: - Crisis Detection System (score < 0.2 auto-detection) - University Resources Integration (9 UW-Madison resources) - Enhanced Coaching Content (professional messaging) - Emergency Response System (fast-mode for crisis) πŸ“š Documentation Updates: - apps/server/README.md: Crisis detection API guide - docs/postman/API-Testing-Guide.md: Phase 4 testing scenarios - docs/postman/Frontend-Integration-Examples.md: React Native integration - Enhanced OptimizedCoachingService with university resources 🚨 Crisis Features: - Automatic emergency resource prioritization - Professional crisis messaging - React Native crisis UI components - Comprehensive testing validation πŸ₯ University Resources: - 3 Counseling services (UHS Mental Health, Individual, Training Clinic) - 3 Meditation resources (UW Classes, Healthy Minds, Health Program) - 3 Emergency resources (Get Help Now, Emergency Procedures, Police) πŸ“± Frontend Integration: - Crisis detection components and styling - Resource categorization and prioritization - Enhanced breathing exercise animations - Professional messaging with sentiment-based theming πŸ§ͺ Testing Coverage: - Crisis detection validation scripts - Resource availability checking - Professional messaging tone validation - Emergency response time testing All content verified in English-only as per project requirements. --- apps/server/README.md | 129 ++++ .../src/services/optimizedCoachingService.ts | 381 +++++++--- docs/postman/API-Testing-Guide.md | 306 +++++++- docs/postman/Frontend-Integration-Examples.md | 666 ++++++++++++++++++ 4 files changed, 1402 insertions(+), 80 deletions(-) create mode 100644 docs/postman/Frontend-Integration-Examples.md diff --git a/apps/server/README.md b/apps/server/README.md index 752bbcb..8f79049 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -307,6 +307,135 @@ model StressLog { --- +## 🚨 Phase 4: Enhanced AI Coaching & Crisis Detection + +### Crisis Detection System + +The API now includes automatic crisis detection for severe negative emotional states: + +#### Crisis Detection Logic + +```typescript +// Crisis is detected when: +const isCrisis = sentiment.score < 0.2 && sentiment.label === 'negative'; +``` + +**When crisis is detected:** + +- Emergency resources are prioritized first +- Professional crisis messaging is provided +- Fast coaching mode is automatically used for immediate response +- Additional safety checks are logged + +#### Crisis Response Example + +```json +{ + "coaching": { + "motivationalMessage": "Your feelings are valid and important. You don't have to face this alone. Please reach out to the emergency resources listed below or call 911 if you're in immediate danger. Professional support is available 24/7 to help you through this difficult time.", + "resources": [ + { + "title": "Student Affairs – Get Help Now", + "description": "Quick access page for immediate help in emergencies, including medical, mental health, or safety crises. Directs to 911 and campus resources.", + "url": "https://students.wisc.edu/guides/get-help-now/", + "category": "emergency" + }, + { + "title": "UHS Mental Health Services", + "description": "Provides free and confidential mental health services for students, including individual, group, and couples counseling, crisis support, and mental health management.", + "url": "https://www.uhs.wisc.edu/mental-health/", + "category": "counseling" + } + ] + } +} +``` + +### University Resources Integration + +**Real UW-Madison Mental Health Resources (9 total):** + +#### Counseling Services (3) + +- **UHS Mental Health Services** - Free confidential services +- **UHS Individual Counseling** - One-on-one professional support +- **Counseling Psychology Training Clinic** - Low-cost community services + +#### Mindfulness & Meditation (3) + +- **UW Mindfulness & Meditation Classes** - Campus recreation center classes +- **Center for Healthy Minds** - Free guided meditations and apps +- **UW Health Mindfulness Program** - Clinical mindfulness programs + +#### Emergency Resources (3) + +- **Student Affairs – Get Help Now** - Crisis emergency access +- **UW–Madison Emergency Procedures** - Campus emergency protocols +- **Emergency Management – UW Police** - Crisis response and training + +### Intelligent Resource Selection + +The API automatically selects appropriate resources based on emotional state: + +| Sentiment Score | Label | Selected Resources | User Experience | +| --------------- | -------- | --------------------------- | ------------------------------ | +| < 0.2 | negative | **Emergency + Counseling** | Crisis intervention priority | +| 0.2 - 0.4 | negative | **Counseling + Meditation** | Professional support focus | +| 0.4 - 0.6 | neutral | **Meditation + Preventive** | Proactive wellness maintenance | +| > 0.6 | positive | **Meditation + Growth** | Positive state reinforcement | + +### Enhanced Coaching Content + +#### Professional Breathing Exercises + +- **4-7-8 Stress Relief Breathing** - Clinical anxiety reduction technique +- **Mindful Daily Breathing** - Meditation-based awareness practice +- **Energy Enhancement Breathing** - Positive state amplification + +#### Therapeutic Stretch Instructions + +- **Tension Relief Stretches** - Physical stress release techniques +- **Energizing Workplace Stretches** - Productivity and focus improvement +- **Vitality Flow Stretches** - Positive energy cultivation + +### API Response Changes for Frontend + +**New Resource Categories:** + +```typescript +type ResourceCategory = 'counseling' | 'meditation' | 'emergency'; +``` + +**Enhanced Motivational Messages:** + +- Crisis-safe language for emergency situations +- Professional tone matching emotional severity +- Empathetic acknowledgment of user feelings + +**Example Integration Code:** + +```typescript +// Check for crisis response +if (response.data.sentiment.score < 0.2 && response.data.sentiment.label === 'negative') { + // Handle crisis UI - show emergency resources prominently + showEmergencyAlert(response.data.coaching.resources); + + // Use crisis-specific styling + applyEmergencyTheme(); +} + +// Resource categorization for UI +const emergencyResources = response.data.coaching.resources.filter(r => r.category === 'emergency'); +const counselingResources = response.data.coaching.resources.filter( + r => r.category === 'counseling' +); +const meditationResources = response.data.coaching.resources.filter( + r => r.category === 'meditation' +); +``` + +--- + ## 🚨 Error Handling ### Common Error Codes diff --git a/apps/server/src/services/optimizedCoachingService.ts b/apps/server/src/services/optimizedCoachingService.ts index f8690ee..45661d3 100644 --- a/apps/server/src/services/optimizedCoachingService.ts +++ b/apps/server/src/services/optimizedCoachingService.ts @@ -10,100 +10,242 @@ export class OptimizedCoachingService { }); } - // Cached coaching messages (ultra-fast response) + // University of Wisconsin-Madison Mental Health Resources + private static readonly UNIVERSITY_RESOURCES = { + counseling: [ + { + title: 'UHS Mental Health Services', + description: + 'Provides free and confidential mental health services for students, including individual, group, and couples counseling, crisis support, and mental health management.', + url: 'https://www.uhs.wisc.edu/mental-health/', + category: 'counseling' as const, + }, + { + title: 'UHS Individual Counseling', + description: + 'Offers short-term and ongoing confidential counseling for a wide range of concerns including emotional, interpersonal, and academic issues.', + url: 'https://www.uhs.wisc.edu/mental-health/individual/', + category: 'counseling' as const, + }, + { + title: 'Counseling Psychology Training Clinic', + description: + 'Located in the Department of Educational Psychology, this clinic provides low-cost individual, couples, family, and group counseling to students and the community.', + url: 'https://counselingpsych.education.wisc.edu/cp/outreach-clinic/training-clinic/about-cptc', + category: 'counseling' as const, + }, + ], + meditation: [ + { + title: 'UW Mindfulness & Meditation Classes', + description: + 'Offers mindfulness and meditation classes at the Nicholas Recreation Center and Bakke Recreation & Wellbeing Center, including guided meditation and relaxation sessions.', + url: 'https://recwell.wisc.edu/mindfulness/', + category: 'meditation' as const, + }, + { + title: 'Center for Healthy Minds – Mindfulness Resources', + description: + 'Provides free guided meditations, mindfulness audio resources, and recommended apps such as Healthy Minds Program and Insight Timer.', + url: 'https://cultivatingjustice.chm.wisc.edu/resources/', + category: 'meditation' as const, + }, + { + title: 'UW Health Mindfulness Program', + description: + 'Offers mindfulness and meditation programs through the UW Integrative Health Clinic, with online resources and guided practices.', + url: 'https://www.fammed.wisc.edu/aware-medicine/mindfulness/resources/', + category: 'meditation' as const, + }, + ], + emergency: [ + { + title: 'Student Affairs – Get Help Now', + description: + 'Quick access page for immediate help in emergencies, including medical, mental health, or safety crises. Directs to 911 and campus resources.', + url: 'https://students.wisc.edu/guides/get-help-now/', + category: 'emergency' as const, + }, + { + title: 'UW–Madison Emergency Procedures', + description: + 'Guides students and staff on what to do in any emergency, including when to call 911 and campus-specific emergency protocols.', + url: 'https://ehs.wisc.edu/emergencies/', + category: 'emergency' as const, + }, + { + title: 'Emergency Management – UW Police', + description: + 'Provides information and training on campus emergency preparedness, crisis response, CPR/AED, and active threat response.', + url: 'https://uwpd.wisc.edu/services/emergency-management/', + category: 'emergency' as const, + }, + ], + }; + + /** + * Intelligent resource selection based on sentiment and crisis detection + */ + private selectAppropriateResources( + sentiment: SentimentResult + ): CoachingResponse['resources'] { + const { score, label } = sentiment; + + // Crisis detection: Very low sentiment score indicates potential emergency + const isCrisisSituation = score < 0.2 && label === 'negative'; + + if (isCrisisSituation) { + // Emergency situation: Provide immediate crisis resources + return [ + OptimizedCoachingService.UNIVERSITY_RESOURCES.emergency[0], // Get Help Now - priority + OptimizedCoachingService.UNIVERSITY_RESOURCES.counseling[0], // UHS Mental Health Services + OptimizedCoachingService.UNIVERSITY_RESOURCES.emergency[1], // Emergency Procedures + ]; + } + + switch (label) { + case 'negative': + // Moderate negative: counseling + meditation support + return [ + OptimizedCoachingService.UNIVERSITY_RESOURCES.counseling[0], // UHS Mental Health Services + OptimizedCoachingService.UNIVERSITY_RESOURCES.counseling[1], // Individual Counseling + OptimizedCoachingService.UNIVERSITY_RESOURCES.meditation[0], // Mindfulness Classes + ]; + + case 'neutral': + // Neutral: proactive mental health maintenance + return [ + OptimizedCoachingService.UNIVERSITY_RESOURCES.meditation[0], // Mindfulness Classes + OptimizedCoachingService.UNIVERSITY_RESOURCES.meditation[1], // Center for Healthy Minds + OptimizedCoachingService.UNIVERSITY_RESOURCES.counseling[2], // Training Clinic (preventive) + ]; + + case 'positive': + // Positive: maintain wellbeing and growth + return [ + OptimizedCoachingService.UNIVERSITY_RESOURCES.meditation[1], // Center for Healthy Minds + OptimizedCoachingService.UNIVERSITY_RESOURCES.meditation[2], // UW Health Mindfulness + OptimizedCoachingService.UNIVERSITY_RESOURCES.meditation[0], // Mindfulness Classes + ]; + + default: + // Fallback to counseling resources + return OptimizedCoachingService.UNIVERSITY_RESOURCES.counseling; + } + } + + /** + * Crisis-aware motivational message generation + */ + private generateMotivationalMessage( + sentiment: SentimentResult, + isCrisis: boolean = false + ): string { + const { score, label } = sentiment; + + if (isCrisis) { + return "Your feelings are valid and important. You don't have to face this alone. Please reach out to the emergency resources listed below or call 911 if you're in immediate danger. Professional support is available 24/7 to help you through this difficult time."; + } + + switch (label) { + case 'negative': + if (score < 0.3) { + return "I hear that you're going through a tough time right now. These feelings are temporary, and seeking support is a sign of strength. The counseling resources below can provide professional guidance tailored to your needs."; + } else { + return "It's completely normal to have challenging moments. Remember that you have the resilience to work through this, and support is always available when you need it."; + } + + case 'neutral': + return 'Thank you for taking time to check in with yourself. This self-awareness is an important step in maintaining your mental wellbeing. The mindfulness resources below can help you build emotional resilience.'; + + case 'positive': + return "It's wonderful to hear that you're feeling positive! Continue nurturing this wellbeing through the mindfulness practices below, which can help you maintain and build upon these good feelings."; + + default: + return 'Taking time for self-care and reflection is always valuable. The resources below can support your continued growth and wellbeing.'; + } + } + + // Enhanced cached coaching responses with university resources private static readonly CACHED_COACHING = { negative: { breathingExercise: { - title: '5-Minute Stress Relief Breathing', + title: '4-7-8 Stress Relief Breathing', instructions: [ - 'Sit comfortably and close your eyes', - 'Breathe in slowly for 4 seconds', - 'Hold your breath for 7 seconds', - 'Exhale slowly for 8 seconds', - 'Repeat 4 times', + 'Find a quiet, comfortable position', + 'Inhale through your nose for 4 counts', + 'Hold your breath for 7 counts', + 'Exhale completely through your mouth for 8 counts', + 'Repeat this cycle 4 times', + 'Focus on the calming rhythm', ], duration: 5, }, - motivationalMessage: - "It's tough right now, but you're doing well enough. Taking it one step at a time, everything will be okay.", stretchExercise: { title: 'Tension Relief Stretches', instructions: [ - 'Slowly roll your neck and shoulders', - 'Stretch your arms up and down', - 'Take deep breaths and release tension', + 'Sit up straight and drop your shoulders', + 'Gently tilt your head to each side (hold 15 seconds)', + 'Roll your shoulders backward 5 times', + 'Stretch your arms across your chest and hold', + 'Take deep breaths throughout each stretch', ], }, - resources: [ - { - title: 'University Counseling Center', - description: 'Professional counseling services', - url: 'https://counseling.university.edu', - category: 'counseling' as const, - }, - ], + // Resources will be dynamically selected based on crisis detection + resources: [], // Will be populated by selectAppropriateResources() + motivationalMessage: '', // Will be generated by generateMotivationalMessage() }, neutral: { breathingExercise: { - title: 'Daily Management Breathing', + title: 'Mindful Daily Breathing', instructions: [ - 'Sit in a comfortable position', - 'Breathe in naturally', - 'Pause briefly and release tension', - 'Exhale slowly', - 'Repeat for 3 minutes', + 'Sit comfortably with your back straight', + 'Close your eyes or soften your gaze', + 'Breathe naturally without forcing', + 'Notice the sensation of each breath', + 'When your mind wanders, gently return focus to breathing', + 'Continue for 3-5 minutes', ], - duration: 3, + duration: 4, }, - motivationalMessage: - 'Cherish this moment. Your efforts will create good results.', stretchExercise: { - title: 'Energy Recharge Stretches', + title: 'Energizing Workplace Stretches', instructions: [ - 'Turn your neck left and right', - 'Raise and lower your shoulders', - 'Stretch your arms to relax your body', + 'Stand up and stretch your arms overhead', + 'Gently twist your torso left and right', + 'Do 10 neck rolls in each direction', + 'Stretch your wrists and ankles', + 'Take 3 deep breaths to center yourself', ], }, - resources: [ - { - title: 'Mindfulness Meditation', - description: 'Daily stress management', - url: 'https://meditation.com', - category: 'meditation' as const, - }, - ], + resources: [], // Will be populated dynamically + motivationalMessage: '', // Will be generated dynamically }, positive: { breathingExercise: { - title: 'Energy Maintenance Breathing', + title: 'Energy Enhancement Breathing', instructions: [ - 'Take a deep breath', - 'Feel the positive energy', - 'Exhale slowly', - 'Maintain this good feeling', - 'Repeat for 2 minutes', + 'Stand tall with your feet hip-width apart', + 'Inhale deeply while raising your arms up', + 'Hold for 3 seconds and feel the positive energy', + 'Exhale slowly while lowering your arms', + 'Smile and repeat 5 times', + 'Carry this energy forward', ], - duration: 2, + duration: 3, }, - motivationalMessage: - "You're doing really well! Keep maintaining this positive energy.", stretchExercise: { - title: 'Vitality Boost Stretches', + title: 'Vitality Flow Stretches', instructions: [ - 'Stretch your arms high up', - 'Lean your body left and right', - 'Feel the positive energy throughout your body', + 'Stand and reach your arms up high', + 'Side bend gently to the left and right', + 'Do gentle spinal twists', + 'Reach forward and back mindfully', + 'End with arms wide open, embracing positivity', ], }, - resources: [ - { - title: 'Achievement Maintenance Tips', - description: 'Ways to sustain positive state', - url: 'https://wellness.com', - category: 'meditation' as const, - }, - ], + resources: [], // Will be populated dynamically + motivationalMessage: '', // Will be generated dynamically }, }; @@ -114,15 +256,24 @@ export class OptimizedCoachingService { async generateFastCoaching( sentiment: SentimentResult ): Promise { - const { label } = sentiment; + const { label, score } = sentiment; - // Use cached response (instant return) + // Crisis detection + const isCrisisSituation = score < 0.2 && label === 'negative'; + + // Use cached response base const cachedCoaching = OptimizedCoachingService.CACHED_COACHING[label] || OptimizedCoachingService.CACHED_COACHING.neutral; + // Apply intelligent resource selection and messaging return { ...cachedCoaching, + resources: this.selectAppropriateResources(sentiment), + motivationalMessage: this.generateMotivationalMessage( + sentiment, + isCrisisSituation + ), stretchExercise: { title: 'Simple Neck and Shoulder Stretches', instructions: [ @@ -145,59 +296,113 @@ export class OptimizedCoachingService { ): Promise { const { score, label } = sentiment; - // Short and efficient prompt + // Crisis detection + const isCrisisSituation = score < 0.2 && label === 'negative'; + + // For crisis situations, use immediate cached response with emergency resources + if (isCrisisSituation) { + console.log( + '🚨 Crisis situation detected - providing emergency resources' + ); + return this.generateFastCoaching(sentiment); + } + + // Enhanced prompt for personalized coaching const prompt = `Sentiment: ${label} (${score.toFixed(2)}) -Text: "${transcript.substring(0, 100)}..." +User transcript: "${transcript.substring(0, 150)}..." -Return JSON only: +Based on this emotional state, provide supportive coaching in JSON format: { - "motivationalMessage": "English encouragement message (1 sentence)", - "breathingTip": "breathing method (1 line)", - "stretchTip": "stretching (1 line)" -}`; + "motivationalMessage": "Personalized, empathetic message in English (2-3 sentences)", + "breathingTip": "Specific breathing exercise description (1-2 lines)", + "stretchTip": "Helpful stretching or movement suggestion (1-2 lines)" +} + +Guidelines: +- Be supportive and professional +- Acknowledge their feelings +- Provide practical, actionable advice +- Use encouraging but not dismissive language`; try { const completion = await this.openai.chat.completions.create({ - model: 'gpt-4o-mini', // Much faster model + model: 'gpt-4o-mini', messages: [ + { + role: 'system', + content: + 'You are a supportive mental health coach helping college students. Provide empathetic, practical guidance.', + }, { role: 'user', content: prompt, }, ], - temperature: 0.3, // Lower temperature for faster response - max_tokens: 200, // Token limit + temperature: 0.3, + max_tokens: 300, }); const response = JSON.parse( completion.choices[0].message.content || '{}' ); - // Combine with cached structure + // Combine AI response with cached structure and intelligent resources const baseCoaching = OptimizedCoachingService.CACHED_COACHING[label] || OptimizedCoachingService.CACHED_COACHING.neutral; return { ...baseCoaching, + resources: this.selectAppropriateResources(sentiment), motivationalMessage: - response.motivationalMessage || baseCoaching.motivationalMessage, + response.motivationalMessage || + this.generateMotivationalMessage(sentiment, isCrisisSituation), + breathingExercise: { + ...baseCoaching.breathingExercise, + instructions: response.breathingTip + ? response.breathingTip + .split('.') + .filter((tip: string) => tip.trim()) + : baseCoaching.breathingExercise.instructions, + }, + stretchExercise: { + ...baseCoaching.stretchExercise, + instructions: response.stretchTip + ? response.stretchTip.split('.').filter((tip: string) => tip.trim()) + : baseCoaching.stretchExercise.instructions, + }, }; } catch (error) { - console.log(`⚠️ AI coaching failed, using cache: ${error}`); + console.log(`⚠️ AI coaching failed, using enhanced cache: ${error}`); return this.generateFastCoaching(sentiment); } } /** - * Main coaching generation method (compatibility maintained) - * Choose fast approach based on environment + * Main coaching generation method with crisis awareness + * Choose appropriate method based on mode and crisis detection */ async generateCoaching( sentiment: SentimentResult, transcript: string, mode: 'fast' | 'optimized' = 'fast' ): Promise { + const { score, label } = sentiment; + const isCrisisSituation = score < 0.2 && label === 'negative'; + + // Log coaching mode and crisis detection + console.log( + `πŸŽ›οΈ Coaching mode: ${mode} | Crisis detected: ${isCrisisSituation ? 'YES' : 'No'} | Sentiment: ${label} (${score})` + ); + + if (isCrisisSituation) { + // Always use fast mode for crisis situations to ensure immediate response + console.log( + '🚨 Crisis situation - using fast mode for immediate support' + ); + return this.generateFastCoaching(sentiment); + } + if (mode === 'fast') { return this.generateFastCoaching(sentiment); } else { @@ -205,6 +410,24 @@ Return JSON only: } } + /** + * Crisis detection utility method + */ + detectCrisisSituation(sentiment: SentimentResult): boolean { + return sentiment.score < 0.2 && sentiment.label === 'negative'; + } + + /** + * Get crisis-specific resources + */ + getCrisisResources(): CoachingResponse['resources'] { + return [ + OptimizedCoachingService.UNIVERSITY_RESOURCES.emergency[0], // Get Help Now - highest priority + OptimizedCoachingService.UNIVERSITY_RESOURCES.counseling[0], // UHS Mental Health Services + OptimizedCoachingService.UNIVERSITY_RESOURCES.emergency[1], // Emergency Procedures + ]; + } + /** * Performance testing method */ diff --git a/docs/postman/API-Testing-Guide.md b/docs/postman/API-Testing-Guide.md index 1be92cb..d433eb8 100644 --- a/docs/postman/API-Testing-Guide.md +++ b/docs/postman/API-Testing-Guide.md @@ -529,5 +529,309 @@ pm.test('Response has required fields', function () { --- +## 🚨 Phase 4: Crisis Detection & Enhanced Features Testing + +### Crisis Detection Testing Scenarios + +**Test the automatic crisis detection system for severe negative emotions:** + +#### 1. Crisis Situation Test (Score < 0.2) + +**Test Audio Content:** + +``` +"I feel hopeless and like nothing matters anymore. I can't handle this stress and I don't know what to do." +``` + +**Expected Response:** + +```json +{ + "data": { + "sentiment": { + "score": 0.1, + "label": "negative", + "confidence": 0.9 + }, + "coaching": { + "motivationalMessage": "Your feelings are valid and important. You don't have to face this alone...", + "resources": [ + { + "title": "Student Affairs – Get Help Now", + "category": "emergency" + } + ] + } + } +} +``` + +#### 2. Moderate Negative Test (Score 0.2-0.4) + +**Test Audio Content:** + +``` +"I'm feeling stressed about my exams and having trouble sleeping." +``` + +**Expected Response:** + +- Sentiment score: 0.2-0.4 +- Resources: Mix of counseling and meditation +- No emergency resources prioritized + +#### 3. Neutral State Test (Score 0.4-0.6) + +**Test Audio Content:** + +``` +"Today was okay, nothing special happened but I feel alright." +``` + +**Expected Response:** + +- Sentiment score: 0.4-0.6 +- Resources: Mindfulness and preventive counseling +- Proactive wellness focus + +#### 4. Positive State Test (Score > 0.6) + +**Test Audio Content:** + +``` +"I had a great day today! Finished my project and feeling accomplished." +``` + +**Expected Response:** + +- Sentiment score: > 0.6 +- Resources: Wellness maintenance and growth +- Positive reinforcement messaging + +### University Resources Verification + +**Validate that all 9 UW-Madison resources are properly integrated:** + +#### Resource Categories to Verify + +**1. Counseling Services (3 resources):** + +```json +[ + { + "title": "UHS Mental Health Services", + "url": "https://www.uhs.wisc.edu/mental-health/", + "category": "counseling" + }, + { + "title": "UHS Individual Counseling", + "url": "https://www.uhs.wisc.edu/mental-health/individual/", + "category": "counseling" + }, + { + "title": "Counseling Psychology Training Clinic", + "url": "https://counselingpsych.education.wisc.edu/cp/outreach-clinic/training-clinic/about-cptc", + "category": "counseling" + } +] +``` + +**2. Meditation Resources (3 resources):** + +```json +[ + { + "title": "UW Mindfulness & Meditation Classes", + "url": "https://recwell.wisc.edu/mindfulness/", + "category": "meditation" + }, + { + "title": "Center for Healthy Minds – Mindfulness Resources", + "url": "https://cultivatingjustice.chm.wisc.edu/resources/", + "category": "meditation" + }, + { + "title": "UW Health Mindfulness Program", + "url": "https://www.fammed.wisc.edu/aware-medicine/mindfulness/resources/", + "category": "meditation" + } +] +``` + +**3. Emergency Resources (3 resources):** + +```json +[ + { + "title": "Student Affairs – Get Help Now", + "url": "https://students.wisc.edu/guides/get-help-now/", + "category": "emergency" + }, + { + "title": "UW–Madison Emergency Procedures", + "url": "https://ehs.wisc.edu/emergencies/", + "category": "emergency" + }, + { + "title": "Emergency Management – UW Police", + "url": "https://uwpd.wisc.edu/services/emergency-management/", + "category": "emergency" + } +] +``` + +### Resource Selection Validation Tests + +#### Crisis Response Test Script + +```javascript +// Postman Test Script for Crisis Detection +pm.test('Crisis detection works correctly', function () { + const responseJson = pm.response.json(); + const sentiment = responseJson.data.sentiment; + const resources = responseJson.data.coaching.resources; + + if (sentiment.score < 0.2 && sentiment.label === 'negative') { + // Verify emergency resources are included + const emergencyResources = resources.filter(r => r.category === 'emergency'); + pm.expect(emergencyResources.length).to.be.at.least(1); + + // Verify "Get Help Now" is prioritized first + pm.expect(resources[0].title).to.include('Get Help Now'); + + // Verify crisis messaging + const message = responseJson.data.coaching.motivationalMessage; + pm.expect(message).to.include("You don't have to face this alone"); + } +}); +``` + +#### Resource Category Test Script + +```javascript +// Validate all resources have proper categories +pm.test('All resources have valid categories', function () { + const responseJson = pm.response.json(); + const resources = responseJson.data.coaching.resources; + const validCategories = ['counseling', 'meditation', 'emergency']; + + resources.forEach(resource => { + pm.expect(validCategories).to.include(resource.category); + pm.expect(resource.url).to.match(/^https?:\/\//); // Valid URL + pm.expect(resource.title).to.not.be.empty; + pm.expect(resource.description).to.not.be.empty; + }); +}); +``` + +### Enhanced Coaching Content Testing + +#### Professional Messaging Validation + +```javascript +// Test for appropriate messaging tone +pm.test('Professional coaching messaging', function () { + const responseJson = pm.response.json(); + const message = responseJson.data.coaching.motivationalMessage; + const sentiment = responseJson.data.sentiment; + + // Crisis messaging should be supportive and professional + if (sentiment.score < 0.2) { + pm.expect(message).to.include('feelings are valid'); + pm.expect(message).to.not.include('just think positive'); // Avoid dismissive language + } + + // All messages should be encouraging without being dismissive + pm.expect(message).to.not.include('snap out of it'); + pm.expect(message).to.not.include('just get over it'); +}); +``` + +#### Breathing Exercise Enhancement Test + +```javascript +// Validate enhanced breathing exercises +pm.test('Enhanced breathing exercises', function () { + const responseJson = pm.response.json(); + const breathingExercise = responseJson.data.coaching.breathingExercise; + + // Check for professional exercise titles + const professionalTitles = [ + '4-7-8 Stress Relief Breathing', + 'Mindful Daily Breathing', + 'Energy Enhancement Breathing', + ]; + + pm.expect(professionalTitles).to.include(breathingExercise.title); + pm.expect(breathingExercise.instructions.length).to.be.at.least(4); + pm.expect(breathingExercise.duration).to.be.within(2, 6); // 2-6 minutes +}); +``` + +### Performance Testing with Crisis Detection + +#### Crisis Response Time Test + +```javascript +// Verify crisis situations get immediate response +pm.test('Crisis situations get fast response', function () { + const responseJson = pm.response.json(); + const sentiment = responseJson.data.sentiment; + + if (sentiment.score < 0.2 && sentiment.label === 'negative') { + // Crisis should use fast mode (coaching should be near-instant) + pm.expect(pm.response.responseTime).to.be.below(6000); // 6 seconds max + + // Should prioritize speed over personalization in crisis + pm.expect(responseJson.data.coaching.motivationalMessage).to.exist; + } +}); +``` + +### Frontend Integration Testing for Phase 4 + +#### Crisis UI Handling Test + +```javascript +// Example frontend integration for crisis detection +const handleCrisisResponse = response => { + const { sentiment, coaching } = response.data; + + // Check for crisis situation + if (sentiment.score < 0.2 && sentiment.label === 'negative') { + // Show emergency alert UI + showEmergencyAlert(); + + // Filter and prioritize emergency resources + const emergencyResources = coaching.resources.filter(r => r.category === 'emergency'); + displayEmergencyResources(emergencyResources); + + // Apply crisis-specific styling + applyEmergencyTheme(); + + // Log crisis detection for support team + logCrisisDetection(response.data.sessionId); + } +}; +``` + +### Pre-Production Testing Checklist + +**Phase 4 Specific Validations:** + +- [ ] Crisis detection accuracy (score < 0.2 triggers emergency resources) +- [ ] All 9 UW-Madison resources are active and accessible +- [ ] Emergency resources appear first in crisis situations +- [ ] Professional messaging tone in all emotional states +- [ ] Enhanced breathing/stretch exercises are therapeutic +- [ ] Resource categorization is correct (counseling/meditation/emergency) +- [ ] Crisis response time is optimized (fast mode auto-selected) +- [ ] No dismissive language in any coaching messages +- [ ] All resource URLs are valid and accessible +- [ ] Crisis messaging includes professional support guidance + +--- + **πŸ’‘ Pro Tip:** Save successful test requests as examples in your Postman collection for consistent -testing and team collaboration.\*\* +testing and team collaboration. Test crisis scenarios regularly to ensure the safety system works +reliably.\*\* diff --git a/docs/postman/Frontend-Integration-Examples.md b/docs/postman/Frontend-Integration-Examples.md new file mode 100644 index 0000000..7df0bea --- /dev/null +++ b/docs/postman/Frontend-Integration-Examples.md @@ -0,0 +1,666 @@ +# PulseMates Phase 4: Frontend Integration Examples + +> **React Native Integration Guide for Enhanced AI Coaching & Crisis Detection** +> **Phase 4 Features:** Crisis Detection, University Resources, Enhanced Coaching +> **Last Updated:** 2025-01-09 + +--- + +## 🚨 Crisis Detection Integration + +### Crisis Response Handler + +```typescript +// types/api.ts +interface CrisisResponse { + isCrisis: boolean; + emergencyResources: Resource[]; + message: string; + urgencyLevel: 'critical' | 'moderate' | 'low'; +} + +interface Resource { + title: string; + description: string; + url: string; + category: 'counseling' | 'meditation' | 'emergency'; + phoneNumber?: string; +} +``` + +```typescript +// services/crisisDetection.ts +export class CrisisDetectionService { + static detectCrisis(sentiment: any, coaching: any): CrisisResponse { + const isCrisis = sentiment.score < 0.2 && sentiment.label === 'negative'; + + if (isCrisis) { + return { + isCrisis: true, + emergencyResources: coaching.resources.filter(r => r.category === 'emergency'), + message: coaching.motivationalMessage, + urgencyLevel: 'critical', + }; + } + + return { + isCrisis: false, + emergencyResources: [], + message: coaching.motivationalMessage, + urgencyLevel: sentiment.score < 0.4 ? 'moderate' : 'low', + }; + } +} +``` + +### Crisis UI Components + +```tsx +// components/CrisisAlert.tsx +import React from 'react'; +import { View, Text, TouchableOpacity, Alert, Linking } from 'react-native'; + +interface CrisisAlertProps { + visible: boolean; + emergencyResources: Resource[]; + onDismiss: () => void; +} + +export const CrisisAlert: React.FC = ({ + visible, + emergencyResources, + onDismiss, +}) => { + if (!visible) return null; + + const handleEmergencyCall = () => { + Alert.alert( + 'Emergency Support', + "If you're in immediate danger, please call 911. Otherwise, you can reach out to campus resources.", + [ + { text: 'Call 911', onPress: () => Linking.openURL('tel:911') }, + { text: 'Campus Resources', onPress: () => openFirstResource() }, + { text: 'Not Now', style: 'cancel' }, + ] + ); + }; + + const openFirstResource = () => { + if (emergencyResources.length > 0) { + Linking.openURL(emergencyResources[0].url); + } + }; + + return ( + + + 🚨 Emergency Support Available + + Your feelings are important. Professional help is available 24/7. + + + + Get Help Now + + + + Continue + + + + ); +}; +``` + +### Crisis Styling Theme + +```typescript +// styles/crisisTheme.ts +import { StyleSheet } from 'react-native'; + +export const crisisStyles = StyleSheet.create({ + crisisContainer: { + position: 'absolute', + top: 0, + left: 0, + right: 0, + bottom: 0, + backgroundColor: 'rgba(220, 38, 38, 0.95)', // Red overlay + justifyContent: 'center', + alignItems: 'center', + zIndex: 1000, + }, + alertBox: { + backgroundColor: 'white', + margin: 20, + padding: 24, + borderRadius: 12, + borderLeftWidth: 4, + borderLeftColor: '#DC2626', // Red accent + shadowColor: '#000', + shadowOffset: { width: 0, height: 4 }, + shadowOpacity: 0.3, + shadowRadius: 8, + elevation: 8, + }, + crisisTitle: { + fontSize: 20, + fontWeight: 'bold', + color: '#DC2626', + textAlign: 'center', + marginBottom: 12, + }, + crisisMessage: { + fontSize: 16, + color: '#374151', + textAlign: 'center', + lineHeight: 24, + marginBottom: 20, + }, + emergencyButton: { + backgroundColor: '#DC2626', + paddingVertical: 12, + paddingHorizontal: 24, + borderRadius: 8, + marginBottom: 12, + }, + emergencyButtonText: { + color: 'white', + fontSize: 16, + fontWeight: 'bold', + textAlign: 'center', + }, + dismissButton: { + paddingVertical: 8, + paddingHorizontal: 16, + }, + dismissButtonText: { + color: '#6B7280', + fontSize: 14, + textAlign: 'center', + }, +}); +``` + +--- + +## πŸ₯ University Resources Integration + +### Resource Category Manager + +```typescript +// services/resourceManager.ts +export class ResourceManager { + static categorizeResources(resources: Resource[]) { + return { + emergency: resources.filter(r => r.category === 'emergency'), + counseling: resources.filter(r => r.category === 'counseling'), + meditation: resources.filter(r => r.category === 'meditation'), + }; + } + + static prioritizeForSentiment(resources: Resource[], sentimentScore: number) { + if (sentimentScore < 0.2) { + // Crisis: Emergency first, then counseling + return [ + ...this.categorizeResources(resources).emergency, + ...this.categorizeResources(resources).counseling, + ]; + } else if (sentimentScore < 0.4) { + // Negative: Counseling first, then meditation + return [ + ...this.categorizeResources(resources).counseling, + ...this.categorizeResources(resources).meditation, + ]; + } else if (sentimentScore < 0.6) { + // Neutral: Meditation first, then preventive counseling + return [ + ...this.categorizeResources(resources).meditation, + ...this.categorizeResources(resources).counseling, + ]; + } else { + // Positive: Meditation and growth resources + return [...this.categorizeResources(resources).meditation]; + } + } + + static async validateResourceAvailability(resource: Resource): Promise { + try { + const response = await fetch(resource.url, { method: 'HEAD' }); + return response.ok; + } catch { + return false; + } + } +} +``` + +### Resource Display Component + +```tsx +// components/UniversityResources.tsx +import React, { useState, useEffect } from 'react'; +import { View, Text, TouchableOpacity, ScrollView, Linking } from 'react-native'; + +interface UniversityResourcesProps { + resources: Resource[]; + sentimentScore: number; +} + +export const UniversityResources: React.FC = ({ + resources, + sentimentScore, +}) => { + const [prioritizedResources, setPrioritizedResources] = useState([]); + + useEffect(() => { + const prioritized = ResourceManager.prioritizeForSentiment(resources, sentimentScore); + setPrioritizedResources(prioritized); + }, [resources, sentimentScore]); + + const openResource = (resource: Resource) => { + Linking.openURL(resource.url); + }; + + const getCategoryColor = (category: string) => { + switch (category) { + case 'emergency': + return '#DC2626'; // Red + case 'counseling': + return '#2563EB'; // Blue + case 'meditation': + return '#059669'; // Green + default: + return '#6B7280'; // Gray + } + }; + + const getCategoryIcon = (category: string) => { + switch (category) { + case 'emergency': + return '🚨'; + case 'counseling': + return 'πŸ’¬'; + case 'meditation': + return '🧘'; + default: + return 'πŸ”—'; + } + }; + + return ( + + University Resources + + {sentimentScore < 0.2 + ? 'Emergency support is available 24/7' + : sentimentScore < 0.4 + ? 'Professional counseling services' + : sentimentScore < 0.6 + ? 'Mindfulness and wellness resources' + : 'Continue your wellness journey'} + + + + {prioritizedResources.map((resource, index) => ( + openResource(resource)} + > + + {getCategoryIcon(resource.category)} + + {resource.title} + + {resource.category.toUpperCase()} + + + + {resource.description} + + ))} + + + ); +}; +``` + +--- + +## 🎯 Enhanced Coaching Features + +### Professional Breathing Exercise Component + +```tsx +// components/BreathingExercise.tsx +import React, { useState, useEffect } from 'react'; +import { View, Text, TouchableOpacity, Animated } from 'react-native'; + +interface BreathingExerciseProps { + exercise: { + title: string; + instructions: string[]; + duration: number; // in minutes + }; +} + +export const BreathingExercise: React.FC = ({ exercise }) => { + const [isActive, setIsActive] = useState(false); + const [currentStep, setCurrentStep] = useState(0); + const [breathAnimation] = useState(new Animated.Value(1)); + + const startExercise = () => { + setIsActive(true); + setCurrentStep(0); + animateBreathing(); + }; + + const animateBreathing = () => { + const breathCycle = () => { + // Inhale (4 seconds) + Animated.timing(breathAnimation, { + toValue: 1.5, + duration: 4000, + useNativeDriver: true, + }).start(() => { + // Hold (7 seconds) + setTimeout(() => { + // Exhale (8 seconds) + Animated.timing(breathAnimation, { + toValue: 1, + duration: 8000, + useNativeDriver: true, + }).start(() => { + if (isActive) { + setCurrentStep(prev => (prev + 1) % exercise.instructions.length); + breathCycle(); + } + }); + }, 7000); + }); + }; + breathCycle(); + }; + + const stopExercise = () => { + setIsActive(false); + breathAnimation.setValue(1); + }; + + return ( + + {exercise.title} + Duration: {exercise.duration} minutes + + + {exercise.instructions.map((instruction, index) => ( + + {index + 1}. {instruction} + + ))} + + + + + {isActive && ( + + {currentStep < 4 ? 'Breathe slowly' : 'Complete the cycle'} + + )} + + + + + {isActive ? 'Stop Exercise' : 'Start Breathing'} + + + + ); +}; +``` + +### Enhanced Motivational Messaging + +```tsx +// components/MotivationalMessage.tsx +import React from 'react'; +import { View, Text } from 'react-native'; + +interface MotivationalMessageProps { + message: string; + sentimentScore: number; + isCrisis: boolean; +} + +export const MotivationalMessage: React.FC = ({ + message, + sentimentScore, + isCrisis, +}) => { + const getMessageStyle = () => { + if (isCrisis) { + return { + ...styles.messageContainer, + backgroundColor: '#FEF2F2', // Light red background + borderColor: '#DC2626', + }; + } else if (sentimentScore < 0.4) { + return { + ...styles.messageContainer, + backgroundColor: '#F3F4F6', // Light gray background + borderColor: '#6B7280', + }; + } else if (sentimentScore > 0.6) { + return { + ...styles.messageContainer, + backgroundColor: '#F0FDF4', // Light green background + borderColor: '#059669', + }; + } + return styles.messageContainer; + }; + + const getMessageIcon = () => { + if (isCrisis) return '🀝'; + if (sentimentScore < 0.4) return 'πŸ’™'; + if (sentimentScore > 0.6) return '✨'; + return '🌱'; + }; + + return ( + + {getMessageIcon()} + {message} + {isCrisis && ( + + Professional support is available 24/7. You are not alone. + + )} + + ); +}; +``` + +--- + +## πŸ“± Complete Integration Example + +### Main Check-in Screen + +```tsx +// screens/CheckinScreen.tsx +import React, { useState } from 'react'; +import { View, Alert } from 'react-native'; +import { CrisisDetectionService } from '../services/crisisDetection'; +import { CrisisAlert } from '../components/CrisisAlert'; +import { UniversityResources } from '../components/UniversityResources'; +import { MotivationalMessage } from '../components/MotivationalMessage'; + +export const CheckinScreen: React.FC = () => { + const [apiResponse, setApiResponse] = useState(null); + const [showCrisisAlert, setShowCrisisAlert] = useState(false); + + const handleAudioUpload = async (audioFile: any) => { + try { + const response = await uploadAudio(audioFile); + setApiResponse(response); + + // Phase 4: Crisis Detection + const crisisAnalysis = CrisisDetectionService.detectCrisis( + response.data.sentiment, + response.data.coaching + ); + + if (crisisAnalysis.isCrisis) { + setShowCrisisAlert(true); + // Log crisis detection for support team + console.log('🚨 Crisis detected:', { + sessionId: response.data.sessionId, + sentimentScore: response.data.sentiment.score, + timestamp: new Date().toISOString(), + }); + } + } catch (error) { + Alert.alert('Error', 'Failed to process audio. Please try again.'); + } + }; + + if (!apiResponse) { + return ; + } + + const { sentiment, coaching } = apiResponse.data; + const crisisAnalysis = CrisisDetectionService.detectCrisis(sentiment, coaching); + + return ( + + setShowCrisisAlert(false)} + /> + + + + + + + + ); +}; +``` + +### Error Handling for Phase 4 + +```typescript +// services/errorHandling.ts +export class Phase4ErrorHandler { + static handleCrisisDetectionError(error: any, sessionId: string) { + console.error('Crisis detection failed:', error); + + // Fallback: Show emergency resources anyway + return { + isCrisis: true, + emergencyResources: [ + { + title: 'Emergency Services', + description: 'Call 911 for immediate help', + url: 'tel:911', + category: 'emergency', + }, + ], + message: "If you're in crisis, please call 911 or go to your nearest emergency room.", + urgencyLevel: 'critical', + }; + } + + static handleResourceLoadError(resource: Resource) { + Alert.alert( + 'Resource Unavailable', + `${resource.title} is temporarily unavailable. Please try again later or contact campus support directly.`, + [{ text: 'OK' }, { text: 'Call Campus', onPress: () => Linking.openURL('tel:+16082631122') }] + ); + } +} +``` + +--- + +## βœ… Testing Integration + +### Unit Tests for Phase 4 + +```typescript +// __tests__/CrisisDetection.test.ts +import { CrisisDetectionService } from '../services/crisisDetection'; + +describe('Crisis Detection Service', () => { + test('detects crisis for score < 0.2', () => { + const sentiment = { score: 0.1, label: 'negative' }; + const coaching = { + resources: [{ title: 'Get Help Now', category: 'emergency' }], + motivationalMessage: 'You are not alone', + }; + + const result = CrisisDetectionService.detectCrisis(sentiment, coaching); + + expect(result.isCrisis).toBe(true); + expect(result.urgencyLevel).toBe('critical'); + expect(result.emergencyResources.length).toBeGreaterThan(0); + }); + + test('does not detect crisis for moderate negative', () => { + const sentiment = { score: 0.3, label: 'negative' }; + const coaching = { resources: [], motivationalMessage: 'Keep going' }; + + const result = CrisisDetectionService.detectCrisis(sentiment, coaching); + + expect(result.isCrisis).toBe(false); + expect(result.urgencyLevel).toBe('moderate'); + }); +}); +``` + +### Integration Testing Checklist + +**Phase 4 Mobile Integration Tests:** + +- [ ] Crisis detection triggers emergency alert UI +- [ ] Emergency resources are prioritized in crisis situations +- [ ] University resources open correctly in mobile browser +- [ ] Crisis messaging displays appropriately +- [ ] Enhanced breathing exercises function properly +- [ ] Resource categorization works for all emotional states +- [ ] Crisis alert can be dismissed safely +- [ ] Professional tone maintained across all scenarios +- [ ] Error handling works for resource loading failures +- [ ] Analytics logging captures crisis detections + +--- + +**πŸš€ This integration guide ensures your React Native app can fully utilize the Phase 4 Enhanced AI +Coaching and Crisis Detection features while maintaining a professional, supportive user +experience.**