snikhilesh commited on
Commit
9c479c4
·
verified ·
1 Parent(s): 336cdbf

Deploy medical_prompt_templates.py to backend/ directory

Browse files
Files changed (1) hide show
  1. backend/medical_prompt_templates.py +728 -0
backend/medical_prompt_templates.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Medical Prompt Templates for MedGemma Synthesis
3
+ Comprehensive templates for generating clinician-level and patient-friendly summaries
4
+
5
+ Author: MiniMax Agent
6
+ Date: 2025-10-29
7
+ Version: 1.0.0
8
+ """
9
+
10
+ from typing import Dict, Any, List, Optional
11
+ from enum import Enum
12
+
13
+
14
+ class SummaryType(Enum):
15
+ """Types of medical summaries that can be generated"""
16
+ CLINICIAN_TECHNICAL = "clinician_technical"
17
+ PATIENT_FRIENDLY = "patient_friendly"
18
+ MULTI_MODAL = "multi_modal"
19
+ RISK_ASSESSMENT = "risk_assessment"
20
+
21
+
22
+ class PromptTemplateLibrary:
23
+ """
24
+ Comprehensive library of medical prompt templates for MedGemma
25
+ Supports all medical modalities with evidence-based generation
26
+ """
27
+
28
+ @staticmethod
29
+ def get_clinician_summary_template(
30
+ modality: str,
31
+ structured_data: Dict[str, Any],
32
+ model_outputs: List[Dict[str, Any]],
33
+ confidence_scores: Dict[str, float]
34
+ ) -> str:
35
+ """
36
+ Generate clinician-level technical summary prompt
37
+
38
+ Features:
39
+ - Technical medical terminology
40
+ - Detailed analysis with evidence
41
+ - Confidence scores and uncertainty
42
+ - Clinical decision support
43
+ """
44
+
45
+ if modality == "ECG":
46
+ return PromptTemplateLibrary._ecg_clinician_template(
47
+ structured_data, model_outputs, confidence_scores
48
+ )
49
+ elif modality == "radiology":
50
+ return PromptTemplateLibrary._radiology_clinician_template(
51
+ structured_data, model_outputs, confidence_scores
52
+ )
53
+ elif modality == "laboratory":
54
+ return PromptTemplateLibrary._laboratory_clinician_template(
55
+ structured_data, model_outputs, confidence_scores
56
+ )
57
+ elif modality == "clinical_notes":
58
+ return PromptTemplateLibrary._clinical_notes_clinician_template(
59
+ structured_data, model_outputs, confidence_scores
60
+ )
61
+ else:
62
+ return PromptTemplateLibrary._general_clinician_template(
63
+ structured_data, model_outputs, confidence_scores
64
+ )
65
+
66
+ @staticmethod
67
+ def get_patient_summary_template(
68
+ modality: str,
69
+ structured_data: Dict[str, Any],
70
+ model_outputs: List[Dict[str, Any]],
71
+ confidence_scores: Dict[str, float]
72
+ ) -> str:
73
+ """
74
+ Generate patient-friendly summary prompt
75
+
76
+ Features:
77
+ - Plain language explanations
78
+ - Key findings highlighted
79
+ - Actionable next steps
80
+ - Reassurance when appropriate
81
+ """
82
+
83
+ if modality == "ECG":
84
+ return PromptTemplateLibrary._ecg_patient_template(
85
+ structured_data, model_outputs, confidence_scores
86
+ )
87
+ elif modality == "radiology":
88
+ return PromptTemplateLibrary._radiology_patient_template(
89
+ structured_data, model_outputs, confidence_scores
90
+ )
91
+ elif modality == "laboratory":
92
+ return PromptTemplateLibrary._laboratory_patient_template(
93
+ structured_data, model_outputs, confidence_scores
94
+ )
95
+ elif modality == "clinical_notes":
96
+ return PromptTemplateLibrary._clinical_notes_patient_template(
97
+ structured_data, model_outputs, confidence_scores
98
+ )
99
+ else:
100
+ return PromptTemplateLibrary._general_patient_template(
101
+ structured_data, model_outputs, confidence_scores
102
+ )
103
+
104
+ # ========================
105
+ # ECG TEMPLATES
106
+ # ========================
107
+
108
+ @staticmethod
109
+ def _ecg_clinician_template(
110
+ data: Dict[str, Any],
111
+ outputs: List[Dict[str, Any]],
112
+ confidence: Dict[str, float]
113
+ ) -> str:
114
+ """Clinician-level ECG summary template"""
115
+
116
+ intervals = data.get("intervals", {})
117
+ rhythm = data.get("rhythm_classification", {})
118
+ arrhythmia_probs = data.get("arrhythmia_probabilities", {})
119
+ derived = data.get("derived_features", {})
120
+
121
+ overall_confidence = confidence.get("overall_confidence", 0.0)
122
+
123
+ prompt = f"""You are a medical AI assistant generating a comprehensive ECG analysis report for clinicians.
124
+
125
+ PATIENT CONTEXT:
126
+ - Document ID: {data.get('metadata', {}).get('document_id', 'N/A')}
127
+ - Facility: {data.get('metadata', {}).get('facility', 'N/A')}
128
+ - Recording Date: {data.get('metadata', {}).get('document_date', 'N/A')}
129
+
130
+ ECG MEASUREMENTS:
131
+ - Heart Rate: {rhythm.get('heart_rate_bpm', 'N/A')} bpm
132
+ - PR Interval: {intervals.get('pr_ms', 'N/A')} ms
133
+ - QRS Duration: {intervals.get('qrs_ms', 'N/A')} ms
134
+ - QT Interval: {intervals.get('qt_ms', 'N/A')} ms
135
+ - QTc Interval: {intervals.get('qtc_ms', 'N/A')} ms
136
+ - RR Interval: {intervals.get('rr_ms', 'N/A')} ms
137
+
138
+ RHYTHM ANALYSIS:
139
+ - Primary Rhythm: {rhythm.get('primary_rhythm', 'N/A')}
140
+ - Rhythm Regularity: {rhythm.get('heart_rate_regularity', 'N/A')}
141
+ - Detected Arrhythmias: {', '.join(rhythm.get('arrhythmia_types', [])) or 'None'}
142
+
143
+ ARRHYTHMIA PROBABILITIES:
144
+ - Normal Sinus Rhythm: {arrhythmia_probs.get('normal_rhythm', 'N/A')}
145
+ - Atrial Fibrillation: {arrhythmia_probs.get('atrial_fibrillation', 'N/A')}
146
+ - Atrial Flutter: {arrhythmia_probs.get('atrial_flutter', 'N/A')}
147
+ - Ventricular Tachycardia: {arrhythmia_probs.get('ventricular_tachycardia', 'N/A')}
148
+ - Heart Block: {arrhythmia_probs.get('heart_block', 'N/A')}
149
+
150
+ ST-SEGMENT & T-WAVE FINDINGS:
151
+ - ST Elevation: {derived.get('st_elevation_mm', 'None detected')}
152
+ - ST Depression: {derived.get('st_depression_mm', 'None detected')}
153
+ - T-wave Abnormalities: {', '.join(derived.get('t_wave_abnormalities', [])) or 'None'}
154
+ - Axis Deviation: {derived.get('axis_deviation', 'Normal')}
155
+
156
+ AI MODEL OUTPUTS:
157
+ {PromptTemplateLibrary._format_model_outputs(outputs)}
158
+
159
+ ANALYSIS CONFIDENCE: {overall_confidence * 100:.1f}%
160
+
161
+ INSTRUCTIONS:
162
+ Generate a comprehensive clinical ECG report with the following sections:
163
+
164
+ 1. TECHNICAL SUMMARY
165
+ - Concise interpretation of rhythm and intervals
166
+ - Significance of any abnormal findings
167
+
168
+ 2. CLINICAL SIGNIFICANCE
169
+ - Pathophysiological implications
170
+ - Risk stratification (low/moderate/high)
171
+
172
+ 3. DIFFERENTIAL DIAGNOSIS
173
+ - Most likely diagnoses based on findings
174
+ - Alternative considerations
175
+
176
+ 4. RECOMMENDATIONS
177
+ - Immediate actions required (if any)
178
+ - Follow-up studies or monitoring
179
+ - Cardiology referral if indicated
180
+
181
+ 5. CONFIDENCE EXPLANATION
182
+ - Why the AI confidence is {overall_confidence * 100:.1f}%
183
+ - Which findings are most/least certain
184
+ - Limitations of the analysis
185
+
186
+ Use precise medical terminology. Be evidence-based. Flag any critical findings requiring immediate attention.
187
+
188
+ Generate the report now:"""
189
+
190
+ return prompt
191
+
192
+ @staticmethod
193
+ def _ecg_patient_template(
194
+ data: Dict[str, Any],
195
+ outputs: List[Dict[str, Any]],
196
+ confidence: Dict[str, float]
197
+ ) -> str:
198
+ """Patient-friendly ECG summary template"""
199
+
200
+ rhythm = data.get("rhythm_classification", {})
201
+ intervals = data.get("intervals", {})
202
+
203
+ prompt = f"""You are a medical AI assistant explaining ECG results to a patient in simple, clear language.
204
+
205
+ YOUR ECG RESULTS:
206
+ - Heart Rate: {rhythm.get('heart_rate_bpm', 'N/A')} beats per minute
207
+ - Heart Rhythm: {rhythm.get('primary_rhythm', 'N/A')}
208
+
209
+ WHAT THIS MEANS:
210
+ Generate a patient-friendly explanation that:
211
+
212
+ 1. WHAT WE FOUND
213
+ - Explain the heart rate and rhythm in simple terms
214
+ - Describe any abnormalities without medical jargon
215
+
216
+ 2. WHAT THIS MEANS FOR YOU
217
+ - Is this normal or concerning?
218
+ - What might be causing any abnormalities?
219
+
220
+ 3. NEXT STEPS
221
+ - What should you do next?
222
+ - Do you need to see a doctor urgently?
223
+ - Any lifestyle changes to consider?
224
+
225
+ 4. OUR CONFIDENCE
226
+ - How certain are we about these findings?
227
+ - Why you should still talk to your doctor
228
+
229
+ Use everyday language. Be reassuring when appropriate. Be clear about urgency if there are concerns.
230
+
231
+ Generate the patient explanation now:"""
232
+
233
+ return prompt
234
+
235
+ # ========================
236
+ # RADIOLOGY TEMPLATES
237
+ # ========================
238
+
239
+ @staticmethod
240
+ def _radiology_clinician_template(
241
+ data: Dict[str, Any],
242
+ outputs: List[Dict[str, Any]],
243
+ confidence: Dict[str, float]
244
+ ) -> str:
245
+ """Clinician-level radiology summary template"""
246
+
247
+ findings = data.get("findings", {})
248
+ metrics = data.get("metrics", {})
249
+ images = data.get("image_references", [])
250
+
251
+ prompt = f"""You are a radiologist AI assistant generating a comprehensive imaging report.
252
+
253
+ IMAGING STUDY DETAILS:
254
+ - Modality: {', '.join([img.get('modality', 'N/A') for img in images[:3]])}
255
+ - Body Parts: {', '.join([img.get('body_part', 'N/A') for img in images[:3]])}
256
+ - Study Date: {data.get('metadata', {}).get('document_date', 'N/A')}
257
+
258
+ FINDINGS:
259
+ {findings.get('findings_text', 'N/A')}
260
+
261
+ IMPRESSION:
262
+ {findings.get('impression_text', 'N/A')}
263
+
264
+ CRITICAL FINDINGS: {', '.join(findings.get('critical_findings', [])) or 'None'}
265
+ INCIDENTAL FINDINGS: {', '.join(findings.get('incidental_findings', [])) or 'None'}
266
+
267
+ QUANTITATIVE METRICS:
268
+ - Organ Volumes: {metrics.get('organ_volumes', {})}
269
+ - Lesion Measurements: {len(metrics.get('lesion_measurements', []))} lesions measured
270
+
271
+ AI MODEL ANALYSIS:
272
+ {PromptTemplateLibrary._format_model_outputs(outputs)}
273
+
274
+ ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%
275
+
276
+ Generate a structured radiology report with:
277
+
278
+ 1. TECHNIQUE & COMPARISON
279
+ 2. FINDINGS (organized by anatomical region)
280
+ 3. IMPRESSION
281
+ 4. RECOMMENDATIONS
282
+ 5. CONFIDENCE ASSESSMENT
283
+
284
+ Use standard radiology terminology (BI-RADS, Lung-RADS, etc. if applicable).
285
+
286
+ Generate the report now:"""
287
+
288
+ return prompt
289
+
290
+ @staticmethod
291
+ def _radiology_patient_template(
292
+ data: Dict[str, Any],
293
+ outputs: List[Dict[str, Any]],
294
+ confidence: Dict[str, float]
295
+ ) -> str:
296
+ """Patient-friendly radiology summary template"""
297
+
298
+ findings = data.get("findings", {})
299
+ images = data.get("image_references", [])
300
+
301
+ prompt = f"""You are explaining imaging results to a patient in clear, simple language.
302
+
303
+ YOUR IMAGING STUDY:
304
+ - Type of Scan: {', '.join([img.get('modality', 'N/A') for img in images[:3]])}
305
+ - Body Area: {', '.join([img.get('body_part', 'N/A') for img in images[:3]])}
306
+
307
+ Generate a patient-friendly explanation:
308
+
309
+ 1. WHAT THE SCAN SHOWED
310
+ - Main findings in simple terms
311
+ - Any areas of concern
312
+
313
+ 2. WHAT THIS MEANS
314
+ - Are the findings normal or abnormal?
315
+ - What conditions might this suggest?
316
+
317
+ 3. NEXT STEPS
318
+ - Do you need additional tests?
319
+ - Should you see a specialist?
320
+ - Timeline for follow-up
321
+
322
+ 4. QUESTIONS TO ASK YOUR DOCTOR
323
+ - List 3-4 relevant questions
324
+
325
+ Use everyday language. Explain medical terms when necessary. Be clear about urgency.
326
+
327
+ Generate the patient explanation now:"""
328
+
329
+ return prompt
330
+
331
+ # ========================
332
+ # LABORATORY TEMPLATES
333
+ # ========================
334
+
335
+ @staticmethod
336
+ def _laboratory_clinician_template(
337
+ data: Dict[str, Any],
338
+ outputs: List[Dict[str, Any]],
339
+ confidence: Dict[str, float]
340
+ ) -> str:
341
+ """Clinician-level laboratory results template"""
342
+
343
+ tests = data.get("tests", [])
344
+ abnormal_count = data.get("abnormal_count", 0)
345
+ critical_values = data.get("critical_values", [])
346
+
347
+ test_summary = "\n".join([
348
+ f"- {test.get('test_name', 'N/A')}: {test.get('value', 'N/A')} {test.get('unit', '')} "
349
+ f"(Ref: {test.get('reference_range_low', 'N/A')}-{test.get('reference_range_high', 'N/A')}) "
350
+ f"{test.get('flags', [])}"
351
+ for test in tests[:20] # Limit to 20 tests
352
+ ])
353
+
354
+ prompt = f"""You are a clinical laboratory AI assistant generating a comprehensive lab results analysis.
355
+
356
+ LABORATORY PANEL:
357
+ - Panel Type: {data.get('panel_name', 'General Laboratory Panel')}
358
+ - Collection Date: {data.get('collection_date', 'N/A')}
359
+ - Total Tests: {len(tests)}
360
+ - Abnormal Results: {abnormal_count}
361
+ - Critical Values: {len(critical_values)}
362
+
363
+ TEST RESULTS:
364
+ {test_summary}
365
+
366
+ CRITICAL VALUES: {', '.join(critical_values) or 'None'}
367
+
368
+ AI MODEL ANALYSIS:
369
+ {PromptTemplateLibrary._format_model_outputs(outputs)}
370
+
371
+ ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%
372
+
373
+ Generate a comprehensive laboratory interpretation with:
374
+
375
+ 1. SUMMARY OF KEY FINDINGS
376
+ - Normal vs abnormal results
377
+ - Critical values requiring immediate attention
378
+
379
+ 2. CLINICAL CORRELATION
380
+ - Pattern recognition (e.g., renal dysfunction, electrolyte imbalance)
381
+ - Physiological significance
382
+
383
+ 3. DIFFERENTIAL DIAGNOSIS
384
+ - Most likely conditions based on lab pattern
385
+
386
+ 4. RECOMMENDATIONS
387
+ - Immediate interventions for critical values
388
+ - Additional testing needed
389
+ - Follow-up timeline
390
+
391
+ 5. CONFIDENCE ASSESSMENT
392
+ - Reliability of each test result
393
+ - Need for repeat testing
394
+
395
+ Generate the interpretation now:"""
396
+
397
+ return prompt
398
+
399
+ @staticmethod
400
+ def _laboratory_patient_template(
401
+ data: Dict[str, Any],
402
+ outputs: List[Dict[str, Any]],
403
+ confidence: Dict[str, float]
404
+ ) -> str:
405
+ """Patient-friendly laboratory results template"""
406
+
407
+ tests = data.get("tests", [])
408
+ abnormal_count = data.get("abnormal_count", 0)
409
+
410
+ prompt = f"""You are explaining laboratory test results to a patient in simple language.
411
+
412
+ YOUR LAB RESULTS:
413
+ - Total Tests: {len(tests)}
414
+ - Abnormal Results: {abnormal_count}
415
+
416
+ Generate a patient-friendly explanation:
417
+
418
+ 1. OVERVIEW
419
+ - What tests were done and why
420
+ - Overall picture (mostly normal, some concerns, etc.)
421
+
422
+ 2. KEY FINDINGS
423
+ - Which results are normal
424
+ - Which results are outside the normal range
425
+ - What each abnormal result means in simple terms
426
+
427
+ 3. WHAT THIS MEANS FOR YOUR HEALTH
428
+ - Are these results concerning?
429
+ - What conditions might they suggest?
430
+
431
+ 4. NEXT STEPS
432
+ - Do you need to see your doctor urgently?
433
+ - Lifestyle changes that might help
434
+ - Additional tests that might be needed
435
+
436
+ 5. IMPORTANT NOTES
437
+ - Lab values can vary based on many factors
438
+ - Always discuss results with your doctor
439
+
440
+ Use everyday language. Explain abbreviations. Be clear about urgency.
441
+
442
+ Generate the patient explanation now:"""
443
+
444
+ return prompt
445
+
446
+ # ========================
447
+ # CLINICAL NOTES TEMPLATES
448
+ # ========================
449
+
450
+ @staticmethod
451
+ def _clinical_notes_clinician_template(
452
+ data: Dict[str, Any],
453
+ outputs: List[Dict[str, Any]],
454
+ confidence: Dict[str, float]
455
+ ) -> str:
456
+ """Clinician-level clinical notes summary template"""
457
+
458
+ sections = data.get("sections", [])
459
+ entities = data.get("entities", [])
460
+ diagnoses = data.get("diagnoses", [])
461
+ medications = data.get("medications", [])
462
+
463
+ sections_summary = "\n".join([
464
+ f"- {section.get('section_type', 'N/A')}: {section.get('content', 'N/A')[:200]}..."
465
+ for section in sections[:10]
466
+ ])
467
+
468
+ prompt = f"""You are a clinical documentation AI assistant synthesizing medical notes.
469
+
470
+ NOTE TYPE: {data.get('note_type', 'Clinical Documentation')}
471
+ DOCUMENTATION DATE: {data.get('metadata', {}).get('document_date', 'N/A')}
472
+
473
+ CLINICAL SECTIONS:
474
+ {sections_summary}
475
+
476
+ EXTRACTED ENTITIES:
477
+ - Diagnoses: {', '.join(diagnoses[:10]) or 'None identified'}
478
+ - Medications: {', '.join(medications[:10]) or 'None identified'}
479
+
480
+ AI MODEL ANALYSIS:
481
+ {PromptTemplateLibrary._format_model_outputs(outputs)}
482
+
483
+ ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%
484
+
485
+ Generate a comprehensive clinical synthesis with:
486
+
487
+ 1. CLINICAL SUMMARY
488
+ - Chief complaint and HPI synthesis
489
+ - Pertinent positives and negatives
490
+
491
+ 2. ASSESSMENT
492
+ - Problem list with prioritization
493
+ - Clinical reasoning
494
+
495
+ 3. PLAN
496
+ - Management for each problem
497
+ - Medications and interventions
498
+ - Follow-up and monitoring
499
+
500
+ 4. DOCUMENTATION QUALITY
501
+ - Completeness assessment
502
+ - Missing information
503
+
504
+ 5. CONFIDENCE ASSESSMENT
505
+
506
+ Generate the clinical synthesis now:"""
507
+
508
+ return prompt
509
+
510
+ @staticmethod
511
+ def _clinical_notes_patient_template(
512
+ data: Dict[str, Any],
513
+ outputs: List[Dict[str, Any]],
514
+ confidence: Dict[str, float]
515
+ ) -> str:
516
+ """Patient-friendly clinical notes summary template"""
517
+
518
+ diagnoses = data.get("diagnoses", [])
519
+ medications = data.get("medications", [])
520
+
521
+ prompt = f"""You are explaining a clinical visit summary to a patient in clear, simple language.
522
+
523
+ Generate a patient-friendly visit summary:
524
+
525
+ 1. REASON FOR YOUR VISIT
526
+ - Why you came to see the doctor
527
+
528
+ 2. WHAT THE DOCTOR FOUND
529
+ - Key findings from examination
530
+ - Test results discussed
531
+
532
+ 3. YOUR DIAGNOSES
533
+ - {', '.join(diagnoses[:5]) if diagnoses else 'To be discussed with your doctor'}
534
+ - What each diagnosis means in simple terms
535
+
536
+ 4. YOUR TREATMENT PLAN
537
+ - Medications prescribed
538
+ - Other treatments or therapies
539
+
540
+ 5. WHAT YOU NEED TO DO
541
+ - Follow-up appointments
542
+ - Tests or procedures needed
543
+ - Lifestyle changes
544
+ - Warning signs to watch for
545
+
546
+ 6. QUESTIONS FOR YOUR DOCTOR
547
+ - List important questions to ask
548
+
549
+ Use everyday language. Explain medical terms. Organize by priority.
550
+
551
+ Generate the patient summary now:"""
552
+
553
+ return prompt
554
+
555
+ # ========================
556
+ # GENERAL TEMPLATES
557
+ # ========================
558
+
559
+ @staticmethod
560
+ def _general_clinician_template(
561
+ data: Dict[str, Any],
562
+ outputs: List[Dict[str, Any]],
563
+ confidence: Dict[str, float]
564
+ ) -> str:
565
+ """General clinician-level summary template"""
566
+
567
+ prompt = f"""You are a medical AI assistant generating a comprehensive clinical summary.
568
+
569
+ DOCUMENT TYPE: {data.get('metadata', {}).get('source_type', 'Medical Document')}
570
+ DOCUMENT DATE: {data.get('metadata', {}).get('document_date', 'N/A')}
571
+
572
+ AI MODEL ANALYSIS:
573
+ {PromptTemplateLibrary._format_model_outputs(outputs)}
574
+
575
+ ANALYSIS CONFIDENCE: {confidence.get('overall_confidence', 0.0) * 100:.1f}%
576
+
577
+ Generate a structured medical summary with:
578
+ 1. KEY FINDINGS
579
+ 2. CLINICAL SIGNIFICANCE
580
+ 3. RECOMMENDATIONS
581
+ 4. CONFIDENCE ASSESSMENT
582
+
583
+ Use appropriate medical terminology.
584
+
585
+ Generate the summary now:"""
586
+
587
+ return prompt
588
+
589
+ @staticmethod
590
+ def _general_patient_template(
591
+ data: Dict[str, Any],
592
+ outputs: List[Dict[str, Any]],
593
+ confidence: Dict[str, float]
594
+ ) -> str:
595
+ """General patient-friendly summary template"""
596
+
597
+ prompt = f"""You are explaining medical information to a patient in simple, clear language.
598
+
599
+ Generate a patient-friendly explanation:
600
+ 1. WHAT WE FOUND
601
+ 2. WHAT THIS MEANS FOR YOU
602
+ 3. NEXT STEPS
603
+ 4. QUESTIONS TO ASK YOUR DOCTOR
604
+
605
+ Use everyday language. Be clear and reassuring when appropriate.
606
+
607
+ Generate the explanation now:"""
608
+
609
+ return prompt
610
+
611
+ # ========================
612
+ # MULTI-MODAL SYNTHESIS
613
+ # ========================
614
+
615
+ @staticmethod
616
+ def get_multi_modal_synthesis_template(
617
+ modalities: List[str],
618
+ all_data: Dict[str, Dict[str, Any]],
619
+ confidence_scores: Dict[str, float]
620
+ ) -> str:
621
+ """
622
+ Generate prompt for multi-modal clinical synthesis
623
+ Combines multiple document types into unified summary
624
+ """
625
+
626
+ modality_summaries = []
627
+ for modality in modalities:
628
+ data = all_data.get(modality, {})
629
+ modality_summaries.append(f"- {modality.upper()}: Available with {confidence_scores.get(modality, 0.0)*100:.1f}% confidence")
630
+
631
+ prompt = f"""You are a medical AI assistant synthesizing multiple medical documents into a comprehensive clinical picture.
632
+
633
+ AVAILABLE DOCUMENTS:
634
+ {chr(10).join(modality_summaries)}
635
+
636
+ TASK:
637
+ Generate a unified clinical summary that:
638
+
639
+ 1. INTEGRATED CLINICAL PICTURE
640
+ - Synthesize findings across all modalities
641
+ - Identify consistent patterns
642
+ - Flag contradictions or discrepancies
643
+
644
+ 2. TIMELINE CORRELATION
645
+ - How findings relate temporally
646
+ - Disease progression or improvement
647
+
648
+ 3. COMPREHENSIVE ASSESSMENT
649
+ - Overall patient status
650
+ - Risk stratification
651
+
652
+ 4. COORDINATED CARE PLAN
653
+ - Unified recommendations
654
+ - Priority actions
655
+ - Specialist referrals
656
+
657
+ 5. CONFIDENCE SYNTHESIS
658
+ - Overall reliability of the integrated analysis
659
+ - Areas needing additional investigation
660
+
661
+ Generate the integrated clinical synthesis now:"""
662
+
663
+ return prompt
664
+
665
+ # ========================
666
+ # UTILITY METHODS
667
+ # ========================
668
+
669
+ @staticmethod
670
+ def _format_model_outputs(outputs: List[Dict[str, Any]]) -> str:
671
+ """Format model outputs for inclusion in prompts"""
672
+ if not outputs:
673
+ return "No specialized model outputs available"
674
+
675
+ formatted = []
676
+ for idx, output in enumerate(outputs[:5], 1): # Limit to top 5
677
+ model_name = output.get("model_name", "Unknown Model")
678
+ domain = output.get("domain", "general")
679
+ result = output.get("result", {})
680
+
681
+ # Extract key information from result
682
+ if isinstance(result, dict):
683
+ confidence = result.get("confidence", 0.0)
684
+ summary = result.get("summary", result.get("analysis", "Analysis completed"))[:200]
685
+ formatted.append(f"{idx}. {model_name} ({domain}): {summary}... [Confidence: {confidence*100:.1f}%]")
686
+ else:
687
+ formatted.append(f"{idx}. {model_name} ({domain}): {str(result)[:200]}...")
688
+
689
+ return "\n".join(formatted)
690
+
691
+ @staticmethod
692
+ def get_confidence_explanation_template(
693
+ confidence_scores: Dict[str, float],
694
+ modality: str
695
+ ) -> str:
696
+ """Generate prompt for explaining confidence scores"""
697
+
698
+ overall = confidence_scores.get("overall_confidence", 0.0)
699
+ extraction = confidence_scores.get("extraction_confidence", 0.0)
700
+ model = confidence_scores.get("model_confidence", 0.0)
701
+ quality = confidence_scores.get("data_quality", 0.0)
702
+
703
+ if overall >= 0.85:
704
+ threshold = "AUTO-APPROVED (≥85%)"
705
+ elif overall >= 0.60:
706
+ threshold = "REQUIRES REVIEW (60-85%)"
707
+ else:
708
+ threshold = "MANUAL REVIEW REQUIRED (<60%)"
709
+
710
+ prompt = f"""Explain the confidence scores for this {modality} analysis to a clinician:
711
+
712
+ CONFIDENCE BREAKDOWN:
713
+ - Overall Confidence: {overall*100:.1f}% [{threshold}]
714
+ - Data Extraction: {extraction*100:.1f}%
715
+ - Model Analysis: {model*100:.1f}%
716
+ - Data Quality: {quality*100:.1f}%
717
+
718
+ Generate a brief explanation that:
719
+ 1. Why this confidence level?
720
+ 2. What factors contributed to the score?
721
+ 3. What should the clinician be aware of?
722
+ 4. Is human review recommended?
723
+
724
+ Be concise and practical.
725
+
726
+ Generate the explanation now:"""
727
+
728
+ return prompt