File size: 23,200 Bytes
9c479c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
"""
Medical Prompt Templates for MedGemma Synthesis
Comprehensive templates for generating clinician-level and patient-friendly summaries

Author: MiniMax Agent
Date: 2025-10-29
Version: 1.0.0
"""

from typing import Dict, Any, List, Optional
from enum import Enum


class SummaryType(Enum):
    """Types of medical summaries that can be generated"""
    CLINICIAN_TECHNICAL = "clinician_technical"
    PATIENT_FRIENDLY = "patient_friendly"
    MULTI_MODAL = "multi_modal"
    RISK_ASSESSMENT = "risk_assessment"


class PromptTemplateLibrary:
    """
    Comprehensive library of medical prompt templates for MedGemma
    Supports all medical modalities with evidence-based generation
    """
    
    @staticmethod
    def get_clinician_summary_template(
        modality: str,
        structured_data: Dict[str, Any],
        model_outputs: List[Dict[str, Any]],
        confidence_scores: Dict[str, float]
    ) -> str:
        """
        Generate clinician-level technical summary prompt
        
        Features:
        - Technical medical terminology
        - Detailed analysis with evidence
        - Confidence scores and uncertainty
        - Clinical decision support
        """
        
        if modality == "ECG":
            return PromptTemplateLibrary._ecg_clinician_template(
                structured_data, model_outputs, confidence_scores
            )
        elif modality == "radiology":
            return PromptTemplateLibrary._radiology_clinician_template(
                structured_data, model_outputs, confidence_scores
            )
        elif modality == "laboratory":
            return PromptTemplateLibrary._laboratory_clinician_template(
                structured_data, model_outputs, confidence_scores
            )
        elif modality == "clinical_notes":
            return PromptTemplateLibrary._clinical_notes_clinician_template(
                structured_data, model_outputs, confidence_scores
            )
        else:
            return PromptTemplateLibrary._general_clinician_template(
                structured_data, model_outputs, confidence_scores
            )
    
    @staticmethod
    def get_patient_summary_template(
        modality: str,
        structured_data: Dict[str, Any],
        model_outputs: List[Dict[str, Any]],
        confidence_scores: Dict[str, float]
    ) -> str:
        """
        Generate patient-friendly summary prompt
        
        Features:
        - Plain language explanations
        - Key findings highlighted
        - Actionable next steps
        - Reassurance when appropriate
        """
        
        if modality == "ECG":
            return PromptTemplateLibrary._ecg_patient_template(
                structured_data, model_outputs, confidence_scores
            )
        elif modality == "radiology":
            return PromptTemplateLibrary._radiology_patient_template(
                structured_data, model_outputs, confidence_scores
            )
        elif modality == "laboratory":
            return PromptTemplateLibrary._laboratory_patient_template(
                structured_data, model_outputs, confidence_scores
            )
        elif modality == "clinical_notes":
            return PromptTemplateLibrary._clinical_notes_patient_template(
                structured_data, model_outputs, confidence_scores
            )
        else:
            return PromptTemplateLibrary._general_patient_template(
                structured_data, model_outputs, confidence_scores
            )
    
    # ========================
    # ECG TEMPLATES
    # ========================
    
    @staticmethod
    def _ecg_clinician_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Clinician-level ECG summary template"""
        
        intervals = data.get("intervals", {})
        rhythm = data.get("rhythm_classification", {})
        arrhythmia_probs = data.get("arrhythmia_probabilities", {})
        derived = data.get("derived_features", {})
        
        overall_confidence = confidence.get("overall_confidence", 0.0)
        
        prompt = f"""You are a medical AI assistant generating a comprehensive ECG analysis report for clinicians.

PATIENT CONTEXT:
- Document ID: {data.get('metadata', {}).get('document_id', 'N/A')}
- Facility: {data.get('metadata', {}).get('facility', 'N/A')}
- Recording Date: {data.get('metadata', {}).get('document_date', 'N/A')}

ECG MEASUREMENTS:
- Heart Rate: {rhythm.get('heart_rate_bpm', 'N/A')} bpm
- PR Interval: {intervals.get('pr_ms', 'N/A')} ms
- QRS Duration: {intervals.get('qrs_ms', 'N/A')} ms
- QT Interval: {intervals.get('qt_ms', 'N/A')} ms
- QTc Interval: {intervals.get('qtc_ms', 'N/A')} ms
- RR Interval: {intervals.get('rr_ms', 'N/A')} ms

RHYTHM ANALYSIS:
- Primary Rhythm: {rhythm.get('primary_rhythm', 'N/A')}
- Rhythm Regularity: {rhythm.get('heart_rate_regularity', 'N/A')}
- Detected Arrhythmias: {', '.join(rhythm.get('arrhythmia_types', [])) or 'None'}

ARRHYTHMIA PROBABILITIES:
- Normal Sinus Rhythm: {arrhythmia_probs.get('normal_rhythm', 'N/A')}
- Atrial Fibrillation: {arrhythmia_probs.get('atrial_fibrillation', 'N/A')}
- Atrial Flutter: {arrhythmia_probs.get('atrial_flutter', 'N/A')}
- Ventricular Tachycardia: {arrhythmia_probs.get('ventricular_tachycardia', 'N/A')}
- Heart Block: {arrhythmia_probs.get('heart_block', 'N/A')}

ST-SEGMENT & T-WAVE FINDINGS:
- ST Elevation: {derived.get('st_elevation_mm', 'None detected')}
- ST Depression: {derived.get('st_depression_mm', 'None detected')}
- T-wave Abnormalities: {', '.join(derived.get('t_wave_abnormalities', [])) or 'None'}
- Axis Deviation: {derived.get('axis_deviation', 'Normal')}

AI MODEL OUTPUTS:
{PromptTemplateLibrary._format_model_outputs(outputs)}

ANALYSIS CONFIDENCE: {overall_confidence * 100:.1f}%

INSTRUCTIONS:
Generate a comprehensive clinical ECG report with the following sections:

1. TECHNICAL SUMMARY
   - Concise interpretation of rhythm and intervals
   - Significance of any abnormal findings
   
2. CLINICAL SIGNIFICANCE
   - Pathophysiological implications
   - Risk stratification (low/moderate/high)
   
3. DIFFERENTIAL DIAGNOSIS
   - Most likely diagnoses based on findings
   - Alternative considerations
   
4. RECOMMENDATIONS
   - Immediate actions required (if any)
   - Follow-up studies or monitoring
   - Cardiology referral if indicated
   
5. CONFIDENCE EXPLANATION
   - Why the AI confidence is {overall_confidence * 100:.1f}%
   - Which findings are most/least certain
   - Limitations of the analysis

Use precise medical terminology. Be evidence-based. Flag any critical findings requiring immediate attention.

Generate the report now:"""
        
        return prompt
    
    @staticmethod
    def _ecg_patient_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Patient-friendly ECG summary template"""
        
        rhythm = data.get("rhythm_classification", {})
        intervals = data.get("intervals", {})
        
        prompt = f"""You are a medical AI assistant explaining ECG results to a patient in simple, clear language.

YOUR ECG RESULTS:
- Heart Rate: {rhythm.get('heart_rate_bpm', 'N/A')} beats per minute
- Heart Rhythm: {rhythm.get('primary_rhythm', 'N/A')}

WHAT THIS MEANS:
Generate a patient-friendly explanation that:

1. WHAT WE FOUND
   - Explain the heart rate and rhythm in simple terms
   - Describe any abnormalities without medical jargon
   
2. WHAT THIS MEANS FOR YOU
   - Is this normal or concerning?
   - What might be causing any abnormalities?
   
3. NEXT STEPS
   - What should you do next?
   - Do you need to see a doctor urgently?
   - Any lifestyle changes to consider?
   
4. OUR CONFIDENCE
   - How certain are we about these findings?
   - Why you should still talk to your doctor

Use everyday language. Be reassuring when appropriate. Be clear about urgency if there are concerns.

Generate the patient explanation now:"""
        
        return prompt
    
    # ========================
    # RADIOLOGY TEMPLATES
    # ========================
    
    @staticmethod
    def _radiology_clinician_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Clinician-level radiology summary template"""
        
        findings = data.get("findings", {})
        metrics = data.get("metrics", {})
        images = data.get("image_references", [])
        
        prompt = f"""You are a radiologist AI assistant generating a comprehensive imaging report.

IMAGING STUDY DETAILS:
- Modality: {', '.join([img.get('modality', 'N/A') for img in images[:3]])}
- Body Parts: {', '.join([img.get('body_part', 'N/A') for img in images[:3]])}
- Study Date: {data.get('metadata', {}).get('document_date', 'N/A')}

FINDINGS:
{findings.get('findings_text', 'N/A')}

IMPRESSION:
{findings.get('impression_text', 'N/A')}

CRITICAL FINDINGS: {', '.join(findings.get('critical_findings', [])) or 'None'}
INCIDENTAL FINDINGS: {', '.join(findings.get('incidental_findings', [])) or 'None'}

QUANTITATIVE METRICS:
- Organ Volumes: {metrics.get('organ_volumes', {})}
- Lesion Measurements: {len(metrics.get('lesion_measurements', []))} lesions measured

AI MODEL ANALYSIS:
{PromptTemplateLibrary._format_model_outputs(outputs)}

ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%

Generate a structured radiology report with:

1. TECHNIQUE & COMPARISON
2. FINDINGS (organized by anatomical region)
3. IMPRESSION
4. RECOMMENDATIONS
5. CONFIDENCE ASSESSMENT

Use standard radiology terminology (BI-RADS, Lung-RADS, etc. if applicable).

Generate the report now:"""
        
        return prompt
    
    @staticmethod
    def _radiology_patient_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Patient-friendly radiology summary template"""
        
        findings = data.get("findings", {})
        images = data.get("image_references", [])
        
        prompt = f"""You are explaining imaging results to a patient in clear, simple language.

YOUR IMAGING STUDY:
- Type of Scan: {', '.join([img.get('modality', 'N/A') for img in images[:3]])}
- Body Area: {', '.join([img.get('body_part', 'N/A') for img in images[:3]])}

Generate a patient-friendly explanation:

1. WHAT THE SCAN SHOWED
   - Main findings in simple terms
   - Any areas of concern
   
2. WHAT THIS MEANS
   - Are the findings normal or abnormal?
   - What conditions might this suggest?
   
3. NEXT STEPS
   - Do you need additional tests?
   - Should you see a specialist?
   - Timeline for follow-up
   
4. QUESTIONS TO ASK YOUR DOCTOR
   - List 3-4 relevant questions

Use everyday language. Explain medical terms when necessary. Be clear about urgency.

Generate the patient explanation now:"""
        
        return prompt
    
    # ========================
    # LABORATORY TEMPLATES
    # ========================
    
    @staticmethod
    def _laboratory_clinician_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Clinician-level laboratory results template"""
        
        tests = data.get("tests", [])
        abnormal_count = data.get("abnormal_count", 0)
        critical_values = data.get("critical_values", [])
        
        test_summary = "\n".join([
            f"- {test.get('test_name', 'N/A')}: {test.get('value', 'N/A')} {test.get('unit', '')} "
            f"(Ref: {test.get('reference_range_low', 'N/A')}-{test.get('reference_range_high', 'N/A')}) "
            f"{test.get('flags', [])}"
            for test in tests[:20]  # Limit to 20 tests
        ])
        
        prompt = f"""You are a clinical laboratory AI assistant generating a comprehensive lab results analysis.

LABORATORY PANEL:
- Panel Type: {data.get('panel_name', 'General Laboratory Panel')}
- Collection Date: {data.get('collection_date', 'N/A')}
- Total Tests: {len(tests)}
- Abnormal Results: {abnormal_count}
- Critical Values: {len(critical_values)}

TEST RESULTS:
{test_summary}

CRITICAL VALUES: {', '.join(critical_values) or 'None'}

AI MODEL ANALYSIS:
{PromptTemplateLibrary._format_model_outputs(outputs)}

ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%

Generate a comprehensive laboratory interpretation with:

1. SUMMARY OF KEY FINDINGS
   - Normal vs abnormal results
   - Critical values requiring immediate attention
   
2. CLINICAL CORRELATION
   - Pattern recognition (e.g., renal dysfunction, electrolyte imbalance)
   - Physiological significance
   
3. DIFFERENTIAL DIAGNOSIS
   - Most likely conditions based on lab pattern
   
4. RECOMMENDATIONS
   - Immediate interventions for critical values
   - Additional testing needed
   - Follow-up timeline
   
5. CONFIDENCE ASSESSMENT
   - Reliability of each test result
   - Need for repeat testing

Generate the interpretation now:"""
        
        return prompt
    
    @staticmethod
    def _laboratory_patient_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Patient-friendly laboratory results template"""
        
        tests = data.get("tests", [])
        abnormal_count = data.get("abnormal_count", 0)
        
        prompt = f"""You are explaining laboratory test results to a patient in simple language.

YOUR LAB RESULTS:
- Total Tests: {len(tests)}
- Abnormal Results: {abnormal_count}

Generate a patient-friendly explanation:

1. OVERVIEW
   - What tests were done and why
   - Overall picture (mostly normal, some concerns, etc.)
   
2. KEY FINDINGS
   - Which results are normal
   - Which results are outside the normal range
   - What each abnormal result means in simple terms
   
3. WHAT THIS MEANS FOR YOUR HEALTH
   - Are these results concerning?
   - What conditions might they suggest?
   
4. NEXT STEPS
   - Do you need to see your doctor urgently?
   - Lifestyle changes that might help
   - Additional tests that might be needed
   
5. IMPORTANT NOTES
   - Lab values can vary based on many factors
   - Always discuss results with your doctor

Use everyday language. Explain abbreviations. Be clear about urgency.

Generate the patient explanation now:"""
        
        return prompt
    
    # ========================
    # CLINICAL NOTES TEMPLATES
    # ========================
    
    @staticmethod
    def _clinical_notes_clinician_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Clinician-level clinical notes summary template"""
        
        sections = data.get("sections", [])
        entities = data.get("entities", [])
        diagnoses = data.get("diagnoses", [])
        medications = data.get("medications", [])
        
        sections_summary = "\n".join([
            f"- {section.get('section_type', 'N/A')}: {section.get('content', 'N/A')[:200]}..."
            for section in sections[:10]
        ])
        
        prompt = f"""You are a clinical documentation AI assistant synthesizing medical notes.

NOTE TYPE: {data.get('note_type', 'Clinical Documentation')}
DOCUMENTATION DATE: {data.get('metadata', {}).get('document_date', 'N/A')}

CLINICAL SECTIONS:
{sections_summary}

EXTRACTED ENTITIES:
- Diagnoses: {', '.join(diagnoses[:10]) or 'None identified'}
- Medications: {', '.join(medications[:10]) or 'None identified'}

AI MODEL ANALYSIS:
{PromptTemplateLibrary._format_model_outputs(outputs)}

ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%

Generate a comprehensive clinical synthesis with:

1. CLINICAL SUMMARY
   - Chief complaint and HPI synthesis
   - Pertinent positives and negatives
   
2. ASSESSMENT
   - Problem list with prioritization
   - Clinical reasoning
   
3. PLAN
   - Management for each problem
   - Medications and interventions
   - Follow-up and monitoring
   
4. DOCUMENTATION QUALITY
   - Completeness assessment
   - Missing information
   
5. CONFIDENCE ASSESSMENT

Generate the clinical synthesis now:"""
        
        return prompt
    
    @staticmethod
    def _clinical_notes_patient_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """Patient-friendly clinical notes summary template"""
        
        diagnoses = data.get("diagnoses", [])
        medications = data.get("medications", [])
        
        prompt = f"""You are explaining a clinical visit summary to a patient in clear, simple language.

Generate a patient-friendly visit summary:

1. REASON FOR YOUR VISIT
   - Why you came to see the doctor
   
2. WHAT THE DOCTOR FOUND
   - Key findings from examination
   - Test results discussed
   
3. YOUR DIAGNOSES
   - {', '.join(diagnoses[:5]) if diagnoses else 'To be discussed with your doctor'}
   - What each diagnosis means in simple terms
   
4. YOUR TREATMENT PLAN
   - Medications prescribed
   - Other treatments or therapies
   
5. WHAT YOU NEED TO DO
   - Follow-up appointments
   - Tests or procedures needed
   - Lifestyle changes
   - Warning signs to watch for
   
6. QUESTIONS FOR YOUR DOCTOR
   - List important questions to ask

Use everyday language. Explain medical terms. Organize by priority.

Generate the patient summary now:"""
        
        return prompt
    
    # ========================
    # GENERAL TEMPLATES
    # ========================
    
    @staticmethod
    def _general_clinician_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """General clinician-level summary template"""
        
        prompt = f"""You are a medical AI assistant generating a comprehensive clinical summary.

DOCUMENT TYPE: {data.get('metadata', {}).get('source_type', 'Medical Document')}
DOCUMENT DATE: {data.get('metadata', {}).get('document_date', 'N/A')}

AI MODEL ANALYSIS:
{PromptTemplateLibrary._format_model_outputs(outputs)}

ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%

Generate a structured medical summary with:
1. KEY FINDINGS
2. CLINICAL SIGNIFICANCE
3. RECOMMENDATIONS
4. CONFIDENCE ASSESSMENT

Use appropriate medical terminology.

Generate the summary now:"""
        
        return prompt
    
    @staticmethod
    def _general_patient_template(
        data: Dict[str, Any],
        outputs: List[Dict[str, Any]],
        confidence: Dict[str, float]
    ) -> str:
        """General patient-friendly summary template"""
        
        prompt = f"""You are explaining medical information to a patient in simple, clear language.

Generate a patient-friendly explanation:
1. WHAT WE FOUND
2. WHAT THIS MEANS FOR YOU
3. NEXT STEPS
4. QUESTIONS TO ASK YOUR DOCTOR

Use everyday language. Be clear and reassuring when appropriate.

Generate the explanation now:"""
        
        return prompt
    
    # ========================
    # MULTI-MODAL SYNTHESIS
    # ========================
    
    @staticmethod
    def get_multi_modal_synthesis_template(
        modalities: List[str],
        all_data: Dict[str, Dict[str, Any]],
        confidence_scores: Dict[str, float]
    ) -> str:
        """
        Generate prompt for multi-modal clinical synthesis
        Combines multiple document types into unified summary
        """
        
        modality_summaries = []
        for modality in modalities:
            data = all_data.get(modality, {})
            modality_summaries.append(f"- {modality.upper()}: Available with {confidence_scores.get(modality, 0.0)*100:.1f}% confidence")
        
        prompt = f"""You are a medical AI assistant synthesizing multiple medical documents into a comprehensive clinical picture.

AVAILABLE DOCUMENTS:
{chr(10).join(modality_summaries)}

TASK:
Generate a unified clinical summary that:

1. INTEGRATED CLINICAL PICTURE
   - Synthesize findings across all modalities
   - Identify consistent patterns
   - Flag contradictions or discrepancies
   
2. TIMELINE CORRELATION
   - How findings relate temporally
   - Disease progression or improvement
   
3. COMPREHENSIVE ASSESSMENT
   - Overall patient status
   - Risk stratification
   
4. COORDINATED CARE PLAN
   - Unified recommendations
   - Priority actions
   - Specialist referrals
   
5. CONFIDENCE SYNTHESIS
   - Overall reliability of the integrated analysis
   - Areas needing additional investigation

Generate the integrated clinical synthesis now:"""
        
        return prompt
    
    # ========================
    # UTILITY METHODS
    # ========================
    
    @staticmethod
    def _format_model_outputs(outputs: List[Dict[str, Any]]) -> str:
        """Format model outputs for inclusion in prompts"""
        if not outputs:
            return "No specialized model outputs available"
        
        formatted = []
        for idx, output in enumerate(outputs[:5], 1):  # Limit to top 5
            model_name = output.get("model_name", "Unknown Model")
            domain = output.get("domain", "general")
            result = output.get("result", {})
            
            # Extract key information from result
            if isinstance(result, dict):
                confidence = result.get("confidence", 0.0)
                summary = result.get("summary", result.get("analysis", "Analysis completed"))[:200]
                formatted.append(f"{idx}. {model_name} ({domain}): {summary}... [Confidence: {confidence*100:.1f}%]")
            else:
                formatted.append(f"{idx}. {model_name} ({domain}): {str(result)[:200]}...")
        
        return "\n".join(formatted)
    
    @staticmethod
    def get_confidence_explanation_template(
        confidence_scores: Dict[str, float],
        modality: str
    ) -> str:
        """Generate prompt for explaining confidence scores"""
        
        overall = confidence_scores.get("overall_confidence", 0.0)
        extraction = confidence_scores.get("extraction_confidence", 0.0)
        model = confidence_scores.get("model_confidence", 0.0)
        quality = confidence_scores.get("data_quality", 0.0)
        
        if overall >= 0.85:
            threshold = "AUTO-APPROVED (≥85%)"
        elif overall >= 0.60:
            threshold = "REQUIRES REVIEW (60-85%)"
        else:
            threshold = "MANUAL REVIEW REQUIRED (<60%)"
        
        prompt = f"""Explain the confidence scores for this {modality} analysis to a clinician:

CONFIDENCE BREAKDOWN:
- Overall Confidence: {overall*100:.1f}% [{threshold}]
- Data Extraction: {extraction*100:.1f}%
- Model Analysis: {model*100:.1f}%
- Data Quality: {quality*100:.1f}%

Generate a brief explanation that:
1. Why this confidence level?
2. What factors contributed to the score?
3. What should the clinician be aware of?
4. Is human review recommended?

Be concise and practical.

Generate the explanation now:"""
        
        return prompt