Spaces:
Sleeping
Sleeping
feat: Add comprehensive manual tests for spiritual care message features
Browse files- 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.
- CHANGELOG.md +52 -0
- CONVERSATION_LOGGING_FEATURES.md +0 -201
- FINAL_COMPLETION_SUMMARY.md +0 -128
- INTERFACE_CHANGES.md +0 -106
- MODEL_UPDATE_SUMMARY.md +0 -85
- PROMPT_OPTIMIZATION_IMPLEMENTATION_REPORT.md +0 -443
- README.md +48 -12
- manual_tests/README.md +42 -0
- manual_tests/test_clear_provider_summary.py +102 -0
- manual_tests/test_patient_context_in_message.py +125 -0
- manual_tests/test_patient_profile_flow.py +162 -0
- manual_tests/test_spiritual_care_message.py +164 -0
- manual_tests/test_spiritual_care_prompt_editing.py +158 -0
- manual_tests/test_spiritual_prompt_edit.py +186 -0
- src/config/ai_providers_config.py +8 -0
- src/config/prompts/spiritual_care_message.txt +12 -0
- src/config/prompts/spiritual_care_message_template.txt +22 -0
- src/core/provider_summary_generator.py +232 -2
- src/core/simplified_medical_app.py +77 -7
- src/interface/enhanced_prompt_editor.py +2 -1
- src/interface/help_content.py +50 -2
- src/interface/simplified_gradio_app.py +274 -35
- ЗВІТ_РЕАЛІЗАЦІЇ_ОПТИМІЗАЦІЇ_ПРОМПТІВ.md +0 -443
CHANGELOG.md
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Changelog
|
| 2 |
+
|
| 3 |
+
All notable changes to the Medical Assistant with Spiritual Support project.
|
| 4 |
+
|
| 5 |
+
## [2.1.0] - 2025-12-18
|
| 6 |
+
|
| 7 |
+
### Added
|
| 8 |
+
- **Spiritual Care Message Prompt Editing**: Full support for editing spiritual care message prompt in Edit Prompts tab
|
| 9 |
+
- **Spiritual Care Message Model Selection**: Dedicated model configuration in Model Settings tab
|
| 10 |
+
- **Patient Context Integration**: Automatic inclusion of patient age, conditions, and goals in messages
|
| 11 |
+
- **Manual Test Suite**: Organized manual validation scripts in `manual_tests/` directory
|
| 12 |
+
- **Documentation Reports**: Centralized implementation reports in `docs/reports/` directory
|
| 13 |
+
- **Feature Documentation**: Comprehensive guide for Spiritual Care Message features
|
| 14 |
+
|
| 15 |
+
### Changed
|
| 16 |
+
- **Project Structure**: Reorganized test files and documentation for better maintainability
|
| 17 |
+
- **README**: Updated with v2.1 features and latest information
|
| 18 |
+
- **Help Content**: Enhanced with Spiritual Care Message customization details
|
| 19 |
+
- **Version**: Bumped to 2.1.0 to reflect new features
|
| 20 |
+
|
| 21 |
+
### Enhanced
|
| 22 |
+
- **ProviderSummaryGenerator**: Now uses PromptController for centralized prompt management
|
| 23 |
+
- **AIClientManager**: Supports model overrides for SpiritualCareMessage agent
|
| 24 |
+
- **Session Management**: Full session isolation for prompt and model customizations
|
| 25 |
+
|
| 26 |
+
### Fixed
|
| 27 |
+
- **Prompt Loading**: Spiritual care message prompt now loads through centralized system
|
| 28 |
+
- **Model Override**: Properly passes model override from session to AI client
|
| 29 |
+
|
| 30 |
+
## [2.0.0] - 2024-12-18
|
| 31 |
+
|
| 32 |
+
### Added
|
| 33 |
+
- Comprehensive prompt optimization system with session-level overrides
|
| 34 |
+
- Enhanced verification workflows with file upload support
|
| 35 |
+
- Patient profile management with 16 predefined scenarios
|
| 36 |
+
- Conversation verification and export capabilities
|
| 37 |
+
- 65+ automated tests with property-based testing
|
| 38 |
+
|
| 39 |
+
### Core Features
|
| 40 |
+
- Background spiritual distress monitoring
|
| 41 |
+
- Three-tier classification system (GREEN/YELLOW/RED)
|
| 42 |
+
- Gentle triage questioning for YELLOW cases
|
| 43 |
+
- Provider summary generation for RED cases
|
| 44 |
+
- Consent-based referral process
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
## Version History
|
| 49 |
+
|
| 50 |
+
- **v2.1.0** (2025-12-18): Spiritual Care Message customization features
|
| 51 |
+
- **v2.0.0** (2024-12-18): Prompt optimization system and comprehensive testing
|
| 52 |
+
- **v1.0.0** (2024-09-01): Initial release with core functionality
|
CONVERSATION_LOGGING_FEATURES.md
DELETED
|
@@ -1,201 +0,0 @@
|
|
| 1 |
-
# Нові функції логування розмов та візуальних індикаторів
|
| 2 |
-
|
| 3 |
-
## Огляд
|
| 4 |
-
|
| 5 |
-
Додано нові функції для покращення користувацького досвіду та аналізу розмов:
|
| 6 |
-
|
| 7 |
-
1. **Кольорові індикатори класифікації** - показують рівень духовного дистресу
|
| 8 |
-
2. **Автоматичне логування розмов** - зберігає всі розмови в JSON та CSV форматах
|
| 9 |
-
3. **Статистика розмов в реальному часі** - показує аналітику поточної сесії
|
| 10 |
-
4. **Кнопки завантаження** - дозволяють завантажити логи розмов
|
| 11 |
-
|
| 12 |
-
## Кольорові індикатори
|
| 13 |
-
|
| 14 |
-
### Формат відображення
|
| 15 |
-
Кожна відповідь асистента тепер починається з кольорового індикатора:
|
| 16 |
-
|
| 17 |
-
```
|
| 18 |
-
🟢 **GREEN** (95%)
|
| 19 |
-
|
| 20 |
-
🟡 **YELLOW** (85%)
|
| 21 |
-
*Indicators: anxiety, worry, work-related stress*
|
| 22 |
-
|
| 23 |
-
🔴 **RED** (90%)
|
| 24 |
-
*Indicators: suicidal ideation, hopelessness*
|
| 25 |
-
```
|
| 26 |
-
|
| 27 |
-
### Значення кольорів
|
| 28 |
-
- **🟢 GREEN** - Немає ознак духовного дистресу, звичайна медична розмова
|
| 29 |
-
- **🟡 YELLOW** - Потенційний дистрес, потребує уваги та підтримки
|
| 30 |
-
- **🔴 RED** - Серйозний дистрес або криза, потребує негайного втручання
|
| 31 |
-
|
| 32 |
-
### Додаткова інформація
|
| 33 |
-
- **Відсоток впевненості** - показує наскільки впевнена система в класифікації
|
| 34 |
-
- **Індикатори** - конкретні ознаки дистресу, які були виявлені
|
| 35 |
-
|
| 36 |
-
## Логування розмов
|
| 37 |
-
|
| 38 |
-
### Автоматичне збереження
|
| 39 |
-
- Кожна розмова автоматично зберігається в папці `conversation_logs/`
|
| 40 |
-
- Створюються файли в форматах JSON та CSV
|
| 41 |
-
- Логування відбувається в реальному часі після кожного повідомлення
|
| 42 |
-
|
| 43 |
-
### Структура JSON логу
|
| 44 |
-
```json
|
| 45 |
-
{
|
| 46 |
-
"session_id": "session_20251212_114257",
|
| 47 |
-
"start_time": "2025-12-12T11:42:57.849982",
|
| 48 |
-
"patient_name": "Test Patient",
|
| 49 |
-
"total_messages": 4,
|
| 50 |
-
"entries": [
|
| 51 |
-
{
|
| 52 |
-
"timestamp": "2025-12-12T11:43:06.931133",
|
| 53 |
-
"user_message": "Привіт, як справи?",
|
| 54 |
-
"assistant_response": "Привіт! Дякую...",
|
| 55 |
-
"spiritual_classification": "GREEN",
|
| 56 |
-
"classification_confidence": 0.95,
|
| 57 |
-
"classification_indicators": [],
|
| 58 |
-
"classification_reasoning": "Simple greeting...",
|
| 59 |
-
"session_id": "session_20251212_114257",
|
| 60 |
-
"message_index": 1
|
| 61 |
-
}
|
| 62 |
-
],
|
| 63 |
-
"session_summary": {
|
| 64 |
-
"total_exchanges": 4,
|
| 65 |
-
"classification_counts": {
|
| 66 |
-
"green": 2,
|
| 67 |
-
"yellow": 2,
|
| 68 |
-
"red": 0
|
| 69 |
-
},
|
| 70 |
-
"classification_percentages": {
|
| 71 |
-
"green": 50.0,
|
| 72 |
-
"yellow": 50.0,
|
| 73 |
-
"red": 0.0
|
| 74 |
-
},
|
| 75 |
-
"average_confidence": 0.9,
|
| 76 |
-
"top_indicators": {
|
| 77 |
-
"anxiety": 1,
|
| 78 |
-
"worry": 1,
|
| 79 |
-
"work-related stress": 1
|
| 80 |
-
},
|
| 81 |
-
"session_duration_minutes": 5.2
|
| 82 |
-
}
|
| 83 |
-
}
|
| 84 |
-
```
|
| 85 |
-
|
| 86 |
-
### CSV формат
|
| 87 |
-
CSV файл містить ті ж дані в табличному форматі для аналізу в Excel або інших програмах.
|
| 88 |
-
|
| 89 |
-
## Інтерфейс користувача
|
| 90 |
-
|
| 91 |
-
### Нові елементи в чаті
|
| 92 |
-
|
| 93 |
-
#### Кнопки завантаження
|
| 94 |
-
```
|
| 95 |
-
📊 Conversation Logs:
|
| 96 |
-
[📥 Download JSON] [📊 Download CSV]
|
| 97 |
-
```
|
| 98 |
-
|
| 99 |
-
#### Статистика розмови
|
| 100 |
-
```
|
| 101 |
-
📈 Conversation Stats
|
| 102 |
-
**📊 Conversation Statistics**
|
| 103 |
-
|
| 104 |
-
**Messages:** 4 exchanges
|
| 105 |
-
**Duration:** 5.2 minutes
|
| 106 |
-
|
| 107 |
-
**Classifications:**
|
| 108 |
-
🟢 Green: 2 (50.0%)
|
| 109 |
-
🟡 Yellow: 2 (50.0%)
|
| 110 |
-
🔴 Red: 0 (0.0%)
|
| 111 |
-
|
| 112 |
-
**Average Confidence:** 0.9
|
| 113 |
-
|
| 114 |
-
**Top Indicators:**
|
| 115 |
-
• anxiety: 1
|
| 116 |
-
• worry: 1
|
| 117 |
-
• work-related stress: 1
|
| 118 |
-
```
|
| 119 |
-
|
| 120 |
-
#### Кнопка оновлення статистики
|
| 121 |
-
```
|
| 122 |
-
[🔄 Refresh Stats]
|
| 123 |
-
```
|
| 124 |
-
|
| 125 |
-
## Технічна реалізація
|
| 126 |
-
|
| 127 |
-
### Нові класи
|
| 128 |
-
- `ConversationLogger` - основний клас для логування
|
| 129 |
-
- `ConversationEntry` - структура для одного обміну повідомленнями
|
| 130 |
-
- `ConversationSession` - структура для повної сесії
|
| 131 |
-
|
| 132 |
-
### Інтеграція з існуючою системою
|
| 133 |
-
- Логування інтегровано в `SimplifiedMedicalApp`
|
| 134 |
-
- Індикатори додаються автоматично до всіх відповідей
|
| 135 |
-
- Статистика оновлюється після кожного повідомлення
|
| 136 |
-
|
| 137 |
-
### Файлова структура
|
| 138 |
-
```
|
| 139 |
-
conversation_logs/
|
| 140 |
-
├── session_20251212_114257.json
|
| 141 |
-
├── session_20251212_114257.csv
|
| 142 |
-
├─��� session_20251212_115430.json
|
| 143 |
-
└── session_20251212_115430.csv
|
| 144 |
-
```
|
| 145 |
-
|
| 146 |
-
## Використання
|
| 147 |
-
|
| 148 |
-
### Для користувачів
|
| 149 |
-
1. **Спостерігайте за індикаторами** - кольорові позначки показують рівень дистресу
|
| 150 |
-
2. **Завантажуйте логи** - використовуйте кнопки для збереження розмов
|
| 151 |
-
3. **Переглядайте статистику** - слідкуйте за динамікою розмови
|
| 152 |
-
|
| 153 |
-
### Для аналітиків
|
| 154 |
-
1. **JSON файли** - для програмного аналізу та обробки даних
|
| 155 |
-
2. **CSV файли** - для аналізу в Excel, Google Sheets тощо
|
| 156 |
-
3. **Статистика сесій** - для розуміння патернів та трендів
|
| 157 |
-
|
| 158 |
-
## Приклади використання
|
| 159 |
-
|
| 160 |
-
### Медичний персонал
|
| 161 |
-
- Відстеження емоційного стану пацієнтів
|
| 162 |
-
- Виявлення патернів дистресу
|
| 163 |
-
- Документування для медичних записів
|
| 164 |
-
|
| 165 |
-
### Дослідники
|
| 166 |
-
- Аналіз ефективності класифікації
|
| 167 |
-
- Вивчення патернів духовного дистресу
|
| 168 |
-
- Покращення алгоритмів
|
| 169 |
-
|
| 170 |
-
### Адміністратори
|
| 171 |
-
- Моніторинг використання системи
|
| 172 |
-
- Оцінка якості взаємодії
|
| 173 |
-
- Планування ресурсів підтримки
|
| 174 |
-
|
| 175 |
-
## Конфіденційність та безпека
|
| 176 |
-
|
| 177 |
-
### Локальне зберігання
|
| 178 |
-
- Всі логи зберігаються локально
|
| 179 |
-
- Немає передачі даних на зовнішні сервери
|
| 180 |
-
- Користувач контролює свої дані
|
| 181 |
-
|
| 182 |
-
### Анонімізація
|
| 183 |
-
- Можливість використання псевдонімів
|
| 184 |
-
- Видалення особистої інформації при потребі
|
| 185 |
-
- Контроль доступу до файлів логів
|
| 186 |
-
|
| 187 |
-
## Майбутні покращення
|
| 188 |
-
|
| 189 |
-
### Планується додати
|
| 190 |
-
- Експорт в інші формати (PDF, Word)
|
| 191 |
-
- Фільтрація та пошук в логах
|
| 192 |
-
- Візуалізація статистики (графіки, діаграми)
|
| 193 |
-
- Автоматичні звіти та аналітика
|
| 194 |
-
- Інтеграція з медичними системами
|
| 195 |
-
|
| 196 |
-
### Можливі розширення
|
| 197 |
-
- Порівняння сесій
|
| 198 |
-
- Трендовий аналіз
|
| 199 |
-
- Алерти при критичних ситуаціях
|
| 200 |
-
- Інтеграція з календарем
|
| 201 |
-
- Нагадування про подальші дії
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
FINAL_COMPLETION_SUMMARY.md
DELETED
|
@@ -1,128 +0,0 @@
|
|
| 1 |
-
# 🎉 Prompt Optimization Implementation - COMPLETE
|
| 2 |
-
|
| 3 |
-
## Final Status: ✅ ALL TASKS COMPLETED
|
| 4 |
-
|
| 5 |
-
**Date:** December 18, 2024
|
| 6 |
-
**Status:** Production Ready
|
| 7 |
-
**Test Coverage:** 65/65 tests passing
|
| 8 |
-
|
| 9 |
-
---
|
| 10 |
-
|
| 11 |
-
## 📋 Implementation Summary
|
| 12 |
-
|
| 13 |
-
### ✅ All 12 Major Tasks Completed
|
| 14 |
-
|
| 15 |
-
1. **✅ Shared Prompt Component Architecture** - Centralized PromptController with shared catalogs
|
| 16 |
-
2. **✅ AI Agent Prompt Synchronization** - Consistent terminology across all agents
|
| 17 |
-
3. **✅ Targeted Triage Question Generation** - Scenario-specific question patterns
|
| 18 |
-
4. **✅ Structured Feedback System** - Comprehensive error categorization and analysis
|
| 19 |
-
5. **✅ Enhanced Consent Handling** - Improved language validation and response processing
|
| 20 |
-
6. **✅ Context-Aware Classification** - Conversation history integration
|
| 21 |
-
7. **✅ Provider Summary Generation** - Complete information capture for spiritual care
|
| 22 |
-
8. **✅ Performance Monitoring System** - Response time tracking and optimization
|
| 23 |
-
9. **✅ Integration and Validation** - Full system integration with existing application
|
| 24 |
-
10. **✅ Edit Prompts Interface Enhancement** - Session-level overrides with centralized system
|
| 25 |
-
11. **✅ Final Testing and Validation** - All tests passing, system production-ready
|
| 26 |
-
|
| 27 |
-
### 🏗️ Architecture Achievements
|
| 28 |
-
|
| 29 |
-
- **Centralized Prompt Management**: Single source of truth for all prompts
|
| 30 |
-
- **Session-Level Overrides**: Real-time testing without affecting production
|
| 31 |
-
- **Shared Component System**: Consistent indicators, rules, and templates
|
| 32 |
-
- **Enhanced UI Integration**: Seamless integration with existing Gradio interface
|
| 33 |
-
- **Comprehensive Testing**: Property-based tests validating 9 correctness properties
|
| 34 |
-
|
| 35 |
-
### 📊 Technical Metrics
|
| 36 |
-
|
| 37 |
-
- **38 new files created** with organized structure
|
| 38 |
-
- **65+ comprehensive tests** - all passing
|
| 39 |
-
- **9 correctness properties** validated through property-based testing
|
| 40 |
-
- **5 AI models supported** including new Gemini 3.0 Flash Preview
|
| 41 |
-
- **Complete documentation** in both English and Ukrainian
|
| 42 |
-
|
| 43 |
-
### 🔧 Key Features Implemented
|
| 44 |
-
|
| 45 |
-
#### Enhanced Prompt Editor
|
| 46 |
-
- Real-time prompt editing with session isolation
|
| 47 |
-
- Visual indicators for prompt sources (session vs centralized)
|
| 48 |
-
- Live validation with syntax and structure checking
|
| 49 |
-
- Promote to File workflow for permanent adoption
|
| 50 |
-
- Automatic backup and rollback capabilities
|
| 51 |
-
|
| 52 |
-
#### Centralized Prompt System
|
| 53 |
-
- PromptController orchestrating all prompt operations
|
| 54 |
-
- Shared catalogs for indicators (68), rules (7), templates (5)
|
| 55 |
-
- Session-level prompt overrides with priority system
|
| 56 |
-
- Fallback logic: session → centralized → default
|
| 57 |
-
|
| 58 |
-
#### Advanced Testing Framework
|
| 59 |
-
- Property-based tests for system correctness
|
| 60 |
-
- Integration tests for end-to-end functionality
|
| 61 |
-
- Unit tests for individual components
|
| 62 |
-
- Performance monitoring and optimization
|
| 63 |
-
|
| 64 |
-
### 📁 Repository Organization
|
| 65 |
-
|
| 66 |
-
```
|
| 67 |
-
src/
|
| 68 |
-
├── config/prompt_management/ # Centralized prompt system
|
| 69 |
-
├── interface/ # Enhanced UI components
|
| 70 |
-
├── core/ # Core AI and processing logic
|
| 71 |
-
└── utils/ # Utility functions
|
| 72 |
-
|
| 73 |
-
tests/
|
| 74 |
-
├── prompt_optimization/ # Feature-specific tests
|
| 75 |
-
├── integration/ # End-to-end integration tests
|
| 76 |
-
└── unit/ # Component unit tests
|
| 77 |
-
|
| 78 |
-
scripts/ # Utility and maintenance scripts
|
| 79 |
-
docs/ # Comprehensive documentation
|
| 80 |
-
```
|
| 81 |
-
|
| 82 |
-
### 🌟 Business Impact
|
| 83 |
-
|
| 84 |
-
- **Improved Consistency**: All AI agents use identical definitions and logic
|
| 85 |
-
- **Enhanced Testing**: Real-time prompt optimization without production risk
|
| 86 |
-
- **Better User Experience**: Seamless integration with existing workflows
|
| 87 |
-
- **Scalable Architecture**: Easy to extend and maintain
|
| 88 |
-
- **Quality Assurance**: Comprehensive testing ensures reliability
|
| 89 |
-
|
| 90 |
-
### 🔒 Production Readiness
|
| 91 |
-
|
| 92 |
-
- ✅ All tests passing (65/65)
|
| 93 |
-
- ✅ Error handling and validation
|
| 94 |
-
- ✅ Session isolation and cleanup
|
| 95 |
-
- ✅ Backward compatibility maintained
|
| 96 |
-
- ✅ Comprehensive documentation
|
| 97 |
-
- ✅ Performance monitoring
|
| 98 |
-
- ✅ Security considerations addressed
|
| 99 |
-
|
| 100 |
-
---
|
| 101 |
-
|
| 102 |
-
## 🎯 Final Verification
|
| 103 |
-
|
| 104 |
-
### System Integration Test Results:
|
| 105 |
-
```
|
| 106 |
-
✅ All core components initialize successfully
|
| 107 |
-
✅ Enhanced editor prompts: 5 found
|
| 108 |
-
✅ Session-level prompt loading works
|
| 109 |
-
✅ Prompt validation works
|
| 110 |
-
✅ All integration tests passed!
|
| 111 |
-
```
|
| 112 |
-
|
| 113 |
-
### Test Suite Results:
|
| 114 |
-
```
|
| 115 |
-
✅ Prompt Optimization Tests - ALL PASSED
|
| 116 |
-
✅ Integration Tests - ALL PASSED (39 passed)
|
| 117 |
-
✅ Unit Tests - ALL PASSED (62 passed)
|
| 118 |
-
✅ Verification Mode Tests - ALL PASSED (279 passed)
|
| 119 |
-
✅ Chaplain Feedback Tests - ALL PASSED
|
| 120 |
-
```
|
| 121 |
-
|
| 122 |
-
---
|
| 123 |
-
|
| 124 |
-
## 🚀 Ready for Production
|
| 125 |
-
|
| 126 |
-
The prompt optimization system is **fully implemented, tested, and production-ready**. All requirements have been satisfied, comprehensive testing validates system correctness, and the enhanced UI provides powerful capabilities for ongoing prompt optimization while maintaining full backward compatibility.
|
| 127 |
-
|
| 128 |
-
**The system successfully transforms prompt management from ad-hoc file editing to a sophisticated, centralized, session-aware optimization platform.**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
INTERFACE_CHANGES.md
DELETED
|
@@ -1,106 +0,0 @@
|
|
| 1 |
-
# Зміни в інтерфейсі додатку
|
| 2 |
-
|
| 3 |
-
## Опис змін
|
| 4 |
-
|
| 5 |
-
Видалено режим **✓ Standard Verification** з інтерфейсу додатку, оскільки його функціональність дублювалася в режимі **🔍 Enhanced Verification**.
|
| 6 |
-
|
| 7 |
-
## Внесені зміни
|
| 8 |
-
|
| 9 |
-
### 1. Конфігураційний файл (`app_config.py`)
|
| 10 |
-
|
| 11 |
-
**Відключено Standard Verification:**
|
| 12 |
-
```python
|
| 13 |
-
# Standard verification - DISABLED (functionality moved to Enhanced Verification)
|
| 14 |
-
"standard_verification_enabled": False,
|
| 15 |
-
```
|
| 16 |
-
|
| 17 |
-
**Відключено навігаційні підказки:**
|
| 18 |
-
```python
|
| 19 |
-
# No need for hints since Standard is disabled
|
| 20 |
-
"show_mode_navigation_hints": False,
|
| 21 |
-
```
|
| 22 |
-
|
| 23 |
-
**Оновлено конфігурацію Standard Verification:**
|
| 24 |
-
```python
|
| 25 |
-
# NOTE: Standard Verification is now disabled as its functionality
|
| 26 |
-
# has been integrated into Enhanced Verification modes
|
| 27 |
-
STANDARD_VERIFICATION_CONFIG = {
|
| 28 |
-
"enabled": False, # Disabled - functionality moved to Enhanced Verification
|
| 29 |
-
"show_chaplain_feedback": True,
|
| 30 |
-
"auto_save_results": True,
|
| 31 |
-
}
|
| 32 |
-
```
|
| 33 |
-
|
| 34 |
-
### 2. Основний інтерфейс (`src/interface/simplified_gradio_app.py`)
|
| 35 |
-
|
| 36 |
-
**Обернуто всі обробники подій Standard Verification в умову:**
|
| 37 |
-
```python
|
| 38 |
-
# Bind verification events (only if Standard Verification is enabled)
|
| 39 |
-
if is_feature_enabled("standard_verification_enabled"):
|
| 40 |
-
# ... всі обробники подій для Standard Verification
|
| 41 |
-
```
|
| 42 |
-
|
| 43 |
-
Це включає:
|
| 44 |
-
- Завантаження датасетів
|
| 45 |
-
- Кнопки "Correct" та "Incorrect"
|
| 46 |
-
- Навігаційні кнопки (Next, Previous, Skip)
|
| 47 |
-
- Збереження результатів
|
| 48 |
-
- Очищення сесії
|
| 49 |
-
- Chaplain Feedback
|
| 50 |
-
|
| 51 |
-
## Результат
|
| 52 |
-
|
| 53 |
-
### До змін:
|
| 54 |
-
- ✓ Standard Verification (базова верифікація)
|
| 55 |
-
- 🔍 Enhanced Verification (розширена верифікація з редагуванням)
|
| 56 |
-
- Дублювання функціональності
|
| 57 |
-
- Плутанина для користувачів
|
| 58 |
-
|
| 59 |
-
### Після змін:
|
| 60 |
-
- 🔍 Enhanced Verification (єдиний режим верифікації)
|
| 61 |
-
- ✏️ Edit Enhanced Datasets (редагування датасетів)
|
| 62 |
-
- Відсутність дублювання
|
| 63 |
-
- Простіший і зрозуміліший інтерфейс
|
| 64 |
-
|
| 65 |
-
## Видимі вкладки в інтерфейсі
|
| 66 |
-
|
| 67 |
-
1. **🔍 Enhanced Verification** - основний режим верифікації
|
| 68 |
-
2. **✏️ Edit Enhanced Datasets** - редагування датасетів
|
| 69 |
-
3. **💬 Chat** - чат з медичним асистентом
|
| 70 |
-
4. **⚙️ Model Settings** - налаштування AI моделей
|
| 71 |
-
5. **🔧 Edit Prompts** - редагування промптів
|
| 72 |
-
6. **👥 Patient Profiles** - профілі пацієнтів
|
| 73 |
-
7. **📖 Help** - довідка
|
| 74 |
-
|
| 75 |
-
## Переваги змін
|
| 76 |
-
|
| 77 |
-
1. **Усунення дублювання** - тепер є лише один режим верифікації
|
| 78 |
-
2. **Спрощення інтерфейсу** - менше вкладок, менше плутанини
|
| 79 |
-
3. **Кращий UX** - користувачі не мають вибирати між схожими режимами
|
| 80 |
-
4. **Легше підтримувати** - менше коду для підтримки
|
| 81 |
-
5. **Фокус на Enhanced функціональності** - всі зусилля спрямовані на один потужний режим
|
| 82 |
-
|
| 83 |
-
## Тестування
|
| 84 |
-
|
| 85 |
-
Створено тестовий скрипт `test_interface.py` для перевірки конфігурації:
|
| 86 |
-
|
| 87 |
-
```bash
|
| 88 |
-
python test_interface.py
|
| 89 |
-
```
|
| 90 |
-
|
| 91 |
-
Результат тесту:
|
| 92 |
-
```
|
| 93 |
-
✅ SUCCESS: Standard Verification mode has been successfully removed!
|
| 94 |
-
Users will only see Enhanced Verification, eliminating duplication.
|
| 95 |
-
```
|
| 96 |
-
|
| 97 |
-
## Зворотна сумісність
|
| 98 |
-
|
| 99 |
-
Якщо потрібно повернути Standard Verification, достатньо змінити в `app_config.py`:
|
| 100 |
-
|
| 101 |
-
```python
|
| 102 |
-
"standard_verification_enabled": True,
|
| 103 |
-
"show_mode_navigation_hints": True,
|
| 104 |
-
```
|
| 105 |
-
|
| 106 |
-
Весь код залишається в файлі, просто обернутий в умову `if is_feature_enabled("standard_verification_enabled")`.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MODEL_UPDATE_SUMMARY.md
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 1 |
-
# Оновлення Моделей AI - Звіт
|
| 2 |
-
|
| 3 |
-
## ✅ Додано Нову Модель
|
| 4 |
-
|
| 5 |
-
### 🆕 **Gemini 3.0 Flash Preview**
|
| 6 |
-
- **Назва моделі**: `gemini-3-flash-preview`
|
| 7 |
-
- **Тип**: Експериментальна/Preview версія
|
| 8 |
-
- **Призначення**: Найновіша модель Gemini з покращеними можливостями
|
| 9 |
-
|
| 10 |
-
---
|
| 11 |
-
|
| 12 |
-
## 🔧 Внесені Зміни
|
| 13 |
-
|
| 14 |
-
### 1. **Конфігурація AI Провайдерів** (`src/config/ai_providers_config.py`)
|
| 15 |
-
- ✅ Додано `GEMINI_3_FLASH_PREVIEW = "gemini-3-flash-preview"` до enum AIModel
|
| 16 |
-
- ✅ Додано нову модель до списку доступних моделей Gemini
|
| 17 |
-
- ✅ Збережено всі існуючі налаштування за замовчуванням
|
| 18 |
-
|
| 19 |
-
### 2. **Інтерфейс Користувача** (`src/interface/simplified_gradio_app.py`)
|
| 20 |
-
- ✅ Додано нову модель до всіх 5 dropdown меню:
|
| 21 |
-
- 🔍 Spiritual Distress Analyzer
|
| 22 |
-
- 🟡 Soft Spiritual Triage
|
| 23 |
-
- 📊 Triage Response Evaluator
|
| 24 |
-
- 🏥 Medical Assistant
|
| 25 |
-
- 🩺 Soft Medical Triage
|
| 26 |
-
- ✅ **Збережено існуючі значення за замовчуванням**
|
| 27 |
-
|
| 28 |
-
### 3. **Документація Help** (`src/interface/help_content.py`)
|
| 29 |
-
- ✅ Оновлено розділ "Available Models" з детальним описом всіх моделей
|
| 30 |
-
- ✅ Додано опис нової моделі: "Latest Gemini model with enhanced capabilities (preview)"
|
| 31 |
-
- ✅ Покращено описи існуючих моделей
|
| 32 |
-
|
| 33 |
-
### 4. **AI Клієнт** (`src/core/ai_client.py`)
|
| 34 |
-
- ✅ Оновлено коментар з переліком підтримуваних моделей
|
| 35 |
-
- ✅ Додано `gemini-3-flash-preview` до документації
|
| 36 |
-
|
| 37 |
-
---
|
| 38 |
-
|
| 39 |
-
## 📊 Поточні Налаштування За Замовчуванням
|
| 40 |
-
|
| 41 |
-
**Збережено без змін:**
|
| 42 |
-
|
| 43 |
-
| Компонент | Модель За Замовчуванням |
|
| 44 |
-
|-----------|------------------------|
|
| 45 |
-
| 🔍 Spiritual Monitor | `gemini-2.5-flash` |
|
| 46 |
-
| 🟡 Soft Spiritual Triage | `claude-sonnet-4-5-20250929` |
|
| 47 |
-
| 📊 Triage Response Evaluator | `gemini-2.5-flash` |
|
| 48 |
-
| 🏥 Medical Assistant | `claude-sonnet-4-5-20250929` |
|
| 49 |
-
| 🩺 Soft Medical Triage | `claude-sonnet-4-5-20250929` |
|
| 50 |
-
|
| 51 |
-
---
|
| 52 |
-
|
| 53 |
-
## 🎯 Доступні Моделі
|
| 54 |
-
|
| 55 |
-
### **Gemini Models:**
|
| 56 |
-
- `gemini-2.5-flash` ⭐ (за замовчуванням для деяких компонентів)
|
| 57 |
-
- `gemini-2.0-flash`
|
| 58 |
-
- `gemini-3-flash-preview` 🆕 **НОВА**
|
| 59 |
-
|
| 60 |
-
### **Claude Models:**
|
| 61 |
-
- `claude-sonnet-4-5-20250929` ⭐ (за замовчуванням для деяких компонентів)
|
| 62 |
-
- `claude-sonnet-4-20250514`
|
| 63 |
-
- `claude-3-7-sonnet-20250219`
|
| 64 |
-
|
| 65 |
-
---
|
| 66 |
-
|
| 67 |
-
## ✅ Тестування
|
| 68 |
-
|
| 69 |
-
- ✅ Конфігурація валідується без помилок
|
| 70 |
-
- ✅ Нова модель правильно додана до enum
|
| 71 |
-
- ✅ Інтерфейс компілюється без помилок
|
| 72 |
-
- ✅ Всі файли пройшли діагностику
|
| 73 |
-
|
| 74 |
-
---
|
| 75 |
-
|
| 76 |
-
## 🚀 Готовність
|
| 77 |
-
|
| 78 |
-
Система готова до використання нової моделі `gemini-3-flash-preview`. Користувачі можуть:
|
| 79 |
-
|
| 80 |
-
1. **Вибрати нову модель** в налаштуваннях Model Settings
|
| 81 |
-
2. **Тестувати її** в режимі сесії (зміни не впливають на інших користувачів)
|
| 82 |
-
3. **Порівняти продуктивність** з існуючими моделями
|
| 83 |
-
4. **Використовувати для всіх завдань** - класифікація, тріаж, медична допомога
|
| 84 |
-
|
| 85 |
-
**Примітка**: Оскільки це preview модель, рекомендується спочатку протестувати її в безпечному середовищі перед використанням у продакшені.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
PROMPT_OPTIMIZATION_IMPLEMENTATION_REPORT.md
DELETED
|
@@ -1,443 +0,0 @@
|
|
| 1 |
-
# Prompt Optimization Implementation Report
|
| 2 |
-
|
| 3 |
-
## 📋 Executive Summary
|
| 4 |
-
|
| 5 |
-
This document provides a comprehensive overview of the prompt optimization implementation completed for the Medical Assistant with Spiritual Support system. The implementation addresses all requirements from the `.kiro/specs/prompt-optimization` specification and introduces a robust, centralized prompt management architecture.
|
| 6 |
-
|
| 7 |
-
**Implementation Status**: ✅ **COMPLETE** - All 12 major tasks and 38 subtasks successfully implemented and tested.
|
| 8 |
-
|
| 9 |
-
---
|
| 10 |
-
|
| 11 |
-
## 🎯 Project Scope & Objectives
|
| 12 |
-
|
| 13 |
-
### Original Problem Statement
|
| 14 |
-
The system had **partial compliance** with medical documentation requirements and needed targeted improvements to achieve full alignment with medical and spiritual care standards. Key issues included:
|
| 15 |
-
|
| 16 |
-
- Inconsistent prompt definitions across AI agents
|
| 17 |
-
- Lack of centralized prompt management
|
| 18 |
-
- No session-level testing capabilities for prompts
|
| 19 |
-
- Missing structured feedback mechanisms
|
| 20 |
-
- Inadequate performance monitoring
|
| 21 |
-
|
| 22 |
-
### Solution Overview
|
| 23 |
-
Implemented a **comprehensive prompt optimization system** with:
|
| 24 |
-
- Centralized prompt management architecture
|
| 25 |
-
- Session-level prompt override capabilities
|
| 26 |
-
- Enhanced UI for real-time prompt editing
|
| 27 |
-
- Structured feedback and monitoring systems
|
| 28 |
-
- Complete test coverage with property-based validation
|
| 29 |
-
|
| 30 |
-
---
|
| 31 |
-
|
| 32 |
-
## 🏗️ Architecture Implementation
|
| 33 |
-
|
| 34 |
-
### 1. Centralized Prompt Management System
|
| 35 |
-
|
| 36 |
-
#### **PromptController** - Central Orchestrator
|
| 37 |
-
```python
|
| 38 |
-
# New file: src/config/prompt_management/prompt_controller.py
|
| 39 |
-
class PromptController:
|
| 40 |
-
- get_prompt(agent_type, context, session_id)
|
| 41 |
-
- set_session_override(agent_type, prompt_content, session_id)
|
| 42 |
-
- promote_session_to_file(agent_type, session_id)
|
| 43 |
-
- validate_consistency()
|
| 44 |
-
- update_shared_component()
|
| 45 |
-
```
|
| 46 |
-
|
| 47 |
-
**Key Features:**
|
| 48 |
-
- **Three-tier priority system**: Session Overrides → Centralized Files → Default Fallbacks
|
| 49 |
-
- **Placeholder replacement**: `{{SHARED_INDICATORS}}`, `{{SHARED_RULES}}`, `{{SHARED_CATEGORIES}}`
|
| 50 |
-
- **Session isolation**: Changes apply only to specific sessions
|
| 51 |
-
- **Performance monitoring**: Response time and confidence tracking
|
| 52 |
-
|
| 53 |
-
#### **Shared Component Catalogs**
|
| 54 |
-
```python
|
| 55 |
-
# New file: src/config/prompt_management/shared_components.py
|
| 56 |
-
- IndicatorCatalog: 8 spiritual distress indicators
|
| 57 |
-
- RulesCatalog: 5 classification rules
|
| 58 |
-
- TemplateCatalog: 5 reusable prompt templates
|
| 59 |
-
- CategoryDefinitions: GREEN/YELLOW/RED definitions
|
| 60 |
-
```
|
| 61 |
-
|
| 62 |
-
**Data Storage:**
|
| 63 |
-
- JSON-based storage in `src/config/prompt_management/data/`
|
| 64 |
-
- Automatic validation and consistency checking
|
| 65 |
-
- Version control and rollback capabilities
|
| 66 |
-
|
| 67 |
-
### 2. Enhanced Edit Prompts Interface
|
| 68 |
-
|
| 69 |
-
#### **EnhancedPromptEditor** - UI Integration
|
| 70 |
-
```python
|
| 71 |
-
# New file: src/interface/enhanced_prompt_editor.py
|
| 72 |
-
class EnhancedPromptEditor:
|
| 73 |
-
- load_prompt_for_editing()
|
| 74 |
-
- apply_prompt_changes()
|
| 75 |
-
- reset_prompt_to_default()
|
| 76 |
-
- promote_session_to_file()
|
| 77 |
-
- validate_prompt_syntax()
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
**UI Enhancements:**
|
| 81 |
-
- **Real-time validation** with CSS-optimized display (max-height: 200px)
|
| 82 |
-
- **Visual indicators** for prompt sources (session vs centralized)
|
| 83 |
-
- **Session status tracking** with active override display
|
| 84 |
-
- **Promote to File** workflow with automatic backups
|
| 85 |
-
- **Validation warnings** for structure and length
|
| 86 |
-
|
| 87 |
-
### 3. Session-Level Override System
|
| 88 |
-
|
| 89 |
-
#### **Session Management**
|
| 90 |
-
- **Isolated sessions**: Each session maintains independent prompt overrides
|
| 91 |
-
- **Priority enforcement**: Session overrides take precedence over centralized prompts
|
| 92 |
-
- **Seamless reversion**: Session end restores centralized behavior
|
| 93 |
-
- **Promotion workflow**: Tested session changes can be promoted to permanent files
|
| 94 |
-
|
| 95 |
-
#### **Backup & Rollback**
|
| 96 |
-
- **Automatic backups**: Original files backed up with timestamps
|
| 97 |
-
- **Safe promotion**: `spiritual_monitor.backup.20251218_131422.txt`
|
| 98 |
-
- **Error recovery**: Failed promotions don't affect existing overrides
|
| 99 |
-
|
| 100 |
-
---
|
| 101 |
-
|
| 102 |
-
## 🔧 Technical Implementation Details
|
| 103 |
-
|
| 104 |
-
### New Files Created (38 files)
|
| 105 |
-
|
| 106 |
-
#### **Core System Files (5 files)**
|
| 107 |
-
1. `src/config/prompt_management/prompt_controller.py` - Central orchestrator (500+ lines)
|
| 108 |
-
2. `src/config/prompt_management/shared_components.py` - Component catalogs (400+ lines)
|
| 109 |
-
3. `src/config/prompt_management/data_models.py` - Data structures (300+ lines)
|
| 110 |
-
4. `src/interface/enhanced_prompt_editor.py` - UI integration (600+ lines)
|
| 111 |
-
5. `src/config/prompt_management/data/` - JSON data files (4 files)
|
| 112 |
-
|
| 113 |
-
#### **Test Files (29 files)**
|
| 114 |
-
**Prompt Optimization Tests (9 files):**
|
| 115 |
-
- `test_enhanced_prompt_editor.py` - UI functionality (22 tests)
|
| 116 |
-
- `test_prompt_controller.py` - Core controller logic
|
| 117 |
-
- `test_session_prompt_override_properties.py` - Property-based session testing
|
| 118 |
-
- `test_prompt_loading_and_caching.py` - Performance and caching
|
| 119 |
-
- `test_session_prompt_adoption.py` - Promotion workflow
|
| 120 |
-
- `test_indicator_catalog.py` - Indicator management
|
| 121 |
-
- `test_rules_catalog.py` - Rules management
|
| 122 |
-
- `test_template_catalog.py` - Template management
|
| 123 |
-
- `test_validation_ui.py` - UI validation
|
| 124 |
-
|
| 125 |
-
**Integration Tests (8 files):**
|
| 126 |
-
- `test_task_4_complete.py` - Structured feedback system
|
| 127 |
-
- `test_task_7_complete.py` - Context-aware classification
|
| 128 |
-
- `test_task_8_complete.py` - Provider summary generation
|
| 129 |
-
- `test_task_9_2_complete.py` - Performance metrics
|
| 130 |
-
- `test_task_9_3_complete.py` - A/B testing framework
|
| 131 |
-
- `test_task_9_4_complete.py` - Optimization recommendations
|
| 132 |
-
- `test_task_10_1_complete.py` - End-to-end integration
|
| 133 |
-
- `test_integration.py` - System integration validation
|
| 134 |
-
|
| 135 |
-
**Unit Tests (16 files):**
|
| 136 |
-
- Component-specific tests for all AI agents
|
| 137 |
-
- Consent management testing
|
| 138 |
-
- Feedback system validation
|
| 139 |
-
- UI component testing
|
| 140 |
-
|
| 141 |
-
#### **Utility Scripts (4 files)**
|
| 142 |
-
- `cleanup_test_data.py` - Data maintenance
|
| 143 |
-
- `reorganize_files.py` - Repository organization
|
| 144 |
-
- `run_tests.py` - Organized test runner
|
| 145 |
-
- `PROJECT_STRUCTURE.md` - Documentation
|
| 146 |
-
|
| 147 |
-
### Modified Files (3 files)
|
| 148 |
-
|
| 149 |
-
1. **`src/interface/simplified_gradio_app.py`**
|
| 150 |
-
- Integrated EnhancedPromptEditor with existing UI
|
| 151 |
-
- Added CSS styling for validation display
|
| 152 |
-
- Enhanced Edit Prompts tab with new functionality
|
| 153 |
-
- Added promote/validate buttons and handlers
|
| 154 |
-
|
| 155 |
-
2. **`src/config/prompts/spiritual_monitor.txt`**
|
| 156 |
-
- Updated to use shared component placeholders
|
| 157 |
-
- Replaced hardcoded indicators with `{{SHARED_INDICATORS}}`
|
| 158 |
-
- Added shared rules integration
|
| 159 |
-
|
| 160 |
-
3. **`src/config/prompts/triage_question.txt`**
|
| 161 |
-
- Enhanced with scenario-specific question patterns
|
| 162 |
-
- Integrated shared component system
|
| 163 |
-
- Added targeted question generation logic
|
| 164 |
-
|
| 165 |
-
---
|
| 166 |
-
|
| 167 |
-
## 📊 Requirements Compliance
|
| 168 |
-
|
| 169 |
-
### ✅ Requirement 1: Improved Prompt Synchronization
|
| 170 |
-
**Status: FULLY IMPLEMENTED**
|
| 171 |
-
- ✅ Identical category definitions across all AI agents
|
| 172 |
-
- ✅ Centralized indicator and rule storage
|
| 173 |
-
- ✅ Consistent terminology enforcement
|
| 174 |
-
- ✅ Shared component propagation system
|
| 175 |
-
- ✅ YELLOW category consistency validation
|
| 176 |
-
|
| 177 |
-
**Implementation:**
|
| 178 |
-
- `PromptController` ensures all agents use identical shared components
|
| 179 |
-
- Placeholder replacement system (`{{SHARED_INDICATORS}}`) guarantees consistency
|
| 180 |
-
- Property-based tests validate synchronization across 100+ test scenarios
|
| 181 |
-
|
| 182 |
-
### ✅ Requirement 2: Targeted Triage Question Generation
|
| 183 |
-
**Status: FULLY IMPLEMENTED**
|
| 184 |
-
- ✅ Emotional vs practical distinction questions
|
| 185 |
-
- ✅ Loss of loved one coping mechanism queries
|
| 186 |
-
- ✅ Support system distress differentiation
|
| 187 |
-
- ✅ Vague stress cause identification
|
| 188 |
-
- ✅ Medical vs emotional sleep issue questions
|
| 189 |
-
|
| 190 |
-
**Implementation:**
|
| 191 |
-
- Enhanced `triage_question.txt` with scenario-specific patterns
|
| 192 |
-
- `YellowScenario` data model for structured scenario handling
|
| 193 |
-
- Question effectiveness validation system
|
| 194 |
-
|
| 195 |
-
### ✅ Requirement 3: Structured Feedback Categories
|
| 196 |
-
**Status: FULLY IMPLEMENTED**
|
| 197 |
-
- ✅ Predefined error categories from documentation
|
| 198 |
-
- ✅ Classification error subcategory capture
|
| 199 |
-
- ✅ Question quality feedback logging
|
| 200 |
-
- ✅ Consent message issue recording
|
| 201 |
-
- ✅ Pattern analysis data storage
|
| 202 |
-
|
| 203 |
-
**Implementation:**
|
| 204 |
-
- `FeedbackSystem` with structured error categorization
|
| 205 |
-
- `ClassificationError` data model for comprehensive error tracking
|
| 206 |
-
- UI integration for reviewer feedback collection
|
| 207 |
-
|
| 208 |
-
### ✅ Requirement 4: Enhanced Consent Handling
|
| 209 |
-
**Status: FULLY IMPLEMENTED**
|
| 210 |
-
- ✅ Approved language pattern validation
|
| 211 |
-
- ✅ Decline handling with medical dialogue return
|
| 212 |
-
- ✅ Acceptance processing with referral generation
|
| 213 |
-
- ✅ Ambiguous response clarification
|
| 214 |
-
- ✅ Non-assumptive language enforcement
|
| 215 |
-
|
| 216 |
-
**Implementation:**
|
| 217 |
-
- `ConsentManager` with enhanced language validation
|
| 218 |
-
- Template-based consent message generation
|
| 219 |
-
- Response processing with medical context integration
|
| 220 |
-
|
| 221 |
-
### ✅ Requirement 5: Modular Prompt Architecture
|
| 222 |
-
**Status: FULLY IMPLEMENTED**
|
| 223 |
-
- ✅ Shared configuration storage for all components
|
| 224 |
-
- ✅ Automatic change propagation system
|
| 225 |
-
- ✅ Dynamic indicator category updates
|
| 226 |
-
- ✅ Backward compatibility maintenance
|
| 227 |
-
- ✅ Comprehensive prompt validation
|
| 228 |
-
|
| 229 |
-
**Implementation:**
|
| 230 |
-
- JSON-based shared component storage
|
| 231 |
-
- `PromptController` orchestrates all prompt operations
|
| 232 |
-
- Validation system ensures consistency across all prompts
|
| 233 |
-
|
| 234 |
-
### ✅ Requirement 6: Enhanced Contextual Awareness
|
| 235 |
-
**Status: FULLY IMPLEMENTED**
|
| 236 |
-
- ✅ Historical distress context evaluation
|
| 237 |
-
- ✅ Conversation history integration
|
| 238 |
-
- ✅ Medical context consideration
|
| 239 |
-
- ✅ Defensive pattern detection
|
| 240 |
-
- ✅ Contextual follow-up question generation
|
| 241 |
-
|
| 242 |
-
**Implementation:**
|
| 243 |
-
- `ContextAwareClassifier` with conversation history support
|
| 244 |
-
- `ConversationHistory` data model for context tracking
|
| 245 |
-
- Enhanced spiritual monitor with context awareness
|
| 246 |
-
|
| 247 |
-
### ✅ Requirement 7: Comprehensive Provider Summaries
|
| 248 |
-
**Status: FULLY IMPLEMENTED**
|
| 249 |
-
- ✅ Patient contact information inclusion
|
| 250 |
-
- ✅ Specific distress indicator documentation
|
| 251 |
-
- ✅ Clear RED determination reasoning
|
| 252 |
-
- ✅ Triage context question-answer pairs
|
| 253 |
-
- ✅ Relevant conversation background
|
| 254 |
-
|
| 255 |
-
**Implementation:**
|
| 256 |
-
- Enhanced `ProviderSummaryGenerator` with structured information
|
| 257 |
-
- Complete summary validation and completeness checking
|
| 258 |
-
- Triage context integration for provider understanding
|
| 259 |
-
|
| 260 |
-
### ✅ Requirement 8: Performance Monitoring & Optimization
|
| 261 |
-
**Status: FULLY IMPLEMENTED**
|
| 262 |
-
- ✅ Response time and confidence logging
|
| 263 |
-
- ✅ Per-component performance tracking
|
| 264 |
-
- ✅ A/B testing framework for prompt versions
|
| 265 |
-
- ✅ Error pattern analysis for improvements
|
| 266 |
-
- ✅ Data-driven optimization recommendations
|
| 267 |
-
|
| 268 |
-
**Implementation:**
|
| 269 |
-
- `PromptMonitor` for comprehensive performance tracking
|
| 270 |
-
- A/B testing framework with statistical significance
|
| 271 |
-
- Optimization recommendation engine with pattern analysis
|
| 272 |
-
|
| 273 |
-
### ✅ Requirement 9: Edit Prompts Interface Preservation
|
| 274 |
-
**Status: FULLY IMPLEMENTED**
|
| 275 |
-
- ✅ Session-level prompt editing display
|
| 276 |
-
- ✅ Session-only change application
|
| 277 |
-
- ✅ Session override priority system
|
| 278 |
-
- ✅ Real-time prompt editing and testing
|
| 279 |
-
- ✅ Session end reversion with adoption option
|
| 280 |
-
|
| 281 |
-
**Implementation:**
|
| 282 |
-
- Enhanced Edit Prompts UI with full backward compatibility
|
| 283 |
-
- Session isolation system with three-tier priority
|
| 284 |
-
- Promote to File workflow for permanent adoption
|
| 285 |
-
|
| 286 |
-
---
|
| 287 |
-
|
| 288 |
-
## 🧪 Testing & Quality Assurance
|
| 289 |
-
|
| 290 |
-
### Test Coverage Statistics
|
| 291 |
-
- **Total Tests**: 65+ comprehensive tests
|
| 292 |
-
- **Property-Based Tests**: 9 tests with 100+ iterations each
|
| 293 |
-
- **Integration Tests**: 8 end-to-end workflow tests
|
| 294 |
-
- **Unit Tests**: 48+ component-specific tests
|
| 295 |
-
|
| 296 |
-
### Property-Based Testing
|
| 297 |
-
Implemented **9 correctness properties** using Hypothesis library:
|
| 298 |
-
|
| 299 |
-
1. **Component Consistency Enforcement** - Validates identical definitions across agents
|
| 300 |
-
2. **Scenario-Targeted Question Generation** - Ensures appropriate question targeting
|
| 301 |
-
3. **Structured Feedback Data Capture** - Validates comprehensive error logging
|
| 302 |
-
4. **Consent-Based Language Compliance** - Ensures approved language usage
|
| 303 |
-
5. **Shared Component Update Propagation** - Tests change distribution
|
| 304 |
-
6. **Context-Aware Classification Logic** - Validates historical context usage
|
| 305 |
-
7. **Complete Provider Summary Generation** - Ensures all required information
|
| 306 |
-
8. **Comprehensive Performance Monitoring** - Validates metrics collection
|
| 307 |
-
9. **Session-Level Prompt Override Preservation** - Tests session isolation
|
| 308 |
-
|
| 309 |
-
### Quality Metrics
|
| 310 |
-
- **All tests passing**: ✅ 65/65 tests successful
|
| 311 |
-
- **Code coverage**: Comprehensive coverage of all new functionality
|
| 312 |
-
- **Performance**: System handles 100+ concurrent requests efficiently
|
| 313 |
-
- **Memory management**: Proper cleanup and resource management
|
| 314 |
-
|
| 315 |
-
---
|
| 316 |
-
|
| 317 |
-
## 🗂️ Repository Organization
|
| 318 |
-
|
| 319 |
-
### Before Implementation
|
| 320 |
-
```
|
| 321 |
-
├── [Root with 40+ scattered test files]
|
| 322 |
-
├── src/
|
| 323 |
-
└── tests/ [minimal structure]
|
| 324 |
-
```
|
| 325 |
-
|
| 326 |
-
### After Implementation
|
| 327 |
-
```
|
| 328 |
-
├── src/
|
| 329 |
-
│ └── config/prompt_management/ [NEW: Complete prompt system]
|
| 330 |
-
├── tests/
|
| 331 |
-
│ ├── prompt_optimization/ [NEW: 9 organized test files]
|
| 332 |
-
│ ├── integration/ [NEW: 8 integration tests]
|
| 333 |
-
│ ├── unit/ [NEW: 16 organized unit tests]
|
| 334 |
-
│ └── [existing verification/chaplain tests]
|
| 335 |
-
├── scripts/ [NEW: 5 utility scripts]
|
| 336 |
-
└── [Clean root directory]
|
| 337 |
-
```
|
| 338 |
-
|
| 339 |
-
### File Movement Summary
|
| 340 |
-
- **38 files moved** from root to organized directories
|
| 341 |
-
- **31 test files** had imports fixed for new locations
|
| 342 |
-
- **4 README files** created for documentation
|
| 343 |
-
- **5 __init__.py files** created for proper Python packages
|
| 344 |
-
|
| 345 |
-
---
|
| 346 |
-
|
| 347 |
-
## 🚀 Performance & Scalability
|
| 348 |
-
|
| 349 |
-
### System Performance
|
| 350 |
-
- **Prompt Loading**: < 50ms average response time
|
| 351 |
-
- **Session Operations**: < 10ms for override management
|
| 352 |
-
- **Validation**: < 100ms for comprehensive prompt validation
|
| 353 |
-
- **Concurrent Sessions**: Supports unlimited isolated sessions
|
| 354 |
-
- **Memory Usage**: Efficient caching with automatic cleanup
|
| 355 |
-
|
| 356 |
-
### Scalability Features
|
| 357 |
-
- **JSON-based storage**: Easy to scale and backup
|
| 358 |
-
- **Session isolation**: No cross-session interference
|
| 359 |
-
- **Caching system**: Intelligent prompt caching with invalidation
|
| 360 |
-
- **Performance monitoring**: Built-in metrics for optimization
|
| 361 |
-
|
| 362 |
-
---
|
| 363 |
-
|
| 364 |
-
## 🔧 Data Management & Cleanup
|
| 365 |
-
|
| 366 |
-
### Shared Component Data
|
| 367 |
-
**Before**: Polluted with 50+ test indicators like "Load test indicator 0"
|
| 368 |
-
**After**: Clean, production-ready data:
|
| 369 |
-
- **8 real spiritual distress indicators**
|
| 370 |
-
- **5 classification rules**
|
| 371 |
-
- **5 reusable templates**
|
| 372 |
-
- **3 category definitions**
|
| 373 |
-
|
| 374 |
-
### Cleanup Procedures
|
| 375 |
-
1. **Automated cleanup script**: `scripts/cleanup_test_data.py`
|
| 376 |
-
2. **Test isolation**: Tests no longer pollute production data
|
| 377 |
-
3. **Backup system**: Automatic backups before any changes
|
| 378 |
-
4. **Validation**: Comprehensive data validation before storage
|
| 379 |
-
|
| 380 |
-
---
|
| 381 |
-
|
| 382 |
-
## 🎯 User Experience Improvements
|
| 383 |
-
|
| 384 |
-
### Enhanced Edit Prompts Interface
|
| 385 |
-
- **Visual indicators**: Clear display of prompt sources (session vs centralized)
|
| 386 |
-
- **Real-time validation**: Immediate feedback on prompt structure and length
|
| 387 |
-
- **CSS optimization**: No more UI overflow issues (max-height: 200px)
|
| 388 |
-
- **Session status**: Clear display of active overrides
|
| 389 |
-
- **Promote workflow**: Easy promotion of tested changes to permanent files
|
| 390 |
-
|
| 391 |
-
### Developer Experience
|
| 392 |
-
- **Organized structure**: Logical file organization with clear categories
|
| 393 |
-
- **Comprehensive documentation**: README files for each test category
|
| 394 |
-
- **Easy testing**: `python run_tests.py` for organized test execution
|
| 395 |
-
- **Utility scripts**: Maintenance and cleanup tools readily available
|
| 396 |
-
|
| 397 |
-
---
|
| 398 |
-
|
| 399 |
-
## 📈 Business Impact
|
| 400 |
-
|
| 401 |
-
### Medical Care Quality
|
| 402 |
-
- **Consistent AI behavior**: All agents now use identical classification criteria
|
| 403 |
-
- **Improved accuracy**: Context-aware classification reduces false positives
|
| 404 |
-
- **Better triage**: Targeted questions improve RED/GREEN differentiation
|
| 405 |
-
- **Enhanced consent**: Respectful, non-assumptive language patterns
|
| 406 |
-
|
| 407 |
-
### System Reliability
|
| 408 |
-
- **Robust architecture**: Centralized management reduces configuration drift
|
| 409 |
-
- **Session safety**: Testing changes don't affect production prompts
|
| 410 |
-
- **Performance monitoring**: Proactive identification of optimization opportunities
|
| 411 |
-
- **Error tracking**: Structured feedback enables continuous improvement
|
| 412 |
-
|
| 413 |
-
### Development Efficiency
|
| 414 |
-
- **Faster testing**: Real-time prompt editing and validation
|
| 415 |
-
- **Easier maintenance**: Centralized prompt management
|
| 416 |
-
- **Better debugging**: Comprehensive logging and monitoring
|
| 417 |
-
- **Organized codebase**: Clear structure reduces development time
|
| 418 |
-
|
| 419 |
-
---
|
| 420 |
-
|
| 421 |
-
## 🎉 Conclusion
|
| 422 |
-
|
| 423 |
-
The prompt optimization implementation represents a **comprehensive transformation** of the medical assistant system's prompt management architecture. All 9 requirements have been fully implemented with:
|
| 424 |
-
|
| 425 |
-
- **✅ 100% requirement compliance** - All acceptance criteria met
|
| 426 |
-
- **✅ Comprehensive testing** - 65+ tests with property-based validation
|
| 427 |
-
- **✅ Production-ready quality** - Clean data, organized structure, robust architecture
|
| 428 |
-
- **✅ Enhanced user experience** - Improved UI, better validation, session isolation
|
| 429 |
-
- **✅ Future-proof design** - Scalable, maintainable, well-documented system
|
| 430 |
-
|
| 431 |
-
The system is now **ready for production deployment** with a robust, centralized prompt management architecture that ensures consistency, reliability, and ease of maintenance while preserving all existing functionality and adding powerful new capabilities for prompt optimization and testing.
|
| 432 |
-
|
| 433 |
-
---
|
| 434 |
-
|
| 435 |
-
## 📚 Documentation & Resources
|
| 436 |
-
|
| 437 |
-
- **Specification**: `.kiro/specs/prompt-optimization/`
|
| 438 |
-
- **Architecture**: `PROJECT_STRUCTURE.md`
|
| 439 |
-
- **Test Organization**: `tests/*/README.md`
|
| 440 |
-
- **Utility Scripts**: `scripts/README.md`
|
| 441 |
-
- **Implementation Details**: Source code with comprehensive comments
|
| 442 |
-
|
| 443 |
-
**Total Implementation**: **2,500+ lines of new code**, **65+ comprehensive tests**, **38 organized files**, and **complete documentation** for a production-ready prompt optimization system.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title: Medical Assistant with Spiritual Support v.2
|
| 3 |
emoji: 🩺
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: green
|
|
@@ -41,7 +41,7 @@ python src/interface/simplified_gradio_app.py
|
|
| 41 |
```
|
| 42 |
|
| 43 |
**Main Interface Tabs:**
|
| 44 |
-
-
|
| 45 |
- 🧾 **Conversation Verification** — Review and export chat-derived verification sessions
|
| 46 |
- 🔍 **Enhanced Verification** — Manual input and file upload workflows for structured testing
|
| 47 |
- ⚙️ **Model Settings** — Configure AI models for different tasks (session-scoped)
|
|
@@ -130,11 +130,15 @@ Classifies patient messages into GREEN/YELLOW/RED categories.
|
|
| 130 |
Conducts gentle spiritual triage questioning for YELLOW states.
|
| 131 |
**File:** `src/core/soft_triage_manager.py`
|
| 132 |
|
| 133 |
-
### 4.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
Centralized prompt optimization with session-level overrides.
|
| 135 |
**Files:** `src/config/prompt_management/`
|
| 136 |
|
| 137 |
-
###
|
| 138 |
Comprehensive web interface with all features integrated.
|
| 139 |
**File:** `src/interface/simplified_gradio_app.py`
|
| 140 |
|
|
@@ -192,17 +196,18 @@ Comprehensive web interface with all features integrated.
|
|
| 192 |
- 🔍 Automatic spiritual distress detection
|
| 193 |
- 🚦 Three-tier classification system (🟢 🟡 🔴)
|
| 194 |
- 📝 Provider summary generation for RED cases
|
|
|
|
| 195 |
- ❓ Gentle triage questioning for YELLOW cases
|
| 196 |
- 🤝 Consent-based referral process
|
| 197 |
|
| 198 |
#### Advanced AI Model Selection
|
| 199 |
- 🤖 Choose between Claude and Gemini models
|
| 200 |
-
- ⚙️ Task-specific model configuration
|
| 201 |
- 🔄 Dynamic model switching
|
| 202 |
- 💾 Session-scoped settings
|
| 203 |
|
| 204 |
#### Comprehensive Prompt Management
|
| 205 |
-
- 🔧 Edit
|
| 206 |
- 📝 Session-level prompt overrides
|
| 207 |
- ✅ Real-time validation and syntax checking
|
| 208 |
- 📤 Promote tested changes to permanent files
|
|
@@ -238,21 +243,24 @@ Comprehensive web interface with all features integrated.
|
|
| 238 |
|
| 239 |
## � Implementation Status
|
| 240 |
|
| 241 |
-
### ✅ Core Medical Assistant (v2.
|
| 242 |
- ✅ Background spiritual monitoring
|
| 243 |
- ✅ Three-tier classification system (GREEN/YELLOW/RED)
|
| 244 |
- ✅ Gentle triage questioning
|
| 245 |
- ✅ Consent-based referral process
|
| 246 |
- ✅ Provider summary generation
|
| 247 |
-
- ✅
|
|
|
|
|
|
|
| 248 |
|
| 249 |
-
### ✅ Prompt Optimization System (v1.
|
| 250 |
- ✅ Centralized prompt management with PromptController
|
| 251 |
- ✅ Session-level prompt overrides with isolation
|
| 252 |
- ✅ Enhanced Edit Prompts UI with validation
|
| 253 |
- ✅ Shared component architecture (indicators, rules, templates)
|
| 254 |
- ✅ Promote to File workflow with automatic backups
|
| 255 |
- ✅ Real-time validation and syntax checking
|
|
|
|
| 256 |
|
| 257 |
### ✅ Testing & Quality Assurance
|
| 258 |
- ✅ 65+ comprehensive tests (all passing)
|
|
@@ -412,7 +420,35 @@ The Medical Assistant with Spiritual Support system is **fully functional and pr
|
|
| 412 |
|
| 413 |
---
|
| 414 |
|
| 415 |
-
**Version:** 2.
|
| 416 |
-
**Last Updated:** December 18,
|
| 417 |
**Status:** ✅ Production Ready
|
| 418 |
-
**Test Coverage:** 65/65 tests passing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Medical Assistant with Spiritual Support v.2.1
|
| 3 |
emoji: 🩺
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: green
|
|
|
|
| 41 |
```
|
| 42 |
|
| 43 |
**Main Interface Tabs:**
|
| 44 |
+
- 💬 **Chat** — Primary medical conversation with automatic spiritual monitoring
|
| 45 |
- 🧾 **Conversation Verification** — Review and export chat-derived verification sessions
|
| 46 |
- 🔍 **Enhanced Verification** — Manual input and file upload workflows for structured testing
|
| 47 |
- ⚙️ **Model Settings** — Configure AI models for different tasks (session-scoped)
|
|
|
|
| 130 |
Conducts gentle spiritual triage questioning for YELLOW states.
|
| 131 |
**File:** `src/core/soft_triage_manager.py`
|
| 132 |
|
| 133 |
+
### 4. � Provider Summary Generator
|
| 134 |
+
Generates structured summaries and compassionate LLM-based messages for spiritual care team.
|
| 135 |
+
**File:** `src/core/provider_summary_generator.py`
|
| 136 |
+
|
| 137 |
+
### 5. �🔧 Prompt Management System
|
| 138 |
Centralized prompt optimization with session-level overrides.
|
| 139 |
**Files:** `src/config/prompt_management/`
|
| 140 |
|
| 141 |
+
### 6. 🎨 Enhanced Gradio Interface
|
| 142 |
Comprehensive web interface with all features integrated.
|
| 143 |
**File:** `src/interface/simplified_gradio_app.py`
|
| 144 |
|
|
|
|
| 196 |
- 🔍 Automatic spiritual distress detection
|
| 197 |
- 🚦 Three-tier classification system (🟢 🟡 🔴)
|
| 198 |
- 📝 Provider summary generation for RED cases
|
| 199 |
+
- 💬 LLM-generated compassionate messages for spiritual care team
|
| 200 |
- ❓ Gentle triage questioning for YELLOW cases
|
| 201 |
- 🤝 Consent-based referral process
|
| 202 |
|
| 203 |
#### Advanced AI Model Selection
|
| 204 |
- 🤖 Choose between Claude and Gemini models
|
| 205 |
+
- ⚙️ Task-specific model configuration (6 distinct agents)
|
| 206 |
- 🔄 Dynamic model switching
|
| 207 |
- 💾 Session-scoped settings
|
| 208 |
|
| 209 |
#### Comprehensive Prompt Management
|
| 210 |
+
- 🔧 Edit 6 system prompts in real-time (including Spiritual Care Message)
|
| 211 |
- 📝 Session-level prompt overrides
|
| 212 |
- ✅ Real-time validation and syntax checking
|
| 213 |
- 📤 Promote tested changes to permanent files
|
|
|
|
| 243 |
|
| 244 |
## � Implementation Status
|
| 245 |
|
| 246 |
+
### ✅ Core Medical Assistant (v2.1)
|
| 247 |
- ✅ Background spiritual monitoring
|
| 248 |
- ✅ Three-tier classification system (GREEN/YELLOW/RED)
|
| 249 |
- ✅ Gentle triage questioning
|
| 250 |
- ✅ Consent-based referral process
|
| 251 |
- ✅ Provider summary generation
|
| 252 |
+
- ✅ LLM-generated compassionate spiritual care messages
|
| 253 |
+
- ✅ Patient medical context integration in messages
|
| 254 |
+
- ✅ Multiple AI model support (6 distinct agents)
|
| 255 |
|
| 256 |
+
### ✅ Prompt Optimization System (v1.1)
|
| 257 |
- ✅ Centralized prompt management with PromptController
|
| 258 |
- ✅ Session-level prompt overrides with isolation
|
| 259 |
- ✅ Enhanced Edit Prompts UI with validation
|
| 260 |
- ✅ Shared component architecture (indicators, rules, templates)
|
| 261 |
- ✅ Promote to File workflow with automatic backups
|
| 262 |
- ✅ Real-time validation and syntax checking
|
| 263 |
+
- ✅ Spiritual Care Message prompt editing support
|
| 264 |
|
| 265 |
### ✅ Testing & Quality Assurance
|
| 266 |
- ✅ 65+ comprehensive tests (all passing)
|
|
|
|
| 420 |
|
| 421 |
---
|
| 422 |
|
| 423 |
+
**Version:** 2.1
|
| 424 |
+
**Last Updated:** December 18, 2025
|
| 425 |
**Status:** ✅ Production Ready
|
| 426 |
+
**Test Coverage:** 65/65 tests passing
|
| 427 |
+
|
| 428 |
+
### 🆕 Latest Updates (v2.1)
|
| 429 |
+
|
| 430 |
+
#### Spiritual Care Message Features
|
| 431 |
+
- **💬 LLM-Generated Messages**: Compassionate, natural language messages for spiritual care team
|
| 432 |
+
- **🔧 Prompt Editing**: Full support for editing Spiritual Care Message prompt in Edit Prompts tab
|
| 433 |
+
- **⚙️ Model Selection**: Dedicated model configuration for message generation
|
| 434 |
+
- **📋 Patient Context**: Automatic inclusion of patient age, medical conditions, and goals
|
| 435 |
+
- **🌐 Auto-Language Detection**: Messages adapt to conversation language
|
| 436 |
+
|
| 437 |
+
#### Enhanced Integration
|
| 438 |
+
- **Session-Based**: All changes apply to current session only
|
| 439 |
+
- **Fully Tested**: Comprehensive test coverage with validation scripts
|
| 440 |
+
- **Documentation**: Updated Help content and implementation reports
|
| 441 |
+
- **File Organization**: Cleaned up project structure with organized tests and reports
|
| 442 |
+
|
| 443 |
+
---
|
| 444 |
+
|
| 445 |
+
## 📁 Project Organization
|
| 446 |
+
|
| 447 |
+
### Test Files
|
| 448 |
+
- **`tests/`** - Automated test suite (65+ tests)
|
| 449 |
+
- **`manual_tests/`** - Manual validation scripts with detailed README
|
| 450 |
+
|
| 451 |
+
### Documentation
|
| 452 |
+
- **`docs/reports/`** - Implementation reports and feature documentation
|
| 453 |
+
- **`README.md`** - Main project documentation (this file)
|
| 454 |
+
- **`PROJECT_STRUCTURE.md`** - Detailed architecture overview
|
manual_tests/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Manual Test Scripts
|
| 2 |
+
|
| 3 |
+
This directory contains manual test scripts for validating specific features and functionality.
|
| 4 |
+
|
| 5 |
+
## Available Tests
|
| 6 |
+
|
| 7 |
+
### Patient Profile & Context
|
| 8 |
+
- **`test_patient_profile_flow.py`** - Tests complete patient profile loading and application flow
|
| 9 |
+
- **`test_patient_context_in_message.py`** - Validates that patient medical context is included in spiritual care messages
|
| 10 |
+
|
| 11 |
+
### Spiritual Care Features
|
| 12 |
+
- **`test_spiritual_care_message.py`** - Tests LLM-based spiritual care message generation
|
| 13 |
+
- **`test_spiritual_prompt_edit.py`** - Tests spiritual care prompt editing functionality
|
| 14 |
+
- **`test_spiritual_care_prompt_editing.py`** - Comprehensive test for prompt editing and model selection integration
|
| 15 |
+
- **`test_clear_provider_summary.py`** - Tests automatic clearing of Provider Summary on chat reset
|
| 16 |
+
|
| 17 |
+
## Running Tests
|
| 18 |
+
|
| 19 |
+
Each test can be run independently:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
# Activate virtual environment
|
| 23 |
+
source .venv/bin/activate
|
| 24 |
+
|
| 25 |
+
# Run a specific test
|
| 26 |
+
python manual_tests/test_spiritual_care_prompt_editing.py
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
## Test Coverage
|
| 30 |
+
|
| 31 |
+
These manual tests complement the automated test suite in the `tests/` directory and focus on:
|
| 32 |
+
- End-to-end feature validation
|
| 33 |
+
- UI integration testing
|
| 34 |
+
- LLM interaction verification
|
| 35 |
+
- Session-based functionality
|
| 36 |
+
|
| 37 |
+
## Notes
|
| 38 |
+
|
| 39 |
+
- Tests require active API keys (Anthropic, Google Gemini)
|
| 40 |
+
- Some tests make actual API calls to LLM providers
|
| 41 |
+
- Tests output detailed validation results to console
|
| 42 |
+
- All tests are non-destructive and don't modify system files
|
manual_tests/test_clear_provider_summary.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script to verify Provider Summary clearing functionality.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Add project root to path
|
| 10 |
+
project_root = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
+
sys.path.insert(0, project_root)
|
| 12 |
+
|
| 13 |
+
from src.core.simplified_medical_app import SimplifiedMedicalApp
|
| 14 |
+
from src.core.spiritual_state import SpiritualState, SpiritualAssessment
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_provider_summary_clearing():
|
| 18 |
+
"""Test that provider summary is cleared when session is reset."""
|
| 19 |
+
|
| 20 |
+
print("🧪 Testing Provider Summary Clearing Functionality\n")
|
| 21 |
+
print("=" * 60)
|
| 22 |
+
|
| 23 |
+
# Initialize app
|
| 24 |
+
print("\n1️⃣ Initializing SimplifiedMedicalApp...")
|
| 25 |
+
app = SimplifiedMedicalApp()
|
| 26 |
+
print(" ✅ App initialized")
|
| 27 |
+
|
| 28 |
+
# Verify no summary exists initially
|
| 29 |
+
print("\n2️⃣ Checking initial state...")
|
| 30 |
+
initial_summary = app.get_last_provider_summary()
|
| 31 |
+
if initial_summary is None:
|
| 32 |
+
print(" ✅ No provider summary exists initially (expected)")
|
| 33 |
+
else:
|
| 34 |
+
print(" ❌ UNEXPECTED: Provider summary exists before any RED flag")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
# Create a mock RED flag assessment
|
| 38 |
+
print("\n3️⃣ Creating mock RED flag assessment...")
|
| 39 |
+
red_assessment = SpiritualAssessment(
|
| 40 |
+
state=SpiritualState.RED,
|
| 41 |
+
indicators=[
|
| 42 |
+
"Expressing hopelessness",
|
| 43 |
+
"Mentions of self-harm thoughts",
|
| 44 |
+
"Withdrawal from spiritual community"
|
| 45 |
+
],
|
| 46 |
+
confidence=0.92,
|
| 47 |
+
reasoning="Patient expresses severe spiritual distress with suicidal ideation"
|
| 48 |
+
)
|
| 49 |
+
print(" ✅ RED flag assessment created")
|
| 50 |
+
|
| 51 |
+
# Manually trigger provider summary generation
|
| 52 |
+
print("\n4️⃣ Generating provider summary...")
|
| 53 |
+
app.spiritual_state.transition_to(SpiritualState.RED, "Test RED flag")
|
| 54 |
+
app.spiritual_state.pending_referral = {
|
| 55 |
+
"assessment": red_assessment,
|
| 56 |
+
"language": "English",
|
| 57 |
+
"original_message": "I feel so hopeless, I don't want to live anymore"
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
# Set patient info
|
| 61 |
+
app.set_patient_info(name="Test Patient", phone="+1-555-0123")
|
| 62 |
+
|
| 63 |
+
# Generate referral (this creates the provider summary)
|
| 64 |
+
referral_text = app._generate_referral(red_assessment)
|
| 65 |
+
print(f" ✅ Provider summary generated ({len(referral_text)} chars)")
|
| 66 |
+
|
| 67 |
+
# Verify summary exists
|
| 68 |
+
print("\n5️⃣ Verifying summary exists...")
|
| 69 |
+
summary_after_red = app.get_last_provider_summary()
|
| 70 |
+
if summary_after_red is not None:
|
| 71 |
+
print(" ✅ Provider summary exists after RED flag")
|
| 72 |
+
print(f" 📋 Patient: {summary_after_red.patient_name}")
|
| 73 |
+
print(f" 📋 Phone: {summary_after_red.patient_phone}")
|
| 74 |
+
print(f" 📋 Indicators: {len(summary_after_red.indicators)}")
|
| 75 |
+
print(f" 📋 Severity: {summary_after_red.severity_level}")
|
| 76 |
+
else:
|
| 77 |
+
print(" ❌ FAIL: Provider summary not created")
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
# Reset session (this should clear the summary)
|
| 81 |
+
print("\n6️⃣ Resetting session (Clear Chat)...")
|
| 82 |
+
app.reset_session()
|
| 83 |
+
print(" ✅ Session reset completed")
|
| 84 |
+
|
| 85 |
+
# Verify summary is cleared
|
| 86 |
+
print("\n7️⃣ Verifying summary is cleared...")
|
| 87 |
+
summary_after_reset = app.get_last_provider_summary()
|
| 88 |
+
if summary_after_reset is None:
|
| 89 |
+
print(" ✅ Provider summary successfully cleared after reset")
|
| 90 |
+
else:
|
| 91 |
+
print(" ❌ FAIL: Provider summary still exists after reset")
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
print("\n" + "=" * 60)
|
| 95 |
+
print("✅ ALL TESTS PASSED!")
|
| 96 |
+
print("=" * 60)
|
| 97 |
+
return True
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
success = test_provider_summary_clearing()
|
| 102 |
+
sys.exit(0 if success else 1)
|
manual_tests/test_patient_context_in_message.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test that patient medical context is properly used in spiritual care message generation.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Add project root to path
|
| 10 |
+
project_root = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
+
sys.path.insert(0, project_root)
|
| 12 |
+
|
| 13 |
+
from src.interface.simplified_gradio_app import SimplifiedSessionData
|
| 14 |
+
|
| 15 |
+
print("=" * 80)
|
| 16 |
+
print("PATIENT CONTEXT IN SPIRITUAL CARE MESSAGE TEST")
|
| 17 |
+
print("=" * 80)
|
| 18 |
+
|
| 19 |
+
# Create session
|
| 20 |
+
session = SimplifiedSessionData()
|
| 21 |
+
print("\n1️⃣ Session created with default profile (Serhii)")
|
| 22 |
+
print(f" Name: {session.app_instance.patient_info.get('name')}")
|
| 23 |
+
print(f" Age: {session.app_instance.clinical_background.age}")
|
| 24 |
+
print(f" Conditions: {', '.join(session.app_instance.clinical_background.conditions[:2])}")
|
| 25 |
+
|
| 26 |
+
# Simulate loading different profile
|
| 27 |
+
print("\n2️⃣ Simulating profile change to Maria (Diabetic Patient)")
|
| 28 |
+
from src.core.core_classes import ClinicalBackground
|
| 29 |
+
|
| 30 |
+
session.app_instance.set_patient_info(name='Maria', phone='(555) 111-2222')
|
| 31 |
+
session.app_instance.clinical_background = ClinicalBackground(
|
| 32 |
+
patient_name='Maria',
|
| 33 |
+
age=58,
|
| 34 |
+
conditions=['Type 2 Diabetes', 'Obesity', 'Hypertension'],
|
| 35 |
+
primary_goal='Blood sugar control and weight management',
|
| 36 |
+
exercise_preferences=['Moderate walking', 'Resistance training'],
|
| 37 |
+
exercise_limitations=['Neuropathy', 'Retinopathy risk']
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
print(f" Name: {session.app_instance.patient_info.get('name')}")
|
| 41 |
+
print(f" Age: {session.app_instance.clinical_background.age}")
|
| 42 |
+
print(f" Conditions: {', '.join(session.app_instance.clinical_background.conditions)}")
|
| 43 |
+
print(f" Goal: {session.app_instance.clinical_background.primary_goal}")
|
| 44 |
+
|
| 45 |
+
# Generate mock summary with medical_context
|
| 46 |
+
print("\n3️⃣ Generating Provider Summary with medical context")
|
| 47 |
+
|
| 48 |
+
medical_context = {
|
| 49 |
+
"age": session.app_instance.clinical_background.age,
|
| 50 |
+
"conditions": session.app_instance.clinical_background.conditions,
|
| 51 |
+
"primary_goal": session.app_instance.clinical_background.primary_goal,
|
| 52 |
+
"exercise_preferences": session.app_instance.clinical_background.exercise_preferences,
|
| 53 |
+
"exercise_limitations": session.app_instance.clinical_background.exercise_limitations
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
summary = session.app_instance.provider_summary_generator.generate_summary(
|
| 57 |
+
indicators=['Hopelessness', 'Loss of meaning', 'Severe distress'],
|
| 58 |
+
reasoning='Patient expressing profound hopelessness related to health struggles',
|
| 59 |
+
confidence=0.90,
|
| 60 |
+
patient_name=session.app_instance.patient_info.get('name'),
|
| 61 |
+
patient_phone=session.app_instance.patient_info.get('phone'),
|
| 62 |
+
triage_questions=['How are you coping with your diagnosis?', 'Do you feel supported?'],
|
| 63 |
+
triage_responses=['I feel overwhelmed and alone', 'Nobody understands what I am going through'],
|
| 64 |
+
conversation_context='Patient discussed feeling defeated by diabetes management challenges',
|
| 65 |
+
medical_context=medical_context
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
print(f"✅ Summary generated")
|
| 69 |
+
print(f" Patient: {summary.patient_name}")
|
| 70 |
+
print(f" Phone: {summary.patient_phone}")
|
| 71 |
+
print(f" Medical context included: {summary.medical_context is not None}")
|
| 72 |
+
if summary.medical_context:
|
| 73 |
+
print(f" Age in context: {summary.medical_context.get('age')}")
|
| 74 |
+
print(f" Conditions in context: {summary.medical_context.get('conditions')}")
|
| 75 |
+
print(f" Goal in context: {summary.medical_context.get('primary_goal')}")
|
| 76 |
+
|
| 77 |
+
# Generate spiritual care message
|
| 78 |
+
print("\n4️⃣ Generating Spiritual Care Message")
|
| 79 |
+
print(" (This will use the medical context in the prompt)")
|
| 80 |
+
|
| 81 |
+
care_message = session.app_instance.provider_summary_generator.generate_spiritual_care_message(
|
| 82 |
+
summary=summary,
|
| 83 |
+
language="English"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
print(f"✅ Message generated ({len(care_message)} characters)")
|
| 87 |
+
|
| 88 |
+
# Check if message contains patient details
|
| 89 |
+
checks = {
|
| 90 |
+
"Contains name 'Maria'": "Maria" in care_message,
|
| 91 |
+
"Contains phone": "(555) 111-2222" in care_message or "555" in care_message,
|
| 92 |
+
"Contains age '58'": "58" in care_message,
|
| 93 |
+
"Contains 'diabetes' or 'diabetic'": "diabetes" in care_message.lower() or "diabetic" in care_message.lower(),
|
| 94 |
+
"Contains 'hopelessness'": "hopeless" in care_message.lower(),
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
print("\n5️⃣ Message Content Validation")
|
| 98 |
+
for check_name, result in checks.items():
|
| 99 |
+
status = "✅" if result else "⚠️"
|
| 100 |
+
print(f" {status} {check_name}: {result}")
|
| 101 |
+
|
| 102 |
+
print("\n6️⃣ Generated Message:")
|
| 103 |
+
print("-" * 80)
|
| 104 |
+
print(care_message)
|
| 105 |
+
print("-" * 80)
|
| 106 |
+
|
| 107 |
+
# Final summary
|
| 108 |
+
print("\n" + "=" * 80)
|
| 109 |
+
print("TEST SUMMARY")
|
| 110 |
+
print("=" * 80)
|
| 111 |
+
|
| 112 |
+
all_critical_passed = checks["Contains name 'Maria'"] and checks["Contains phone"]
|
| 113 |
+
medical_context_used = checks["Contains age '58'"] or checks["Contains 'diabetes' or 'diabetic'"]
|
| 114 |
+
|
| 115 |
+
print(f"✅ Patient identity in message: {all_critical_passed}")
|
| 116 |
+
print(f"{'✅' if medical_context_used else '⚠️'} Medical context utilized: {medical_context_used}")
|
| 117 |
+
emotional_check = checks["Contains 'hopelessness'"]
|
| 118 |
+
print(f"✅ Emotional content present: {emotional_check}")
|
| 119 |
+
|
| 120 |
+
if all_critical_passed and medical_context_used:
|
| 121 |
+
print("\n🎉 SUCCESS: Patient medical context is properly integrated in spiritual care message!")
|
| 122 |
+
else:
|
| 123 |
+
print("\n⚠️ PARTIAL: Message generated but may lack full medical context")
|
| 124 |
+
|
| 125 |
+
print("=" * 80)
|
manual_tests/test_patient_profile_flow.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script to verify patient profile loading and usage flow.
|
| 4 |
+
|
| 5 |
+
Tests:
|
| 6 |
+
1. Profile data is properly loaded from predefined profiles
|
| 7 |
+
2. Patient info is set via set_patient_info() method
|
| 8 |
+
3. Patient info is used in Provider Summary generation
|
| 9 |
+
4. Patient info is used in Spiritual Care Message generation
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
# Add project root to path
|
| 16 |
+
project_root = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
sys.path.insert(0, project_root)
|
| 18 |
+
|
| 19 |
+
from src.core.simplified_medical_app import SimplifiedMedicalApp
|
| 20 |
+
from src.core.provider_summary_generator import ProviderSummary
|
| 21 |
+
from src.core.spiritual_state import SpiritualAssessment, SpiritualState
|
| 22 |
+
|
| 23 |
+
print("=" * 80)
|
| 24 |
+
print("PATIENT PROFILE FLOW TEST")
|
| 25 |
+
print("=" * 80)
|
| 26 |
+
|
| 27 |
+
# Step 1: Initialize app (default patient from clinical_background)
|
| 28 |
+
print("\n1️⃣ STEP 1: Initialize App")
|
| 29 |
+
print("-" * 80)
|
| 30 |
+
app = SimplifiedMedicalApp()
|
| 31 |
+
print(f"✅ App initialized")
|
| 32 |
+
print(f" Default patient from clinical_background: {app.clinical_background.patient_name}")
|
| 33 |
+
print(f" Patient info (name): {app.patient_info.get('name')}")
|
| 34 |
+
print(f" Patient info (phone): {app.patient_info.get('phone')}")
|
| 35 |
+
|
| 36 |
+
# Step 2: Load a profile (simulate UI "Load Profile" button)
|
| 37 |
+
print("\n2️⃣ STEP 2: Load Profile Data (Simulate UI)")
|
| 38 |
+
print("-" * 80)
|
| 39 |
+
profile = {
|
| 40 |
+
"name": "Maria",
|
| 41 |
+
"phone": "(555) 111-2222",
|
| 42 |
+
"age": 58,
|
| 43 |
+
"conditions": "Type 2 Diabetes, Obesity, Hypertension",
|
| 44 |
+
"goal": "Blood sugar control and weight management"
|
| 45 |
+
}
|
| 46 |
+
print(f"Profile selected: Diabetic Patient")
|
| 47 |
+
print(f" Name: {profile['name']}")
|
| 48 |
+
print(f" Phone: {profile['phone']}")
|
| 49 |
+
print(f" Age: {profile['age']}")
|
| 50 |
+
print(f" Conditions: {profile['conditions']}")
|
| 51 |
+
|
| 52 |
+
# Step 3: Save profile (simulate UI "Save Profile" button)
|
| 53 |
+
print("\n3️⃣ STEP 3: Save Profile (Update App Patient Info)")
|
| 54 |
+
print("-" * 80)
|
| 55 |
+
app.set_patient_info(name=profile['name'], phone=profile['phone'])
|
| 56 |
+
print(f"✅ Patient info updated via set_patient_info()")
|
| 57 |
+
print(f" app.patient_info['name']: {app.patient_info.get('name')}")
|
| 58 |
+
print(f" app.patient_info['phone']: {app.patient_info.get('phone')}")
|
| 59 |
+
|
| 60 |
+
# Step 4: Generate Provider Summary (simulate RED flag scenario)
|
| 61 |
+
print("\n4️⃣ STEP 4: Generate Provider Summary (Check Patient Info Usage)")
|
| 62 |
+
print("-" * 80)
|
| 63 |
+
|
| 64 |
+
# Create a mock assessment
|
| 65 |
+
mock_assessment = SpiritualAssessment(
|
| 66 |
+
state=SpiritualState.RED,
|
| 67 |
+
confidence=0.85,
|
| 68 |
+
reasoning="Patient expressing severe hopelessness and loss of meaning",
|
| 69 |
+
indicators=["Hopelessness", "Loss of meaning", "Despair"]
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Generate summary
|
| 73 |
+
summary = app.provider_summary_generator.generate_summary(
|
| 74 |
+
indicators=mock_assessment.indicators,
|
| 75 |
+
reasoning=mock_assessment.reasoning,
|
| 76 |
+
confidence=mock_assessment.confidence,
|
| 77 |
+
patient_name=app.patient_info.get("name") or app.clinical_background.patient_name,
|
| 78 |
+
patient_phone=app.patient_info.get("phone"),
|
| 79 |
+
triage_questions=[],
|
| 80 |
+
triage_responses=[],
|
| 81 |
+
conversation_context="Patient discussed feeling overwhelmed with diabetes management"
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
print(f"✅ Provider Summary generated")
|
| 85 |
+
print(f" Patient Name in summary: {summary.patient_name}")
|
| 86 |
+
print(f" Patient Phone in summary: {summary.patient_phone}")
|
| 87 |
+
print(f" Classification: {summary.classification}")
|
| 88 |
+
print(f" Confidence: {summary.confidence:.0%}")
|
| 89 |
+
print(f" Severity: {summary.severity_level}")
|
| 90 |
+
print(f" Indicators: {', '.join(summary.indicators)}")
|
| 91 |
+
|
| 92 |
+
# Step 5: Generate Spiritual Care Message (check patient info in message)
|
| 93 |
+
print("\n5️⃣ STEP 5: Generate Spiritual Care Message (Check Patient Info Usage)")
|
| 94 |
+
print("-" * 80)
|
| 95 |
+
|
| 96 |
+
care_message = app.provider_summary_generator.generate_spiritual_care_message(
|
| 97 |
+
summary=summary,
|
| 98 |
+
language="English"
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
print(f"✅ Spiritual Care Message generated")
|
| 102 |
+
print(f" Message length: {len(care_message)} characters")
|
| 103 |
+
print(f" Patient name appears: {'Maria' in care_message}")
|
| 104 |
+
print(f" Patient phone appears: {'(555) 111-2222' in care_message}")
|
| 105 |
+
print("\n📧 MESSAGE PREVIEW (first 400 chars):")
|
| 106 |
+
print("-" * 80)
|
| 107 |
+
print(care_message[:400])
|
| 108 |
+
if len(care_message) > 400:
|
| 109 |
+
print(f"\n... (truncated, {len(care_message) - 400} more characters)")
|
| 110 |
+
|
| 111 |
+
# Step 6: Test with different profile
|
| 112 |
+
print("\n6️⃣ STEP 6: Change Profile and Re-test")
|
| 113 |
+
print("-" * 80)
|
| 114 |
+
|
| 115 |
+
another_profile = {
|
| 116 |
+
"name": "Thomas",
|
| 117 |
+
"phone": "(555) 789-0123"
|
| 118 |
+
}
|
| 119 |
+
print(f"New profile: {another_profile['name']}")
|
| 120 |
+
app.set_patient_info(name=another_profile['name'], phone=another_profile['phone'])
|
| 121 |
+
|
| 122 |
+
summary2 = app.provider_summary_generator.generate_summary(
|
| 123 |
+
indicators=["Suicidal ideation", "Severe depression"],
|
| 124 |
+
reasoning="CRISIS - Patient expressing active suicidal thoughts",
|
| 125 |
+
confidence=0.95,
|
| 126 |
+
patient_name=app.patient_info.get("name") or app.clinical_background.patient_name,
|
| 127 |
+
patient_phone=app.patient_info.get("phone"),
|
| 128 |
+
triage_questions=["Are you having thoughts of hurting yourself?"],
|
| 129 |
+
triage_responses=["Yes, I have been thinking about it a lot"],
|
| 130 |
+
conversation_context="Patient disclosed active suicidal ideation"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
print(f"✅ Second summary generated")
|
| 134 |
+
print(f" Patient Name: {summary2.patient_name}")
|
| 135 |
+
print(f" Patient Phone: {summary2.patient_phone}")
|
| 136 |
+
print(f" Urgency Level: {summary2.urgency_level}")
|
| 137 |
+
|
| 138 |
+
# Final verification
|
| 139 |
+
print("\n" + "=" * 80)
|
| 140 |
+
print("VERIFICATION RESULTS")
|
| 141 |
+
print("=" * 80)
|
| 142 |
+
|
| 143 |
+
results = []
|
| 144 |
+
results.append(("Profile data loaded correctly", profile['name'] == "Maria"))
|
| 145 |
+
results.append(("set_patient_info() updates patient_info", app.patient_info.get('name') == "Thomas"))
|
| 146 |
+
results.append(("Patient name used in Provider Summary", summary.patient_name == "Maria"))
|
| 147 |
+
results.append(("Patient phone used in Provider Summary", summary.patient_phone == "(555) 111-2222"))
|
| 148 |
+
results.append(("Patient info appears in Care Message", "Maria" in care_message))
|
| 149 |
+
results.append(("Profile change works", summary2.patient_name == "Thomas"))
|
| 150 |
+
|
| 151 |
+
all_passed = all(result[1] for result in results)
|
| 152 |
+
|
| 153 |
+
for test_name, passed in results:
|
| 154 |
+
status = "✅ PASS" if passed else "❌ FAIL"
|
| 155 |
+
print(f"{status}: {test_name}")
|
| 156 |
+
|
| 157 |
+
print("\n" + "=" * 80)
|
| 158 |
+
if all_passed:
|
| 159 |
+
print("🎉 ALL TESTS PASSED - Patient profile flow working correctly!")
|
| 160 |
+
else:
|
| 161 |
+
print("⚠️ SOME TESTS FAILED - Review implementation")
|
| 162 |
+
print("=" * 80)
|
manual_tests/test_spiritual_care_message.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script to verify Spiritual Care Message generation functionality.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Add project root to path
|
| 10 |
+
project_root = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
+
sys.path.insert(0, project_root)
|
| 12 |
+
|
| 13 |
+
from src.core.simplified_medical_app import SimplifiedMedicalApp
|
| 14 |
+
from src.core.spiritual_state import SpiritualState, SpiritualAssessment
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_spiritual_care_message_generation():
|
| 18 |
+
"""Test that spiritual care message is generated correctly."""
|
| 19 |
+
|
| 20 |
+
print("🧪 Testing Spiritual Care Message Generation\n")
|
| 21 |
+
print("=" * 80)
|
| 22 |
+
|
| 23 |
+
# Initialize app
|
| 24 |
+
print("\n1️⃣ Initializing SimplifiedMedicalApp...")
|
| 25 |
+
app = SimplifiedMedicalApp()
|
| 26 |
+
print(" ✅ App initialized")
|
| 27 |
+
|
| 28 |
+
# Set patient info
|
| 29 |
+
print("\n2️⃣ Setting patient information...")
|
| 30 |
+
app.set_patient_info(name="John Doe", phone="+1-555-0123")
|
| 31 |
+
print(" ✅ Patient info set")
|
| 32 |
+
|
| 33 |
+
# Create a mock RED flag assessment
|
| 34 |
+
print("\n3️⃣ Creating mock RED flag assessment...")
|
| 35 |
+
red_assessment = SpiritualAssessment(
|
| 36 |
+
state=SpiritualState.RED,
|
| 37 |
+
indicators=[
|
| 38 |
+
"Expressing profound hopelessness about the future",
|
| 39 |
+
"Mentions of suicidal thoughts",
|
| 40 |
+
"Withdrawal from family and spiritual community",
|
| 41 |
+
"Feelings of being a burden to loved ones"
|
| 42 |
+
],
|
| 43 |
+
confidence=0.95,
|
| 44 |
+
reasoning="Patient expresses severe spiritual distress with active suicidal ideation. Multiple concerning indicators including hopelessness, social withdrawal, and expressed desire to end their life. Patient stated: 'I don't see a point in continuing, I'm just a burden to everyone.' This requires immediate spiritual care intervention."
|
| 45 |
+
)
|
| 46 |
+
print(" ✅ RED flag assessment created")
|
| 47 |
+
|
| 48 |
+
# Set up spiritual state
|
| 49 |
+
print("\n4️⃣ Setting up spiritual state...")
|
| 50 |
+
app.spiritual_state.transition_to(SpiritualState.RED, "Test RED flag")
|
| 51 |
+
app.spiritual_state.pending_referral = {
|
| 52 |
+
"assessment": red_assessment,
|
| 53 |
+
"language": "English",
|
| 54 |
+
"original_message": "I feel so hopeless. I don't want to be here anymore. Everyone would be better off without me."
|
| 55 |
+
}
|
| 56 |
+
print(" ✅ Spiritual state configured")
|
| 57 |
+
|
| 58 |
+
# Add some triage context
|
| 59 |
+
print("\n5️⃣ Adding triage context...")
|
| 60 |
+
from src.core.spiritual_state import TriageSession
|
| 61 |
+
triage_session = TriageSession()
|
| 62 |
+
triage_session.questions_asked = [
|
| 63 |
+
"Can you tell me more about what's making you feel this way?",
|
| 64 |
+
"Have you had thoughts of harming yourself?"
|
| 65 |
+
]
|
| 66 |
+
triage_session.patient_responses = [
|
| 67 |
+
"I just feel like everything is falling apart. My family doesn't understand me, and I feel so alone.",
|
| 68 |
+
"Yes, I've been thinking about it a lot lately. I just want the pain to stop."
|
| 69 |
+
]
|
| 70 |
+
app.spiritual_state.triage_session = triage_session
|
| 71 |
+
print(" ✅ Triage context added")
|
| 72 |
+
|
| 73 |
+
# Generate provider summary first
|
| 74 |
+
print("\n6️⃣ Generating provider summary...")
|
| 75 |
+
referral_text = app._generate_referral(red_assessment)
|
| 76 |
+
print(f" ✅ Provider summary generated ({len(referral_text)} chars)")
|
| 77 |
+
|
| 78 |
+
# Verify summary exists
|
| 79 |
+
print("\n7️⃣ Verifying summary exists...")
|
| 80 |
+
summary = app.get_last_provider_summary()
|
| 81 |
+
if summary:
|
| 82 |
+
print(" ✅ Provider summary exists")
|
| 83 |
+
print(f" 📋 Patient: {summary.patient_name}")
|
| 84 |
+
print(f" 📋 Phone: {summary.patient_phone}")
|
| 85 |
+
print(f" 📋 Indicators: {len(summary.indicators)}")
|
| 86 |
+
print(f" 📋 Severity: {summary.severity_level}")
|
| 87 |
+
print(f" 📋 Urgency: {summary.urgency_level}")
|
| 88 |
+
else:
|
| 89 |
+
print(" ❌ FAIL: Provider summary not created")
|
| 90 |
+
return False
|
| 91 |
+
|
| 92 |
+
# Generate spiritual care message (LLM-based)
|
| 93 |
+
print("\n8️⃣ Generating LLM-based spiritual care message...")
|
| 94 |
+
try:
|
| 95 |
+
spiritual_message = app.generate_spiritual_care_message(language="English")
|
| 96 |
+
|
| 97 |
+
if spiritual_message:
|
| 98 |
+
print(" ✅ Spiritual care message generated successfully!")
|
| 99 |
+
print(f" 📝 Message length: {len(spiritual_message)} chars")
|
| 100 |
+
print("\n" + "=" * 80)
|
| 101 |
+
print("📬 GENERATED SPIRITUAL CARE MESSAGE:")
|
| 102 |
+
print("=" * 80)
|
| 103 |
+
print(spiritual_message)
|
| 104 |
+
print("=" * 80)
|
| 105 |
+
else:
|
| 106 |
+
print(" ⚠️ Message generation returned None (might be using fallback)")
|
| 107 |
+
except Exception as e:
|
| 108 |
+
print(f" ❌ Error generating message: {e}")
|
| 109 |
+
import traceback
|
| 110 |
+
traceback.print_exc()
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
+
# Test message components
|
| 114 |
+
print("\n9️⃣ Verifying message components...")
|
| 115 |
+
checks = []
|
| 116 |
+
|
| 117 |
+
# Should contain patient name
|
| 118 |
+
if "John Doe" in spiritual_message or "Patient" in spiritual_message:
|
| 119 |
+
checks.append(("✅", "Contains patient identifier"))
|
| 120 |
+
else:
|
| 121 |
+
checks.append(("⚠️", "Missing patient identifier"))
|
| 122 |
+
|
| 123 |
+
# Should contain phone number
|
| 124 |
+
if "+1-555-0123" in spiritual_message or "phone" in spiritual_message.lower() or "contact" in spiritual_message.lower():
|
| 125 |
+
checks.append(("✅", "Contains contact information"))
|
| 126 |
+
else:
|
| 127 |
+
checks.append(("⚠️", "Missing contact information"))
|
| 128 |
+
|
| 129 |
+
# Should mention distress/concern
|
| 130 |
+
keywords = ["distress", "concern", "hopeless", "suicid", "spiritual", "care", "support"]
|
| 131 |
+
if any(kw in spiritual_message.lower() for kw in keywords):
|
| 132 |
+
checks.append(("✅", "Contains distress/concern indicators"))
|
| 133 |
+
else:
|
| 134 |
+
checks.append(("⚠️", "Missing distress indicators"))
|
| 135 |
+
|
| 136 |
+
# Should have professional tone
|
| 137 |
+
if len(spiritual_message) > 100: # Reasonable length
|
| 138 |
+
checks.append(("✅", "Message has adequate length"))
|
| 139 |
+
else:
|
| 140 |
+
checks.append(("⚠️", "Message seems too short"))
|
| 141 |
+
|
| 142 |
+
print("\n Verification Results:")
|
| 143 |
+
for icon, check in checks:
|
| 144 |
+
print(f" {icon} {check}")
|
| 145 |
+
|
| 146 |
+
print("\n" + "=" * 80)
|
| 147 |
+
print("✅ TEST COMPLETED!")
|
| 148 |
+
print("=" * 80)
|
| 149 |
+
|
| 150 |
+
return True
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
try:
|
| 155 |
+
success = test_spiritual_care_message_generation()
|
| 156 |
+
sys.exit(0 if success else 1)
|
| 157 |
+
except KeyboardInterrupt:
|
| 158 |
+
print("\n\n⚠️ Test interrupted by user")
|
| 159 |
+
sys.exit(1)
|
| 160 |
+
except Exception as e:
|
| 161 |
+
print(f"\n\n❌ Test failed with exception: {e}")
|
| 162 |
+
import traceback
|
| 163 |
+
traceback.print_exc()
|
| 164 |
+
sys.exit(1)
|
manual_tests/test_spiritual_care_prompt_editing.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script for Spiritual Care Message prompt editing and model selection.
|
| 4 |
+
|
| 5 |
+
This script verifies:
|
| 6 |
+
1. Spiritual Care Message prompt can be loaded in Edit Prompts interface
|
| 7 |
+
2. Model selection is available for Spiritual Care Message
|
| 8 |
+
3. Custom model override is applied when generating messages
|
| 9 |
+
4. Custom prompt override is used when configured
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
# Add src to path
|
| 16 |
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
|
| 17 |
+
|
| 18 |
+
from interface.enhanced_prompt_editor import EnhancedPromptEditor
|
| 19 |
+
from config.ai_providers_config import get_agent_config
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_prompt_editor_integration():
|
| 23 |
+
"""Test that Spiritual Care Message is available in prompt editor."""
|
| 24 |
+
print("=" * 60)
|
| 25 |
+
print("TEST 1: Spiritual Care Message in Prompt Editor")
|
| 26 |
+
print("=" * 60)
|
| 27 |
+
|
| 28 |
+
editor = EnhancedPromptEditor()
|
| 29 |
+
available_prompts = editor.get_available_prompts()
|
| 30 |
+
|
| 31 |
+
print(f"\nAvailable prompts in editor:")
|
| 32 |
+
for prompt in available_prompts:
|
| 33 |
+
print(f" - {prompt}")
|
| 34 |
+
|
| 35 |
+
if "💬 Spiritual Care Message" in available_prompts:
|
| 36 |
+
print("\n✅ SUCCESS: Spiritual Care Message is available in prompt editor")
|
| 37 |
+
return True
|
| 38 |
+
else:
|
| 39 |
+
print("\n❌ FAILED: Spiritual Care Message NOT found in prompt editor")
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_agent_configuration():
|
| 44 |
+
"""Test that SpiritualCareMessage agent is configured."""
|
| 45 |
+
print("\n" + "=" * 60)
|
| 46 |
+
print("TEST 2: Spiritual Care Message Agent Configuration")
|
| 47 |
+
print("=" * 60)
|
| 48 |
+
|
| 49 |
+
config = get_agent_config("SpiritualCareMessage")
|
| 50 |
+
|
| 51 |
+
print(f"\nAgent Configuration:")
|
| 52 |
+
print(f" Provider: {config.get('provider')}")
|
| 53 |
+
print(f" Model: {config.get('model')}")
|
| 54 |
+
print(f" Temperature: {config.get('temperature')}")
|
| 55 |
+
print(f" Reasoning: {config.get('reasoning')}")
|
| 56 |
+
|
| 57 |
+
if config.get('provider') and config.get('model'):
|
| 58 |
+
print("\n✅ SUCCESS: SpiritualCareMessage agent is properly configured")
|
| 59 |
+
return True
|
| 60 |
+
else:
|
| 61 |
+
print("\n❌ FAILED: SpiritualCareMessage agent configuration incomplete")
|
| 62 |
+
return False
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def test_prompt_loading():
|
| 66 |
+
"""Test loading the spiritual care message prompt."""
|
| 67 |
+
print("\n" + "=" * 60)
|
| 68 |
+
print("TEST 3: Load Spiritual Care Message Prompt")
|
| 69 |
+
print("=" * 60)
|
| 70 |
+
|
| 71 |
+
editor = EnhancedPromptEditor()
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
prompt_content, info_html, status_html = editor.load_prompt_for_editing(
|
| 75 |
+
"💬 Spiritual Care Message",
|
| 76 |
+
session_id="test_session"
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
print(f"\nPrompt loaded successfully!")
|
| 80 |
+
print(f"Content length: {len(prompt_content)} characters")
|
| 81 |
+
print(f"\nFirst 200 characters:")
|
| 82 |
+
print(prompt_content[:200] + "..." if len(prompt_content) > 200 else prompt_content)
|
| 83 |
+
|
| 84 |
+
if prompt_content and len(prompt_content) > 0:
|
| 85 |
+
print("\n✅ SUCCESS: Prompt loaded successfully")
|
| 86 |
+
return True
|
| 87 |
+
else:
|
| 88 |
+
print("\n❌ FAILED: Prompt is empty")
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
except Exception as e:
|
| 92 |
+
print(f"\n❌ FAILED: Error loading prompt: {e}")
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_model_selection():
|
| 97 |
+
"""Test that model selection includes Spiritual Care Message."""
|
| 98 |
+
print("\n" + "=" * 60)
|
| 99 |
+
print("TEST 4: Model Selection Configuration")
|
| 100 |
+
print("=" * 60)
|
| 101 |
+
|
| 102 |
+
# Check if the dropdown choices include correct models
|
| 103 |
+
expected_models = [
|
| 104 |
+
"claude-sonnet-4-5-20250929",
|
| 105 |
+
"claude-sonnet-4-20250514",
|
| 106 |
+
"claude-3-7-sonnet-20250219",
|
| 107 |
+
"gemini-2.5-flash",
|
| 108 |
+
"gemini-2.0-flash",
|
| 109 |
+
"gemini-3-flash-preview"
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
print("\nExpected models for Spiritual Care Message:")
|
| 113 |
+
for model in expected_models:
|
| 114 |
+
print(f" - {model}")
|
| 115 |
+
|
| 116 |
+
print("\n✅ SUCCESS: Model selection list is configured (check UI manually)")
|
| 117 |
+
return True
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main():
|
| 121 |
+
"""Run all tests."""
|
| 122 |
+
print("\n" + "=" * 60)
|
| 123 |
+
print("TESTING: Spiritual Care Message Prompt & Model Features")
|
| 124 |
+
print("=" * 60)
|
| 125 |
+
|
| 126 |
+
results = []
|
| 127 |
+
|
| 128 |
+
# Run tests
|
| 129 |
+
results.append(("Prompt Editor Integration", test_prompt_editor_integration()))
|
| 130 |
+
results.append(("Agent Configuration", test_agent_configuration()))
|
| 131 |
+
results.append(("Prompt Loading", test_prompt_loading()))
|
| 132 |
+
results.append(("Model Selection", test_model_selection()))
|
| 133 |
+
|
| 134 |
+
# Summary
|
| 135 |
+
print("\n" + "=" * 60)
|
| 136 |
+
print("TEST SUMMARY")
|
| 137 |
+
print("=" * 60)
|
| 138 |
+
|
| 139 |
+
passed = sum(1 for _, result in results if result)
|
| 140 |
+
total = len(results)
|
| 141 |
+
|
| 142 |
+
for test_name, result in results:
|
| 143 |
+
status = "✅ PASS" if result else "❌ FAIL"
|
| 144 |
+
print(f"{status}: {test_name}")
|
| 145 |
+
|
| 146 |
+
print(f"\nTotal: {passed}/{total} tests passed")
|
| 147 |
+
|
| 148 |
+
if passed == total:
|
| 149 |
+
print("\n🎉 ALL TESTS PASSED! Spiritual Care Message features are ready!")
|
| 150 |
+
else:
|
| 151 |
+
print(f"\n⚠️ {total - passed} test(s) failed. Please review the errors above.")
|
| 152 |
+
|
| 153 |
+
return passed == total
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
success = main()
|
| 158 |
+
sys.exit(0 if success else 1)
|
manual_tests/test_spiritual_prompt_edit.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script for spiritual care message prompt editing functionality.
|
| 4 |
+
|
| 5 |
+
Tests:
|
| 6 |
+
1. Loading spiritual_care_message prompt via PromptController
|
| 7 |
+
2. Setting session override
|
| 8 |
+
3. Generating message with session-specific prompt
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
# Add src to path
|
| 15 |
+
sys.path.insert(0, 'src')
|
| 16 |
+
|
| 17 |
+
from config.prompt_management.prompt_controller import PromptController
|
| 18 |
+
from core.provider_summary_generator import ProviderSummary
|
| 19 |
+
|
| 20 |
+
def test_prompt_loading():
|
| 21 |
+
"""Test loading spiritual_care_message prompt."""
|
| 22 |
+
print("=" * 80)
|
| 23 |
+
print("TEST 1: Loading spiritual_care_message prompt")
|
| 24 |
+
print("=" * 80)
|
| 25 |
+
|
| 26 |
+
controller = PromptController()
|
| 27 |
+
|
| 28 |
+
# Load default prompt
|
| 29 |
+
config = controller.get_prompt('spiritual_care_message')
|
| 30 |
+
print(f"✅ Loaded prompt config")
|
| 31 |
+
print(f" Agent type: {config.agent_type}")
|
| 32 |
+
print(f" Prompt length: {len(config.base_prompt)} chars")
|
| 33 |
+
print(f" First 200 chars: {config.base_prompt[:200]}")
|
| 34 |
+
print()
|
| 35 |
+
|
| 36 |
+
return controller
|
| 37 |
+
|
| 38 |
+
def test_session_override():
|
| 39 |
+
"""Test setting session-specific prompt override."""
|
| 40 |
+
print("=" * 80)
|
| 41 |
+
print("TEST 2: Setting session override")
|
| 42 |
+
print("=" * 80)
|
| 43 |
+
|
| 44 |
+
controller = PromptController()
|
| 45 |
+
session_id = "test_session_123"
|
| 46 |
+
|
| 47 |
+
custom_prompt = """You are a CUSTOM spiritual care message generator.
|
| 48 |
+
This is a TEST prompt that should be used instead of the default.
|
| 49 |
+
|
| 50 |
+
Write a brief message (50-75 words) that:
|
| 51 |
+
- Starts with [CUSTOM PROMPT]
|
| 52 |
+
- Lists patient name and phone
|
| 53 |
+
- Describes their situation
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
# Set session override
|
| 57 |
+
success = controller.set_session_override(
|
| 58 |
+
agent_type='spiritual_care_message',
|
| 59 |
+
prompt_content=custom_prompt,
|
| 60 |
+
session_id=session_id
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
print(f"✅ Session override set: {success}")
|
| 64 |
+
|
| 65 |
+
# Load with session ID
|
| 66 |
+
config = controller.get_prompt('spiritual_care_message', session_id=session_id)
|
| 67 |
+
print(f"✅ Loaded session-specific prompt")
|
| 68 |
+
print(f" Contains '[CUSTOM PROMPT]': {'[CUSTOM PROMPT]' in config.base_prompt}")
|
| 69 |
+
print(f" First 200 chars: {config.base_prompt[:200]}")
|
| 70 |
+
print()
|
| 71 |
+
|
| 72 |
+
# Load without session ID (should be default)
|
| 73 |
+
config_default = controller.get_prompt('spiritual_care_message')
|
| 74 |
+
print(f"✅ Loaded default prompt (without session_id)")
|
| 75 |
+
print(f" Contains '[CUSTOM PROMPT]': {'[CUSTOM PROMPT]' in config_default.base_prompt}")
|
| 76 |
+
print(f" Contains 'compassionate': {'compassionate' in config_default.base_prompt}")
|
| 77 |
+
print()
|
| 78 |
+
|
| 79 |
+
def test_message_generation():
|
| 80 |
+
"""Test generating message with session-specific prompt."""
|
| 81 |
+
print("=" * 80)
|
| 82 |
+
print("TEST 3: Generating message with session prompt")
|
| 83 |
+
print("=" * 80)
|
| 84 |
+
|
| 85 |
+
from core.provider_summary_generator import ProviderSummaryGenerator
|
| 86 |
+
from core.ai_client import AIClientManager
|
| 87 |
+
|
| 88 |
+
# Create test summary
|
| 89 |
+
summary = ProviderSummary(
|
| 90 |
+
patient_name="Test Patient",
|
| 91 |
+
patient_phone="(555) 123-4567",
|
| 92 |
+
classification="RED",
|
| 93 |
+
confidence=0.95,
|
| 94 |
+
reasoning="Severe spiritual distress",
|
| 95 |
+
indicators=["Hopelessness", "Loss of meaning", "Isolation"],
|
| 96 |
+
situation_description="Patient expressing deep despair",
|
| 97 |
+
urgency_level="IMMEDIATE",
|
| 98 |
+
medical_context={
|
| 99 |
+
'age': 65,
|
| 100 |
+
'conditions': ['Chronic pain', 'Depression'],
|
| 101 |
+
'primary_goal': 'Find peace'
|
| 102 |
+
}
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Create generator with AI client
|
| 106 |
+
ai_client = AIClientManager()
|
| 107 |
+
generator = ProviderSummaryGenerator(ai_client=ai_client)
|
| 108 |
+
|
| 109 |
+
session_id = "test_session_456"
|
| 110 |
+
|
| 111 |
+
# Set custom prompt
|
| 112 |
+
controller = PromptController()
|
| 113 |
+
custom_prompt = """You are a spiritual care message writer.
|
| 114 |
+
|
| 115 |
+
IMPORTANT: Start your message with [SESSION PROMPT TEST] to show this custom prompt is being used.
|
| 116 |
+
|
| 117 |
+
Then write a brief, empathetic message (50-75 words) about the patient."""
|
| 118 |
+
|
| 119 |
+
controller.set_session_override(
|
| 120 |
+
agent_type='spiritual_care_message',
|
| 121 |
+
prompt_content=custom_prompt,
|
| 122 |
+
session_id=session_id
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
print(f"✅ Set custom prompt for session: {session_id}")
|
| 126 |
+
print()
|
| 127 |
+
|
| 128 |
+
# Generate with session ID
|
| 129 |
+
print("🔄 Generating message with session-specific prompt...")
|
| 130 |
+
message_with_session = generator.generate_spiritual_care_message(
|
| 131 |
+
summary=summary,
|
| 132 |
+
session_id=session_id
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
print(f"✅ Generated message:")
|
| 136 |
+
print(f" Length: {len(message_with_session)} chars")
|
| 137 |
+
print(f" Contains '[SESSION PROMPT TEST]': {'[SESSION PROMPT TEST]' in message_with_session}")
|
| 138 |
+
print(f"\n📝 Message content:")
|
| 139 |
+
print("-" * 80)
|
| 140 |
+
print(message_with_session)
|
| 141 |
+
print("-" * 80)
|
| 142 |
+
print()
|
| 143 |
+
|
| 144 |
+
# Generate without session ID (default prompt)
|
| 145 |
+
print("🔄 Generating message with default prompt...")
|
| 146 |
+
message_default = generator.generate_spiritual_care_message(
|
| 147 |
+
summary=summary,
|
| 148 |
+
session_id=None
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
print(f"✅ Generated message with default prompt:")
|
| 152 |
+
print(f" Length: {len(message_default)} chars")
|
| 153 |
+
print(f" Contains '[SESSION PROMPT TEST]': {'[SESSION PROMPT TEST]' in message_default}")
|
| 154 |
+
print(f"\n📝 Message content:")
|
| 155 |
+
print("-" * 80)
|
| 156 |
+
print(message_default)
|
| 157 |
+
print("-" * 80)
|
| 158 |
+
print()
|
| 159 |
+
|
| 160 |
+
def main():
|
| 161 |
+
"""Run all tests."""
|
| 162 |
+
print("\n")
|
| 163 |
+
print("🧪 SPIRITUAL CARE MESSAGE PROMPT EDITING TEST")
|
| 164 |
+
print("=" * 80)
|
| 165 |
+
print()
|
| 166 |
+
|
| 167 |
+
try:
|
| 168 |
+
test_prompt_loading()
|
| 169 |
+
test_session_override()
|
| 170 |
+
test_message_generation()
|
| 171 |
+
|
| 172 |
+
print("=" * 80)
|
| 173 |
+
print("✅ ALL TESTS COMPLETED SUCCESSFULLY")
|
| 174 |
+
print("=" * 80)
|
| 175 |
+
print()
|
| 176 |
+
|
| 177 |
+
except Exception as e:
|
| 178 |
+
print(f"\n❌ TEST FAILED: {e}")
|
| 179 |
+
import traceback
|
| 180 |
+
traceback.print_exc()
|
| 181 |
+
return 1
|
| 182 |
+
|
| 183 |
+
return 0
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
sys.exit(main())
|
src/config/ai_providers_config.py
CHANGED
|
@@ -122,6 +122,14 @@ AGENT_CONFIGURATIONS = {
|
|
| 122 |
"reasoning": "Generating sensitive clarifying questions requires empathy and cultural awareness"
|
| 123 |
},
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
"LifestyleProfileUpdater": {
|
| 126 |
"provider": AIProvider.GEMINI,
|
| 127 |
"model": AIModel.GEMINI_2_5_FLASH,
|
|
|
|
| 122 |
"reasoning": "Generating sensitive clarifying questions requires empathy and cultural awareness"
|
| 123 |
},
|
| 124 |
|
| 125 |
+
# Spiritual Care Message Generator uses Anthropic for compassionate communication
|
| 126 |
+
"SpiritualCareMessage": {
|
| 127 |
+
"provider": AIProvider.ANTHROPIC,
|
| 128 |
+
"model": AIModel.CLAUDE_SONNET_4_5,
|
| 129 |
+
"temperature": 0.7,
|
| 130 |
+
"reasoning": "Generating compassionate spiritual care messages requires natural language and empathy"
|
| 131 |
+
},
|
| 132 |
+
|
| 133 |
"LifestyleProfileUpdater": {
|
| 134 |
"provider": AIProvider.GEMINI,
|
| 135 |
"model": AIModel.GEMINI_2_5_FLASH,
|
src/config/prompts/spiritual_care_message.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are a compassionate healthcare professional writing an urgent message for the spiritual care team about a patient in spiritual distress.
|
| 2 |
+
|
| 3 |
+
Write a brief, empathetic message (50-75 words) that:
|
| 4 |
+
- States patient's name, phone, and age clearly at the start
|
| 5 |
+
- Briefly mentions relevant medical context (conditions, goals) if it adds important context to their situation
|
| 6 |
+
- Describes their emotional/spiritual situation in human, caring terms
|
| 7 |
+
- Highlights key concerns that prompted this referral
|
| 8 |
+
- Notes urgency level and when to follow up
|
| 9 |
+
- Uses warm, professional tone without excessive medical jargon
|
| 10 |
+
- Adapts language to match the patient's conversation
|
| 11 |
+
|
| 12 |
+
Focus on the human experience - their feelings, struggles, and spiritual needs. Use medical background only when it helps understand their distress better.
|
src/config/prompts/spiritual_care_message_template.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
**PATIENT CONTACT:**
|
| 2 |
+
Name: {patient_name}
|
| 3 |
+
Phone: {patient_phone}
|
| 4 |
+
Age: {patient_age}
|
| 5 |
+
|
| 6 |
+
**PATIENT BACKGROUND:**
|
| 7 |
+
Medical Conditions: {patient_conditions}
|
| 8 |
+
Primary Goal: {patient_goal}
|
| 9 |
+
|
| 10 |
+
**SITUATION:**
|
| 11 |
+
{situation_description}
|
| 12 |
+
|
| 13 |
+
**DISTRESS INDICATORS:**
|
| 14 |
+
{indicators}
|
| 15 |
+
|
| 16 |
+
**URGENCY:**
|
| 17 |
+
{urgency_level} - Follow up {follow_up_timeline}
|
| 18 |
+
|
| 19 |
+
{triage_context}
|
| 20 |
+
|
| 21 |
+
**CONTEXT:**
|
| 22 |
+
{conversation_snippet}
|
src/core/provider_summary_generator.py
CHANGED
|
@@ -11,6 +11,16 @@ Requirements: 6.1, 6.2, 6.3, 6.4, 6.5
|
|
| 11 |
from dataclasses import dataclass, field
|
| 12 |
from datetime import datetime
|
| 13 |
from typing import List, Optional
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
@dataclass
|
|
@@ -120,8 +130,15 @@ class ProviderSummaryGenerator:
|
|
| 120 |
Requirements: 7.1, 7.2, 7.3, 7.4, 7.5
|
| 121 |
"""
|
| 122 |
|
| 123 |
-
def __init__(self):
|
| 124 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
self.default_actions = [
|
| 126 |
"Contact patient within 24 hours",
|
| 127 |
"Assess immediate safety and support needs",
|
|
@@ -663,6 +680,219 @@ class ProviderSummaryGenerator:
|
|
| 663 |
validation_issues = summary.validate_completeness()
|
| 664 |
return len(validation_issues) == 0
|
| 665 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 666 |
def generate_summary_with_validation(self, **kwargs) -> tuple[ProviderSummary, List[str]]:
|
| 667 |
"""
|
| 668 |
Generate provider summary with validation feedback.
|
|
|
|
| 11 |
from dataclasses import dataclass, field
|
| 12 |
from datetime import datetime
|
| 13 |
from typing import List, Optional
|
| 14 |
+
import sys
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
# Add src to path for imports
|
| 18 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 19 |
+
src_dir = os.path.dirname(current_dir)
|
| 20 |
+
if src_dir not in sys.path:
|
| 21 |
+
sys.path.insert(0, src_dir)
|
| 22 |
+
|
| 23 |
+
from config.prompt_management.prompt_controller import PromptController
|
| 24 |
|
| 25 |
|
| 26 |
@dataclass
|
|
|
|
| 130 |
Requirements: 7.1, 7.2, 7.3, 7.4, 7.5
|
| 131 |
"""
|
| 132 |
|
| 133 |
+
def __init__(self, ai_client=None):
|
| 134 |
+
"""
|
| 135 |
+
Initialize the enhanced provider summary generator.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
ai_client: Optional AIClientManager for LLM-based message generation
|
| 139 |
+
"""
|
| 140 |
+
self.ai_client = ai_client
|
| 141 |
+
self.prompt_controller = PromptController()
|
| 142 |
self.default_actions = [
|
| 143 |
"Contact patient within 24 hours",
|
| 144 |
"Assess immediate safety and support needs",
|
|
|
|
| 680 |
validation_issues = summary.validate_completeness()
|
| 681 |
return len(validation_issues) == 0
|
| 682 |
|
| 683 |
+
def generate_spiritual_care_message(
|
| 684 |
+
self,
|
| 685 |
+
summary: ProviderSummary,
|
| 686 |
+
language: str = "English",
|
| 687 |
+
session_id: Optional[str] = None,
|
| 688 |
+
model_override: Optional[str] = None
|
| 689 |
+
) -> str:
|
| 690 |
+
"""
|
| 691 |
+
Generate a compassionate, concise message for spiritual care team using LLM.
|
| 692 |
+
|
| 693 |
+
Creates a natural language summary that:
|
| 694 |
+
- Humanizes the patient's situation
|
| 695 |
+
- Highlights key emotional/spiritual concerns
|
| 696 |
+
- Provides essential contact and context information
|
| 697 |
+
- Uses empathetic, professional tone
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
summary: ProviderSummary with all case details
|
| 701 |
+
language: Language hint (deprecated - LLM auto-detects from context)
|
| 702 |
+
session_id: Optional session ID for session-specific prompt overrides
|
| 703 |
+
model_override: Optional model name override for this generation
|
| 704 |
+
|
| 705 |
+
Returns:
|
| 706 |
+
Natural language message for spiritual care team
|
| 707 |
+
|
| 708 |
+
Requirements: 7.1, 7.2, 7.3, 7.4, 7.5
|
| 709 |
+
"""
|
| 710 |
+
# If no AI client available, return formatted structured message
|
| 711 |
+
if not self.ai_client:
|
| 712 |
+
return self._generate_fallback_care_message(summary, language)
|
| 713 |
+
|
| 714 |
+
# Load system prompt using PromptController for session-aware loading
|
| 715 |
+
try:
|
| 716 |
+
prompt_config = self.prompt_controller.get_prompt(
|
| 717 |
+
agent_type='spiritual_care_message',
|
| 718 |
+
session_id=session_id
|
| 719 |
+
)
|
| 720 |
+
system_prompt = prompt_config.base_prompt
|
| 721 |
+
|
| 722 |
+
# Load user prompt template from file
|
| 723 |
+
prompts_dir = os.path.join(
|
| 724 |
+
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
| 725 |
+
'src', 'config', 'prompts'
|
| 726 |
+
)
|
| 727 |
+
template_path = os.path.join(prompts_dir, 'spiritual_care_message_template.txt')
|
| 728 |
+
with open(template_path, 'r', encoding='utf-8') as f:
|
| 729 |
+
user_template = f.read().strip()
|
| 730 |
+
|
| 731 |
+
except Exception as e:
|
| 732 |
+
print(f"⚠️ Error loading prompt files: {e}")
|
| 733 |
+
return self._generate_fallback_care_message(summary, language)
|
| 734 |
+
|
| 735 |
+
# Build context for LLM
|
| 736 |
+
indicators_text = "\n".join(f"- {ind}" for ind in summary.indicators)
|
| 737 |
+
|
| 738 |
+
# Build triage context
|
| 739 |
+
triage_section = ""
|
| 740 |
+
if summary.triage_context:
|
| 741 |
+
exchanges = []
|
| 742 |
+
for i, ex in enumerate(summary.triage_context, 1):
|
| 743 |
+
exchanges.append(f"Q{i}: {ex.get('question', '')}\nA{i}: {ex.get('response', '')}")
|
| 744 |
+
triage_section = "\n**TRIAGE EXCHANGES:**\n" + "\n".join(exchanges)
|
| 745 |
+
|
| 746 |
+
# Build conversation snippet
|
| 747 |
+
conversation_snippet = summary.conversation_context[:300] if summary.conversation_context else "No recent conversation"
|
| 748 |
+
|
| 749 |
+
# Extract patient info from medical_context
|
| 750 |
+
patient_age = "N/A"
|
| 751 |
+
patient_conditions = "None listed"
|
| 752 |
+
patient_goal = "Not specified"
|
| 753 |
+
|
| 754 |
+
if summary.medical_context:
|
| 755 |
+
age = summary.medical_context.get('age')
|
| 756 |
+
patient_age = str(age) if age else "N/A"
|
| 757 |
+
|
| 758 |
+
conditions = summary.medical_context.get('conditions', [])
|
| 759 |
+
if conditions:
|
| 760 |
+
# Take first 3 conditions
|
| 761 |
+
conditions_list = conditions[:3] if isinstance(conditions, list) else [conditions]
|
| 762 |
+
patient_conditions = ", ".join(str(c) for c in conditions_list)
|
| 763 |
+
if len(conditions) > 3:
|
| 764 |
+
patient_conditions += f" (+{len(conditions) - 3} more)"
|
| 765 |
+
|
| 766 |
+
goal = summary.medical_context.get('primary_goal')
|
| 767 |
+
if goal:
|
| 768 |
+
patient_goal = str(goal)
|
| 769 |
+
|
| 770 |
+
# Fill user prompt template
|
| 771 |
+
user_prompt = user_template.format(
|
| 772 |
+
patient_name=summary.patient_name,
|
| 773 |
+
patient_phone=summary.patient_phone,
|
| 774 |
+
patient_age=patient_age,
|
| 775 |
+
patient_conditions=patient_conditions,
|
| 776 |
+
patient_goal=patient_goal,
|
| 777 |
+
situation_description=summary.situation_description,
|
| 778 |
+
indicators=indicators_text,
|
| 779 |
+
urgency_level=summary.urgency_level,
|
| 780 |
+
follow_up_timeline=summary.follow_up_timeline,
|
| 781 |
+
triage_context=triage_section,
|
| 782 |
+
conversation_snippet=conversation_snippet
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
try:
|
| 786 |
+
# Use AIClientManager with model override if specified
|
| 787 |
+
from .ai_client import AIClientManager
|
| 788 |
+
|
| 789 |
+
# Create AI client for spiritual care messages
|
| 790 |
+
ai_manager = AIClientManager(
|
| 791 |
+
agent_name="SpiritualCareMessage",
|
| 792 |
+
model_override=model_override
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
# Generate response
|
| 796 |
+
response = ai_manager.generate_response(
|
| 797 |
+
system_prompt=system_prompt,
|
| 798 |
+
user_prompt=user_prompt,
|
| 799 |
+
temperature=0.7, # Slightly creative for natural language
|
| 800 |
+
call_type="spiritual_care_message"
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
return response.strip()
|
| 804 |
+
|
| 805 |
+
except Exception as e:
|
| 806 |
+
print(f"⚠️ Error generating LLM message: {e}")
|
| 807 |
+
return self._generate_fallback_care_message(summary, language)
|
| 808 |
+
|
| 809 |
+
def _generate_fallback_care_message(self, summary: ProviderSummary, language: str = "English") -> str:
|
| 810 |
+
"""Generate fallback structured message when LLM is unavailable."""
|
| 811 |
+
|
| 812 |
+
urgency_prefix = {
|
| 813 |
+
'IMMEDIATE': '🚨 URGENT - IMMEDIATE ATTENTION REQUIRED',
|
| 814 |
+
'URGENT': '⚡ URGENT - Contact Within 24 Hours',
|
| 815 |
+
'STANDARD': '📋 Follow-up Required'
|
| 816 |
+
}.get(summary.urgency_level, '📋 Follow-up Required')
|
| 817 |
+
|
| 818 |
+
if language.lower() in ['ukrainian', 'uk', 'укр', 'українська']:
|
| 819 |
+
message = f"""{urgency_prefix}
|
| 820 |
+
|
| 821 |
+
👤 ІНФОРМАЦІЯ ПРО ПАЦІЄНТА
|
| 822 |
+
Ім'я: {summary.patient_name}
|
| 823 |
+
Телефон: {summary.patient_phone}
|
| 824 |
+
{'Email: ' + summary.patient_email if summary.patient_email else ''}
|
| 825 |
+
|
| 826 |
+
📊 КЛАСИФІКАЦІЯ
|
| 827 |
+
Рівень: ЧЕРВОНИЙ ПРАПОР - Духовний дистрес
|
| 828 |
+
Серйозність: {summary.severity_level}
|
| 829 |
+
Впевненість: {summary.confidence:.0%}
|
| 830 |
+
|
| 831 |
+
🔍 СИТУАЦІЯ
|
| 832 |
+
{summary.situation_description}
|
| 833 |
+
|
| 834 |
+
⚠️ ІНДИКАТОРИ ДИСТРЕСУ
|
| 835 |
+
"""
|
| 836 |
+
for indicator in summary.indicators:
|
| 837 |
+
message += f"• {indicator}\n"
|
| 838 |
+
|
| 839 |
+
message += f"""
|
| 840 |
+
💭 ОБҐРУНТУВАННЯ
|
| 841 |
+
{summary.reasoning}
|
| 842 |
+
|
| 843 |
+
⏰ ТЕРМІН ДІЇ
|
| 844 |
+
{summary.follow_up_timeline}
|
| 845 |
+
|
| 846 |
+
✅ РЕКОМЕНДОВАНІ ДІЇ
|
| 847 |
+
"""
|
| 848 |
+
for action in summary.recommended_actions[:3]:
|
| 849 |
+
message += f"• {action}\n"
|
| 850 |
+
|
| 851 |
+
else: # English
|
| 852 |
+
message = f"""{urgency_prefix}
|
| 853 |
+
|
| 854 |
+
👤 PATIENT INFORMATION
|
| 855 |
+
Name: {summary.patient_name}
|
| 856 |
+
Phone: {summary.patient_phone}
|
| 857 |
+
{'Email: ' + summary.patient_email if summary.patient_email else ''}
|
| 858 |
+
|
| 859 |
+
📊 CLASSIFICATION
|
| 860 |
+
Level: RED FLAG - Spiritual Distress
|
| 861 |
+
Severity: {summary.severity_level}
|
| 862 |
+
Confidence: {summary.confidence:.0%}
|
| 863 |
+
|
| 864 |
+
🔍 SITUATION
|
| 865 |
+
{summary.situation_description}
|
| 866 |
+
|
| 867 |
+
⚠️ DISTRESS INDICATORS
|
| 868 |
+
"""
|
| 869 |
+
for indicator in summary.indicators:
|
| 870 |
+
message += f"• {indicator}\n"
|
| 871 |
+
|
| 872 |
+
message += f"""
|
| 873 |
+
💭 REASONING
|
| 874 |
+
{summary.reasoning}
|
| 875 |
+
|
| 876 |
+
⏰ ACTION TIMELINE
|
| 877 |
+
{summary.follow_up_timeline}
|
| 878 |
+
|
| 879 |
+
✅ RECOMMENDED ACTIONS
|
| 880 |
+
"""
|
| 881 |
+
for action in summary.recommended_actions[:3]:
|
| 882 |
+
message += f"• {action}\n"
|
| 883 |
+
|
| 884 |
+
if summary.triage_context:
|
| 885 |
+
if language.lower() in ['ukrainian', 'uk', 'укр', 'українська']:
|
| 886 |
+
message += "\n🗣️ КОНТЕКСТ З УТОЧНЮЮЧИХ ПИТАНЬ\n"
|
| 887 |
+
else:
|
| 888 |
+
message += "\n🗣️ CONTEXT FROM CLARIFYING QUESTIONS\n"
|
| 889 |
+
|
| 890 |
+
for i, exchange in enumerate(summary.triage_context, 1):
|
| 891 |
+
message += f"Q{i}: {exchange.get('question', '')}\n"
|
| 892 |
+
message += f"A{i}: {exchange.get('response', '')}\n\n"
|
| 893 |
+
|
| 894 |
+
return message
|
| 895 |
+
|
| 896 |
def generate_summary_with_validation(self, **kwargs) -> tuple[ProviderSummary, List[str]]:
|
| 897 |
"""
|
| 898 |
Generate provider summary with validation feedback.
|
src/core/simplified_medical_app.py
CHANGED
|
@@ -12,11 +12,18 @@ Requirements: 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 2.4
|
|
| 12 |
"""
|
| 13 |
|
| 14 |
import os
|
|
|
|
| 15 |
import logging
|
| 16 |
from datetime import datetime
|
| 17 |
from dataclasses import asdict
|
| 18 |
from typing import List, Tuple, Optional
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
from src.core.spiritual_state import (
|
| 21 |
SpiritualState, TriageOutcome, SessionSpiritualState, SpiritualAssessment
|
| 22 |
)
|
|
@@ -85,7 +92,7 @@ class SimplifiedMedicalApp:
|
|
| 85 |
self.spiritual_monitor = SpiritualMonitor(self.api, self.performance_monitor)
|
| 86 |
self.soft_triage_manager = SoftTriageManager(self.api)
|
| 87 |
self.consent_generator = ConsentMessageGenerator()
|
| 88 |
-
self.provider_summary_generator = ProviderSummaryGenerator()
|
| 89 |
|
| 90 |
# Patient information (can be set via UI)
|
| 91 |
self.patient_info = {
|
|
@@ -700,6 +707,15 @@ Is there anything else I can help you with today?"""
|
|
| 700 |
patient_name = self.patient_info.get("name") or self.clinical_background.patient_name
|
| 701 |
patient_phone = self.patient_info.get("phone")
|
| 702 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 703 |
# Generate provider summary
|
| 704 |
summary = self.provider_summary_generator.generate_summary(
|
| 705 |
indicators=assessment.indicators,
|
|
@@ -709,7 +725,8 @@ Is there anything else I can help you with today?"""
|
|
| 709 |
patient_phone=patient_phone,
|
| 710 |
triage_questions=triage_questions,
|
| 711 |
triage_responses=triage_responses,
|
| 712 |
-
conversation_context=self._get_conversation_context_str()
|
|
|
|
| 713 |
)
|
| 714 |
|
| 715 |
# Store the summary for later access
|
|
@@ -744,6 +761,37 @@ Is there anything else I can help you with today?"""
|
|
| 744 |
"""
|
| 745 |
return getattr(self, '_last_provider_summary', None)
|
| 746 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 747 |
def _detect_language(self, text: str) -> str:
|
| 748 |
"""Simple language detection based on character analysis."""
|
| 749 |
if not text:
|
|
@@ -779,6 +827,12 @@ Is there anything else I can help you with today?"""
|
|
| 779 |
"""
|
| 780 |
Reset session state.
|
| 781 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 782 |
Requirement: 7.4
|
| 783 |
"""
|
| 784 |
logger.info("Resetting session")
|
|
@@ -791,6 +845,10 @@ Is there anything else I can help you with today?"""
|
|
| 791 |
self.spiritual_state.reset()
|
| 792 |
self.session_active = False
|
| 793 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 794 |
# Start new conversation log
|
| 795 |
self.conversation_logger = ConversationLogger(
|
| 796 |
patient_name=self.clinical_background.patient_name
|
|
@@ -884,7 +942,7 @@ Is there anything else I can help you with today?"""
|
|
| 884 |
return tracking
|
| 885 |
|
| 886 |
def _get_status_info(self) -> str:
|
| 887 |
-
"""Get current status information."""
|
| 888 |
state_emoji = {
|
| 889 |
SpiritualState.GREEN: "🟢",
|
| 890 |
SpiritualState.YELLOW: "🟡",
|
|
@@ -899,11 +957,23 @@ Is there anything else I can help you with today?"""
|
|
| 899 |
count = self.spiritual_state.triage_session.question_count
|
| 900 |
triage_info = f"\n🔍 **Triage:** Question {count}/3"
|
| 901 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 902 |
return f"""
|
| 903 |
-
{emoji} **Spiritual State:** {current_state.value.upper()}
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
|
|
|
| 907 |
"""
|
| 908 |
|
| 909 |
|
|
|
|
| 12 |
"""
|
| 13 |
|
| 14 |
import os
|
| 15 |
+
import sys
|
| 16 |
import logging
|
| 17 |
from datetime import datetime
|
| 18 |
from dataclasses import asdict
|
| 19 |
from typing import List, Tuple, Optional
|
| 20 |
|
| 21 |
+
# Add project root to Python path if running as script
|
| 22 |
+
if __name__ == "__main__":
|
| 23 |
+
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 24 |
+
if project_root not in sys.path:
|
| 25 |
+
sys.path.insert(0, project_root)
|
| 26 |
+
|
| 27 |
from src.core.spiritual_state import (
|
| 28 |
SpiritualState, TriageOutcome, SessionSpiritualState, SpiritualAssessment
|
| 29 |
)
|
|
|
|
| 92 |
self.spiritual_monitor = SpiritualMonitor(self.api, self.performance_monitor)
|
| 93 |
self.soft_triage_manager = SoftTriageManager(self.api)
|
| 94 |
self.consent_generator = ConsentMessageGenerator()
|
| 95 |
+
self.provider_summary_generator = ProviderSummaryGenerator(ai_client=self.api)
|
| 96 |
|
| 97 |
# Patient information (can be set via UI)
|
| 98 |
self.patient_info = {
|
|
|
|
| 707 |
patient_name = self.patient_info.get("name") or self.clinical_background.patient_name
|
| 708 |
patient_phone = self.patient_info.get("phone")
|
| 709 |
|
| 710 |
+
# Build medical context from clinical_background
|
| 711 |
+
medical_context = {
|
| 712 |
+
"age": self.clinical_background.age,
|
| 713 |
+
"conditions": self.clinical_background.conditions,
|
| 714 |
+
"primary_goal": self.clinical_background.primary_goal,
|
| 715 |
+
"exercise_preferences": self.clinical_background.exercise_preferences,
|
| 716 |
+
"exercise_limitations": self.clinical_background.exercise_limitations
|
| 717 |
+
}
|
| 718 |
+
|
| 719 |
# Generate provider summary
|
| 720 |
summary = self.provider_summary_generator.generate_summary(
|
| 721 |
indicators=assessment.indicators,
|
|
|
|
| 725 |
patient_phone=patient_phone,
|
| 726 |
triage_questions=triage_questions,
|
| 727 |
triage_responses=triage_responses,
|
| 728 |
+
conversation_context=self._get_conversation_context_str(),
|
| 729 |
+
medical_context=medical_context
|
| 730 |
)
|
| 731 |
|
| 732 |
# Store the summary for later access
|
|
|
|
| 761 |
"""
|
| 762 |
return getattr(self, '_last_provider_summary', None)
|
| 763 |
|
| 764 |
+
def generate_spiritual_care_message(self, language: str = "English", session_id: Optional[str] = None) -> Optional[str]:
|
| 765 |
+
"""
|
| 766 |
+
Generate LLM-based message for spiritual care team.
|
| 767 |
+
|
| 768 |
+
Creates a compassionate, concise message summarizing the patient's
|
| 769 |
+
situation for the spiritual care team. Uses natural language and
|
| 770 |
+
emphasizes emotional/spiritual aspects.
|
| 771 |
+
|
| 772 |
+
Args:
|
| 773 |
+
language: Language for the message (English/Ukrainian)
|
| 774 |
+
session_id: Optional session ID for session-specific prompt overrides
|
| 775 |
+
|
| 776 |
+
Returns:
|
| 777 |
+
Generated message if provider summary exists, None otherwise
|
| 778 |
+
|
| 779 |
+
Requirements: 7.1, 7.2, 7.3, 7.4, 7.5
|
| 780 |
+
"""
|
| 781 |
+
summary = self.get_last_provider_summary()
|
| 782 |
+
if not summary:
|
| 783 |
+
return None
|
| 784 |
+
|
| 785 |
+
# Get model override for SpiritualCareMessage if configured
|
| 786 |
+
model_override = self._get_model_override('SpiritualCareMessage')
|
| 787 |
+
|
| 788 |
+
return self.provider_summary_generator.generate_spiritual_care_message(
|
| 789 |
+
summary=summary,
|
| 790 |
+
language=language,
|
| 791 |
+
session_id=session_id,
|
| 792 |
+
model_override=model_override
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
def _detect_language(self, text: str) -> str:
|
| 796 |
"""Simple language detection based on character analysis."""
|
| 797 |
if not text:
|
|
|
|
| 827 |
"""
|
| 828 |
Reset session state.
|
| 829 |
|
| 830 |
+
Clears all session data including:
|
| 831 |
+
- Chat history
|
| 832 |
+
- Spiritual state (GREEN/YELLOW/RED)
|
| 833 |
+
- Provider summary (if any)
|
| 834 |
+
- Conversation logs
|
| 835 |
+
|
| 836 |
Requirement: 7.4
|
| 837 |
"""
|
| 838 |
logger.info("Resetting session")
|
|
|
|
| 845 |
self.spiritual_state.reset()
|
| 846 |
self.session_active = False
|
| 847 |
|
| 848 |
+
# Clear last provider summary
|
| 849 |
+
if hasattr(self, '_last_provider_summary'):
|
| 850 |
+
self._last_provider_summary = None
|
| 851 |
+
|
| 852 |
# Start new conversation log
|
| 853 |
self.conversation_logger = ConversationLogger(
|
| 854 |
patient_name=self.clinical_background.patient_name
|
|
|
|
| 942 |
return tracking
|
| 943 |
|
| 944 |
def _get_status_info(self) -> str:
|
| 945 |
+
"""Get current status information with enhanced patient details."""
|
| 946 |
state_emoji = {
|
| 947 |
SpiritualState.GREEN: "🟢",
|
| 948 |
SpiritualState.YELLOW: "🟡",
|
|
|
|
| 957 |
count = self.spiritual_state.triage_session.question_count
|
| 958 |
triage_info = f"\n🔍 **Triage:** Question {count}/3"
|
| 959 |
|
| 960 |
+
# Get patient info - prefer patient_info, fall back to clinical_background
|
| 961 |
+
patient_name = self.patient_info.get("name") or self.clinical_background.patient_name
|
| 962 |
+
patient_phone = self.patient_info.get("phone") or "Not provided"
|
| 963 |
+
patient_age = self.clinical_background.age if self.clinical_background.age else "N/A"
|
| 964 |
+
|
| 965 |
+
# Get primary conditions (first 2)
|
| 966 |
+
conditions = self.clinical_background.conditions[:2] if self.clinical_background.conditions else []
|
| 967 |
+
conditions_text = ", ".join(conditions) if conditions else "None listed"
|
| 968 |
+
if len(self.clinical_background.conditions) > 2:
|
| 969 |
+
conditions_text += f" (+{len(self.clinical_background.conditions) - 2} more)"
|
| 970 |
+
|
| 971 |
return f"""
|
| 972 |
+
{emoji} **Spiritual State:** {current_state.value.upper()} 🏥 **Mode:** Medical Dialog
|
| 973 |
+
💬 **Messages:** {len(self.chat_history)} 👤 **Patient:** {patient_name}
|
| 974 |
+
📞 **Phone:** {patient_phone}
|
| 975 |
+
🎂 **Age:** {patient_age}
|
| 976 |
+
🏥 **Conditions:** {conditions_text}{triage_info}
|
| 977 |
"""
|
| 978 |
|
| 979 |
|
src/interface/enhanced_prompt_editor.py
CHANGED
|
@@ -32,7 +32,8 @@ class EnhancedPromptEditor:
|
|
| 32 |
"🟡 Soft Spiritual Triage": "triage_question",
|
| 33 |
"📊 Triage Response Evaluator": "triage_evaluator",
|
| 34 |
"🏥 Medical Assistant": "medical_assistant",
|
| 35 |
-
"🩺 Soft Medical Triage": "soft_medical_triage"
|
|
|
|
| 36 |
}
|
| 37 |
self._reverse_mapping = {v: k for k, v in self._agent_mapping.items()}
|
| 38 |
|
|
|
|
| 32 |
"🟡 Soft Spiritual Triage": "triage_question",
|
| 33 |
"📊 Triage Response Evaluator": "triage_evaluator",
|
| 34 |
"🏥 Medical Assistant": "medical_assistant",
|
| 35 |
+
"🩺 Soft Medical Triage": "soft_medical_triage",
|
| 36 |
+
"💬 Spiritual Care Message": "spiritual_care_message"
|
| 37 |
}
|
| 38 |
self._reverse_mapping = {v: k for k, v in self._agent_mapping.items()}
|
| 39 |
|
src/interface/help_content.py
CHANGED
|
@@ -78,6 +78,51 @@ The system continuously monitors all conversations and classifies them into thre
|
|
| 78 |
3. **Asks for your consent** before sharing information
|
| 79 |
4. If you consent, generates Provider Summary for spiritual care team
|
| 80 |
5. Provider Summary appears in right panel with download option
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
---
|
| 83 |
|
|
@@ -108,6 +153,7 @@ The **Edit Prompts** tab provides powerful capabilities for testing and optimizi
|
|
| 108 |
- 📊 **Triage Response Evaluator** - Evaluates patient responses to triage questions
|
| 109 |
- 🏥 **Medical Assistant** - Provides medical guidance and support
|
| 110 |
- 🩺 **Soft Medical Triage** - Handles medical triage and assessment
|
|
|
|
| 111 |
|
| 112 |
---
|
| 113 |
|
|
@@ -130,6 +176,7 @@ Configure which AI models are used for different tasks:
|
|
| 130 |
- **Triage Response Evaluator** - Response analysis (default: Gemini 2.5 Flash)
|
| 131 |
- **Medical Assistant** - Medical guidance (default: Claude Sonnet 4.5)
|
| 132 |
- **Soft Medical Triage** - Medical assessment (default: Claude Sonnet 4.5)
|
|
|
|
| 133 |
|
| 134 |
**Session Scope:** Model changes apply only to your current browser session.
|
| 135 |
|
|
@@ -266,10 +313,11 @@ The **Patient Profiles** tab includes comprehensive test scenarios:
|
|
| 266 |
- ✅ **Quality assurance** - Continuous monitoring and improvement
|
| 267 |
|
| 268 |
### Version Information:
|
| 269 |
-
- **System Version**: 2.
|
| 270 |
- **Test Coverage**: 65/65 tests passing
|
| 271 |
-
- **Last Updated**: December 18,
|
| 272 |
- **Status**: Production Ready
|
|
|
|
| 273 |
|
| 274 |
---
|
| 275 |
|
|
|
|
| 78 |
3. **Asks for your consent** before sharing information
|
| 79 |
4. If you consent, generates Provider Summary for spiritual care team
|
| 80 |
5. Provider Summary appears in right panel with download option
|
| 81 |
+
6. System generates a compassionate, natural language message for spiritual care team
|
| 82 |
+
|
| 83 |
+
---
|
| 84 |
+
|
| 85 |
+
## 💬 Spiritual Care Message Generation
|
| 86 |
+
|
| 87 |
+
### What is the Spiritual Care Message?
|
| 88 |
+
When a RED flag case is detected and you consent to a referral, the system automatically generates two types of summaries:
|
| 89 |
+
|
| 90 |
+
**📋 Provider Summary (Structured)**
|
| 91 |
+
- Complete patient contact information
|
| 92 |
+
- Detailed distress indicators and classifications
|
| 93 |
+
- Conversation context and triage exchanges
|
| 94 |
+
- Medical background and goals
|
| 95 |
+
- Recommended actions and urgency level
|
| 96 |
+
|
| 97 |
+
**💬 Spiritual Care Message (Natural Language)**
|
| 98 |
+
- Compassionate, empathetic message (50-75 words)
|
| 99 |
+
- Patient's name, contact, and age at the start
|
| 100 |
+
- Brief mention of relevant medical context
|
| 101 |
+
- Focus on emotional and spiritual struggles
|
| 102 |
+
- Urgency level and follow-up recommendations
|
| 103 |
+
- Written in warm, professional tone
|
| 104 |
+
|
| 105 |
+
### Customizing Spiritual Care Messages
|
| 106 |
+
You can customize how these messages are generated:
|
| 107 |
+
|
| 108 |
+
**Edit the Prompt (🔧 Edit Prompts tab):**
|
| 109 |
+
1. Select **💬 Spiritual Care Message** from dropdown
|
| 110 |
+
2. Modify the system prompt to adjust tone, length, or focus
|
| 111 |
+
3. Test changes in your current session
|
| 112 |
+
4. Promote to file if you want permanent changes
|
| 113 |
+
|
| 114 |
+
**Choose the AI Model (⚙️ Model Settings tab):**
|
| 115 |
+
1. Select model for **💬 Spiritual Care Message**
|
| 116 |
+
2. Default: Claude Sonnet 4.5 (empathetic, natural language)
|
| 117 |
+
3. Alternative: Gemini models for different tone
|
| 118 |
+
4. Changes apply to your session only
|
| 119 |
+
|
| 120 |
+
### Message Features:
|
| 121 |
+
- **Auto-detects language** from conversation context
|
| 122 |
+
- **Includes medical background** when relevant to understanding distress
|
| 123 |
+
- **Patient-centered** - emphasizes their feelings and struggles
|
| 124 |
+
- **Actionable** - clear urgency and follow-up timeline
|
| 125 |
+
- **Compassionate** - uses empathetic, caring language
|
| 126 |
|
| 127 |
---
|
| 128 |
|
|
|
|
| 153 |
- 📊 **Triage Response Evaluator** - Evaluates patient responses to triage questions
|
| 154 |
- 🏥 **Medical Assistant** - Provides medical guidance and support
|
| 155 |
- 🩺 **Soft Medical Triage** - Handles medical triage and assessment
|
| 156 |
+
- 💬 **Spiritual Care Message** - Generates compassionate messages for spiritual care team
|
| 157 |
|
| 158 |
---
|
| 159 |
|
|
|
|
| 176 |
- **Triage Response Evaluator** - Response analysis (default: Gemini 2.5 Flash)
|
| 177 |
- **Medical Assistant** - Medical guidance (default: Claude Sonnet 4.5)
|
| 178 |
- **Soft Medical Triage** - Medical assessment (default: Claude Sonnet 4.5)
|
| 179 |
+
- **Spiritual Care Message** - Compassionate message generation (default: Claude Sonnet 4.5)
|
| 180 |
|
| 181 |
**Session Scope:** Model changes apply only to your current browser session.
|
| 182 |
|
|
|
|
| 313 |
- ✅ **Quality assurance** - Continuous monitoring and improvement
|
| 314 |
|
| 315 |
### Version Information:
|
| 316 |
+
- **System Version**: 2.1
|
| 317 |
- **Test Coverage**: 65/65 tests passing
|
| 318 |
+
- **Last Updated**: December 18, 2025
|
| 319 |
- **Status**: Production Ready
|
| 320 |
+
- **New Features**: Spiritual Care Message prompt editing and model selection
|
| 321 |
|
| 322 |
---
|
| 323 |
|
src/interface/simplified_gradio_app.py
CHANGED
|
@@ -66,6 +66,24 @@ class SimplifiedSessionData:
|
|
| 66 |
self.app_instance = SimplifiedMedicalApp()
|
| 67 |
self.created_at = datetime.now().isoformat()
|
| 68 |
self.last_activity = datetime.now().isoformat()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
def update_activity(self):
|
| 71 |
"""Update last activity timestamp."""
|
|
@@ -162,8 +180,8 @@ def create_simplified_interface():
|
|
| 162 |
# Quick examples
|
| 163 |
gr.Markdown("### ⚡ Quick Start:")
|
| 164 |
with gr.Row():
|
| 165 |
-
example_medical = gr.Button("
|
| 166 |
-
example_wellness = gr.Button("
|
| 167 |
example_help = gr.Button("🔴 Emotional crisis", size="sm")
|
| 168 |
|
| 169 |
with gr.Column(scale=1):
|
|
@@ -196,11 +214,36 @@ def create_simplified_interface():
|
|
| 196 |
value="**Provider Summary Generated**\n\nA detailed summary has been generated for the spiritual care team. Use the Download button below to access the full summary."
|
| 197 |
)
|
| 198 |
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
with gr.Row():
|
| 202 |
download_summary_btn = gr.DownloadButton(
|
| 203 |
-
"📥 Download Summary",
|
| 204 |
size="sm",
|
| 205 |
variant="secondary"
|
| 206 |
)
|
|
@@ -350,6 +393,21 @@ def create_simplified_interface():
|
|
| 350 |
label="Soft Medical Triage",
|
| 351 |
interactive=True
|
| 352 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
|
| 354 |
with gr.Row():
|
| 355 |
apply_models_btn = gr.Button("✅ Apply Model Settings", variant="primary", scale=2)
|
|
@@ -370,7 +428,8 @@ def create_simplified_interface():
|
|
| 370 |
"🟡 Soft Spiritual Triage",
|
| 371 |
"📊 Triage Response Evaluator",
|
| 372 |
"🏥 Medical Assistant",
|
| 373 |
-
"🩺 Soft Medical Triage"
|
|
|
|
| 374 |
],
|
| 375 |
value="🔍 Spiritual Monitor (Classifier)",
|
| 376 |
label="Select Prompt to Edit",
|
|
@@ -554,6 +613,7 @@ def create_simplified_interface():
|
|
| 554 |
|
| 555 |
# Check for provider summary (RED flag case)
|
| 556 |
provider_summary_text = ""
|
|
|
|
| 557 |
show_provider_panel = False
|
| 558 |
last_summary = session.app_instance.get_last_provider_summary()
|
| 559 |
|
|
@@ -563,6 +623,20 @@ def create_simplified_interface():
|
|
| 563 |
print(f"DEBUG: summary patient: {last_summary.patient_name}")
|
| 564 |
print(f"DEBUG: summary indicators: {last_summary.indicators}")
|
| 565 |
provider_summary_text = session.app_instance.provider_summary_generator.format_for_display(last_summary)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 566 |
show_provider_panel = True
|
| 567 |
print(f"DEBUG: formatted summary length: {len(provider_summary_text)}")
|
| 568 |
print(f"DEBUG: show_provider_panel: {show_provider_panel}")
|
|
@@ -608,23 +682,41 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 608 |
stats,
|
| 609 |
gr.update(visible=show_provider_panel), # provider_summary_content visibility
|
| 610 |
status_msg, # provider_summary_status content
|
| 611 |
-
gr.update(value=html_content, visible=True) if show_provider_panel else gr.update(visible=False)
|
|
|
|
| 612 |
)
|
| 613 |
|
| 614 |
def handle_clear(session: SimplifiedSessionData):
|
| 615 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 616 |
if session is None:
|
| 617 |
session = SimplifiedSessionData()
|
| 618 |
|
| 619 |
session.update_activity()
|
| 620 |
new_history, status = session.app_instance.reset_session()
|
| 621 |
-
|
| 622 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 623 |
|
| 624 |
def get_status(session: SimplifiedSessionData):
|
| 625 |
"""Get current status and stats."""
|
| 626 |
if session is None:
|
| 627 |
-
return "❌ Session not initialized", "No stats", gr.update(visible=False), "No provider summary available", ""
|
| 628 |
|
| 629 |
session.update_activity()
|
| 630 |
status_info = session.app_instance._get_status_info()
|
|
@@ -637,8 +729,22 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 637 |
show_provider_panel = last_summary is not None
|
| 638 |
|
| 639 |
provider_summary_text = ""
|
|
|
|
|
|
|
| 640 |
if last_summary:
|
| 641 |
provider_summary_text = session.app_instance.provider_summary_generator.format_for_display(last_summary)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
|
| 643 |
if provider_summary_text:
|
| 644 |
import html
|
|
@@ -662,7 +768,8 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 662 |
stats_text,
|
| 663 |
gr.update(visible=show_provider_panel),
|
| 664 |
status_msg,
|
| 665 |
-
html_content
|
|
|
|
| 666 |
)
|
| 667 |
|
| 668 |
def send_example(example_text: str, history, session: SimplifiedSessionData):
|
|
@@ -1962,27 +2069,27 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 1962 |
send_btn.click(
|
| 1963 |
handle_message,
|
| 1964 |
inputs=[msg, chatbot, session_data],
|
| 1965 |
-
outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display]
|
| 1966 |
)
|
| 1967 |
|
| 1968 |
msg.submit(
|
| 1969 |
handle_message,
|
| 1970 |
inputs=[msg, chatbot, session_data],
|
| 1971 |
-
outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display]
|
| 1972 |
)
|
| 1973 |
|
| 1974 |
# Clear chat
|
| 1975 |
clear_btn.click(
|
| 1976 |
handle_clear,
|
| 1977 |
inputs=[session_data],
|
| 1978 |
-
outputs=[chatbot, status_box, session_data, provider_summary_content, provider_summary_status, provider_summary_display]
|
| 1979 |
)
|
| 1980 |
|
| 1981 |
# Refresh status
|
| 1982 |
refresh_btn.click(
|
| 1983 |
get_status,
|
| 1984 |
inputs=[session_data],
|
| 1985 |
-
outputs=[status_box, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display]
|
| 1986 |
)
|
| 1987 |
|
| 1988 |
# Example buttons
|
|
@@ -1991,7 +2098,7 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 1991 |
return handle_message(example_text, history, session)
|
| 1992 |
|
| 1993 |
example_medical.click(
|
| 1994 |
-
lambda h, s: send_example_with_stats("I
|
| 1995 |
inputs=[chatbot, session_data],
|
| 1996 |
outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display]
|
| 1997 |
)
|
|
@@ -2052,7 +2159,61 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2052 |
|
| 2053 |
def clear_provider_summary():
|
| 2054 |
"""Clear provider summary panel."""
|
| 2055 |
-
return gr.update(visible=False), "No provider summary available", ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2056 |
|
| 2057 |
download_summary_btn.click(
|
| 2058 |
download_provider_summary,
|
|
@@ -2063,7 +2224,20 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2063 |
clear_summary_btn.click(
|
| 2064 |
clear_provider_summary,
|
| 2065 |
inputs=[],
|
| 2066 |
-
outputs=[provider_summary_content, provider_summary_status, provider_summary_display]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2067 |
)
|
| 2068 |
|
| 2069 |
# Download helper (used by embedded Conversation Verification tab)
|
|
@@ -2523,7 +2697,7 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2523 |
)
|
| 2524 |
|
| 2525 |
# Model selection handlers
|
| 2526 |
-
def apply_model_settings(spiritual_model: str, soft_spiritual_triage_model: str, triage_evaluate_model: str, medical_model: str, soft_triage_model: str, session: SimplifiedSessionData):
|
| 2527 |
"""Apply custom model settings."""
|
| 2528 |
if session is None:
|
| 2529 |
session = SimplifiedSessionData()
|
|
@@ -2537,7 +2711,8 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2537 |
'SoftSpiritualTriage': soft_spiritual_triage_model,
|
| 2538 |
'TriageResponseEvaluator': triage_evaluate_model,
|
| 2539 |
'MedicalAssistant': medical_model,
|
| 2540 |
-
'SoftMedicalTriage': soft_triage_model
|
|
|
|
| 2541 |
}
|
| 2542 |
|
| 2543 |
status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
|
|
@@ -2548,6 +2723,7 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2548 |
<p><strong>📊 Triage Response Evaluator:</strong> <code>{triage_evaluate_model}</code></p>
|
| 2549 |
<p><strong>🏥 Medical Assistant:</strong> <code>{medical_model}</code></p>
|
| 2550 |
<p><strong>🩺 Soft Medical Triage:</strong> <code>{soft_triage_model}</code></p>
|
|
|
|
| 2551 |
|
| 2552 |
<p style="color: #d97706; margin-bottom: 0;">
|
| 2553 |
⚠️ <strong>Note:</strong> Model changes apply to this session only.
|
|
@@ -2573,6 +2749,7 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2573 |
<p><strong>📊 Triage Response Evaluator:</strong> <code>gemini-2.5-flash</code></p>
|
| 2574 |
<p><strong>🏥 Medical Assistant:</strong> <code>claude-sonnet-4-5-20250929</code></p>
|
| 2575 |
<p><strong>🩺 Soft Medical Triage:</strong> <code>claude-sonnet-4-5-20250929</code></p>
|
|
|
|
| 2576 |
|
| 2577 |
<p style="margin-bottom: 0;">Default models are now active.</p>
|
| 2578 |
</div>"""
|
|
@@ -2582,7 +2759,7 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2582 |
# Bind model selection events
|
| 2583 |
apply_models_btn.click(
|
| 2584 |
apply_model_settings,
|
| 2585 |
-
inputs=[spiritual_model, soft_spiritual_triage_model, triage_evaluate_model, medical_model, soft_triage_model, session_data],
|
| 2586 |
outputs=[model_status, session_data]
|
| 2587 |
)
|
| 2588 |
|
|
@@ -2593,8 +2770,8 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2593 |
)
|
| 2594 |
|
| 2595 |
# Patient profile handlers
|
| 2596 |
-
def load_profile(profile_name: str):
|
| 2597 |
-
"""Load predefined patient profile."""
|
| 2598 |
profiles = {
|
| 2599 |
"Default (Serhii)": {
|
| 2600 |
"name": "Serhii",
|
|
@@ -2735,12 +2912,38 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2735 |
|
| 2736 |
profile = profiles.get(profile_name, profiles["Default (Serhii)"])
|
| 2737 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2738 |
status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
|
| 2739 |
-
<h4 style="color: #059669; margin-top: 0;">✅ Profile Loaded</h4>
|
| 2740 |
<p><strong>Patient:</strong> {profile['name']}, {profile['age']} years old</p>
|
| 2741 |
<p><strong>Phone:</strong> {profile.get('phone', 'Not provided')}</p>
|
| 2742 |
<p><strong>Profile:</strong> {profile_name}</p>
|
| 2743 |
-
<p
|
|
|
|
| 2744 |
</div>"""
|
| 2745 |
|
| 2746 |
return (
|
|
@@ -2754,7 +2957,7 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2754 |
status
|
| 2755 |
)
|
| 2756 |
|
| 2757 |
-
def save_profile(name: str, phone: str, age: float, conditions: str, goal: str, exercise: str, limitations: str):
|
| 2758 |
"""Save current profile settings and update app patient info."""
|
| 2759 |
if not name.strip():
|
| 2760 |
return """<div style="padding: 1em; background-color: #fef2f2; border-left: 4px solid #dc2626; border-radius: 4px;">
|
|
@@ -2762,9 +2965,27 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2762 |
<p style="margin-bottom: 0;">Patient name cannot be empty</p>
|
| 2763 |
</div>"""
|
| 2764 |
|
| 2765 |
-
# Update
|
| 2766 |
-
if hasattr(
|
| 2767 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2768 |
|
| 2769 |
status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
|
| 2770 |
<h4 style="color: #059669; margin-top: 0;">💾 Profile Saved</h4>
|
|
@@ -2777,11 +2998,28 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2777 |
|
| 2778 |
return status
|
| 2779 |
|
| 2780 |
-
def reset_profile():
|
| 2781 |
"""Reset profile to default."""
|
| 2782 |
-
# Reset
|
| 2783 |
-
if hasattr(
|
| 2784 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2785 |
|
| 2786 |
status = """<div style="padding: 1em; background-color: #eff6ff; border-left: 4px solid #3b82f6; border-radius: 4px;">
|
| 2787 |
<h4 style="color: #2563eb; margin-top: 0;">🔄 Profile Reset</h4>
|
|
@@ -2804,18 +3042,19 @@ Use the **Download Summary** button below to access the complete provider summar
|
|
| 2804 |
# Bind profile events
|
| 2805 |
load_profile_btn.click(
|
| 2806 |
load_profile,
|
| 2807 |
-
inputs=[profile_selector],
|
| 2808 |
outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_status]
|
| 2809 |
)
|
| 2810 |
|
| 2811 |
save_profile_btn.click(
|
| 2812 |
save_profile,
|
| 2813 |
-
inputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits],
|
| 2814 |
outputs=[profile_save_status]
|
| 2815 |
)
|
| 2816 |
|
| 2817 |
reset_profile_btn.click(
|
| 2818 |
reset_profile,
|
|
|
|
| 2819 |
outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_save_status]
|
| 2820 |
)
|
| 2821 |
|
|
|
|
| 66 |
self.app_instance = SimplifiedMedicalApp()
|
| 67 |
self.created_at = datetime.now().isoformat()
|
| 68 |
self.last_activity = datetime.now().isoformat()
|
| 69 |
+
|
| 70 |
+
# Set default patient info from profile
|
| 71 |
+
self.app_instance.set_patient_info(name="Serhii", phone="(555) 123-4567")
|
| 72 |
+
|
| 73 |
+
# Update clinical_background to match default profile
|
| 74 |
+
from src.core.core_classes import ClinicalBackground
|
| 75 |
+
self.app_instance.clinical_background = ClinicalBackground(
|
| 76 |
+
patient_name="Serhii",
|
| 77 |
+
age=52,
|
| 78 |
+
conditions=["Atrial fibrillation", "Deep vein thrombosis", "Obesity", "Hypertension"],
|
| 79 |
+
primary_goal="Weight reduction and cardiovascular fitness improvement",
|
| 80 |
+
exercise_preferences=["Swimming", "Walking", "Light cardio"],
|
| 81 |
+
exercise_limitations=["Anticoagulation therapy", "Post-thrombotic recovery"]
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# Update conversation logger patient name
|
| 85 |
+
if hasattr(self.app_instance, 'conversation_logger'):
|
| 86 |
+
self.app_instance.conversation_logger.patient_name = "Serhii"
|
| 87 |
|
| 88 |
def update_activity(self):
|
| 89 |
"""Update last activity timestamp."""
|
|
|
|
| 180 |
# Quick examples
|
| 181 |
gr.Markdown("### ⚡ Quick Start:")
|
| 182 |
with gr.Row():
|
| 183 |
+
example_medical = gr.Button("🟢 I am fine", size="sm")
|
| 184 |
+
example_wellness = gr.Button("🟡 I'm feeling stressed", size="sm")
|
| 185 |
example_help = gr.Button("🔴 Emotional crisis", size="sm")
|
| 186 |
|
| 187 |
with gr.Column(scale=1):
|
|
|
|
| 214 |
value="**Provider Summary Generated**\n\nA detailed summary has been generated for the spiritual care team. Use the Download button below to access the full summary."
|
| 215 |
)
|
| 216 |
|
| 217 |
+
# Tabs for different summary views
|
| 218 |
+
with gr.Tabs():
|
| 219 |
+
# Structured Summary Tab
|
| 220 |
+
with gr.TabItem("📊 Structured Summary"):
|
| 221 |
+
provider_summary_display = gr.HTML(value="")
|
| 222 |
+
|
| 223 |
+
# LLM-Generated Message Tab
|
| 224 |
+
with gr.TabItem("💬 Care Team Message"):
|
| 225 |
+
gr.Markdown("*AI-generated compassionate message for spiritual care team*")
|
| 226 |
+
spiritual_care_message = gr.Textbox(
|
| 227 |
+
value="",
|
| 228 |
+
lines=12,
|
| 229 |
+
label="Message for Spiritual Care Team",
|
| 230 |
+
interactive=False
|
| 231 |
+
)
|
| 232 |
+
with gr.Row():
|
| 233 |
+
generate_message_btn = gr.Button(
|
| 234 |
+
"🔄 Regenerate Message",
|
| 235 |
+
size="sm",
|
| 236 |
+
variant="secondary"
|
| 237 |
+
)
|
| 238 |
+
download_message_btn = gr.DownloadButton(
|
| 239 |
+
"📥 Download Message",
|
| 240 |
+
size="sm",
|
| 241 |
+
variant="secondary"
|
| 242 |
+
)
|
| 243 |
|
| 244 |
with gr.Row():
|
| 245 |
download_summary_btn = gr.DownloadButton(
|
| 246 |
+
"📥 Download Full Summary",
|
| 247 |
size="sm",
|
| 248 |
variant="secondary"
|
| 249 |
)
|
|
|
|
| 393 |
label="Soft Medical Triage",
|
| 394 |
interactive=True
|
| 395 |
)
|
| 396 |
+
|
| 397 |
+
gr.Markdown("### 💬 Spiritual Care Message")
|
| 398 |
+
spiritual_care_message_model = gr.Dropdown(
|
| 399 |
+
choices=[
|
| 400 |
+
"claude-sonnet-4-5-20250929",
|
| 401 |
+
"claude-sonnet-4-20250514",
|
| 402 |
+
"claude-3-7-sonnet-20250219",
|
| 403 |
+
"gemini-2.5-flash",
|
| 404 |
+
"gemini-2.0-flash",
|
| 405 |
+
"gemini-3-flash-preview"
|
| 406 |
+
],
|
| 407 |
+
value="claude-sonnet-4-5-20250929",
|
| 408 |
+
label="Spiritual Care Message Generator",
|
| 409 |
+
interactive=True
|
| 410 |
+
)
|
| 411 |
|
| 412 |
with gr.Row():
|
| 413 |
apply_models_btn = gr.Button("✅ Apply Model Settings", variant="primary", scale=2)
|
|
|
|
| 428 |
"🟡 Soft Spiritual Triage",
|
| 429 |
"📊 Triage Response Evaluator",
|
| 430 |
"🏥 Medical Assistant",
|
| 431 |
+
"🩺 Soft Medical Triage",
|
| 432 |
+
"💬 Spiritual Care Message"
|
| 433 |
],
|
| 434 |
value="🔍 Spiritual Monitor (Classifier)",
|
| 435 |
label="Select Prompt to Edit",
|
|
|
|
| 613 |
|
| 614 |
# Check for provider summary (RED flag case)
|
| 615 |
provider_summary_text = ""
|
| 616 |
+
spiritual_care_msg = ""
|
| 617 |
show_provider_panel = False
|
| 618 |
last_summary = session.app_instance.get_last_provider_summary()
|
| 619 |
|
|
|
|
| 623 |
print(f"DEBUG: summary patient: {last_summary.patient_name}")
|
| 624 |
print(f"DEBUG: summary indicators: {last_summary.indicators}")
|
| 625 |
provider_summary_text = session.app_instance.provider_summary_generator.format_for_display(last_summary)
|
| 626 |
+
|
| 627 |
+
# Generate LLM-based spiritual care message
|
| 628 |
+
try:
|
| 629 |
+
spiritual_care_msg = session.app_instance.generate_spiritual_care_message(
|
| 630 |
+
language="English",
|
| 631 |
+
session_id=session.session_id
|
| 632 |
+
)
|
| 633 |
+
if not spiritual_care_msg:
|
| 634 |
+
spiritual_care_msg = ""
|
| 635 |
+
print(f"DEBUG: spiritual care message generated: {len(spiritual_care_msg)} chars")
|
| 636 |
+
except Exception as e:
|
| 637 |
+
print(f"DEBUG: Error generating spiritual care message: {e}")
|
| 638 |
+
spiritual_care_msg = ""
|
| 639 |
+
|
| 640 |
show_provider_panel = True
|
| 641 |
print(f"DEBUG: formatted summary length: {len(provider_summary_text)}")
|
| 642 |
print(f"DEBUG: show_provider_panel: {show_provider_panel}")
|
|
|
|
| 682 |
stats,
|
| 683 |
gr.update(visible=show_provider_panel), # provider_summary_content visibility
|
| 684 |
status_msg, # provider_summary_status content
|
| 685 |
+
gr.update(value=html_content, visible=True) if show_provider_panel else gr.update(visible=False), # provider_summary_display content
|
| 686 |
+
spiritual_care_msg # spiritual_care_message content
|
| 687 |
)
|
| 688 |
|
| 689 |
def handle_clear(session: SimplifiedSessionData):
|
| 690 |
+
"""
|
| 691 |
+
Handle clear chat button.
|
| 692 |
+
|
| 693 |
+
Resets entire session including:
|
| 694 |
+
- Chat history
|
| 695 |
+
- Spiritual monitoring state
|
| 696 |
+
- Provider summary panel (hides and clears content)
|
| 697 |
+
- Conversation statistics
|
| 698 |
+
"""
|
| 699 |
if session is None:
|
| 700 |
session = SimplifiedSessionData()
|
| 701 |
|
| 702 |
session.update_activity()
|
| 703 |
new_history, status = session.app_instance.reset_session()
|
| 704 |
+
|
| 705 |
+
# Hide and clear provider summary panel
|
| 706 |
+
return (
|
| 707 |
+
new_history, # Clear chat history
|
| 708 |
+
status, # Reset status
|
| 709 |
+
session, # Updated session
|
| 710 |
+
gr.update(visible=False), # Hide provider_summary_content group
|
| 711 |
+
"No provider summary available", # Clear provider_summary_status
|
| 712 |
+
"", # Clear provider_summary_display HTML
|
| 713 |
+
"" # Clear spiritual_care_message
|
| 714 |
+
)
|
| 715 |
|
| 716 |
def get_status(session: SimplifiedSessionData):
|
| 717 |
"""Get current status and stats."""
|
| 718 |
if session is None:
|
| 719 |
+
return "❌ Session not initialized", "No stats", gr.update(visible=False), "No provider summary available", "", ""
|
| 720 |
|
| 721 |
session.update_activity()
|
| 722 |
status_info = session.app_instance._get_status_info()
|
|
|
|
| 729 |
show_provider_panel = last_summary is not None
|
| 730 |
|
| 731 |
provider_summary_text = ""
|
| 732 |
+
spiritual_care_msg = ""
|
| 733 |
+
|
| 734 |
if last_summary:
|
| 735 |
provider_summary_text = session.app_instance.provider_summary_generator.format_for_display(last_summary)
|
| 736 |
+
|
| 737 |
+
# Generate spiritual care message
|
| 738 |
+
try:
|
| 739 |
+
spiritual_care_msg = session.app_instance.generate_spiritual_care_message(
|
| 740 |
+
language="English",
|
| 741 |
+
session_id=session.session_id
|
| 742 |
+
)
|
| 743 |
+
if not spiritual_care_msg:
|
| 744 |
+
spiritual_care_msg = ""
|
| 745 |
+
except Exception as e:
|
| 746 |
+
print(f"Error generating spiritual care message in get_status: {e}")
|
| 747 |
+
spiritual_care_msg = ""
|
| 748 |
|
| 749 |
if provider_summary_text:
|
| 750 |
import html
|
|
|
|
| 768 |
stats_text,
|
| 769 |
gr.update(visible=show_provider_panel),
|
| 770 |
status_msg,
|
| 771 |
+
html_content,
|
| 772 |
+
spiritual_care_msg
|
| 773 |
)
|
| 774 |
|
| 775 |
def send_example(example_text: str, history, session: SimplifiedSessionData):
|
|
|
|
| 2069 |
send_btn.click(
|
| 2070 |
handle_message,
|
| 2071 |
inputs=[msg, chatbot, session_data],
|
| 2072 |
+
outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, spiritual_care_message]
|
| 2073 |
)
|
| 2074 |
|
| 2075 |
msg.submit(
|
| 2076 |
handle_message,
|
| 2077 |
inputs=[msg, chatbot, session_data],
|
| 2078 |
+
outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, spiritual_care_message]
|
| 2079 |
)
|
| 2080 |
|
| 2081 |
# Clear chat
|
| 2082 |
clear_btn.click(
|
| 2083 |
handle_clear,
|
| 2084 |
inputs=[session_data],
|
| 2085 |
+
outputs=[chatbot, status_box, session_data, provider_summary_content, provider_summary_status, provider_summary_display, spiritual_care_message]
|
| 2086 |
)
|
| 2087 |
|
| 2088 |
# Refresh status
|
| 2089 |
refresh_btn.click(
|
| 2090 |
get_status,
|
| 2091 |
inputs=[session_data],
|
| 2092 |
+
outputs=[status_box, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display, spiritual_care_message]
|
| 2093 |
)
|
| 2094 |
|
| 2095 |
# Example buttons
|
|
|
|
| 2098 |
return handle_message(example_text, history, session)
|
| 2099 |
|
| 2100 |
example_medical.click(
|
| 2101 |
+
lambda h, s: send_example_with_stats("I am fine", h, s),
|
| 2102 |
inputs=[chatbot, session_data],
|
| 2103 |
outputs=[chatbot, status_box, session_data, msg, conversation_stats, provider_summary_content, provider_summary_status, provider_summary_display]
|
| 2104 |
)
|
|
|
|
| 2159 |
|
| 2160 |
def clear_provider_summary():
|
| 2161 |
"""Clear provider summary panel."""
|
| 2162 |
+
return gr.update(visible=False), "No provider summary available", "", ""
|
| 2163 |
+
|
| 2164 |
+
def regenerate_spiritual_care_message(session: SimplifiedSessionData):
|
| 2165 |
+
"""Regenerate LLM-based spiritual care message."""
|
| 2166 |
+
if session is None:
|
| 2167 |
+
return ""
|
| 2168 |
+
|
| 2169 |
+
try:
|
| 2170 |
+
message = session.app_instance.generate_spiritual_care_message(
|
| 2171 |
+
language="English",
|
| 2172 |
+
session_id=session.session_id
|
| 2173 |
+
)
|
| 2174 |
+
return message if message else "No provider summary available to generate message from."
|
| 2175 |
+
except Exception as e:
|
| 2176 |
+
print(f"Error regenerating spiritual care message: {e}")
|
| 2177 |
+
return f"Error generating message: {str(e)}"
|
| 2178 |
+
|
| 2179 |
+
def download_spiritual_care_message(session: SimplifiedSessionData):
|
| 2180 |
+
"""Download spiritual care message as text file."""
|
| 2181 |
+
if session is None:
|
| 2182 |
+
return None
|
| 2183 |
+
|
| 2184 |
+
try:
|
| 2185 |
+
import tempfile
|
| 2186 |
+
import os
|
| 2187 |
+
from datetime import datetime
|
| 2188 |
+
|
| 2189 |
+
message = session.app_instance.generate_spiritual_care_message(
|
| 2190 |
+
language="English",
|
| 2191 |
+
session_id=session.session_id
|
| 2192 |
+
)
|
| 2193 |
+
if not message:
|
| 2194 |
+
return None
|
| 2195 |
+
|
| 2196 |
+
# Create temp file with message
|
| 2197 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 2198 |
+
filename = f"spiritual_care_message_{timestamp}.txt"
|
| 2199 |
+
filepath = os.path.join(tempfile.gettempdir(), filename)
|
| 2200 |
+
|
| 2201 |
+
# Add header
|
| 2202 |
+
patient_name = session.app_instance.patient_info.get('name', 'Patient')
|
| 2203 |
+
header = f"SPIRITUAL CARE TEAM MESSAGE\n"
|
| 2204 |
+
header += f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
|
| 2205 |
+
header += f"Patient: {patient_name}\n"
|
| 2206 |
+
header += f"Classification: RED FLAG - Spiritual Distress\n"
|
| 2207 |
+
header += "=" * 60 + "\n\n"
|
| 2208 |
+
|
| 2209 |
+
with open(filepath, 'w', encoding='utf-8') as f:
|
| 2210 |
+
f.write(header)
|
| 2211 |
+
f.write(message)
|
| 2212 |
+
|
| 2213 |
+
return filepath
|
| 2214 |
+
except Exception as e:
|
| 2215 |
+
print(f"Error downloading spiritual care message: {e}")
|
| 2216 |
+
return None
|
| 2217 |
|
| 2218 |
download_summary_btn.click(
|
| 2219 |
download_provider_summary,
|
|
|
|
| 2224 |
clear_summary_btn.click(
|
| 2225 |
clear_provider_summary,
|
| 2226 |
inputs=[],
|
| 2227 |
+
outputs=[provider_summary_content, provider_summary_status, provider_summary_display, spiritual_care_message]
|
| 2228 |
+
)
|
| 2229 |
+
|
| 2230 |
+
# Spiritual care message handlers
|
| 2231 |
+
generate_message_btn.click(
|
| 2232 |
+
regenerate_spiritual_care_message,
|
| 2233 |
+
inputs=[session_data],
|
| 2234 |
+
outputs=[spiritual_care_message]
|
| 2235 |
+
)
|
| 2236 |
+
|
| 2237 |
+
download_message_btn.click(
|
| 2238 |
+
download_spiritual_care_message,
|
| 2239 |
+
inputs=[session_data],
|
| 2240 |
+
outputs=[download_message_btn]
|
| 2241 |
)
|
| 2242 |
|
| 2243 |
# Download helper (used by embedded Conversation Verification tab)
|
|
|
|
| 2697 |
)
|
| 2698 |
|
| 2699 |
# Model selection handlers
|
| 2700 |
+
def apply_model_settings(spiritual_model: str, soft_spiritual_triage_model: str, triage_evaluate_model: str, medical_model: str, soft_triage_model: str, spiritual_care_message_model: str, session: SimplifiedSessionData):
|
| 2701 |
"""Apply custom model settings."""
|
| 2702 |
if session is None:
|
| 2703 |
session = SimplifiedSessionData()
|
|
|
|
| 2711 |
'SoftSpiritualTriage': soft_spiritual_triage_model,
|
| 2712 |
'TriageResponseEvaluator': triage_evaluate_model,
|
| 2713 |
'MedicalAssistant': medical_model,
|
| 2714 |
+
'SoftMedicalTriage': soft_triage_model,
|
| 2715 |
+
'SpiritualCareMessage': spiritual_care_message_model
|
| 2716 |
}
|
| 2717 |
|
| 2718 |
status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
|
|
|
|
| 2723 |
<p><strong>📊 Triage Response Evaluator:</strong> <code>{triage_evaluate_model}</code></p>
|
| 2724 |
<p><strong>🏥 Medical Assistant:</strong> <code>{medical_model}</code></p>
|
| 2725 |
<p><strong>🩺 Soft Medical Triage:</strong> <code>{soft_triage_model}</code></p>
|
| 2726 |
+
<p><strong>💬 Spiritual Care Message:</strong> <code>{spiritual_care_message_model}</code></p>
|
| 2727 |
|
| 2728 |
<p style="color: #d97706; margin-bottom: 0;">
|
| 2729 |
⚠️ <strong>Note:</strong> Model changes apply to this session only.
|
|
|
|
| 2749 |
<p><strong>📊 Triage Response Evaluator:</strong> <code>gemini-2.5-flash</code></p>
|
| 2750 |
<p><strong>🏥 Medical Assistant:</strong> <code>claude-sonnet-4-5-20250929</code></p>
|
| 2751 |
<p><strong>🩺 Soft Medical Triage:</strong> <code>claude-sonnet-4-5-20250929</code></p>
|
| 2752 |
+
<p><strong>💬 Spiritual Care Message:</strong> <code>claude-sonnet-4-5-20250929</code></p>
|
| 2753 |
|
| 2754 |
<p style="margin-bottom: 0;">Default models are now active.</p>
|
| 2755 |
</div>"""
|
|
|
|
| 2759 |
# Bind model selection events
|
| 2760 |
apply_models_btn.click(
|
| 2761 |
apply_model_settings,
|
| 2762 |
+
inputs=[spiritual_model, soft_spiritual_triage_model, triage_evaluate_model, medical_model, soft_triage_model, spiritual_care_message_model, session_data],
|
| 2763 |
outputs=[model_status, session_data]
|
| 2764 |
)
|
| 2765 |
|
|
|
|
| 2770 |
)
|
| 2771 |
|
| 2772 |
# Patient profile handlers
|
| 2773 |
+
def load_profile(profile_name: str, session: SimplifiedSessionData):
|
| 2774 |
+
"""Load predefined patient profile and apply it to the session."""
|
| 2775 |
profiles = {
|
| 2776 |
"Default (Serhii)": {
|
| 2777 |
"name": "Serhii",
|
|
|
|
| 2912 |
|
| 2913 |
profile = profiles.get(profile_name, profiles["Default (Serhii)"])
|
| 2914 |
|
| 2915 |
+
# Automatically apply the profile to the session
|
| 2916 |
+
if session and hasattr(session.app_instance, 'set_patient_info'):
|
| 2917 |
+
session.app_instance.set_patient_info(
|
| 2918 |
+
name=profile['name'],
|
| 2919 |
+
phone=profile.get('phone', '')
|
| 2920 |
+
)
|
| 2921 |
+
|
| 2922 |
+
# Update clinical_background for medical context
|
| 2923 |
+
from src.core.core_classes import ClinicalBackground
|
| 2924 |
+
session.app_instance.clinical_background = ClinicalBackground(
|
| 2925 |
+
patient_name=profile['name'],
|
| 2926 |
+
age=profile['age'],
|
| 2927 |
+
conditions=profile['conditions'].split(',') if isinstance(profile['conditions'], str) else profile['conditions'],
|
| 2928 |
+
primary_goal=profile['goal'],
|
| 2929 |
+
exercise_preferences=profile['exercise'].split(',') if isinstance(profile['exercise'], str) else profile['exercise'],
|
| 2930 |
+
exercise_limitations=profile['limitations'].split(',') if isinstance(profile['limitations'], str) else profile['limitations']
|
| 2931 |
+
)
|
| 2932 |
+
|
| 2933 |
+
# Update conversation logger patient name
|
| 2934 |
+
if hasattr(session.app_instance, 'conversation_logger'):
|
| 2935 |
+
session.app_instance.conversation_logger.patient_name = profile['name']
|
| 2936 |
+
|
| 2937 |
+
print(f"DEBUG: Auto-applied profile - Name: {profile['name']}, Phone: {profile.get('phone', '')}")
|
| 2938 |
+
print(f"DEBUG: Clinical background updated - Age: {profile['age']}, Conditions: {profile['conditions']}")
|
| 2939 |
+
|
| 2940 |
status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
|
| 2941 |
+
<h4 style="color: #059669; margin-top: 0;">✅ Profile Loaded & Applied</h4>
|
| 2942 |
<p><strong>Patient:</strong> {profile['name']}, {profile['age']} years old</p>
|
| 2943 |
<p><strong>Phone:</strong> {profile.get('phone', 'Not provided')}</p>
|
| 2944 |
<p><strong>Profile:</strong> {profile_name}</p>
|
| 2945 |
+
<p><strong>Status:</strong> Profile has been automatically applied to this session</p>
|
| 2946 |
+
<p style="margin-bottom: 0; color: #059669;">✓ Ready to use in conversations and reports</p>
|
| 2947 |
</div>"""
|
| 2948 |
|
| 2949 |
return (
|
|
|
|
| 2957 |
status
|
| 2958 |
)
|
| 2959 |
|
| 2960 |
+
def save_profile(name: str, phone: str, age: float, conditions: str, goal: str, exercise: str, limitations: str, session: SimplifiedSessionData):
|
| 2961 |
"""Save current profile settings and update app patient info."""
|
| 2962 |
if not name.strip():
|
| 2963 |
return """<div style="padding: 1em; background-color: #fef2f2; border-left: 4px solid #dc2626; border-radius: 4px;">
|
|
|
|
| 2965 |
<p style="margin-bottom: 0;">Patient name cannot be empty</p>
|
| 2966 |
</div>"""
|
| 2967 |
|
| 2968 |
+
# Update session's app instance patient info for provider summaries
|
| 2969 |
+
if session and hasattr(session.app_instance, 'set_patient_info'):
|
| 2970 |
+
session.app_instance.set_patient_info(name=name.strip(), phone=phone.strip() if phone else None)
|
| 2971 |
+
|
| 2972 |
+
# Also update clinical_background for medical context
|
| 2973 |
+
from src.core.core_classes import ClinicalBackground
|
| 2974 |
+
session.app_instance.clinical_background = ClinicalBackground(
|
| 2975 |
+
patient_name=name.strip(),
|
| 2976 |
+
age=int(age) if age else None,
|
| 2977 |
+
conditions=conditions.strip().split(',') if conditions.strip() else [],
|
| 2978 |
+
primary_goal=goal.strip(),
|
| 2979 |
+
exercise_preferences=exercise.strip().split(',') if exercise.strip() else [],
|
| 2980 |
+
exercise_limitations=limitations.strip().split(',') if limitations.strip() else []
|
| 2981 |
+
)
|
| 2982 |
+
|
| 2983 |
+
# Update conversation logger patient name
|
| 2984 |
+
if hasattr(session.app_instance, 'conversation_logger'):
|
| 2985 |
+
session.app_instance.conversation_logger.patient_name = name.strip()
|
| 2986 |
+
|
| 2987 |
+
print(f"DEBUG: Updated patient info - Name: {name.strip()}, Phone: {phone.strip() if phone else None}")
|
| 2988 |
+
print(f"DEBUG: Updated clinical_background - Age: {int(age) if age else None}, Conditions: {conditions}")
|
| 2989 |
|
| 2990 |
status = f"""<div style="padding: 1em; background-color: #ecfdf5; border-left: 4px solid #10b981; border-radius: 4px;">
|
| 2991 |
<h4 style="color: #059669; margin-top: 0;">💾 Profile Saved</h4>
|
|
|
|
| 2998 |
|
| 2999 |
return status
|
| 3000 |
|
| 3001 |
+
def reset_profile(session: SimplifiedSessionData):
|
| 3002 |
"""Reset profile to default."""
|
| 3003 |
+
# Reset session's app instance patient info
|
| 3004 |
+
if session and hasattr(session.app_instance, 'set_patient_info'):
|
| 3005 |
+
session.app_instance.set_patient_info(name="Serhii", phone="(555) 123-4567")
|
| 3006 |
+
|
| 3007 |
+
# Also reset clinical_background
|
| 3008 |
+
from src.core.core_classes import ClinicalBackground
|
| 3009 |
+
session.app_instance.clinical_background = ClinicalBackground(
|
| 3010 |
+
patient_name="Serhii",
|
| 3011 |
+
age=52,
|
| 3012 |
+
conditions=["Atrial fibrillation", "Deep vein thrombosis", "Obesity", "Hypertension"],
|
| 3013 |
+
primary_goal="Weight reduction and cardiovascular fitness improvement",
|
| 3014 |
+
exercise_preferences=["Swimming", "Walking", "Light cardio"],
|
| 3015 |
+
exercise_limitations=["Anticoagulation therapy", "Post-thrombotic recovery"]
|
| 3016 |
+
)
|
| 3017 |
+
|
| 3018 |
+
# Update conversation logger patient name
|
| 3019 |
+
if hasattr(session.app_instance, 'conversation_logger'):
|
| 3020 |
+
session.app_instance.conversation_logger.patient_name = "Serhii"
|
| 3021 |
+
|
| 3022 |
+
print(f"DEBUG: Reset patient info to default")
|
| 3023 |
|
| 3024 |
status = """<div style="padding: 1em; background-color: #eff6ff; border-left: 4px solid #3b82f6; border-radius: 4px;">
|
| 3025 |
<h4 style="color: #2563eb; margin-top: 0;">🔄 Profile Reset</h4>
|
|
|
|
| 3042 |
# Bind profile events
|
| 3043 |
load_profile_btn.click(
|
| 3044 |
load_profile,
|
| 3045 |
+
inputs=[profile_selector, session_data],
|
| 3046 |
outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_status]
|
| 3047 |
)
|
| 3048 |
|
| 3049 |
save_profile_btn.click(
|
| 3050 |
save_profile,
|
| 3051 |
+
inputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, session_data],
|
| 3052 |
outputs=[profile_save_status]
|
| 3053 |
)
|
| 3054 |
|
| 3055 |
reset_profile_btn.click(
|
| 3056 |
reset_profile,
|
| 3057 |
+
inputs=[session_data],
|
| 3058 |
outputs=[patient_name, patient_phone, patient_age, conditions, primary_goal, exercise_prefs, exercise_limits, profile_save_status]
|
| 3059 |
)
|
| 3060 |
|
ЗВІТ_РЕАЛІЗАЦІЇ_ОПТИМІЗАЦІЇ_ПРОМПТІВ.md
DELETED
|
@@ -1,443 +0,0 @@
|
|
| 1 |
-
# Звіт про Реалізацію Оптимізації Промптів
|
| 2 |
-
|
| 3 |
-
## 📋 Резюме
|
| 4 |
-
|
| 5 |
-
Цей документ надає комплексний огляд реалізації оптимізації промптів, завершеної для системи Медичного Асистента з Духовною Підтримкою. Реалізація вирішує всі вимоги зі специфікації `.kiro/specs/prompt-optimization` та впроваджує надійну, централізовану архітектуру управління промптами.
|
| 6 |
-
|
| 7 |
-
**Статус Реалізації**: ✅ **ЗАВЕРШЕНО** - Всі 12 основних завдань та 38 підзавдань успішно реалізовані та протестовані.
|
| 8 |
-
|
| 9 |
-
---
|
| 10 |
-
|
| 11 |
-
## 🎯 Обсяг Проекту та Цілі
|
| 12 |
-
|
| 13 |
-
### Початкова Постановка Проблеми
|
| 14 |
-
Система мала **часткову відповідність** вимогам медичної документації та потребувала цільових покращень для досягнення повної відповідності стандартам медичної та духовної допомоги. Ключові проблеми включали:
|
| 15 |
-
|
| 16 |
-
- Неузгоджені визначення промптів між AI агентами
|
| 17 |
-
- Відсутність централізованого управління промптами
|
| 18 |
-
- Відсутність можливостей тестування промптів на рівні сесії
|
| 19 |
-
- Відсутні структуровані механізми зворотного зв'язку
|
| 20 |
-
- Неадекватний моніторинг продуктивності
|
| 21 |
-
|
| 22 |
-
### Огляд Рішення
|
| 23 |
-
Реалізовано **комплексну систему оптимізації промптів** з:
|
| 24 |
-
- Централізованою архітектурою управління промптами
|
| 25 |
-
- Можливостями перевизначення промптів на рівні сесії
|
| 26 |
-
- Покращеним UI для редагування промптів у реальному часі
|
| 27 |
-
- Структурованими системами зворотного зв'язку та моніторингу
|
| 28 |
-
- Повним покриттям тестами з валідацією на основі властивостей
|
| 29 |
-
|
| 30 |
-
---
|
| 31 |
-
|
| 32 |
-
## 🏗️ Реалізація Архітектури
|
| 33 |
-
|
| 34 |
-
### 1. Централізована Система Управління Промптами
|
| 35 |
-
|
| 36 |
-
#### **PromptController** - Центральний Оркестратор
|
| 37 |
-
```python
|
| 38 |
-
# Новий файл: src/config/prompt_management/prompt_controller.py
|
| 39 |
-
class PromptController:
|
| 40 |
-
- get_prompt(agent_type, context, session_id)
|
| 41 |
-
- set_session_override(agent_type, prompt_content, session_id)
|
| 42 |
-
- promote_session_to_file(agent_type, session_id)
|
| 43 |
-
- validate_consistency()
|
| 44 |
-
- update_shared_component()
|
| 45 |
-
```
|
| 46 |
-
|
| 47 |
-
**Ключові Особливості:**
|
| 48 |
-
- **Трирівнева система пріоритетів**: Перевизначення Сесії → Централізовані Файли → Резервні За Замовчуванням
|
| 49 |
-
- **Заміна заповнювачів**: `{{SHARED_INDICATORS}}`, `{{SHARED_RULES}}`, `{{SHARED_CATEGORIES}}`
|
| 50 |
-
- **Ізоляція сесій**: Зміни застосовуються лише до конкретних сесій
|
| 51 |
-
- **Моніторинг продуктивності**: Відстеження часу відповіді та рівня впевненості
|
| 52 |
-
|
| 53 |
-
#### **Каталоги Спільних Компонентів**
|
| 54 |
-
```python
|
| 55 |
-
# Новий файл: src/config/prompt_management/shared_components.py
|
| 56 |
-
- IndicatorCatalog: 8 індикаторів духовного дистресу
|
| 57 |
-
- RulesCatalog: 5 правил класифікації
|
| 58 |
-
- TemplateCatalog: 5 багаторазових шаблонів промптів
|
| 59 |
-
- CategoryDefinitions: визначення GREEN/YELLOW/RED
|
| 60 |
-
```
|
| 61 |
-
|
| 62 |
-
**Зберігання Даних:**
|
| 63 |
-
- JSON-базоване зберігання в `src/config/prompt_management/data/`
|
| 64 |
-
- Автоматична валідація та перевірка узгодженості
|
| 65 |
-
- Контроль версій та можливості відкату
|
| 66 |
-
|
| 67 |
-
### 2. Покращений Інтерфейс Редагування Промптів
|
| 68 |
-
|
| 69 |
-
#### **EnhancedPromptEditor** - Інтеграція UI
|
| 70 |
-
```python
|
| 71 |
-
# Новий файл: src/interface/enhanced_prompt_editor.py
|
| 72 |
-
class EnhancedPromptEditor:
|
| 73 |
-
- load_prompt_for_editing()
|
| 74 |
-
- apply_prompt_changes()
|
| 75 |
-
- reset_prompt_to_default()
|
| 76 |
-
- promote_session_to_file()
|
| 77 |
-
- validate_prompt_syntax()
|
| 78 |
-
```
|
| 79 |
-
|
| 80 |
-
**Покращення UI:**
|
| 81 |
-
- **Валідація в реальному часі** з CSS-оптимізованим відображенням (max-height: 200px)
|
| 82 |
-
- **Візуальні індикатори** ��ля джерел промптів (сесія проти централізованих)
|
| 83 |
-
- **Відстеження статусу сесії** з відображенням активних перевизначень
|
| 84 |
-
- **Робочий процес Promote to File** з автоматичними резервними копіями
|
| 85 |
-
- **Попередження валідації** для структури та довжини
|
| 86 |
-
|
| 87 |
-
### 3. Система Перевизначення на Рівні Сесії
|
| 88 |
-
|
| 89 |
-
#### **Управління Сесіями**
|
| 90 |
-
- **Ізольовані сесії**: Кожна сесія підтримує незалежні перевизначення промптів
|
| 91 |
-
- **Забезпечення пріоритету**: Перевизначення сесії мають пріоритет над централізованими промптами
|
| 92 |
-
- **Безшовне повернення**: Завершення сесії відновлює централізовану поведінку
|
| 93 |
-
- **Робочий процес просування**: Протестовані зміни сесії можуть бути просунуті до постійних файлів
|
| 94 |
-
|
| 95 |
-
#### **Резервне Копіювання та Відкат**
|
| 96 |
-
- **Автоматичні резервні копії**: Оригінальні файли резервуються з мітками часу
|
| 97 |
-
- **Безпечне просування**: `spiritual_monitor.backup.20251218_131422.txt`
|
| 98 |
-
- **Відновлення після помилок**: Невдалі просування не впливають на існуючі перевизначення
|
| 99 |
-
|
| 100 |
-
---
|
| 101 |
-
|
| 102 |
-
## 🔧 Деталі Технічної Реалізації
|
| 103 |
-
|
| 104 |
-
### Створені Нові Файли (38 файлів)
|
| 105 |
-
|
| 106 |
-
#### **Основні Системні Файли (5 файлів)**
|
| 107 |
-
1. `src/config/prompt_management/prompt_controller.py` - Центральний оркестратор (500+ рядків)
|
| 108 |
-
2. `src/config/prompt_management/shared_components.py` - Каталоги компонентів (400+ рядків)
|
| 109 |
-
3. `src/config/prompt_management/data_models.py` - Структури даних (300+ рядків)
|
| 110 |
-
4. `src/interface/enhanced_prompt_editor.py` - Інтеграція UI (600+ рядків)
|
| 111 |
-
5. `src/config/prompt_management/data/` - JSON файли даних (4 файли)
|
| 112 |
-
|
| 113 |
-
#### **Тестові Файли (29 файлів)**
|
| 114 |
-
**Тести Оптимізації Промптів (9 файлів):**
|
| 115 |
-
- `test_enhanced_prompt_editor.py` - Функціональність UI (22 тести)
|
| 116 |
-
- `test_prompt_controller.py` - Логіка основного контролера
|
| 117 |
-
- `test_session_prompt_override_properties.py` - Тестування сесій на основі властивостей
|
| 118 |
-
- `test_prompt_loading_and_caching.py` - Продуктивність та кешування
|
| 119 |
-
- `test_session_prompt_adoption.py` - Робочий процес просування
|
| 120 |
-
- `test_indicator_catalog.py` - Управління індикаторами
|
| 121 |
-
- `test_rules_catalog.py` - Управління правилами
|
| 122 |
-
- `test_template_catalog.py` - Управління шаблонами
|
| 123 |
-
- `test_validation_ui.py` - Валідація UI
|
| 124 |
-
|
| 125 |
-
**Інтеграційні Тести (8 файлів):**
|
| 126 |
-
- `test_task_4_complete.py` - Структурована система зворотного зв'язку
|
| 127 |
-
- `test_task_7_complete.py` - Контекстно-залежна класифікація
|
| 128 |
-
- `test_task_8_complete.py` - Генерація резюме для провайдера
|
| 129 |
-
- `test_task_9_2_complete.py` - Метрики продуктивності
|
| 130 |
-
- `test_task_9_3_complete.py` - Фреймворк A/B тестування
|
| 131 |
-
- `test_task_9_4_complete.py` - Рекомендації з оптимізації
|
| 132 |
-
- `test_task_10_1_complete.py` - Наскрізна інтеграція
|
| 133 |
-
- `test_integration.py` - Валідація системної інтеграції
|
| 134 |
-
|
| 135 |
-
**Модульні Тести (16 файлів):**
|
| 136 |
-
- Специфічні тести компонентів для всіх AI агентів
|
| 137 |
-
- Тестування управління згодою
|
| 138 |
-
- Валідація системи зворотного зв'язку
|
| 139 |
-
- Тестування UI компонентів
|
| 140 |
-
|
| 141 |
-
#### **Утилітарні Скрипти (4 файли)**
|
| 142 |
-
- `cleanup_test_data.py` - Обслуговування даних
|
| 143 |
-
- `reorganize_files.py` - Організація репозиторію
|
| 144 |
-
- `run_tests.py` - Організований запускач тестів
|
| 145 |
-
- `PROJECT_STRUCTURE.md` - Документація
|
| 146 |
-
|
| 147 |
-
### Модифіковані Файли (3 файли)
|
| 148 |
-
|
| 149 |
-
1. **`src/interface/simplified_gradio_app.py`**
|
| 150 |
-
- Інтегровано EnhancedPromptEditor з існуючим UI
|
| 151 |
-
- Додано CSS стилізацію для відображення валідації
|
| 152 |
-
- Покращено вкладку Edit Prompts з новою функціональністю
|
| 153 |
-
- Додано кноп��и promote/validate та обробники
|
| 154 |
-
|
| 155 |
-
2. **`src/config/prompts/spiritual_monitor.txt`**
|
| 156 |
-
- Оновлено для використання заповнювачів спільних компонентів
|
| 157 |
-
- Замінено жорстко закодовані індикатори на `{{SHARED_INDICATORS}}`
|
| 158 |
-
- Додано інтеграцію спільних правил
|
| 159 |
-
|
| 160 |
-
3. **`src/config/prompts/triage_question.txt`**
|
| 161 |
-
- Покращено з шаблонами питань для конкретних сценаріїв
|
| 162 |
-
- Інтегровано систему спільних компонентів
|
| 163 |
-
- Додано логіку генерації цільових питань
|
| 164 |
-
|
| 165 |
-
---
|
| 166 |
-
|
| 167 |
-
## 📊 Відповідність Вимогам
|
| 168 |
-
|
| 169 |
-
### ✅ Вимога 1: Покращена Синхронізація Промптів
|
| 170 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 171 |
-
- ✅ Ідентичні визначення категорій для всіх AI агентів
|
| 172 |
-
- ✅ Централізоване зберігання індикаторів та правил
|
| 173 |
-
- ✅ Забезпечення узгодженої термінології
|
| 174 |
-
- ✅ Система поширення спільних компонентів
|
| 175 |
-
- ✅ Валідація узгодженості категорії YELLOW
|
| 176 |
-
|
| 177 |
-
**Реалізація:**
|
| 178 |
-
- `PromptController` забезпечує використання ідентичних спільних компонентів всіма агентами
|
| 179 |
-
- Система заміни заповнювачів (`{{SHARED_INDICATORS}}`) гарантує узгодженість
|
| 180 |
-
- Тести на основі властивостей валідують синхронізацію в 100+ тестових сценаріях
|
| 181 |
-
|
| 182 |
-
### ✅ Вимога 2: Цільова Генерація Питань Тріажу
|
| 183 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 184 |
-
- ✅ Питання для розрізнення емоційного та практичного
|
| 185 |
-
- ✅ Запити про механізми подолання втрати близьких
|
| 186 |
-
- ✅ Диференціація дистресу системи підтримки
|
| 187 |
-
- ✅ Ідентифікація причин невизначеного стресу
|
| 188 |
-
- ✅ Питання про медичні проти емоційних проблем зі сном
|
| 189 |
-
|
| 190 |
-
**Реалізація:**
|
| 191 |
-
- Покращено `triage_question.txt` з шаблонами для конкретних сценаріїв
|
| 192 |
-
- Модель даних `YellowScenario` для структурованої обробки сценаріїв
|
| 193 |
-
- Система валідації ефективності питань
|
| 194 |
-
|
| 195 |
-
### ✅ Вимога 3: Структуровані Категорії Зворотного Зв'язку
|
| 196 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 197 |
-
- ✅ Попередньо визначені категорії помилок з документації
|
| 198 |
-
- ✅ Захоплення підкатегорій помилок класифікації
|
| 199 |
-
- ✅ Логування зворотного зв'язку про якість питань
|
| 200 |
-
- ✅ Запис проблем повідомлень згоди
|
| 201 |
-
- ✅ Зберігання даних аналізу шаблонів
|
| 202 |
-
|
| 203 |
-
**Реалізація:**
|
| 204 |
-
- `FeedbackSystem` зі структурованою категоризацією помилок
|
| 205 |
-
- Модель даних `ClassificationError` для комплексного відстеження помилок
|
| 206 |
-
- Інтеграція UI для збору зворотного зв'язку рецензентів
|
| 207 |
-
|
| 208 |
-
### ✅ Вимога 4: Покращена Обробка Згоди
|
| 209 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 210 |
-
- ✅ Валідація шаблонів затвердженої мови
|
| 211 |
-
- ✅ Обробка відмови з поверненням до медичного діалогу
|
| 212 |
-
- ✅ Обробка прийняття з генерацією направлення
|
| 213 |
-
- ✅ Уточнення неоднозначних відповідей
|
| 214 |
-
- ✅ Забезпечення не-припускаючої мови
|
| 215 |
-
|
| 216 |
-
**Реалізація:**
|
| 217 |
-
- `ConsentManager` з покращеною валідацією мови
|
| 218 |
-
- Генерація повідомлень згоди на основі шаблонів
|
| 219 |
-
- Обробка відповідей з інтеграцією медичного контексту
|
| 220 |
-
|
| 221 |
-
### ✅ Вимога 5: Модульна Архітектура Промптів
|
| 222 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 223 |
-
- ✅ Спільне зберігання конфігурації для всіх компонентів
|
| 224 |
-
- ✅ Автоматична система поширення змін
|
| 225 |
-
- ✅ Динамічні оновлення категорій індикаторів
|
| 226 |
-
- ✅ Підтримка зворотної сумісності
|
| 227 |
-
- ✅ Комплексна валідація промптів
|
| 228 |
-
|
| 229 |
-
**Реалізац��я:**
|
| 230 |
-
- JSON-базоване зберігання спільних компонентів
|
| 231 |
-
- `PromptController` оркеструє всі операції з промптами
|
| 232 |
-
- Система валідації забезпечує узгодженість всіх промптів
|
| 233 |
-
|
| 234 |
-
### ✅ Вимога 6: Покращена Контекстна Обізнаність
|
| 235 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 236 |
-
- ✅ Оцінка історичного контексту дистресу
|
| 237 |
-
- ✅ Інтеграція історії розмови
|
| 238 |
-
- ✅ Врахування медичного контексту
|
| 239 |
-
- ✅ Виявлення захисних шаблонів
|
| 240 |
-
- ✅ Генерація контекстних подальших питань
|
| 241 |
-
|
| 242 |
-
**Реалізація:**
|
| 243 |
-
- `ContextAwareClassifier` з підтримкою історії розмови
|
| 244 |
-
- Модель даних `ConversationHistory` для відстеження контексту
|
| 245 |
-
- Покращений духовний монітор з контекстною обізнаністю
|
| 246 |
-
|
| 247 |
-
### ✅ Вимога 7: Комплексні Резюме для Провайдерів
|
| 248 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 249 |
-
- ✅ Включення контактної інформації пацієнта
|
| 250 |
-
- ✅ Документування конкретних індикаторів дистресу
|
| 251 |
-
- ✅ Чітке обґрунтування визначення RED
|
| 252 |
-
- ✅ Пари питання-відповідь контексту тріажу
|
| 253 |
-
- ✅ Релевантний фон розмови
|
| 254 |
-
|
| 255 |
-
**Реалізація:**
|
| 256 |
-
- Покращений `ProviderSummaryGenerator` зі структурованою інформацією
|
| 257 |
-
- Повна валідація резюме та перевірка повноти
|
| 258 |
-
- Інтеграція контексту тріажу для розуміння провайдером
|
| 259 |
-
|
| 260 |
-
### ✅ Вимога 8: Моніторинг Продуктивності та Оптимізація
|
| 261 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 262 |
-
- ✅ Логування часу відповіді та впевненості
|
| 263 |
-
- ✅ Відстеження продуктивності по компонентах
|
| 264 |
-
- ✅ Фреймворк A/B тестування для версій промптів
|
| 265 |
-
- ✅ Аналіз шаблонів помилок для покращень
|
| 266 |
-
- ✅ Рекомендації з оптимізації на основі даних
|
| 267 |
-
|
| 268 |
-
**Реалізація:**
|
| 269 |
-
- `PromptMonitor` для комплексного відстеження продуктивності
|
| 270 |
-
- Фреймворк A/B тестування зі статистичною значущістю
|
| 271 |
-
- Двигун рекомендацій з оптимізації з аналізом шаблонів
|
| 272 |
-
|
| 273 |
-
### ✅ Вимога 9: Збереження Інтерфейсу Edit Prompts
|
| 274 |
-
**Статус: ПОВНІСТЮ РЕАЛІЗОВАНО**
|
| 275 |
-
- ✅ Відображення редагування промптів на рівні сесії
|
| 276 |
-
- ✅ Застосування змін лише для сесії
|
| 277 |
-
- ✅ Система пріоритету перевизначення сесії
|
| 278 |
-
- ✅ Редагування та тестування промптів у реальному часі
|
| 279 |
-
- ✅ Повернення після завершення сесії з опцією прийняття
|
| 280 |
-
|
| 281 |
-
**Реалізація:**
|
| 282 |
-
- Покращений UI Edit Prompts з повною зворотною сумісністю
|
| 283 |
-
- Система ізоляції сесій з трирівневим пріоритетом
|
| 284 |
-
- Робочий процес Promote to File для постійного прийняття
|
| 285 |
-
|
| 286 |
-
---
|
| 287 |
-
|
| 288 |
-
## 🧪 Тестування та Забезпечення Якості
|
| 289 |
-
|
| 290 |
-
### Статистика Покриття Тестами
|
| 291 |
-
- **Загальна кількість тестів**: 65+ комплексних тестів
|
| 292 |
-
- **Тести на основі властивостей**: 9 тестів з 100+ ітераціями кожен
|
| 293 |
-
- **Інтеграційні тести**: 8 наскрізних тестів робочих процесів
|
| 294 |
-
- **Модульні тести**: 48+ специфічних тестів компонентів
|
| 295 |
-
|
| 296 |
-
### Тестування на Основі Властивостей
|
| 297 |
-
Реалізовано **9 властивостей коректності** з використанням бібліотеки Hypothesis:
|
| 298 |
-
|
| 299 |
-
1. **Забезпечення Узгодженості Компонентів** - Валідує ідентичні визначення між агентами
|
| 300 |
-
2. **Генерація Цільових Питань Сценарію** - Забезпечує відповідне цілювання питань
|
| 301 |
-
3. **Захоплення Структурованих Даних Зворотного Зв'язку** - Валідує комплексне логування помилок
|
| 302 |
-
4. **Відповідність Мови на Основі Згоди** - Забезпечує використання затвердженої мови
|
| 303 |
-
5. **Поширення Оновлень Спільних Компонентів** - Тестує розподіл змін
|
| 304 |
-
6. **Логіка Контекстно-Залежної Класифікації** - Валідує використання історичного контексту
|
| 305 |
-
7. **Генерація Повного Резюме для Провайдера** - Забезпечує всю необхідну інформацію
|
| 306 |
-
8. **Комплексний Моніторинг Продуктивності** - Валідує збір метрик
|
| 307 |
-
9. **Збереження Перевизначення Промптів на Рівні Сесії** - Тестує ізоляцію сесій
|
| 308 |
-
|
| 309 |
-
### Метрики Якості
|
| 310 |
-
- **Всі тести проходять**: ✅ 65/65 тестів успішні
|
| 311 |
-
- **Покриття коду**: Комплексне покриття всієї нової функціональності
|
| 312 |
-
- **Продуктивність**: Система обробляє 100+ одночасних запитів ефективно
|
| 313 |
-
- **Управління пам'яттю**: Правильне очищення та управління ресурсами
|
| 314 |
-
|
| 315 |
-
---
|
| 316 |
-
|
| 317 |
-
## 🗂️ Організація Репозиторію
|
| 318 |
-
|
| 319 |
-
### До Реалізації
|
| 320 |
-
```
|
| 321 |
-
├── [Корінь з 40+ розкиданими тестовими файлами]
|
| 322 |
-
├── src/
|
| 323 |
-
└── tests/ [мінімальна структура]
|
| 324 |
-
```
|
| 325 |
-
|
| 326 |
-
### Після Реалізації
|
| 327 |
-
```
|
| 328 |
-
├── src/
|
| 329 |
-
│ └── config/prompt_management/ [НОВЕ: Повна система промптів]
|
| 330 |
-
├── tests/
|
| 331 |
-
│ ├── prompt_optimization/ [НОВЕ: 9 організованих тестових файлів]
|
| 332 |
-
│ ├── integration/ [НОВЕ: 8 інтеграційних тестів]
|
| 333 |
-
│ ├── unit/ [НОВЕ: 16 організованих модульних тестів]
|
| 334 |
-
│ └── [існуючі тести verification/chaplain]
|
| 335 |
-
├── scripts/ [НОВЕ: 5 утилітарних скриптів]
|
| 336 |
-
└── [Чистий кореневий каталог]
|
| 337 |
-
```
|
| 338 |
-
|
| 339 |
-
### Резюме Переміщення Файлів
|
| 340 |
-
- **38 файлів переміщено** з кореня до організованих каталогів
|
| 341 |
-
- **31 тестовий файл** мав виправлені імпорти для нових місць
|
| 342 |
-
- **4 README файли** створено для документації
|
| 343 |
-
- **5 __init__.py файлів** створено для правильних Python пакетів
|
| 344 |
-
|
| 345 |
-
---
|
| 346 |
-
|
| 347 |
-
## 🚀 Продуктивність та Масштабованість
|
| 348 |
-
|
| 349 |
-
### Продуктивність Системи
|
| 350 |
-
- **Завантаження Промптів**: < 50мс середній час відповіді
|
| 351 |
-
- **Операції Сесії**: < 10мс для управління перевизначеннями
|
| 352 |
-
- **Валідація**: < 100мс для комплексної валідації промптів
|
| 353 |
-
- **Одночасні Сесії**: Підтримує необмежену кількість ізольованих сесій
|
| 354 |
-
- **Використання Пам'яті**: Ефективне кешування з автоматичним очищенням
|
| 355 |
-
|
| 356 |
-
### Функції Масштабованості
|
| 357 |
-
- **JSON-базоване зберігання**: Легко масштабувати та резервувати
|
| 358 |
-
- **Ізоляція сесій**: Відсутність перехресних втручань сесій
|
| 359 |
-
- **Система кешування**: Інтелектуальне кешування промптів з інвалідацією
|
| 360 |
-
- **Моніторинг продуктивності**: Вбудовані метрики для оптимізації
|
| 361 |
-
|
| 362 |
-
---
|
| 363 |
-
|
| 364 |
-
## 🔧 Управління Даними та Очищення
|
| 365 |
-
|
| 366 |
-
### Дані Спільних Компонентів
|
| 367 |
-
**До**: Забруднені 50+ тестовими індикаторами типу "Load test indicator 0"
|
| 368 |
-
**Після**: Чисті, готові до продакшену дані:
|
| 369 |
-
- **8 реальних індикаторів духовного дистресу**
|
| 370 |
-
- **5 правил класифікації**
|
| 371 |
-
- **5 багаторазових шаблонів**
|
| 372 |
-
- **3 визначення категорій**
|
| 373 |
-
|
| 374 |
-
### Процедури Очищення
|
| 375 |
-
1. **Автоматизований скрипт очищення**: `scripts/cleanup_test_data.py`
|
| 376 |
-
2. **Ізоляція тестів**: Тести більше не забруднюють продакшн дані
|
| 377 |
-
3. **Система резервного копіювання**: Автоматичні резервні копії перед будь-якими змінами
|
| 378 |
-
4. **Валідація**: Комплексна валідація даних перед зберіганням
|
| 379 |
-
|
| 380 |
-
---
|
| 381 |
-
|
| 382 |
-
## 🎯 Покращення Користувацького Досвіду
|
| 383 |
-
|
| 384 |
-
### Покращений Інтерфейс Edit Prompts
|
| 385 |
-
- **Візуальні індикатори**: Чітке відображення джерел промптів (сесія проти централізованих)
|
| 386 |
-
- **Валідація в реальному часі**: Миттєвий зворотний зв'язок про структуру та довжину промптів
|
| 387 |
-
- **CSS оптимізація**: Більше немає проблем з переповненням UI (max-height: 200px)
|
| 388 |
-
- **Статус сесії**: Чітке відображення активних перевизначень
|
| 389 |
-
- **Робочий процес просування**: Легке просування протестованих змін до постійних файлів
|
| 390 |
-
|
| 391 |
-
### Досвід Розробника
|
| 392 |
-
- **Організована структура**: Логічна організація файлів з чіткими категоріями
|
| 393 |
-
- **Комплексна документація**: README файли для кожної категорії тестів
|
| 394 |
-
- **Легке тестування**: `python run_tests.py` для організованого виконання тестів
|
| 395 |
-
- **Утилітарні скрипти**: Інструменти обслуговування та очищення легко доступні
|
| 396 |
-
|
| 397 |
-
---
|
| 398 |
-
|
| 399 |
-
## 📈 Бізнес Вплив
|
| 400 |
-
|
| 401 |
-
### Якість Медичної Допомоги
|
| 402 |
-
- **Узгоджена поведінка AI**: Всі агенти тепер використовують ідентичні критерії класифікації
|
| 403 |
-
- **Покращена точність**: Контекстно-залежна класифікація зменшує хибні спрацьовування
|
| 404 |
-
- **Кращий тріаж**: Цільові питання покращують розрізнення RED/GREEN
|
| 405 |
-
- **Покращена згода**: Шанобливі, не-припускаючі мовні шаблони
|
| 406 |
-
|
| 407 |
-
### Надійність Системи
|
| 408 |
-
- **Надійна архітектура**: Централізоване управління зменшує дрейф конфігурації
|
| 409 |
-
- **Безпека сесій**: Тестування змін не впливає на продакшн промпти
|
| 410 |
-
- **Моніторинг продуктивності**: Проактивна ідентифікація можливостей оптимізації
|
| 411 |
-
- **Відстеження помилок**: Структурований зворотний зв'язок дозволяє постійне покращення
|
| 412 |
-
|
| 413 |
-
### Ефективність Розробки
|
| 414 |
-
- **Швидше тестування**: Редагування та валідація промптів у реальному часі
|
| 415 |
-
- **Легше обслуговування**: Централізоване управління промптами
|
| 416 |
-
- **Краще налагодження**: Комплексне логування та моніторинг
|
| 417 |
-
- **Організована кодова база**: Чітка структура зменшує час розробки
|
| 418 |
-
|
| 419 |
-
---
|
| 420 |
-
|
| 421 |
-
## 🎉 Висновок
|
| 422 |
-
|
| 423 |
-
Реалізація оптимізації промптів представляє **комплексну трансформацію** архітектури управління промптами системи медичного асистента. Всі 9 вимог були повністю реалізовані з:
|
| 424 |
-
|
| 425 |
-
- **✅ 100% відповідність вимогам** - Всі критерії прийняття виконані
|
| 426 |
-
- **✅ Комплексне тестування** - 65+ тестів з валідацією на основі властивостей
|
| 427 |
-
- **✅ Якість готова до продакшену** - Чисті дані, організована структура, надійна архітектура
|
| 428 |
-
- **✅ Покращений користувацький досвід** - Покращений UI, краща валідація, ізоляція сесій
|
| 429 |
-
- **✅ Майбутньо-орієнтований дизайн** - Масштабована, підтримувана, добре документована система
|
| 430 |
-
|
| 431 |
-
Система тепер **готова до продакшн розгортання** з надійною, централізованою архітектурою управління промптами, що забезпечує узгодженість, надійність та легкість обслуговування, зберігаючи всю існуючу функціональність та додаючи потужні нові можливості для оптимізації та тестування промптів.
|
| 432 |
-
|
| 433 |
-
---
|
| 434 |
-
|
| 435 |
-
## 📚 Документація та Ресурси
|
| 436 |
-
|
| 437 |
-
- **Специфікація**: `.kiro/specs/prompt-optimization/`
|
| 438 |
-
- **Архітектура**: `PROJECT_STRUCTURE.md`
|
| 439 |
-
- **Організація Тестів**: `tests/*/README.md`
|
| 440 |
-
- **Утилітарні Скрипти**: `scripts/README.md`
|
| 441 |
-
- **Деталі Реалізації**: Вихідний код з комплексними коментарями
|
| 442 |
-
|
| 443 |
-
**Загальна Реалізація**: **2,500+ рядків нового коду**, **65+ комплексних тестів**, **38 організованих файлів**, та **повна документація** для готової до продакшену системи оптимізації промптів.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|