File size: 8,673 Bytes
143d94c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
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
#!/usr/bin/env python3
"""
Тестовий скрипт для перевірки що логування працює коректно
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import json
from enhanced_mai_dx_logger import MAIDxConversationLogger

def test_basic_logging():
    """Тест базового логування"""
    print("🧪 Тест 1: Базове логування")
    
    logger = MAIDxConversationLogger("test_logs")
    
    # Створюємо тестову сесію
    case_id = logger.start_session(
        case_name="Тестовий випадок",
        patient_info="Тестова інформація",
        mode="test",
        budget=1000
    )
    
    print(f"✅ Створено сесію: {case_id}")
    
    # Симулюємо захоплення виводу
    def mock_orchestrator_run(*args, **kwargs):
        print("Starting Diagnostic Loop 1/3")
        print("2025-07-11 10:00:00 | INFO | mai_dx.main:_run_panel_deliberation:1304 - 🧠 Dr. Hypothesis analyzing differential diagnosis...")
        print("╭─── Agent Name Dr. Hypothesis [Max Loops: 1] ───╮")
        print("│ Analyzing patient symptoms...                   │")
        print("│ High probability of sepsis                      │")
        print("╰────────────────────────────────────────────────╯")
        print("2025-07-11 10:00:05 | INFO | mai_dx.main:run:1689 - ⚕️ Panel decision: DIAGNOSE -> Sepsis")
        
        # Симулюємо результат
        class MockResult:
            final_diagnosis = "Sepsis"
            accuracy_score = 4.0
            total_cost = 500.0
            
        return MockResult()
    
    # Виконуємо з захопленням
    result = logger.capture_orchestrator_output(
        case_id=case_id,
        orchestrator_func=mock_orchestrator_run
    )
    
    print(f"✅ Діагноз: {result.final_diagnosis}")
    
    # Завершуємо сесію
    saved_id = logger.end_session(
        case_id=case_id,
        final_diagnosis=result.final_diagnosis,
        confidence=result.accuracy_score,
        cost=result.total_cost,
        reasoning="Test reasoning"
    )
    
    print(f"✅ Збережено: {saved_id}")
    
    # Перевіряємо що файли створені
    json_file = f"test_logs/{case_id}.json"
    if os.path.exists(json_file):
        with open(json_file, 'r') as f:
            data = json.load(f)
        print(f"✅ JSON файл містить {len(data['conversations'])} розмов")
        
        if data['conversations']:
            conv = data['conversations'][0]
            print(f"  - Раунд {conv['round_number']}: {len(conv['messages'])} повідомлень")
    else:
        print(f"❌ JSON файл не створено!")
        
    print("-" * 60)

def test_conversation_parsing():
    """Тест парсингу розмов"""
    print("🧪 Тест 2: Парсинг складних розмов")
    
    logger = MAIDxConversationLogger("test_logs")
    
    case_id = logger.start_session(
        case_name="Складний випадок",
        patient_info="Множинні симптоми",
        mode="budgeted",
        budget=5000
    )
    
    # Симулюємо складніший вивід
    def complex_orchestrator_run(*args, **kwargs):
        output = """
2025-07-11 10:00:00 | INFO | mai_dx.main:run:1679 - --- Starting Diagnostic Loop 1/3 ---
2025-07-11 10:00:00 | INFO | mai_dx.main:run:1682 - Current cost: $300 | Remaining budget: $4,700
2025-07-11 10:00:01 | INFO | mai_dx.main:_run_panel_deliberation:1304 - 🧠 Dr. Hypothesis analyzing differential diagnosis...
╭─────────────────────────────── Agent Name Dr. Hypothesis [Max Loops: 1 ] ───────────────────────────────╮
│ Structured Output - Attempting Function Call Execution [10:00:02]                                       │
│                                                                                                         │
│  Top differential diagnoses:                                                                            │
│  1. Acute Myocardial Infarction (85%)                                                                  │
│  2. Pulmonary Embolism (10%)                                                                           │
│  3. Aortic Dissection (5%)                                                                              │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────╯

2025-07-11 10:00:05 | INFO | mai_dx.main:_run_panel_deliberation:1320 - 🔬 Dr. Test-Chooser selecting optimal tests...
╭────────────────────────────── Agent Name Dr. Test-Chooser [Max Loops: 1 ] ──────────────────────────────╮
│ Recommending tests:                                                                                      │
│ - ECG (immediate)                                                                                        │
│ - Troponin levels                                                                                        │
│ - Chest X-ray                                                                                            │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────╯

2025-07-11 10:00:10 | INFO | mai_dx.main:run:1689 - ⚕️ Panel decision: TEST -> ECG, Troponin, CXR
2025-07-11 10:00:10 | INFO | mai_dx.main:run:1692 - 💭 Medical reasoning: High suspicion for cardiac event
"""
        print(output)
        
        class MockResult:
            final_diagnosis = "Acute Myocardial Infarction"
            accuracy_score = 4.5
            total_cost = 850.0
            
        return MockResult()
    
    result = logger.capture_orchestrator_output(
        case_id=case_id,
        orchestrator_func=complex_orchestrator_run
    )
    
    # Генеруємо HTML
    html_path = logger.export_conversation_html(case_id)
    print(f"✅ HTML звіт: {html_path}")
    
    # Завершуємо
    logger.end_session(
        case_id=case_id,
        final_diagnosis=result.final_diagnosis,
        confidence=result.accuracy_score,
        cost=result.total_cost
    )
    
    print("-" * 60)

def test_error_handling():
    """Тест обробки помилок"""
    print("🧪 Тест 3: Обробка помилок")
    
    logger = MAIDxConversationLogger("test_logs")
    
    # Спроба завершити неіснуючу сесію
    result = logger.end_session("non_existent_id")
    print(f"✅ Обробка неіснуючої сесії: {result}")
    
    # Спроба отримати розмови неіснуючої сесії
    conversations = logger.get_session_conversations("non_existent_id")
    print(f"✅ Розмови неіснуючої сесії: {len(conversations)} елементів")
    
    print("-" * 60)

def main():
    """Запуск всіх тестів"""
    print("=" * 60)
    print("🔬 Тестування системи логування MAI-DX")
    print("=" * 60)
    
    # Створюємо тестову директорію
    os.makedirs("test_logs", exist_ok=True)
    
    try:
        test_basic_logging()
        test_conversation_parsing()
        test_error_handling()
        
        print("\n✅ Всі тести пройдено успішно!")
        print("📁 Перевірте директорію 'test_logs' для результатів")
        
    except Exception as e:
        print(f"\n❌ Помилка під час тестування: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()