Spaces:
Sleeping
Sleeping
Commit History
-
fix: only explicit refusals decline the Spiritual Health referral
Any consent answer that was not a clear yes or a question used to count as a refusal, so a patient answering with more distress ("praying doesn't help anymore") got "I understand and respect your decision" and lost the referral. Keyword matching was also substring-based ("I know" hit "no", "мене" hit "не"). - Classify consent answers as accept / decline / unclear with word-boundary patterns; negated accept words ("not ok") are not consent - Short explicit refusals (<= 3 words) decline without an LLM call; longer answers with refusal words are checked for distress first - Unclear answer with new distress keeps the consent request open; otherwise re-ask once, then close softly without a referral Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>474586e -
fix: Or_7 feedback — Spiritual Health team wording, coping follow-up, summary trigger
- Consent question now asks "Would you be open to having someone from the team reach out to you?" instead of asking to share the patient's information; confirmation and all consent templates renamed to the Spiritual Health team - Service explanation rewritten from Alex's program description: ambulatory, not hospital/bedside, phone or video, free, and visits are NOT private; the description is also added to the classifier and medical assistant prompts - Triage evaluator: a practical/treatment-related cause alone no longer resolves to GREEN; ongoing burden prompts a question about coping - Drop the canned "I'm glad you have support" on GREEN resolution - Provider summary context keeps only patient lines, most recent 2000 chars, so the triggering distress statement is not truncated; prompt requires naming the reported feeling in the patient's words - CSV export now includes provider_summary on the PROVIDER_SUMMARY row - Medical assistant must not invent appointment times or …948058d
-
fix: Or_6 feedback — consent questions, unrecorded verdicts, feedback types
Findings from Alex's first reviewed test case (review/Or_6.txt). Fixed: - A question about the spiritual care team was scored as a refusal. "I don't know, who are they" contains "don't"/"not", so _check_consent's negative keyword scan matched first, _process_consent_declined closed the topic and moved the session back to GREEN while the patient was still in an unresolved RED. _is_consent_question now runs before _check_consent, explains what the chaplains do, re-asks for consent and stays in AWAITING_CONSENT. - Saving from the always-visible verification panel never set is_correct, so a fully reviewed session exported as "0 reviewed". Picking a classification is now the verdict itself (PROVIDER_SUMMARY step excluded, its radio is hidden). The panel also stays open after Save so a note left on an exchange whose classification was correct doesn't disappear. Added: - "Type of feedback" multi-select (wrong classification / tone / missing information / conversation flo…09c4875
-
delete 🆘 Important...
f65dd20
-
feat: Fix classification logic and remove redundant spiritual care message functionality
## Major Changes ### 🔧 Classification Logic Fixes (review/Or_2.txt recommendations) - Fix JSON parsing bug: LLM returns 'classification' but parser expected 'state' - Update RED flag definition: broader than crisis-only, includes active spiritual distress - Add explicit RED indicators: complex grief, loss of loved one, doubt about meaning of life/suffering/dignity - Fix 'I am fine' classification: now correctly GREEN (was incorrectly YELLOW) - Fix 'feeling sad' classification: now correctly YELLOW without spiritual context (was incorrectly RED) - Loss of meaning/purpose now correctly RED with high confidence ### 🗑️ Remove Redundant Spiritual Care Message UI - Remove redundant '💬 Care Team Message' tab from Provider Summary panel - Remove related UI controls and event handlers - Fix undefined 'spiritual_care_msg' variable in return statements - Preserve prompt editing and model settings (now used for Medical Brain Summary) - Medical Brain Summary now first tab by default in '�� Che…be1b5d2
-
feat: introduce configurable content options and privacy controls for spiritual care messages.
50012e7
-
feat: Add configurable content inclusion for spiritual care messages, allowing dynamic selection of patient profile, situation, distress, and conversation context.
ef61786 -
refactor: Structure spiritual care prompt and simplify fallback message generation to a concise narrative, increasing conversation context length.
b6906ba
-
Fix: Use DynamicAIClient instead of AIClientManager for spiritual care message generation
14938ed -
feat: Add comprehensive manual tests for spiritual care message features
- Introduced a new changelog documenting notable changes and version history. - Created manual test scripts for validating patient profile flow, context integration, and spiritual care message generation. - Implemented tests for prompt editing functionality and model selection in the spiritual care message context. - Enhanced existing prompt templates and configurations for better clarity and usability. - Organized project structure for improved maintainability and documentation accessibility.1d0741a -
feat: Complete prompt optimization system implementation
🎉 MAJOR FEATURE: Comprehensive prompt optimization system ## Core Architecture - ✅ Centralized PromptController with shared component architecture - ✅ Session-level prompt override system with isolation and cleanup - ✅ Enhanced Edit Prompts UI with validation and promotion workflows - ✅ Complete integration with existing Gradio interface ## Key Features Implemented - 🔧 Real-time prompt editing with session isolation - �� Visual indicators for prompt sources (session vs centralized) - ✅ Live validation with syntax and structure checking - 🔄 Promote to File workflow for permanent adoption - 🛡️ Automatic backup and rollback capabilities ## Shared Component System - 📋 Centralized indicators catalog (68 indicators) - 📏 Unified rules catalog (7 classification rules) - 📝 Template catalog (5 reusable patterns) - �� Consistent terminology across all AI agents ## Testing & Quality Assurance - ✅ 65+ comprehensive tests - all passing - 🧪 Property-based tests validating 9 correctness pr…24214fc -
feat: Simplify self-harm support message by removing specific hotline details
dfe11ec
-
feat: Enhance spiritual state management and UI for provider summaries
- Added AWAITING_CONSENT state to SpiritualState enum for tracking consent responses. - Updated SessionSpiritualState to include pending referral data and methods for consent handling. - Implemented a provider summary panel in the Gradio interface, including download and clear functionality. - Enhanced conversation handling to check for provider summaries in RED flag cases, with detailed logging. - Created a simple test script for Gradio UI to simulate provider summary functionality. - Developed a prompt loader to manage spiritual and medical prompts from markdown files, ensuring backward compatibility. - Added comprehensive documentation for prompt structure and loading process. - Implemented triage evaluator and question prompts to improve emotional and spiritual distress assessment.f91e0d7 -
after comments from Or:
feat: Enhance spiritual care classification and consent messaging - Updated the YELLOW category definition in spiritual_monitor.py to clarify ambiguity in distress indicators. - Added follow-up purpose guidelines for YELLOW classifications. - Introduced consent-based messaging requirements for RED classifications, ensuring patient autonomy. - Created a new consent_message_generator.py to handle consent message generation and validation. - Developed a provider_summary_generator.py to generate structured summaries for RED flag cases, including patient information and distress indicators. - Modified the simplified_gradio_app.py to include patient phone number and correct classification options during conversation verification. - Enhanced UI elements to support new classification and consent features.32be239
-
Add per-session prompt override functionality across interfaces and AI client
2e0e95f -
Implement model overrides for AI clients and enhance interfaces for manual input and file upload
37184d4 -
Implement model override functionality for AI clients and enhance session management in the simplified medical app
ba5a70c -
Enhance CSV export functionality by extracting reasoning from notes and streamline file upload interface to support only CSV format
82ca3ff -
Add export options for session results in manual input interface
346aa2c -
Embed conversation verification in main UI and add download button
- Add Conversation Verification tab (no second Gradio server) - Add Download Verification JSON button in Chat tab - Add UI import smoke test - Restore VerificationDataStore import compatibilityded6460 -
feat: Add conversation verification feature with UI and backend support
- Implemented a new verification section in the Gradio interface to allow users to verify conversation exchanges. - Created core models and manager for handling verification sessions, including feedback and progress tracking. - Developed a CSV exporter for verification results, enabling users to export session data. - Built a comprehensive Gradio UI for reviewing and verifying AI classifier decisions, including navigation and statistics display. - Added functionality to mark exchanges as correct or incorrect, with options for providing feedback and reasons for corrections. - Ensured session data is saved and loaded correctly, maintaining state across user interactions.74541bd -
feat: enhance triage assessment handling and update last assessment for display
6683b63 -
feat: add reasoning display to conversation logging and implement test for reasoning indicators
0c6718b -
feat: add conversation logging and statistics features with export options
953a0b1 -
feat: implement medical API call and enhance soft medical triage functionality
f3fbc65
-
Fix TestMessage import in verification_store.py
- Add missing TestMessage import from verification_models - Resolves NameError: name 'TestMessage' is not defined - Completes import fixes for Hugging Face Spaces deployment13ac429 -
Fix Tuple import in verification_store.py
- Add missing Tuple import from typing module - Resolves NameError: name 'Tuple' is not defined - Fixes Hugging Face Spaces deployment runtime error21c19a6 -
✅ Enhanced Verification Modes - Production Ready
🎯 Complete implementation of enhanced verification system: - Enhanced Dataset Mode: Full dataset editing with CRUD operations - Manual Input Mode: Real-time classification and verification - File Upload Mode: Batch CSV/XLSX processing with progress tracking 🚀 Key Features: - Cross-mode session management and switching - Comprehensive export system (CSV, XLSX, JSON) - Robust error handling and data validation - Standardized UI components and integrated help system - Full backward compatibility with existing verification data �� Testing: - 100% integration test pass rate (10/10 tests) - 100% end-to-end workflow test pass rate (5/5 tests) - All 19 development tasks completed successfully 📚 Documentation: - Complete user guides and troubleshooting documentation - File format examples and help system integration - Comprehensive API documentation 🧹 Repository cleanup: - Removed intermediate development documents - Removed temporary integration tests - Clean production-ready codebase …7bbd836 -
Fix CSV download button for Hugging Face Spaces - use DownloadButton for direct file download
ab93d81
-
Add property-based tests for verification mode functionality
- Implement tests for verification data persistence, ensuring records and sessions save and load correctly. - Create tests for progress display accuracy, validating the display reflects the current position in the queue and total messages. - Add tests for message queue advancement, confirming the queue advances correctly after verification. - Develop tests for verification UI components, ensuring classifier decisions, confidence formatting, and indicators display correctly. - Include tests for test dataset management functionality, verifying dataset retrieval and message integrity. - Enhance unit tests for verification UI components, focusing on rendering accuracy for message review components.a3934b1
-
fix: Add missing core_classes module
9a0be34 -
chore: Remove legacy modules and old tests
- Removed .kiro/specs and .vscode directories - Removed old spiritual analyzer and assistant modules - Removed combined assistant and multi-faith modules - Removed old Gradio interface and spiritual interface - Removed prompts, storage, and utils modules - Removed all old tests (kept only simplified app tests) - Repository now contains only essential files for Simplified Medical Assistant - Clean, minimal codebase ready for production6c0e398 -
feat: Add detailed examples from spiritual distress document
Based on 'Spiritual Distress Definitions & Examples' document: YELLOW flag indicators expanded with: - Emotional expressions (sleep issues, fatigue, anxiety, crying) - Spiritual/existential concerns (identity, suffering, beliefs) - Loss and grief (hobbies, nature, anticipatory grieving) - Social/relational issues (loneliness, isolation, burden) - Control/autonomy (overwhelmed, loss of control, independence) - Spiritual practices (altered rituals, cultural conflict) RED flag indicators expanded with: - Crisis language (suicide, self-harm, death wishes) - Severe emotional states (anger at God, excessive guilt, hopelessness) - Severe grief (disenfranchised, maladaptive, complicated) - Existential crisis (meaning of life/suffering, dignity, worthlessness) - Expressions of severe distress (emptiness, unloved, unfinished business) - Physical manifestations (uncontrolled pain causing existential distress) All prompts and examples in English only5e567a8 -
feat: Add XML-style tags to prompts for better structure
Prompts 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 hierarchyd53dcd4 -
fix: Add call_spiritual_api method to AIClientManager
- Added call_spiritual_api method for spiritual/emotional analysis - Routes to SpiritualDistressAnalyzer agent configuration - Fixes 'AIClientManager' object has no attribute 'call_spiritual_api' error3c799d8 -
feat: Implement simplified spiritual triage system (Phases 2-9)
New components: - src/core/spiritual_state.py: State machine (GREEN/YELLOW/RED) - src/core/spiritual_monitor.py: Background distress classifier - src/core/soft_triage_manager.py: Soft triage (2-3 questions max) - src/core/simplified_medical_app.py: Main app with integrated monitoring - src/interface/simplified_gradio_app.py: Simplified UI - run_simplified_app.py: Launch script Property tests (130 passing): - tests/test_spiritual_state_properties.py (22 tests) - tests/test_spiritual_monitor_properties.py (42 tests) - tests/test_soft_triage_properties.py (22 tests) - tests/test_simplified_app_properties.py (27 tests) - tests/test_referral_language_properties.py (17 tests) Correctness properties validated: - Property 1: Spiritual Monitor Always Invoked - Property 2: Green State Preservation - Property 3: Yellow Triggers Triage - Property 4: Red Triggers Immediate Referral - Property 5: Triage Question Limit (max 3) - Property 6: Triage Binary Outcome - Property 7: Triage Timeout Escalat…f2a77d5
-
fix: Generate yellow/red flag responses in patient's language via LLM
- Updated _format_yellow_flag_response to use LLM for language-matched responses - Updated _format_red_flag_response to use LLM for language-matched responses - Removed static English templates for yellow and red flag cases - All spiritual assistant responses now match patient's language (Ukrainian, English, etc.) - Added patient_input parameter to response formatting functionsf19959c -
fix: Fix Claude model name and add dynamic spiritual dialog response
- Fixed Claude Sonnet 4.5 model name: claude-sonnet-4-5-20250929 - Added SYSTEM_PROMPT_SPIRITUAL_DIALOG and PROMPT_SPIRITUAL_DIALOG for natural responses - SpiritualAssistant now generates LLM-based responses for no-flag cases - Responses are now in patient's language (Ukrainian, English, etc.) - Removed static English-only response template for no-flag cases7fbff0e -
add
f5f8487 -
feat: Task 6 - Add comprehensive error handling and fallback
- Add handle_assistant_error() with fallback to Medical mode - Add _retry_with_backoff() for temporary errors (timeout, connection) - Add error handling to _handle_spiritual_mode() - Add error handling to _handle_combined_mode() - Add error handling to _handle_entry_classification() with last-known-mode fallback - Update CombinedAssistant._combine_responses() with partial failure notifications - Log all errors with traceback for debugging Error handling strategy: - Timeout/Connection errors: Retry with exponential backoff (max 3 attempts) - Assistant errors: Fallback to Medical mode with clear user notification - Entry Classifier errors: Use last known mode or default to Medical - Partial failures in Combined mode: Show available assistant + error message Requirements: 11.1, 11.2, 11.3, 11.4, 11.55142baa -
feat: Implement CombinedAssistant for coordinating both modes
- Created CombinedAssistant that coordinates Lifestyle and Spiritual assistants - Implements intelligent prioritization (spiritual red flag > lifestyle close > balanced) - Handles parallel invocation of both assistants - Includes comprehensive error handling with fallback to working assistant - Formats combined responses based on priority - Added 14 unit tests covering all scenarios including error cases - All tests passing ✅ Implements Task 2.1-2.4 from integration spec Requirements: 2.1, 2.2, 2.3, 2.4, 2.5, 6.1, 6.2, 6.3, 6.4, 6.5d4a4a89 -
feat: Implement SpiritualAssistant for dialog mode
- Created SpiritualAssistant class that wraps spiritual health components - Handles red flags (generates referral), yellow flags (asks questions), and no flags (supportive response) - Formats responses for conversational interface - Includes comprehensive error handling with safe fallbacks - Added 13 unit tests covering all scenarios - All tests passing ✅ Implements Task 1.1-1.3 from integration spec Requirements: 5.1, 5.2, 5.3, 5.4, 5.5428869e -
🔧 Виправлення імпортів після реорганізації
- Оновлено імпорти в src/core/ai_client.py - Оновлено імпорти в src/core/core_classes.py - Оновлено імпорти в src/interface/gradio_app.py - Оновлено імпорти в lifestyle_app.py - Оновлено імпорти в tests/test_ai_providers.py Всі імпорти тепер вказують на нові шляхи після переміщення файлів у src/config/, src/utils/, scripts/, tests/f08800b -
🧹 Організація проекту: структурування коду, тестів та документації
✨ Основні зміни: - Переміщено всі тести в tests/spiritual/ (145 тестів) - Переміщено документацію в docs/spiritual/ та docs/general/ - Переміщено демо в demos/, скрипти в scripts/ - Переміщено конфігурацію в src/config/ - Видалено проміжні звіти (TASK_*_SUMMARY.md) - Створено чітку структуру проекту 📁 Нова структура: - src/ - вихідний код - tests/ - всі тести - docs/ - вся документація - demos/ - демонстраційні скрипти - scripts/ - утилітні скрипти - deployment/ - файли для розгортання 📚 Документація: - README.md - головний README - QUICK_START.md - швидкий старт - STRUCTURE.md - структура проекту - FILE_INDEX.md - індекс файлів - FINAL_STATUS.md - статус проекту ✅ Результат: чистий, організований репозиторій готовий до productiona2eebc7 -
feat: Implement spiritual analyzer, multi-faith sensitivity, feedback storage, and spiritual interface with comprehensive tests and documentation.
06da5a5
-
feat: implement task 1 - set up core data classes for spiritual health assessment
- Created src/core/spiritual_classes.py with 4 dataclasses: - PatientInput: stores patient messages with conversation history - DistressClassification: holds classification results (red/yellow/none) - ReferralMessage: contains referral info for spiritual care team - ProviderFeedback: tracks provider feedback on assessments - Created data/spiritual_distress_definitions.json with initial definitions - Added test_spiritual_classes.py with comprehensive tests - All dataclasses follow existing patterns from core_classes.py - Verified AIClientManager is available for reuse - All tests passing ✅5a6a686
-
Оновлено lifestyle_profile.json: уточнено основну мету, додано нотатки про дієту та особисті вподобання пацієнта. Внесено зміни до обмежень щодо фізичної активності, зокрема, знято обмеження на виконання присідань після медичного огляду. Оновлено підсумок останньої сесії з акцентом на новий симптом та підтвердження медичної безпеки. Додано логування динамічних запитів у класі EnhancedMainLifestyleAssistant для покращення відстеження. Змінено обробку конфігурацій у класі EnvironmentConfigurationManager для підтримки тестового середовища.
b7b658f -
Оновлено lifestyle_profile.json: уточнено основну мету, додано нотатки про дієту та особисті вподобання пацієнта. Оновлено підсумок останньої сесії з акцентом на новий симптом болю в нозі. Внесено зміни до формату виходу в prompts.py для покращення обробки даних. У класі MedicalSafetyValidator реалізовано кешування звітів про безпеку для підвищення ефективності перевірок.
c245dab -
The MedicalSafetyValidator class has been updated for integration with AIClientManager, allowing LLM to be used to verify the safety of collected requests. New methods have been added to validate requests with a detailed safety report. In EnhancedMainLifestyleAssistant, the API has been transferred to DynamicTemplateAssembler to improve dynamic request processing.
5265db4 -
Updated the PROMPT_ENTRY_CLASSIFIER function to simplify query formation without clinical context. Added easy logging for dynamic queries in the EnhancedMainLifestyleAssistant class, including markers for successful use and Fallback. Fixed time formatting to UTC in the EntryClassifier class. Removed unnecessary comments and improved code structure.
b4701d8