Spaces:
Running
Running
YanBoChen
commited on
Commit
·
16a2990
1
Parent(s):
a2aaea2
Add multi-system evaluation support for clinical actionability and evidence quality metrics
Browse files- Introduced evaluation rubrics for Clinical Actionability and Clinical Evidence Quality.
- Implemented a new Llama3-70B judge client for evaluating multiple AI systems.
- Refactored evaluation methods to handle comparisons between different systems.
- Enhanced prompt generation to include detailed system descriptions and evaluation criteria.
- Updated response parsing to accommodate results from multiple systems.
- Added functionality to save comparison statistics with detailed system-specific results.
- Improved command-line interface for evaluating single or multiple systems.
evaluation/direct_llm_evaluator.py
CHANGED
|
@@ -329,7 +329,8 @@ if __name__ == "__main__":
|
|
| 329 |
if len(sys.argv) > 1:
|
| 330 |
query_file = sys.argv[1]
|
| 331 |
else:
|
| 332 |
-
|
|
|
|
| 333 |
|
| 334 |
if not os.path.exists(query_file):
|
| 335 |
print(f"❌ Query file not found: {query_file}")
|
|
|
|
| 329 |
if len(sys.argv) > 1:
|
| 330 |
query_file = sys.argv[1]
|
| 331 |
else:
|
| 332 |
+
# Default to evaluation/single_test_query.txt for consistency
|
| 333 |
+
query_file = Path(__file__).parent / "single_test_query.txt"
|
| 334 |
|
| 335 |
if not os.path.exists(query_file):
|
| 336 |
print(f"❌ Query file not found: {query_file}")
|
evaluation/metric5_6_judge_evaluator_manual.md
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Metric 5-6 LLM Judge Evaluator Manual
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
The `metric5_6_llm_judge_evaluator.py` is a multi-system evaluation tool that uses Llama3-70B as a third-party judge to assess medical advice quality across different AI systems. It supports both single-system evaluation and multi-system comparison with a single LLM call for maximum consistency.
|
| 6 |
+
|
| 7 |
+
## Metrics Evaluated
|
| 8 |
+
|
| 9 |
+
**Metric 5: Clinical Actionability (臨床可操作性)**
|
| 10 |
+
- Scale: 1-10 (normalized to 0.0-1.0)
|
| 11 |
+
- Question: "Can healthcare providers immediately act on this advice?"
|
| 12 |
+
- Target: ≥7.0/10 for acceptable actionability
|
| 13 |
+
|
| 14 |
+
**Metric 6: Clinical Evidence Quality (臨床證據品質)**
|
| 15 |
+
- Scale: 1-10 (normalized to 0.0-1.0)
|
| 16 |
+
- Question: "Is the advice evidence-based and follows medical standards?"
|
| 17 |
+
- Target: ≥7.5/10 for acceptable evidence quality
|
| 18 |
+
|
| 19 |
+
## System Architecture
|
| 20 |
+
|
| 21 |
+
### Multi-System Support
|
| 22 |
+
The evaluator supports flexible system combinations:
|
| 23 |
+
- **Single System**: `rag` or `direct`
|
| 24 |
+
- **Two-System Comparison**: `rag,direct`
|
| 25 |
+
- **Future Extension**: `rag,direct,claude,gpt4` (any combination)
|
| 26 |
+
|
| 27 |
+
### Judge LLM
|
| 28 |
+
- **Model**: Llama3-70B-Instruct via Hugging Face API
|
| 29 |
+
- **Strategy**: Single batch call for all evaluations
|
| 30 |
+
- **Temperature**: 0.1 (low for consistent evaluation)
|
| 31 |
+
- **Max Tokens**: 2048 (sufficient for evaluation responses)
|
| 32 |
+
|
| 33 |
+
## Prerequisites
|
| 34 |
+
|
| 35 |
+
### 1. Environment Setup
|
| 36 |
+
```bash
|
| 37 |
+
# Ensure HF_TOKEN is set in your environment
|
| 38 |
+
export HF_TOKEN="your_huggingface_token"
|
| 39 |
+
|
| 40 |
+
# Or add to .env file
|
| 41 |
+
echo "HF_TOKEN=your_huggingface_token" >> .env
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
### 2. Required Data Files
|
| 45 |
+
Before running the judge evaluator, you must have medical outputs from your systems:
|
| 46 |
+
|
| 47 |
+
**For RAG System**:
|
| 48 |
+
```bash
|
| 49 |
+
python latency_evaluator.py single_test_query.txt
|
| 50 |
+
# Generates: results/medical_outputs_YYYYMMDD_HHMMSS.json
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
**For Direct LLM System**:
|
| 54 |
+
```bash
|
| 55 |
+
python direct_llm_evaluator.py single_test_query.txt
|
| 56 |
+
# Generates: results/medical_outputs_direct_YYYYMMDD_HHMMSS.json
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## Usage
|
| 60 |
+
|
| 61 |
+
### Command Line Interface
|
| 62 |
+
|
| 63 |
+
#### Single System Evaluation
|
| 64 |
+
```bash
|
| 65 |
+
# Evaluate RAG system only
|
| 66 |
+
python metric5_6_llm_judge_evaluator.py rag
|
| 67 |
+
|
| 68 |
+
# Evaluate Direct LLM system only
|
| 69 |
+
python metric5_6_llm_judge_evaluator.py direct
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
#### Multi-System Comparison (Recommended)
|
| 73 |
+
```bash
|
| 74 |
+
# Compare RAG vs Direct systems
|
| 75 |
+
python metric5_6_llm_judge_evaluator.py rag,direct
|
| 76 |
+
|
| 77 |
+
# Future: Compare multiple systems
|
| 78 |
+
python metric5_6_llm_judge_evaluator.py rag,direct,claude
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
### Complete Workflow Example
|
| 82 |
+
|
| 83 |
+
```bash
|
| 84 |
+
# Step 1: Navigate to evaluation directory
|
| 85 |
+
cd /path/to/GenAI-OnCallAssistant/evaluation
|
| 86 |
+
|
| 87 |
+
# Step 2: Generate medical outputs from both systems
|
| 88 |
+
python latency_evaluator.py single_test_query.txt
|
| 89 |
+
python direct_llm_evaluator.py single_test_query.txt
|
| 90 |
+
|
| 91 |
+
# Step 3: Run comparative evaluation
|
| 92 |
+
python metric5_6_llm_judge_evaluator.py rag,direct
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
## Output Files
|
| 96 |
+
|
| 97 |
+
### Generated Files
|
| 98 |
+
- **Statistics**: `results/judge_evaluation_comparison_rag_vs_direct_YYYYMMDD_HHMMSS.json`
|
| 99 |
+
- **Detailed Results**: Stored in evaluator's internal results array
|
| 100 |
+
|
| 101 |
+
### File Structure
|
| 102 |
+
```json
|
| 103 |
+
{
|
| 104 |
+
"comparison_metadata": {
|
| 105 |
+
"systems_compared": ["rag", "direct"],
|
| 106 |
+
"comparison_type": "multi_system",
|
| 107 |
+
"timestamp": "2025-08-04T22:00:00"
|
| 108 |
+
},
|
| 109 |
+
"category_results": {
|
| 110 |
+
"diagnosis": {
|
| 111 |
+
"average_actionability": 0.850,
|
| 112 |
+
"average_evidence": 0.780,
|
| 113 |
+
"query_count": 1,
|
| 114 |
+
"actionability_target_met": true,
|
| 115 |
+
"evidence_target_met": true
|
| 116 |
+
}
|
| 117 |
+
},
|
| 118 |
+
"overall_results": {
|
| 119 |
+
"average_actionability": 0.850,
|
| 120 |
+
"average_evidence": 0.780,
|
| 121 |
+
"successful_evaluations": 2,
|
| 122 |
+
"total_queries": 2,
|
| 123 |
+
"actionability_target_met": true,
|
| 124 |
+
"evidence_target_met": true
|
| 125 |
+
}
|
| 126 |
+
}
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
## Evaluation Process
|
| 130 |
+
|
| 131 |
+
### 1. File Discovery
|
| 132 |
+
The evaluator automatically finds the latest medical output files:
|
| 133 |
+
- **RAG**: `medical_outputs_*.json`
|
| 134 |
+
- **Direct**: `medical_outputs_direct_*.json`
|
| 135 |
+
- **Custom**: `medical_outputs_{system}_*.json`
|
| 136 |
+
|
| 137 |
+
### 2. Prompt Generation
|
| 138 |
+
For multi-system comparison, the evaluator creates a structured prompt:
|
| 139 |
+
```
|
| 140 |
+
You are a medical expert evaluating and comparing AI systems...
|
| 141 |
+
|
| 142 |
+
SYSTEM 1 (RAG): Uses medical guidelines + LLM for evidence-based advice
|
| 143 |
+
SYSTEM 2 (Direct): Uses LLM only without external guidelines
|
| 144 |
+
|
| 145 |
+
QUERY 1 (DIAGNOSIS):
|
| 146 |
+
Patient Query: 60-year-old patient with hypertension history...
|
| 147 |
+
|
| 148 |
+
SYSTEM 1 Response: For a 60-year-old patient with...
|
| 149 |
+
SYSTEM 2 Response: Based on the symptoms described...
|
| 150 |
+
|
| 151 |
+
RESPONSE FORMAT:
|
| 152 |
+
Query 1 System 1: Actionability=X, Evidence=Y
|
| 153 |
+
Query 1 System 2: Actionability=X, Evidence=Y
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
### 3. LLM Judge Evaluation
|
| 157 |
+
- **Single API Call**: All systems evaluated in one request for consistency
|
| 158 |
+
- **Response Parsing**: Automatic extraction of numerical scores
|
| 159 |
+
- **Error Handling**: Graceful handling of parsing failures
|
| 160 |
+
|
| 161 |
+
### 4. Results Analysis
|
| 162 |
+
- **System-Specific Statistics**: Individual performance metrics
|
| 163 |
+
- **Comparative Analysis**: Direct system-to-system comparison
|
| 164 |
+
- **Target Compliance**: Automatic threshold checking
|
| 165 |
+
|
| 166 |
+
## Expected Output
|
| 167 |
+
|
| 168 |
+
### Console Output Example
|
| 169 |
+
```
|
| 170 |
+
🧠 OnCall.ai LLM Judge Evaluator - Metrics 5-6 Multi-System Evaluation
|
| 171 |
+
|
| 172 |
+
🧪 Multi-System Comparison: RAG vs DIRECT
|
| 173 |
+
📊 Found rag outputs: results/medical_outputs_20250804_215917.json
|
| 174 |
+
📊 Found direct outputs: results/medical_outputs_direct_20250804_220000.json
|
| 175 |
+
📊 Comparing 2 systems with 1 queries each
|
| 176 |
+
🎯 Metrics: 5 (Actionability) + 6 (Evidence Quality)
|
| 177 |
+
⚡ Strategy: Single comparison call for maximum consistency
|
| 178 |
+
|
| 179 |
+
🧠 Multi-system comparison: rag, direct
|
| 180 |
+
📊 Evaluating 1 queries across 2 systems...
|
| 181 |
+
📝 Comparison prompt created (2150 characters)
|
| 182 |
+
🔄 Calling judge LLM for multi-system comparison...
|
| 183 |
+
✅ Judge LLM completed comparison evaluation in 45.3s
|
| 184 |
+
📄 Response length: 145 characters
|
| 185 |
+
📊 RAG: 1 evaluations parsed
|
| 186 |
+
📊 DIRECT: 1 evaluations parsed
|
| 187 |
+
|
| 188 |
+
📊 === LLM JUDGE EVALUATION SUMMARY ===
|
| 189 |
+
Systems Compared: RAG vs DIRECT
|
| 190 |
+
Overall Performance:
|
| 191 |
+
Average Actionability: 0.850 (8.5/10)
|
| 192 |
+
Average Evidence Quality: 0.780 (7.8/10)
|
| 193 |
+
Actionability Target (≥7.0): ✅ Met
|
| 194 |
+
Evidence Target (≥7.5): ✅ Met
|
| 195 |
+
|
| 196 |
+
System Breakdown:
|
| 197 |
+
RAG: Actionability=0.900, Evidence=0.850 [1 queries]
|
| 198 |
+
DIRECT: Actionability=0.800, Evidence=0.710 [1 queries]
|
| 199 |
+
|
| 200 |
+
✅ LLM judge evaluation complete!
|
| 201 |
+
📊 Statistics: results/judge_evaluation_comparison_rag_vs_direct_20250804_220000.json
|
| 202 |
+
⚡ Efficiency: 2 evaluations in 1 LLM call
|
| 203 |
+
```
|
| 204 |
+
|
| 205 |
+
## Key Features
|
| 206 |
+
|
| 207 |
+
### 1. Scientific Comparison Design
|
| 208 |
+
- **Single Judge Call**: All systems evaluated simultaneously for consistency
|
| 209 |
+
- **Eliminates Temporal Bias**: Same judge, same context, same standards
|
| 210 |
+
- **Direct System Comparison**: Side-by-side evaluation format
|
| 211 |
+
|
| 212 |
+
### 2. Flexible Architecture
|
| 213 |
+
- **Backward Compatible**: Single system evaluation still supported
|
| 214 |
+
- **Future Extensible**: Easy to add new systems (`claude`, `gpt4`, etc.)
|
| 215 |
+
- **Modular Design**: Clean separation of concerns
|
| 216 |
+
|
| 217 |
+
### 3. Robust Error Handling
|
| 218 |
+
- **File Validation**: Automatic detection of missing input files
|
| 219 |
+
- **Query Count Verification**: Warns if systems have different query counts
|
| 220 |
+
- **Graceful Degradation**: Continues operation despite partial failures
|
| 221 |
+
|
| 222 |
+
### 4. Comprehensive Reporting
|
| 223 |
+
- **System-Specific Metrics**: Individual performance analysis
|
| 224 |
+
- **Comparative Statistics**: Direct system-to-system comparison
|
| 225 |
+
- **Target Compliance**: Automatic benchmark checking
|
| 226 |
+
- **Detailed Metadata**: Full traceability of evaluation parameters
|
| 227 |
+
|
| 228 |
+
## Troubleshooting
|
| 229 |
+
|
| 230 |
+
### Common Issues
|
| 231 |
+
|
| 232 |
+
#### 1. Missing Input Files
|
| 233 |
+
```
|
| 234 |
+
❌ No medical outputs files found for rag system
|
| 235 |
+
💡 Please run evaluators first:
|
| 236 |
+
python latency_evaluator.py single_test_query.txt
|
| 237 |
+
```
|
| 238 |
+
**Solution**: Run the prerequisite evaluators to generate medical outputs.
|
| 239 |
+
|
| 240 |
+
#### 2. HF_TOKEN Not Set
|
| 241 |
+
```
|
| 242 |
+
❌ HF_TOKEN is missing from environment variables
|
| 243 |
+
```
|
| 244 |
+
**Solution**: Set your Hugging Face token in environment or `.env` file.
|
| 245 |
+
|
| 246 |
+
#### 3. Query Count Mismatch
|
| 247 |
+
```
|
| 248 |
+
⚠️ Warning: Systems have different query counts: {'rag': 3, 'direct': 1}
|
| 249 |
+
```
|
| 250 |
+
**Solution**: Ensure both systems processed the same input file.
|
| 251 |
+
|
| 252 |
+
#### 4. LLM API Timeout
|
| 253 |
+
```
|
| 254 |
+
❌ Multi-system evaluation failed: timeout
|
| 255 |
+
```
|
| 256 |
+
**Solution**: Check internet connection and Hugging Face API status.
|
| 257 |
+
|
| 258 |
+
### Debug Tips
|
| 259 |
+
|
| 260 |
+
1. **Check File Existence**: Verify medical output files in `results/` directory
|
| 261 |
+
2. **Validate JSON Format**: Ensure input files are properly formatted
|
| 262 |
+
3. **Monitor API Usage**: Check Hugging Face account limits
|
| 263 |
+
4. **Review Logs**: Examine detailed logging output for specific errors
|
| 264 |
+
|
| 265 |
+
## Future Extensions
|
| 266 |
+
|
| 267 |
+
### Phase 2: Generic Multi-System Framework
|
| 268 |
+
```bash
|
| 269 |
+
# Configuration-driven system comparison
|
| 270 |
+
python metric5_6_llm_judge_evaluator.py --config comparison_config.json
|
| 271 |
+
```
|
| 272 |
+
|
| 273 |
+
### Phase 3: Unlimited System Support
|
| 274 |
+
```bash
|
| 275 |
+
# Dynamic system registration
|
| 276 |
+
python metric5_6_llm_judge_evaluator.py med42,claude,gpt4,palm,llama2
|
| 277 |
+
```
|
| 278 |
+
|
| 279 |
+
### Integration with Chart Generators
|
| 280 |
+
```bash
|
| 281 |
+
# Generate comparison visualizations
|
| 282 |
+
python metric5_6_llm_judge_chart_generator.py rag,direct
|
| 283 |
+
```
|
| 284 |
+
|
| 285 |
+
## Best Practices
|
| 286 |
+
|
| 287 |
+
1. **Consistent Test Data**: Use the same query file for all systems
|
| 288 |
+
2. **Sequential Execution**: Complete data collection before evaluation
|
| 289 |
+
3. **Batch Processing**: Use multi-system mode for scientific comparison
|
| 290 |
+
4. **Result Verification**: Review detailed statistics files for accuracy
|
| 291 |
+
5. **Performance Monitoring**: Track evaluation latency and API costs
|
| 292 |
+
|
| 293 |
+
## Scientific Validity
|
| 294 |
+
|
| 295 |
+
The multi-system comparison approach provides superior scientific validity compared to separate evaluations:
|
| 296 |
+
|
| 297 |
+
- **Eliminates Judge Variability**: Same judge evaluates all systems
|
| 298 |
+
- **Reduces Temporal Effects**: All evaluations in single time window
|
| 299 |
+
- **Ensures Consistent Standards**: Identical evaluation criteria applied
|
| 300 |
+
- **Enables Direct Comparison**: Side-by-side system assessment
|
| 301 |
+
- **Maximizes Efficiency**: Single API call vs multiple separate calls
|
| 302 |
+
|
| 303 |
+
This design makes the evaluation results more reliable for research publications and system optimization decisions.
|
evaluation/metric5_6_llm_judge_chart_generator.py
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
OnCall.ai System - LLM Judge Chart Generator (Metrics 5-6)
|
| 4 |
+
==========================================================
|
| 5 |
+
|
| 6 |
+
Generates comprehensive comparison charts for LLM judge evaluation results.
|
| 7 |
+
Supports both single-system and multi-system visualization with professional layouts.
|
| 8 |
+
|
| 9 |
+
Metrics visualized:
|
| 10 |
+
5. Clinical Actionability (臨床可操作性) - 1-10 scale
|
| 11 |
+
6. Clinical Evidence Quality (臨床證據品質) - 1-10 scale
|
| 12 |
+
|
| 13 |
+
Author: YanBo Chen
|
| 14 |
+
Date: 2025-08-04
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
from typing import Dict, List, Any, Tuple
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
import glob
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
# Visualization imports
|
| 27 |
+
import matplotlib.pyplot as plt
|
| 28 |
+
import seaborn as sns
|
| 29 |
+
import pandas as pd
|
| 30 |
+
from matplotlib.patches import Rectangle
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class LLMJudgeChartGenerator:
|
| 34 |
+
"""Generate professional comparison charts for LLM judge evaluation results"""
|
| 35 |
+
|
| 36 |
+
def __init__(self):
|
| 37 |
+
"""Initialize chart generator with professional styling"""
|
| 38 |
+
print("📈 Initializing LLM Judge Chart Generator...")
|
| 39 |
+
|
| 40 |
+
# Set up professional chart style
|
| 41 |
+
plt.style.use('default')
|
| 42 |
+
sns.set_palette("husl")
|
| 43 |
+
|
| 44 |
+
# Professional color scheme for medical evaluation
|
| 45 |
+
self.colors = {
|
| 46 |
+
'rag': '#2E8B57', # Sea Green - represents evidence-based
|
| 47 |
+
'direct': '#4682B4', # Steel Blue - represents direct approach
|
| 48 |
+
'claude': '#9370DB', # Medium Purple - future extension
|
| 49 |
+
'gpt4': '#DC143C', # Crimson - future extension
|
| 50 |
+
'actionability': '#FF6B6B', # Coral Red
|
| 51 |
+
'evidence': '#4ECDC4', # Turquoise
|
| 52 |
+
'target_line': '#FF4444', # Red for target thresholds
|
| 53 |
+
'grid': '#E0E0E0' # Light gray for grid
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
print("✅ Chart Generator ready with professional medical styling")
|
| 57 |
+
|
| 58 |
+
def load_latest_statistics(self, results_dir: str = None) -> Dict[str, Any]:
|
| 59 |
+
"""
|
| 60 |
+
Load the most recent judge evaluation statistics file
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
results_dir: Directory containing statistics files
|
| 64 |
+
"""
|
| 65 |
+
if results_dir is None:
|
| 66 |
+
results_dir = Path(__file__).parent / "results"
|
| 67 |
+
|
| 68 |
+
# Find latest comparison statistics file
|
| 69 |
+
pattern = str(results_dir / "judge_evaluation_comparison_*.json")
|
| 70 |
+
stat_files = glob.glob(pattern)
|
| 71 |
+
|
| 72 |
+
if not stat_files:
|
| 73 |
+
raise FileNotFoundError(f"No judge evaluation comparison files found in {results_dir}")
|
| 74 |
+
|
| 75 |
+
# Get the most recent file
|
| 76 |
+
latest_file = max(stat_files, key=os.path.getmtime)
|
| 77 |
+
|
| 78 |
+
print(f"📊 Loading statistics from: {latest_file}")
|
| 79 |
+
|
| 80 |
+
with open(latest_file, 'r', encoding='utf-8') as f:
|
| 81 |
+
return json.load(f)
|
| 82 |
+
|
| 83 |
+
def generate_comparison_charts(self, stats: Dict[str, Any], save_path: str = None) -> str:
|
| 84 |
+
"""
|
| 85 |
+
Generate comprehensive 4-panel comparison visualization
|
| 86 |
+
|
| 87 |
+
Creates professional charts showing:
|
| 88 |
+
1. System comparison radar chart
|
| 89 |
+
2. Grouped bar chart comparison
|
| 90 |
+
3. Actionability vs Evidence scatter plot
|
| 91 |
+
4. Category-wise heatmap
|
| 92 |
+
"""
|
| 93 |
+
try:
|
| 94 |
+
# Create figure with subplots
|
| 95 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 96 |
+
fig.suptitle(
|
| 97 |
+
'Medical AI Systems Comparison - Clinical Quality Assessment\n'
|
| 98 |
+
'Actionability (1-10): Can healthcare providers act immediately? | '
|
| 99 |
+
'Evidence Quality (1-10): Is advice evidence-based?',
|
| 100 |
+
fontsize=14, fontweight='bold', y=0.95
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Extract comparison metadata
|
| 104 |
+
comparison_meta = stats.get('comparison_metadata', {})
|
| 105 |
+
systems = comparison_meta.get('systems_compared', ['rag', 'direct'])
|
| 106 |
+
|
| 107 |
+
overall_results = stats['overall_results']
|
| 108 |
+
category_results = stats['category_results']
|
| 109 |
+
|
| 110 |
+
# Chart 1: System Comparison Radar Chart
|
| 111 |
+
self._create_radar_chart(axes[0, 0], stats, systems)
|
| 112 |
+
|
| 113 |
+
# Chart 2: Grouped Bar Chart Comparison
|
| 114 |
+
self._create_grouped_bar_chart(axes[0, 1], stats, systems)
|
| 115 |
+
|
| 116 |
+
# Chart 3: Actionability vs Evidence Scatter Plot
|
| 117 |
+
self._create_scatter_plot(axes[1, 0], stats, systems)
|
| 118 |
+
|
| 119 |
+
# Chart 4: Category-wise Performance Heatmap
|
| 120 |
+
self._create_heatmap(axes[1, 1], stats, systems)
|
| 121 |
+
|
| 122 |
+
# Add method annotation at bottom
|
| 123 |
+
method_text = (
|
| 124 |
+
f"Evaluation: Llama3-70B judge | Targets: Actionability ≥7.0, Evidence ≥7.5 | "
|
| 125 |
+
f"Systems: {', '.join([s.upper() for s in systems])} | "
|
| 126 |
+
f"Queries: {overall_results.get('total_queries', 'N/A')}"
|
| 127 |
+
)
|
| 128 |
+
fig.text(0.5, 0.02, method_text, ha='center', fontsize=10,
|
| 129 |
+
style='italic', color='gray')
|
| 130 |
+
|
| 131 |
+
# Adjust layout
|
| 132 |
+
plt.tight_layout()
|
| 133 |
+
plt.subplots_adjust(top=0.88, bottom=0.08)
|
| 134 |
+
|
| 135 |
+
# Save the chart
|
| 136 |
+
if save_path is None:
|
| 137 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 138 |
+
systems_str = "_vs_".join(systems)
|
| 139 |
+
save_path = f"judge_comparison_charts_{systems_str}_{timestamp}.png"
|
| 140 |
+
|
| 141 |
+
results_dir = Path(__file__).parent / "results"
|
| 142 |
+
results_dir.mkdir(exist_ok=True)
|
| 143 |
+
full_path = results_dir / save_path
|
| 144 |
+
|
| 145 |
+
plt.savefig(full_path, dpi=300, bbox_inches='tight')
|
| 146 |
+
plt.show()
|
| 147 |
+
|
| 148 |
+
print(f"📊 Comparison charts saved to: {full_path}")
|
| 149 |
+
return str(full_path)
|
| 150 |
+
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"❌ Chart generation failed: {e}")
|
| 153 |
+
raise
|
| 154 |
+
|
| 155 |
+
def _create_radar_chart(self, ax, stats: Dict, systems: List[str]):
|
| 156 |
+
"""Create radar chart for multi-dimensional system comparison"""
|
| 157 |
+
ax.set_title('Multi-Dimensional System Comparison', fontweight='bold', pad=20)
|
| 158 |
+
|
| 159 |
+
# Prepare data for radar chart using real system-specific data
|
| 160 |
+
categories = ['Overall Actionability', 'Overall Evidence', 'Diagnosis', 'Treatment', 'Mixed']
|
| 161 |
+
|
| 162 |
+
# Extract real system-specific metrics
|
| 163 |
+
detailed_results = stats.get('detailed_system_results', {})
|
| 164 |
+
system_data = {}
|
| 165 |
+
|
| 166 |
+
for system in systems:
|
| 167 |
+
if system in detailed_results:
|
| 168 |
+
system_info = detailed_results[system]
|
| 169 |
+
system_results = system_info['results']
|
| 170 |
+
|
| 171 |
+
# Calculate category-specific performance
|
| 172 |
+
category_performance = {}
|
| 173 |
+
for result in system_results:
|
| 174 |
+
category = result.get('category', 'unknown').lower()
|
| 175 |
+
if category not in category_performance:
|
| 176 |
+
category_performance[category] = {'actionability': [], 'evidence': []}
|
| 177 |
+
category_performance[category]['actionability'].append(result['actionability_score'])
|
| 178 |
+
category_performance[category]['evidence'].append(result['evidence_score'])
|
| 179 |
+
|
| 180 |
+
# Build radar chart data
|
| 181 |
+
system_scores = [
|
| 182 |
+
system_info['avg_actionability'], # Overall Actionability
|
| 183 |
+
system_info['avg_evidence'], # Overall Evidence
|
| 184 |
+
# Category-specific scores (average of actionability and evidence)
|
| 185 |
+
(sum(category_performance.get('diagnosis', {}).get('actionability', [0])) /
|
| 186 |
+
len(category_performance.get('diagnosis', {}).get('actionability', [1])) +
|
| 187 |
+
sum(category_performance.get('diagnosis', {}).get('evidence', [0])) /
|
| 188 |
+
len(category_performance.get('diagnosis', {}).get('evidence', [1]))) / 2 if 'diagnosis' in category_performance else 0.5,
|
| 189 |
+
|
| 190 |
+
(sum(category_performance.get('treatment', {}).get('actionability', [0])) /
|
| 191 |
+
len(category_performance.get('treatment', {}).get('actionability', [1])) +
|
| 192 |
+
sum(category_performance.get('treatment', {}).get('evidence', [0])) /
|
| 193 |
+
len(category_performance.get('treatment', {}).get('evidence', [1]))) / 2 if 'treatment' in category_performance else 0.5,
|
| 194 |
+
|
| 195 |
+
(sum(category_performance.get('mixed', {}).get('actionability', [0])) /
|
| 196 |
+
len(category_performance.get('mixed', {}).get('actionability', [1])) +
|
| 197 |
+
sum(category_performance.get('mixed', {}).get('evidence', [0])) /
|
| 198 |
+
len(category_performance.get('mixed', {}).get('evidence', [1]))) / 2 if 'mixed' in category_performance else 0.5
|
| 199 |
+
]
|
| 200 |
+
system_data[system] = system_scores
|
| 201 |
+
else:
|
| 202 |
+
# Fallback to overall stats if detailed results not available
|
| 203 |
+
overall_results = stats['overall_results']
|
| 204 |
+
system_data[system] = [
|
| 205 |
+
overall_results['average_actionability'],
|
| 206 |
+
overall_results['average_evidence'],
|
| 207 |
+
0.7, 0.6, 0.5 # Placeholder for missing category data
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
# Create radar chart
|
| 211 |
+
angles = np.linspace(0, 2 * np.pi, len(categories), endpoint=False).tolist()
|
| 212 |
+
angles += angles[:1] # Complete the circle
|
| 213 |
+
|
| 214 |
+
for system in systems:
|
| 215 |
+
values = system_data[system] + [system_data[system][0]] # Complete the circle
|
| 216 |
+
ax.plot(angles, values, 'o-', linewidth=2,
|
| 217 |
+
label=f'{system.upper()} System', color=self.colors.get(system, 'gray'))
|
| 218 |
+
ax.fill(angles, values, alpha=0.1, color=self.colors.get(system, 'gray'))
|
| 219 |
+
|
| 220 |
+
# Customize radar chart
|
| 221 |
+
ax.set_xticks(angles[:-1])
|
| 222 |
+
ax.set_xticklabels(categories, fontsize=9)
|
| 223 |
+
ax.set_ylim(0, 1)
|
| 224 |
+
ax.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
|
| 225 |
+
ax.set_yticklabels(['2.0', '4.0', '6.0', '8.0', '10.0'])
|
| 226 |
+
ax.grid(True, alpha=0.3)
|
| 227 |
+
ax.legend(loc='upper right', bbox_to_anchor=(1.2, 1.0))
|
| 228 |
+
|
| 229 |
+
# Add target threshold circle
|
| 230 |
+
target_circle = [0.7] * (len(categories) + 1) # 7.0 threshold
|
| 231 |
+
ax.plot(angles, target_circle, '--', color=self.colors['target_line'],
|
| 232 |
+
alpha=0.7, label='Target (7.0)')
|
| 233 |
+
|
| 234 |
+
def _create_grouped_bar_chart(self, ax, stats: Dict, systems: List[str]):
|
| 235 |
+
"""Create grouped bar chart for direct metric comparison"""
|
| 236 |
+
ax.set_title('Direct Metric Comparison', fontweight='bold', pad=20)
|
| 237 |
+
|
| 238 |
+
# Prepare data using real system-specific metrics
|
| 239 |
+
metrics = ['Actionability', 'Evidence Quality']
|
| 240 |
+
detailed_results = stats.get('detailed_system_results', {})
|
| 241 |
+
|
| 242 |
+
# Extract real system-specific data
|
| 243 |
+
system_scores = {}
|
| 244 |
+
for system in systems:
|
| 245 |
+
if system in detailed_results:
|
| 246 |
+
system_info = detailed_results[system]
|
| 247 |
+
system_scores[system] = [
|
| 248 |
+
system_info['avg_actionability'],
|
| 249 |
+
system_info['avg_evidence']
|
| 250 |
+
]
|
| 251 |
+
else:
|
| 252 |
+
# Fallback to overall results
|
| 253 |
+
overall_results = stats['overall_results']
|
| 254 |
+
system_scores[system] = [
|
| 255 |
+
overall_results['average_actionability'],
|
| 256 |
+
overall_results['average_evidence']
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
# Create grouped bar chart
|
| 260 |
+
x = np.arange(len(metrics))
|
| 261 |
+
width = 0.35 if len(systems) == 2 else 0.25
|
| 262 |
+
|
| 263 |
+
for i, system in enumerate(systems):
|
| 264 |
+
offset = (i - len(systems)/2 + 0.5) * width
|
| 265 |
+
bars = ax.bar(x + offset, system_scores[system], width,
|
| 266 |
+
label=f'{system.upper()}', color=self.colors.get(system, 'gray'),
|
| 267 |
+
alpha=0.8)
|
| 268 |
+
|
| 269 |
+
# Add value labels on bars
|
| 270 |
+
for bar, value in zip(bars, system_scores[system]):
|
| 271 |
+
height = bar.get_height()
|
| 272 |
+
ax.text(bar.get_x() + bar.get_width()/2., height + 0.01,
|
| 273 |
+
f'{value:.3f}', ha='center', va='bottom', fontweight='bold')
|
| 274 |
+
|
| 275 |
+
# Add target threshold lines
|
| 276 |
+
ax.axhline(y=0.7, color=self.colors['target_line'], linestyle='--',
|
| 277 |
+
alpha=0.7, label='Actionability Target (7.0)')
|
| 278 |
+
ax.axhline(y=0.75, color=self.colors['target_line'], linestyle=':',
|
| 279 |
+
alpha=0.7, label='Evidence Target (7.5)')
|
| 280 |
+
|
| 281 |
+
# Customize chart
|
| 282 |
+
ax.set_xlabel('Evaluation Metrics')
|
| 283 |
+
ax.set_ylabel('Score (0-1 scale)')
|
| 284 |
+
ax.set_title('System Performance Comparison')
|
| 285 |
+
ax.set_xticks(x)
|
| 286 |
+
ax.set_xticklabels(metrics)
|
| 287 |
+
ax.legend(loc='upper left')
|
| 288 |
+
ax.grid(True, alpha=0.3, axis='y')
|
| 289 |
+
ax.set_ylim(0, 1.0)
|
| 290 |
+
|
| 291 |
+
def _create_scatter_plot(self, ax, stats: Dict, systems: List[str]):
|
| 292 |
+
"""Create scatter plot for actionability vs evidence quality analysis"""
|
| 293 |
+
ax.set_title('Actionability vs Evidence Quality Analysis', fontweight='bold', pad=20)
|
| 294 |
+
|
| 295 |
+
# Extract real query-level data from detailed results
|
| 296 |
+
detailed_results = stats.get('detailed_system_results', {})
|
| 297 |
+
|
| 298 |
+
for system in systems:
|
| 299 |
+
if system in detailed_results:
|
| 300 |
+
system_results = detailed_results[system]['results']
|
| 301 |
+
|
| 302 |
+
# Extract real actionability and evidence scores for each query
|
| 303 |
+
actionability_scores = [r['actionability_score'] for r in system_results]
|
| 304 |
+
evidence_scores = [r['evidence_score'] for r in system_results]
|
| 305 |
+
|
| 306 |
+
ax.scatter(actionability_scores, evidence_scores,
|
| 307 |
+
label=f'{system.upper()}', color=self.colors.get(system, 'gray'),
|
| 308 |
+
alpha=0.7, s=100, edgecolors='white', linewidth=1)
|
| 309 |
+
else:
|
| 310 |
+
# Fallback: create single point from overall averages
|
| 311 |
+
overall_results = stats['overall_results']
|
| 312 |
+
ax.scatter([overall_results['average_actionability']],
|
| 313 |
+
[overall_results['average_evidence']],
|
| 314 |
+
label=f'{system.upper()}', color=self.colors.get(system, 'gray'),
|
| 315 |
+
alpha=0.7, s=100, edgecolors='white', linewidth=1)
|
| 316 |
+
|
| 317 |
+
# Add target threshold lines
|
| 318 |
+
ax.axvline(x=0.7, color=self.colors['target_line'], linestyle='--',
|
| 319 |
+
alpha=0.7, label='Actionability Target')
|
| 320 |
+
ax.axhline(y=0.75, color=self.colors['target_line'], linestyle='--',
|
| 321 |
+
alpha=0.7, label='Evidence Target')
|
| 322 |
+
|
| 323 |
+
# Add target zone
|
| 324 |
+
target_rect = Rectangle((0.7, 0.75), 0.3, 0.25, linewidth=1,
|
| 325 |
+
edgecolor=self.colors['target_line'], facecolor='green',
|
| 326 |
+
alpha=0.1, label='Target Zone')
|
| 327 |
+
ax.add_patch(target_rect)
|
| 328 |
+
|
| 329 |
+
# Customize chart
|
| 330 |
+
ax.set_xlabel('Clinical Actionability (0-1 scale)')
|
| 331 |
+
ax.set_ylabel('Clinical Evidence Quality (0-1 scale)')
|
| 332 |
+
ax.legend(loc='lower right')
|
| 333 |
+
ax.grid(True, alpha=0.3)
|
| 334 |
+
ax.set_xlim(0, 1)
|
| 335 |
+
ax.set_ylim(0, 1)
|
| 336 |
+
|
| 337 |
+
def _create_heatmap(self, ax, stats: Dict, systems: List[str]):
|
| 338 |
+
"""Create heatmap for category-wise performance matrix"""
|
| 339 |
+
ax.set_title('Category-wise Performance Matrix', fontweight='bold', pad=20)
|
| 340 |
+
|
| 341 |
+
# Prepare data
|
| 342 |
+
categories = ['Diagnosis', 'Treatment', 'Mixed']
|
| 343 |
+
metrics = ['Actionability', 'Evidence']
|
| 344 |
+
category_results = stats['category_results']
|
| 345 |
+
|
| 346 |
+
# Create data matrix
|
| 347 |
+
data_matrix = []
|
| 348 |
+
row_labels = []
|
| 349 |
+
|
| 350 |
+
for system in systems:
|
| 351 |
+
for metric in metrics:
|
| 352 |
+
row_data = []
|
| 353 |
+
for category in categories:
|
| 354 |
+
cat_key = category.lower()
|
| 355 |
+
if cat_key in category_results and category_results[cat_key]['query_count'] > 0:
|
| 356 |
+
if metric == 'Actionability':
|
| 357 |
+
value = category_results[cat_key]['average_actionability']
|
| 358 |
+
else:
|
| 359 |
+
value = category_results[cat_key]['average_evidence']
|
| 360 |
+
else:
|
| 361 |
+
value = 0.5 # Placeholder for missing data
|
| 362 |
+
row_data.append(value)
|
| 363 |
+
|
| 364 |
+
data_matrix.append(row_data)
|
| 365 |
+
row_labels.append(f'{system.upper()}\n{metric}')
|
| 366 |
+
|
| 367 |
+
# Create heatmap
|
| 368 |
+
im = ax.imshow(data_matrix, cmap='RdYlGn', aspect='auto', vmin=0, vmax=1)
|
| 369 |
+
|
| 370 |
+
# Set ticks and labels
|
| 371 |
+
ax.set_xticks(np.arange(len(categories)))
|
| 372 |
+
ax.set_yticks(np.arange(len(row_labels)))
|
| 373 |
+
ax.set_xticklabels(categories)
|
| 374 |
+
ax.set_yticklabels(row_labels, fontsize=9)
|
| 375 |
+
|
| 376 |
+
# Add text annotations
|
| 377 |
+
for i in range(len(row_labels)):
|
| 378 |
+
for j in range(len(categories)):
|
| 379 |
+
text = ax.text(j, i, f'{data_matrix[i][j]:.3f}',
|
| 380 |
+
ha='center', va='center', fontweight='bold',
|
| 381 |
+
color='white' if data_matrix[i][j] < 0.5 else 'black')
|
| 382 |
+
|
| 383 |
+
# Add colorbar
|
| 384 |
+
cbar = plt.colorbar(im, ax=ax, shrink=0.6)
|
| 385 |
+
cbar.set_label('Performance Score (0-1)', rotation=270, labelpad=15)
|
| 386 |
+
|
| 387 |
+
ax.set_xlabel('Query Categories')
|
| 388 |
+
ax.set_ylabel('System × Metric')
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# Independent execution interface
|
| 392 |
+
if __name__ == "__main__":
|
| 393 |
+
"""Independent chart generation interface"""
|
| 394 |
+
|
| 395 |
+
print("📊 OnCall.ai LLM Judge Chart Generator - Metrics 5-6 Visualization")
|
| 396 |
+
|
| 397 |
+
# Initialize generator
|
| 398 |
+
generator = LLMJudgeChartGenerator()
|
| 399 |
+
|
| 400 |
+
try:
|
| 401 |
+
# Load latest statistics
|
| 402 |
+
stats = generator.load_latest_statistics()
|
| 403 |
+
|
| 404 |
+
print(f"📈 Generating comparison charts...")
|
| 405 |
+
|
| 406 |
+
# Generate comprehensive comparison charts
|
| 407 |
+
chart_path = generator.generate_comparison_charts(stats)
|
| 408 |
+
|
| 409 |
+
# Print summary
|
| 410 |
+
comparison_meta = stats.get('comparison_metadata', {})
|
| 411 |
+
systems = comparison_meta.get('systems_compared', ['rag', 'direct'])
|
| 412 |
+
overall_results = stats['overall_results']
|
| 413 |
+
|
| 414 |
+
print(f"\n📊 === CHART GENERATION SUMMARY ===")
|
| 415 |
+
print(f"Systems Visualized: {' vs '.join([s.upper() for s in systems])}")
|
| 416 |
+
print(f"Overall Actionability: {overall_results['average_actionability']:.3f}")
|
| 417 |
+
print(f"Overall Evidence Quality: {overall_results['average_evidence']:.3f}")
|
| 418 |
+
print(f"Total Queries: {overall_results['total_queries']}")
|
| 419 |
+
print(f"Chart Components: Radar Chart, Bar Chart, Scatter Plot, Heatmap")
|
| 420 |
+
|
| 421 |
+
print(f"\n✅ Comprehensive visualization complete!")
|
| 422 |
+
print(f"📊 Charts saved to: {chart_path}")
|
| 423 |
+
print(f"💡 Tip: Charts optimized for research presentations and publications")
|
| 424 |
+
|
| 425 |
+
except FileNotFoundError as e:
|
| 426 |
+
print(f"❌ {e}")
|
| 427 |
+
print(f"💡 Please run judge evaluation first:")
|
| 428 |
+
print(" python metric5_6_llm_judge_evaluator.py rag,direct")
|
| 429 |
+
except Exception as e:
|
| 430 |
+
print(f"❌ Chart generation failed: {e}")
|
evaluation/metric5_6_llm_judge_evaluator.py
CHANGED
|
@@ -10,6 +10,22 @@ Metrics evaluated:
|
|
| 10 |
5. Clinical Actionability (臨床可操作性)
|
| 11 |
6. Clinical Evidence Quality (臨床證據品質)
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
Author: YanBo Chen
|
| 14 |
Date: 2025-08-04
|
| 15 |
"""
|
|
@@ -17,12 +33,62 @@ Date: 2025-08-04
|
|
| 17 |
import json
|
| 18 |
import os
|
| 19 |
import sys
|
|
|
|
| 20 |
from typing import Dict, List, Any, Tuple
|
| 21 |
from datetime import datetime
|
| 22 |
from pathlib import Path
|
| 23 |
import glob
|
| 24 |
import re
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# Add project path
|
| 27 |
current_dir = Path(__file__).parent
|
| 28 |
project_root = current_dir.parent
|
|
@@ -31,8 +97,7 @@ sys.path.insert(0, str(src_dir))
|
|
| 31 |
|
| 32 |
# Import LLM client for judge evaluation
|
| 33 |
try:
|
| 34 |
-
from llm_clients import
|
| 35 |
-
# TODO: Replace with actual Llama3-70B client when available
|
| 36 |
except ImportError as e:
|
| 37 |
print(f"❌ Import failed: {e}")
|
| 38 |
print("Please ensure running from project root directory")
|
|
@@ -46,10 +111,8 @@ class LLMJudgeEvaluator:
|
|
| 46 |
"""Initialize judge LLM client"""
|
| 47 |
print("🔧 Initializing LLM Judge Evaluator...")
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
|
| 51 |
-
self.judge_llm = llm_Med42_70BClient()
|
| 52 |
-
print("⚠️ Note: Using Med42 as placeholder for Llama3-70B judge")
|
| 53 |
|
| 54 |
self.evaluation_results = []
|
| 55 |
|
|
@@ -67,55 +130,109 @@ class LLMJudgeEvaluator:
|
|
| 67 |
|
| 68 |
return medical_outputs
|
| 69 |
|
| 70 |
-
def
|
| 71 |
-
"""Find
|
| 72 |
results_dir = Path(__file__).parent / "results"
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
-
return
|
| 88 |
|
| 89 |
-
def
|
| 90 |
"""
|
| 91 |
-
Create
|
| 92 |
|
| 93 |
-
|
|
|
|
| 94 |
"""
|
|
|
|
|
|
|
| 95 |
prompt_parts = [
|
| 96 |
-
"You are a medical expert evaluating clinical advice quality.",
|
| 97 |
-
"Please evaluate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
"",
|
| 99 |
-
"CRITERIA:",
|
| 100 |
"1. Clinical Actionability (1-10): Can healthcare providers immediately act on this advice?",
|
| 101 |
"2. Clinical Evidence Quality (1-10): Is the advice evidence-based and follows medical standards?",
|
| 102 |
"",
|
| 103 |
"QUERIES TO EVALUATE:",
|
| 104 |
""
|
| 105 |
-
]
|
| 106 |
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
prompt_parts.extend([
|
| 114 |
f"=== QUERY {i} ({category.upper()}) ===",
|
| 115 |
f"Patient Query: {query}",
|
| 116 |
-
f"Medical Advice: {advice}",
|
| 117 |
""
|
| 118 |
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
prompt_parts.extend([
|
| 121 |
"RESPONSE FORMAT (provide exactly this format):",
|
|
@@ -123,120 +240,135 @@ class LLMJudgeEvaluator:
|
|
| 123 |
])
|
| 124 |
|
| 125 |
# Add response format template
|
| 126 |
-
for i in range(1, len(
|
| 127 |
-
|
|
|
|
| 128 |
|
| 129 |
prompt_parts.extend([
|
| 130 |
"",
|
| 131 |
"Replace X and Y with numeric scores 1-10.",
|
| 132 |
-
"Provide only the scores in the exact format above."
|
|
|
|
| 133 |
])
|
| 134 |
|
| 135 |
return "\n".join(prompt_parts)
|
| 136 |
|
| 137 |
-
def
|
| 138 |
-
"""Parse
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
-
# Parse response format: "Query 1: Actionability=8, Evidence=7"
|
| 142 |
lines = response.strip().split('\n')
|
| 143 |
|
| 144 |
-
for
|
| 145 |
line = line.strip()
|
| 146 |
if not line:
|
| 147 |
continue
|
| 148 |
|
| 149 |
-
#
|
| 150 |
-
match = re.match(r'Query\s+(\d+):\s*Actionability\s*=\s*(\d+)\s*,\s*Evidence\s*=\s*(\d+)', line, re.IGNORECASE)
|
| 151 |
|
| 152 |
if match:
|
| 153 |
-
query_num = int(match.group(1)) - 1 #
|
| 154 |
-
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
-
if query_num < len(
|
| 158 |
-
|
|
|
|
| 159 |
|
| 160 |
result = {
|
| 161 |
"query": output.get('query', ''),
|
| 162 |
"category": output.get('category', 'unknown'),
|
| 163 |
-
"
|
| 164 |
"medical_advice": output.get('medical_advice', ''),
|
| 165 |
|
| 166 |
# Metric 5: Clinical Actionability
|
| 167 |
-
"actionability_score": actionability_score / 10.0,
|
| 168 |
"actionability_raw": actionability_score,
|
| 169 |
|
| 170 |
# Metric 6: Clinical Evidence Quality
|
| 171 |
-
"evidence_score": evidence_score / 10.0,
|
| 172 |
"evidence_raw": evidence_score,
|
| 173 |
|
| 174 |
"evaluation_success": True,
|
| 175 |
"timestamp": datetime.now().isoformat()
|
| 176 |
}
|
| 177 |
|
| 178 |
-
|
| 179 |
|
| 180 |
-
return
|
| 181 |
|
| 182 |
-
def
|
| 183 |
"""
|
| 184 |
-
|
| 185 |
|
| 186 |
Args:
|
| 187 |
-
|
| 188 |
"""
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
try:
|
| 192 |
-
# Create
|
| 193 |
-
|
| 194 |
|
| 195 |
-
print(f"📝
|
| 196 |
-
print(f"🔄 Calling judge LLM for
|
| 197 |
|
| 198 |
-
# Single LLM call for all
|
| 199 |
eval_start = time.time()
|
| 200 |
-
response = self.judge_llm.
|
| 201 |
eval_time = time.time() - eval_start
|
| 202 |
|
| 203 |
# Extract response text
|
| 204 |
response_text = response.get('content', '') if isinstance(response, dict) else str(response)
|
| 205 |
|
| 206 |
-
print(f"✅ Judge LLM completed
|
| 207 |
print(f"📄 Response length: {len(response_text)} characters")
|
| 208 |
|
| 209 |
-
# Parse
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
if len(parsed_results) != len(medical_outputs):
|
| 213 |
-
print(f"⚠️ Warning: Expected {len(medical_outputs)} results, got {len(parsed_results)}")
|
| 214 |
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
|
| 219 |
-
return
|
| 220 |
|
| 221 |
except Exception as e:
|
| 222 |
-
print(f"❌
|
| 223 |
|
| 224 |
-
# Create error results for all
|
| 225 |
-
error_results =
|
| 226 |
-
for
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
-
self.evaluation_results.extend(error_results)
|
| 240 |
return error_results
|
| 241 |
|
| 242 |
def calculate_judge_statistics(self) -> Dict[str, Any]:
|
|
@@ -309,93 +441,168 @@ class LLMJudgeEvaluator:
|
|
| 309 |
"timestamp": datetime.now().isoformat()
|
| 310 |
}
|
| 311 |
|
| 312 |
-
def
|
| 313 |
-
"""Save
|
| 314 |
stats = self.calculate_judge_statistics()
|
| 315 |
|
| 316 |
if filename is None:
|
| 317 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 318 |
-
|
|
|
|
| 319 |
|
| 320 |
results_dir = Path(__file__).parent / "results"
|
| 321 |
results_dir.mkdir(exist_ok=True)
|
| 322 |
filepath = results_dir / filename
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
with open(filepath, 'w', encoding='utf-8') as f:
|
| 325 |
json.dump(stats, f, indent=2, ensure_ascii=False)
|
| 326 |
|
| 327 |
-
print(f"📊
|
| 328 |
return str(filepath)
|
| 329 |
|
| 330 |
|
| 331 |
# Independent execution interface
|
| 332 |
if __name__ == "__main__":
|
| 333 |
-
"""Independent LLM judge evaluation interface"""
|
|
|
|
|
|
|
| 334 |
|
| 335 |
-
|
|
|
|
| 336 |
|
| 337 |
-
if len(sys.argv)
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
print("
|
| 341 |
-
print(" rag
|
| 342 |
-
print("
|
| 343 |
sys.exit(1)
|
| 344 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
# Initialize evaluator
|
| 346 |
evaluator = LLMJudgeEvaluator()
|
| 347 |
|
| 348 |
try:
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
# Print summary
|
|
|
|
| 370 |
stats = evaluator.calculate_judge_statistics()
|
| 371 |
overall_results = stats['overall_results']
|
| 372 |
-
category_results = stats['category_results']
|
| 373 |
|
| 374 |
-
print(f"\n📊 === LLM JUDGE EVALUATION SUMMARY
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
print(f"Overall Performance:")
|
| 376 |
-
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
print(f" Actionability Target (≥7.0): {'✅ Met' if overall_results['actionability_target_met'] else '❌ Not Met'}")
|
| 379 |
print(f" Evidence Target (≥7.5): {'✅ Met' if overall_results['evidence_target_met'] else '❌ Not Met'}")
|
| 380 |
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
| 388 |
|
| 389 |
print(f"\n✅ LLM judge evaluation complete!")
|
| 390 |
print(f"📊 Statistics: {stats_path}")
|
| 391 |
-
print(f"⚡ Efficiency: {
|
| 392 |
|
| 393 |
except FileNotFoundError as e:
|
| 394 |
print(f"❌ {e}")
|
| 395 |
-
print(f"💡 Please run
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
| 400 |
except Exception as e:
|
| 401 |
print(f"❌ Judge evaluation failed: {e}")
|
|
|
|
| 10 |
5. Clinical Actionability (臨床可操作性)
|
| 11 |
6. Clinical Evidence Quality (臨床證據品質)
|
| 12 |
|
| 13 |
+
EVALUATION RUBRICS:
|
| 14 |
+
|
| 15 |
+
Metric 5: Clinical Actionability (1-10 scale)
|
| 16 |
+
1-2 points: Almost no actionable advice; extremely abstract or empty responses.
|
| 17 |
+
3-4 points: Provides some directional suggestions but too vague, lacks clear steps.
|
| 18 |
+
5-6 points: Offers basic executable steps but lacks details or insufficient explanation for key aspects.
|
| 19 |
+
7-8 points: Clear and complete steps that clinicians can follow, with occasional gaps needing supplementation.
|
| 20 |
+
9-10 points: Extremely actionable with precise, step-by-step executable guidance; can be used "as-is" immediately.
|
| 21 |
+
|
| 22 |
+
Metric 6: Clinical Evidence Quality (1-10 scale)
|
| 23 |
+
1-2 points: Almost no evidence support; cites completely irrelevant or unreliable sources.
|
| 24 |
+
3-4 points: References lower quality literature or guidelines, or sources lack authority.
|
| 25 |
+
5-6 points: Uses general quality literature/guidelines but lacks depth or currency.
|
| 26 |
+
7-8 points: References reliable, authoritative sources (renowned journals or authoritative guidelines) with accurate explanations.
|
| 27 |
+
9-10 points: Rich and high-quality evidence sources (systematic reviews, RCTs, etc.) combined with latest research; enhances recommendation credibility.
|
| 28 |
+
|
| 29 |
Author: YanBo Chen
|
| 30 |
Date: 2025-08-04
|
| 31 |
"""
|
|
|
|
| 33 |
import json
|
| 34 |
import os
|
| 35 |
import sys
|
| 36 |
+
import time
|
| 37 |
from typing import Dict, List, Any, Tuple
|
| 38 |
from datetime import datetime
|
| 39 |
from pathlib import Path
|
| 40 |
import glob
|
| 41 |
import re
|
| 42 |
|
| 43 |
+
# Evaluation Rubrics as programmable constants
|
| 44 |
+
ACTIONABILITY_RUBRIC = {
|
| 45 |
+
(1, 2): "Almost no actionable advice; extremely abstract or empty responses.",
|
| 46 |
+
(3, 4): "Provides some directional suggestions but too vague, lacks clear steps.",
|
| 47 |
+
(5, 6): "Offers basic executable steps but lacks details or insufficient explanation for key aspects.",
|
| 48 |
+
(7, 8): "Clear and complete steps that clinicians can follow, with occasional gaps needing supplementation.",
|
| 49 |
+
(9, 10): "Extremely actionable with precise, step-by-step executable guidance; can be used 'as-is' immediately."
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
EVIDENCE_RUBRIC = {
|
| 53 |
+
(1, 2): "Almost no evidence support; cites completely irrelevant or unreliable sources.",
|
| 54 |
+
(3, 4): "References lower quality literature or guidelines, or sources lack authority.",
|
| 55 |
+
(5, 6): "Uses general quality literature/guidelines but lacks depth or currency.",
|
| 56 |
+
(7, 8): "References reliable, authoritative sources (renowned journals or authoritative guidelines) with accurate explanations.",
|
| 57 |
+
(9, 10): "Rich and high-quality evidence sources (systematic reviews, RCTs, etc.) combined with latest research; enhances recommendation credibility."
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
def print_evaluation_rubrics():
|
| 61 |
+
"""Print detailed evaluation rubrics for reference"""
|
| 62 |
+
print("=" * 60)
|
| 63 |
+
print("CLINICAL EVALUATION RUBRICS")
|
| 64 |
+
print("=" * 60)
|
| 65 |
+
|
| 66 |
+
print("\n🎯 METRIC 5: Clinical Actionability (1-10 scale)")
|
| 67 |
+
print("-" * 50)
|
| 68 |
+
for score_range, description in ACTIONABILITY_RUBRIC.items():
|
| 69 |
+
print(f"{score_range[0]}–{score_range[1]} points: {description}")
|
| 70 |
+
|
| 71 |
+
print("\n📚 METRIC 6: Clinical Evidence Quality (1-10 scale)")
|
| 72 |
+
print("-" * 50)
|
| 73 |
+
for score_range, description in EVIDENCE_RUBRIC.items():
|
| 74 |
+
print(f"{score_range[0]}–{score_range[1]} points: {description}")
|
| 75 |
+
|
| 76 |
+
print("\n" + "=" * 60)
|
| 77 |
+
print("TARGET THRESHOLDS:")
|
| 78 |
+
print("• Actionability: ≥7.0 (Acceptable clinical utility)")
|
| 79 |
+
print("• Evidence Quality: ≥7.5 (Reliable evidence support)")
|
| 80 |
+
print("=" * 60)
|
| 81 |
+
|
| 82 |
+
def get_rubric_description(score: int, metric_type: str) -> str:
|
| 83 |
+
"""Get rubric description for a given score and metric type"""
|
| 84 |
+
rubric = ACTIONABILITY_RUBRIC if metric_type == "actionability" else EVIDENCE_RUBRIC
|
| 85 |
+
|
| 86 |
+
for score_range, description in rubric.items():
|
| 87 |
+
if score_range[0] <= score <= score_range[1]:
|
| 88 |
+
return description
|
| 89 |
+
|
| 90 |
+
return "Score out of valid range (1-10)"
|
| 91 |
+
|
| 92 |
# Add project path
|
| 93 |
current_dir = Path(__file__).parent
|
| 94 |
project_root = current_dir.parent
|
|
|
|
| 97 |
|
| 98 |
# Import LLM client for judge evaluation
|
| 99 |
try:
|
| 100 |
+
from llm_clients import llm_Llama3_70B_JudgeClient
|
|
|
|
| 101 |
except ImportError as e:
|
| 102 |
print(f"❌ Import failed: {e}")
|
| 103 |
print("Please ensure running from project root directory")
|
|
|
|
| 111 |
"""Initialize judge LLM client"""
|
| 112 |
print("🔧 Initializing LLM Judge Evaluator...")
|
| 113 |
|
| 114 |
+
# Initialize Llama3-70B as judge LLM
|
| 115 |
+
self.judge_llm = llm_Llama3_70B_JudgeClient()
|
|
|
|
|
|
|
| 116 |
|
| 117 |
self.evaluation_results = []
|
| 118 |
|
|
|
|
| 130 |
|
| 131 |
return medical_outputs
|
| 132 |
|
| 133 |
+
def find_medical_outputs_for_systems(self, systems: List[str]) -> Dict[str, str]:
|
| 134 |
+
"""Find medical outputs files for multiple systems"""
|
| 135 |
results_dir = Path(__file__).parent / "results"
|
| 136 |
+
system_files = {}
|
| 137 |
|
| 138 |
+
for system in systems:
|
| 139 |
+
if system == "rag":
|
| 140 |
+
pattern = str(results_dir / "medical_outputs_*.json")
|
| 141 |
+
elif system == "direct":
|
| 142 |
+
pattern = str(results_dir / "medical_outputs_direct_*.json")
|
| 143 |
+
else:
|
| 144 |
+
# Future extension: support other systems
|
| 145 |
+
pattern = str(results_dir / f"medical_outputs_{system}_*.json")
|
| 146 |
+
|
| 147 |
+
output_files = glob.glob(pattern)
|
| 148 |
+
|
| 149 |
+
if not output_files:
|
| 150 |
+
raise FileNotFoundError(f"No medical outputs files found for {system} system")
|
| 151 |
+
|
| 152 |
+
latest_file = max(output_files, key=os.path.getmtime)
|
| 153 |
+
system_files[system] = latest_file
|
| 154 |
+
print(f"📊 Found {system} outputs: {latest_file}")
|
| 155 |
|
| 156 |
+
return system_files
|
| 157 |
|
| 158 |
+
def create_comparison_evaluation_prompt(self, systems_outputs: Dict[str, List[Dict]]) -> str:
|
| 159 |
"""
|
| 160 |
+
Create comparison evaluation prompt for multiple systems
|
| 161 |
|
| 162 |
+
Args:
|
| 163 |
+
systems_outputs: Dict mapping system names to their medical outputs
|
| 164 |
"""
|
| 165 |
+
system_names = list(systems_outputs.keys())
|
| 166 |
+
|
| 167 |
prompt_parts = [
|
| 168 |
+
"You are a medical expert evaluating and comparing AI systems for clinical advice quality.",
|
| 169 |
+
f"Please evaluate {len(system_names)} different systems using the detailed rubrics below:",
|
| 170 |
+
"",
|
| 171 |
+
"EVALUATION RUBRICS:",
|
| 172 |
+
"",
|
| 173 |
+
"METRIC 1: Clinical Actionability (1-10 scale)",
|
| 174 |
+
"Question: Can healthcare providers immediately act on this advice?",
|
| 175 |
+
"1-2 points: Almost no actionable advice; extremely abstract or empty responses.",
|
| 176 |
+
"3-4 points: Provides directional suggestions but too vague, lacks clear steps.",
|
| 177 |
+
"5-6 points: Offers basic executable steps but lacks details for key aspects.",
|
| 178 |
+
"7-8 points: Clear and complete steps that clinicians can follow with occasional gaps.",
|
| 179 |
+
"9-10 points: Extremely actionable with precise, step-by-step executable guidance.",
|
| 180 |
+
"",
|
| 181 |
+
"METRIC 2: Clinical Evidence Quality (1-10 scale)",
|
| 182 |
+
"Question: Is the advice evidence-based and follows medical standards?",
|
| 183 |
+
"1-2 points: Almost no evidence support; cites irrelevant or unreliable sources.",
|
| 184 |
+
"3-4 points: References lower quality literature or sources lack authority.",
|
| 185 |
+
"5-6 points: Uses general quality literature/guidelines but lacks depth or currency.",
|
| 186 |
+
"7-8 points: References reliable, authoritative sources with accurate explanations.",
|
| 187 |
+
"9-10 points: Rich, high-quality evidence sources combined with latest research.",
|
| 188 |
+
"",
|
| 189 |
+
"TARGET THRESHOLDS: Actionability ≥7.0, Evidence Quality ≥7.5",
|
| 190 |
+
""
|
| 191 |
+
]
|
| 192 |
+
|
| 193 |
+
# Add system descriptions
|
| 194 |
+
for i, system in enumerate(system_names, 1):
|
| 195 |
+
if system == "rag":
|
| 196 |
+
prompt_parts.append(f"SYSTEM {i} (RAG): Uses medical guidelines + LLM for evidence-based advice")
|
| 197 |
+
elif system == "direct":
|
| 198 |
+
prompt_parts.append(f"SYSTEM {i} (Direct): Uses LLM only without external guidelines")
|
| 199 |
+
else:
|
| 200 |
+
prompt_parts.append(f"SYSTEM {i} ({system.upper()}): {system} medical AI system")
|
| 201 |
+
|
| 202 |
+
prompt_parts.extend([
|
| 203 |
"",
|
| 204 |
+
"EVALUATION CRITERIA:",
|
| 205 |
"1. Clinical Actionability (1-10): Can healthcare providers immediately act on this advice?",
|
| 206 |
"2. Clinical Evidence Quality (1-10): Is the advice evidence-based and follows medical standards?",
|
| 207 |
"",
|
| 208 |
"QUERIES TO EVALUATE:",
|
| 209 |
""
|
| 210 |
+
])
|
| 211 |
|
| 212 |
+
# Get all queries (assuming all systems processed same queries)
|
| 213 |
+
first_system = system_names[0]
|
| 214 |
+
queries = systems_outputs[first_system]
|
| 215 |
+
|
| 216 |
+
# Add each query with all system responses
|
| 217 |
+
for i, query_data in enumerate(queries, 1):
|
| 218 |
+
query = query_data.get('query', '')
|
| 219 |
+
category = query_data.get('category', 'unknown')
|
| 220 |
|
| 221 |
prompt_parts.extend([
|
| 222 |
f"=== QUERY {i} ({category.upper()}) ===",
|
| 223 |
f"Patient Query: {query}",
|
|
|
|
| 224 |
""
|
| 225 |
])
|
| 226 |
+
|
| 227 |
+
# Add each system's response
|
| 228 |
+
for j, system in enumerate(system_names, 1):
|
| 229 |
+
system_query = systems_outputs[system][i-1] # Get corresponding query from this system
|
| 230 |
+
advice = system_query.get('medical_advice', '')
|
| 231 |
+
|
| 232 |
+
prompt_parts.extend([
|
| 233 |
+
f"SYSTEM {j} Response: {advice}",
|
| 234 |
+
""
|
| 235 |
+
])
|
| 236 |
|
| 237 |
prompt_parts.extend([
|
| 238 |
"RESPONSE FORMAT (provide exactly this format):",
|
|
|
|
| 240 |
])
|
| 241 |
|
| 242 |
# Add response format template
|
| 243 |
+
for i in range(1, len(queries) + 1):
|
| 244 |
+
for j, system in enumerate(system_names, 1):
|
| 245 |
+
prompt_parts.append(f"Query {i} System {j}: Actionability=X, Evidence=Y")
|
| 246 |
|
| 247 |
prompt_parts.extend([
|
| 248 |
"",
|
| 249 |
"Replace X and Y with numeric scores 1-10.",
|
| 250 |
+
"Provide only the scores in the exact format above.",
|
| 251 |
+
f"Note: System 1={system_names[0]}, System 2={system_names[1] if len(system_names) > 1 else 'N/A'}"
|
| 252 |
])
|
| 253 |
|
| 254 |
return "\n".join(prompt_parts)
|
| 255 |
|
| 256 |
+
def parse_comparison_evaluation_response(self, response: str, systems_outputs: Dict[str, List[Dict]]) -> Dict[str, List[Dict]]:
|
| 257 |
+
"""Parse comparison evaluation response into results by system"""
|
| 258 |
+
results_by_system = {}
|
| 259 |
+
system_names = list(systems_outputs.keys())
|
| 260 |
+
|
| 261 |
+
# Initialize results for each system
|
| 262 |
+
for system in system_names:
|
| 263 |
+
results_by_system[system] = []
|
| 264 |
|
|
|
|
| 265 |
lines = response.strip().split('\n')
|
| 266 |
|
| 267 |
+
for line in lines:
|
| 268 |
line = line.strip()
|
| 269 |
if not line:
|
| 270 |
continue
|
| 271 |
|
| 272 |
+
# Parse format: "Query X System Y: Actionability=A, Evidence=B"
|
| 273 |
+
match = re.match(r'Query\s+(\d+)\s+System\s+(\d+):\s*Actionability\s*=\s*(\d+)\s*,\s*Evidence\s*=\s*(\d+)', line, re.IGNORECASE)
|
| 274 |
|
| 275 |
if match:
|
| 276 |
+
query_num = int(match.group(1)) - 1 # 0-based index
|
| 277 |
+
system_num = int(match.group(2)) - 1 # 0-based index
|
| 278 |
+
actionability_score = int(match.group(3))
|
| 279 |
+
evidence_score = int(match.group(4))
|
| 280 |
|
| 281 |
+
if system_num < len(system_names) and query_num < len(systems_outputs[system_names[system_num]]):
|
| 282 |
+
system_name = system_names[system_num]
|
| 283 |
+
output = systems_outputs[system_name][query_num]
|
| 284 |
|
| 285 |
result = {
|
| 286 |
"query": output.get('query', ''),
|
| 287 |
"category": output.get('category', 'unknown'),
|
| 288 |
+
"system_type": system_name,
|
| 289 |
"medical_advice": output.get('medical_advice', ''),
|
| 290 |
|
| 291 |
# Metric 5: Clinical Actionability
|
| 292 |
+
"actionability_score": actionability_score / 10.0,
|
| 293 |
"actionability_raw": actionability_score,
|
| 294 |
|
| 295 |
# Metric 6: Clinical Evidence Quality
|
| 296 |
+
"evidence_score": evidence_score / 10.0,
|
| 297 |
"evidence_raw": evidence_score,
|
| 298 |
|
| 299 |
"evaluation_success": True,
|
| 300 |
"timestamp": datetime.now().isoformat()
|
| 301 |
}
|
| 302 |
|
| 303 |
+
results_by_system[system_name].append(result)
|
| 304 |
|
| 305 |
+
return results_by_system
|
| 306 |
|
| 307 |
+
def evaluate_multiple_systems(self, systems_outputs: Dict[str, List[Dict]]) -> Dict[str, List[Dict]]:
|
| 308 |
"""
|
| 309 |
+
Evaluate multiple systems using single LLM call for comparison
|
| 310 |
|
| 311 |
Args:
|
| 312 |
+
systems_outputs: Dict mapping system names to their medical outputs
|
| 313 |
"""
|
| 314 |
+
system_names = list(systems_outputs.keys())
|
| 315 |
+
total_queries = len(systems_outputs[system_names[0]])
|
| 316 |
+
|
| 317 |
+
print(f"🧠 Multi-system comparison: {', '.join(system_names)}")
|
| 318 |
+
print(f"📊 Evaluating {total_queries} queries across {len(system_names)} systems...")
|
| 319 |
|
| 320 |
try:
|
| 321 |
+
# Create comparison evaluation prompt
|
| 322 |
+
comparison_prompt = self.create_comparison_evaluation_prompt(systems_outputs)
|
| 323 |
|
| 324 |
+
print(f"📝 Comparison prompt created ({len(comparison_prompt)} characters)")
|
| 325 |
+
print(f"🔄 Calling judge LLM for multi-system comparison...")
|
| 326 |
|
| 327 |
+
# Single LLM call for all systems comparison
|
| 328 |
eval_start = time.time()
|
| 329 |
+
response = self.judge_llm.batch_evaluate(comparison_prompt)
|
| 330 |
eval_time = time.time() - eval_start
|
| 331 |
|
| 332 |
# Extract response text
|
| 333 |
response_text = response.get('content', '') if isinstance(response, dict) else str(response)
|
| 334 |
|
| 335 |
+
print(f"✅ Judge LLM completed comparison evaluation in {eval_time:.2f}s")
|
| 336 |
print(f"📄 Response length: {len(response_text)} characters")
|
| 337 |
|
| 338 |
+
# Parse comparison response
|
| 339 |
+
results_by_system = self.parse_comparison_evaluation_response(response_text, systems_outputs)
|
|
|
|
|
|
|
|
|
|
| 340 |
|
| 341 |
+
# Combine all results for storage
|
| 342 |
+
all_results = []
|
| 343 |
+
for system_name, system_results in results_by_system.items():
|
| 344 |
+
all_results.extend(system_results)
|
| 345 |
+
print(f"📊 {system_name.upper()}: {len(system_results)} evaluations parsed")
|
| 346 |
|
| 347 |
+
self.evaluation_results.extend(all_results)
|
| 348 |
|
| 349 |
+
return results_by_system
|
| 350 |
|
| 351 |
except Exception as e:
|
| 352 |
+
print(f"❌ Multi-system evaluation failed: {e}")
|
| 353 |
|
| 354 |
+
# Create error results for all systems
|
| 355 |
+
error_results = {}
|
| 356 |
+
for system_name, outputs in systems_outputs.items():
|
| 357 |
+
error_results[system_name] = []
|
| 358 |
+
for output in outputs:
|
| 359 |
+
error_result = {
|
| 360 |
+
"query": output.get('query', ''),
|
| 361 |
+
"category": output.get('category', 'unknown'),
|
| 362 |
+
"system_type": system_name,
|
| 363 |
+
"actionability_score": 0.0,
|
| 364 |
+
"evidence_score": 0.0,
|
| 365 |
+
"evaluation_success": False,
|
| 366 |
+
"error": str(e),
|
| 367 |
+
"timestamp": datetime.now().isoformat()
|
| 368 |
+
}
|
| 369 |
+
error_results[system_name].append(error_result)
|
| 370 |
+
self.evaluation_results.extend(error_results[system_name])
|
| 371 |
|
|
|
|
| 372 |
return error_results
|
| 373 |
|
| 374 |
def calculate_judge_statistics(self) -> Dict[str, Any]:
|
|
|
|
| 441 |
"timestamp": datetime.now().isoformat()
|
| 442 |
}
|
| 443 |
|
| 444 |
+
def save_comparison_statistics(self, systems: List[str], filename: str = None) -> str:
|
| 445 |
+
"""Save comparison evaluation statistics for multiple systems"""
|
| 446 |
stats = self.calculate_judge_statistics()
|
| 447 |
|
| 448 |
if filename is None:
|
| 449 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 450 |
+
systems_str = "_vs_".join(systems)
|
| 451 |
+
filename = f"judge_evaluation_comparison_{systems_str}_{timestamp}.json"
|
| 452 |
|
| 453 |
results_dir = Path(__file__).parent / "results"
|
| 454 |
results_dir.mkdir(exist_ok=True)
|
| 455 |
filepath = results_dir / filename
|
| 456 |
|
| 457 |
+
# Add comparison metadata
|
| 458 |
+
stats["comparison_metadata"] = {
|
| 459 |
+
"systems_compared": systems,
|
| 460 |
+
"comparison_type": "multi_system",
|
| 461 |
+
"timestamp": datetime.now().isoformat()
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
# Add detailed system-specific results for chart generation
|
| 465 |
+
stats["detailed_system_results"] = {}
|
| 466 |
+
for system in systems:
|
| 467 |
+
system_results = [r for r in self.evaluation_results if r.get('system_type') == system and r.get('evaluation_success')]
|
| 468 |
+
stats["detailed_system_results"][system] = {
|
| 469 |
+
"results": system_results,
|
| 470 |
+
"query_count": len(system_results),
|
| 471 |
+
"avg_actionability": sum(r['actionability_score'] for r in system_results) / len(system_results) if system_results else 0.0,
|
| 472 |
+
"avg_evidence": sum(r['evidence_score'] for r in system_results) / len(system_results) if system_results else 0.0
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
with open(filepath, 'w', encoding='utf-8') as f:
|
| 476 |
json.dump(stats, f, indent=2, ensure_ascii=False)
|
| 477 |
|
| 478 |
+
print(f"📊 Comparison evaluation statistics saved to: {filepath}")
|
| 479 |
return str(filepath)
|
| 480 |
|
| 481 |
|
| 482 |
# Independent execution interface
|
| 483 |
if __name__ == "__main__":
|
| 484 |
+
"""Independent LLM judge evaluation interface with multi-system support"""
|
| 485 |
+
|
| 486 |
+
print("🧠 OnCall.ai LLM Judge Evaluator - Metrics 5-6 Multi-System Evaluation")
|
| 487 |
|
| 488 |
+
# Print evaluation rubrics for reference
|
| 489 |
+
print_evaluation_rubrics()
|
| 490 |
|
| 491 |
+
if len(sys.argv) < 2:
|
| 492 |
+
print("Usage: python metric5_6_llm_judge_evaluator.py [system1] or [system1,system2,...]")
|
| 493 |
+
print(" rag - Evaluate RAG system medical outputs")
|
| 494 |
+
print(" direct - Evaluate direct LLM medical outputs")
|
| 495 |
+
print(" rag,direct - Compare RAG vs Direct systems")
|
| 496 |
+
print(" system1,system2,system3 - Compare multiple systems")
|
| 497 |
sys.exit(1)
|
| 498 |
|
| 499 |
+
# Parse systems from command line
|
| 500 |
+
systems_input = sys.argv[1]
|
| 501 |
+
systems = [s.strip() for s in systems_input.split(',')]
|
| 502 |
+
|
| 503 |
# Initialize evaluator
|
| 504 |
evaluator = LLMJudgeEvaluator()
|
| 505 |
|
| 506 |
try:
|
| 507 |
+
if len(systems) == 1:
|
| 508 |
+
# Single system evaluation (legacy mode)
|
| 509 |
+
system = systems[0]
|
| 510 |
+
print(f"\n🧪 Single System LLM Judge Evaluation: {system.upper()}")
|
| 511 |
+
|
| 512 |
+
# Find and load medical outputs for single system
|
| 513 |
+
system_files = evaluator.find_medical_outputs_for_systems([system])
|
| 514 |
+
medical_outputs = evaluator.load_medical_outputs(system_files[system])
|
| 515 |
+
|
| 516 |
+
if not medical_outputs:
|
| 517 |
+
print(f"❌ No medical outputs found for {system}")
|
| 518 |
+
sys.exit(1)
|
| 519 |
+
|
| 520 |
+
print(f"📊 Evaluating {len(medical_outputs)} medical advice outputs")
|
| 521 |
+
print(f"🎯 Metrics: 5 (Actionability) + 6 (Evidence Quality)")
|
| 522 |
+
|
| 523 |
+
# Convert to multi-system format for consistency
|
| 524 |
+
systems_outputs = {system: medical_outputs}
|
| 525 |
+
results_by_system = evaluator.evaluate_multiple_systems(systems_outputs)
|
| 526 |
+
|
| 527 |
+
# Save results
|
| 528 |
+
stats_path = evaluator.save_comparison_statistics([system])
|
| 529 |
+
|
| 530 |
+
else:
|
| 531 |
+
# Multi-system comparison evaluation
|
| 532 |
+
print(f"\n🧪 Multi-System Comparison: {' vs '.join([s.upper() for s in systems])}")
|
| 533 |
+
|
| 534 |
+
# Find and load medical outputs for all systems
|
| 535 |
+
system_files = evaluator.find_medical_outputs_for_systems(systems)
|
| 536 |
+
systems_outputs = {}
|
| 537 |
+
|
| 538 |
+
for system in systems:
|
| 539 |
+
outputs = evaluator.load_medical_outputs(system_files[system])
|
| 540 |
+
if not outputs:
|
| 541 |
+
print(f"❌ No medical outputs found for {system}")
|
| 542 |
+
sys.exit(1)
|
| 543 |
+
systems_outputs[system] = outputs
|
| 544 |
+
|
| 545 |
+
# Validate all systems have same number of queries
|
| 546 |
+
query_counts = [len(outputs) for outputs in systems_outputs.values()]
|
| 547 |
+
if len(set(query_counts)) > 1:
|
| 548 |
+
print(f"⚠️ Warning: Systems have different query counts: {dict(zip(systems, query_counts))}")
|
| 549 |
+
|
| 550 |
+
print(f"📊 Comparing {len(systems)} systems with {min(query_counts)} queries each")
|
| 551 |
+
print(f"🎯 Metrics: 5 (Actionability) + 6 (Evidence Quality)")
|
| 552 |
+
print(f"⚡ Strategy: Single comparison call for maximum consistency")
|
| 553 |
+
|
| 554 |
+
# Multi-system comparison evaluation
|
| 555 |
+
results_by_system = evaluator.evaluate_multiple_systems(systems_outputs)
|
| 556 |
+
|
| 557 |
+
# Save comparison results
|
| 558 |
+
stats_path = evaluator.save_comparison_statistics(systems)
|
| 559 |
|
| 560 |
# Print summary
|
| 561 |
+
print(f"\n📊 Generating evaluation analysis...")
|
| 562 |
stats = evaluator.calculate_judge_statistics()
|
| 563 |
overall_results = stats['overall_results']
|
|
|
|
| 564 |
|
| 565 |
+
print(f"\n📊 === LLM JUDGE EVALUATION SUMMARY ===")
|
| 566 |
+
|
| 567 |
+
if len(systems) == 1:
|
| 568 |
+
print(f"System: {systems[0].upper()}")
|
| 569 |
+
else:
|
| 570 |
+
print(f"Systems Compared: {' vs '.join([s.upper() for s in systems])}")
|
| 571 |
+
|
| 572 |
print(f"Overall Performance:")
|
| 573 |
+
actionability_raw = overall_results['average_actionability'] * 10
|
| 574 |
+
evidence_raw = overall_results['average_evidence'] * 10
|
| 575 |
+
|
| 576 |
+
print(f" Average Actionability: {overall_results['average_actionability']:.3f} ({actionability_raw:.1f}/10)")
|
| 577 |
+
print(f" • {get_rubric_description(int(actionability_raw), 'actionability')}")
|
| 578 |
+
print(f" Average Evidence Quality: {overall_results['average_evidence']:.3f} ({evidence_raw:.1f}/10)")
|
| 579 |
+
print(f" • {get_rubric_description(int(evidence_raw), 'evidence')}")
|
| 580 |
print(f" Actionability Target (≥7.0): {'✅ Met' if overall_results['actionability_target_met'] else '❌ Not Met'}")
|
| 581 |
print(f" Evidence Target (≥7.5): {'✅ Met' if overall_results['evidence_target_met'] else '❌ Not Met'}")
|
| 582 |
|
| 583 |
+
# System-specific breakdown for multi-system comparison
|
| 584 |
+
if len(systems) > 1:
|
| 585 |
+
print(f"\nSystem Breakdown:")
|
| 586 |
+
for system in systems:
|
| 587 |
+
system_results = [r for r in evaluator.evaluation_results if r.get('system_type') == system and r.get('evaluation_success')]
|
| 588 |
+
if system_results:
|
| 589 |
+
avg_action = sum(r['actionability_score'] for r in system_results) / len(system_results)
|
| 590 |
+
avg_evidence = sum(r['evidence_score'] for r in system_results) / len(system_results)
|
| 591 |
+
print(f" {system.upper()}: Actionability={avg_action:.3f}, Evidence={avg_evidence:.3f} [{len(system_results)} queries]")
|
| 592 |
|
| 593 |
print(f"\n✅ LLM judge evaluation complete!")
|
| 594 |
print(f"📊 Statistics: {stats_path}")
|
| 595 |
+
print(f"⚡ Efficiency: {overall_results['total_queries']} evaluations in 1 LLM call")
|
| 596 |
|
| 597 |
except FileNotFoundError as e:
|
| 598 |
print(f"❌ {e}")
|
| 599 |
+
print(f"💡 Please run evaluators first:")
|
| 600 |
+
for system in systems:
|
| 601 |
+
if system == "rag":
|
| 602 |
+
print(" python latency_evaluator.py single_test_query.txt")
|
| 603 |
+
elif system == "direct":
|
| 604 |
+
print(" python direct_llm_evaluator.py single_test_query.txt")
|
| 605 |
+
else:
|
| 606 |
+
print(f" python {system}_evaluator.py single_test_query.txt")
|
| 607 |
except Exception as e:
|
| 608 |
print(f"❌ Judge evaluation failed: {e}")
|
src/llm_clients.py
CHANGED
|
@@ -461,5 +461,136 @@ def main():
|
|
| 461 |
'total_execution_time': total_execution_time
|
| 462 |
}
|
| 463 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
if __name__ == "__main__":
|
| 465 |
main()
|
|
|
|
| 461 |
'total_execution_time': total_execution_time
|
| 462 |
}
|
| 463 |
|
| 464 |
+
|
| 465 |
+
class llm_Llama3_70B_JudgeClient:
|
| 466 |
+
"""
|
| 467 |
+
Llama3-70B client specifically for LLM judge evaluation.
|
| 468 |
+
Used for metrics 5-6 evaluation: Clinical Actionability & Evidence Quality.
|
| 469 |
+
"""
|
| 470 |
+
|
| 471 |
+
def __init__(
|
| 472 |
+
self,
|
| 473 |
+
model_name: str = "meta-llama/Meta-Llama-3-70B-Instruct",
|
| 474 |
+
timeout: float = 60.0
|
| 475 |
+
):
|
| 476 |
+
"""
|
| 477 |
+
Initialize Llama3-70B judge client for evaluation tasks.
|
| 478 |
+
|
| 479 |
+
Args:
|
| 480 |
+
model_name: Hugging Face model name for Llama3-70B
|
| 481 |
+
timeout: API call timeout duration (longer for judge evaluation)
|
| 482 |
+
|
| 483 |
+
Note: This client is specifically designed for third-party evaluation,
|
| 484 |
+
not for medical advice generation.
|
| 485 |
+
"""
|
| 486 |
+
self.logger = logging.getLogger(__name__)
|
| 487 |
+
self.timeout = timeout
|
| 488 |
+
self.model_name = model_name
|
| 489 |
+
|
| 490 |
+
# Get Hugging Face token from environment
|
| 491 |
+
hf_token = os.getenv('HF_TOKEN')
|
| 492 |
+
if not hf_token:
|
| 493 |
+
self.logger.error("HF_TOKEN is missing from environment variables.")
|
| 494 |
+
raise ValueError(
|
| 495 |
+
"HF_TOKEN not found in environment variables. "
|
| 496 |
+
"Please set HF_TOKEN in your .env file or environment."
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
# Initialize Hugging Face Inference Client for judge evaluation
|
| 500 |
+
try:
|
| 501 |
+
self.client = InferenceClient(
|
| 502 |
+
provider="auto",
|
| 503 |
+
api_key=hf_token,
|
| 504 |
+
)
|
| 505 |
+
self.logger.info(f"Llama3-70B judge client initialized with model: {model_name}")
|
| 506 |
+
self.logger.info("Judge LLM: Evaluation tool only. Not for medical advice generation.")
|
| 507 |
+
|
| 508 |
+
except Exception as e:
|
| 509 |
+
self.logger.error(f"Failed to initialize Llama3-70B judge client: {e}")
|
| 510 |
+
raise
|
| 511 |
+
|
| 512 |
+
def generate_completion(self, prompt: str) -> Dict[str, Union[str, float]]:
|
| 513 |
+
"""
|
| 514 |
+
Generate completion using Llama3-70B for judge evaluation.
|
| 515 |
+
|
| 516 |
+
Args:
|
| 517 |
+
prompt: Evaluation prompt for medical advice assessment
|
| 518 |
+
|
| 519 |
+
Returns:
|
| 520 |
+
Dict containing response content and timing information
|
| 521 |
+
"""
|
| 522 |
+
import time
|
| 523 |
+
|
| 524 |
+
start_time = time.time()
|
| 525 |
+
|
| 526 |
+
try:
|
| 527 |
+
self.logger.info(f"Calling Llama3-70B Judge with evaluation prompt ({len(prompt)} chars)")
|
| 528 |
+
|
| 529 |
+
# Call Llama3-70B for judge evaluation
|
| 530 |
+
completion = self.client.chat.completions.create(
|
| 531 |
+
model=self.model_name,
|
| 532 |
+
messages=[
|
| 533 |
+
{
|
| 534 |
+
"role": "user",
|
| 535 |
+
"content": prompt
|
| 536 |
+
}
|
| 537 |
+
],
|
| 538 |
+
max_tokens=2048, # Sufficient for evaluation responses
|
| 539 |
+
temperature=0.1, # Low temperature for consistent evaluation
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
# Extract response content
|
| 543 |
+
response_content = completion.choices[0].message.content
|
| 544 |
+
|
| 545 |
+
end_time = time.time()
|
| 546 |
+
latency = end_time - start_time
|
| 547 |
+
|
| 548 |
+
self.logger.info(f"Llama3-70B Judge Response: {response_content[:100]}...")
|
| 549 |
+
self.logger.info(f"Judge Evaluation Latency: {latency:.4f} seconds")
|
| 550 |
+
|
| 551 |
+
return {
|
| 552 |
+
'content': response_content,
|
| 553 |
+
'latency': latency,
|
| 554 |
+
'model': self.model_name,
|
| 555 |
+
'timestamp': time.time()
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
except Exception as e:
|
| 559 |
+
end_time = time.time()
|
| 560 |
+
error_latency = end_time - start_time
|
| 561 |
+
|
| 562 |
+
self.logger.error(f"Llama3-70B judge evaluation failed: {e}")
|
| 563 |
+
self.logger.error(f"Error occurred after {error_latency:.4f} seconds")
|
| 564 |
+
|
| 565 |
+
return {
|
| 566 |
+
'content': f"Judge evaluation error: {str(e)}",
|
| 567 |
+
'latency': error_latency,
|
| 568 |
+
'error': str(e),
|
| 569 |
+
'model': self.model_name,
|
| 570 |
+
'timestamp': time.time()
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
def batch_evaluate(self, evaluation_prompt: str) -> Dict[str, Union[str, float]]:
|
| 574 |
+
"""
|
| 575 |
+
Specialized method for batch evaluation of medical advice.
|
| 576 |
+
Alias for generate_completion with judge-specific logging.
|
| 577 |
+
|
| 578 |
+
Args:
|
| 579 |
+
evaluation_prompt: Batch evaluation prompt containing multiple queries
|
| 580 |
+
|
| 581 |
+
Returns:
|
| 582 |
+
Dict containing batch evaluation results and timing
|
| 583 |
+
"""
|
| 584 |
+
self.logger.info("Starting batch judge evaluation...")
|
| 585 |
+
result = self.generate_completion(evaluation_prompt)
|
| 586 |
+
|
| 587 |
+
if 'error' not in result:
|
| 588 |
+
self.logger.info(f"Batch evaluation completed successfully in {result['latency']:.2f}s")
|
| 589 |
+
else:
|
| 590 |
+
self.logger.error(f"Batch evaluation failed: {result.get('error', 'Unknown error')}")
|
| 591 |
+
|
| 592 |
+
return result
|
| 593 |
+
|
| 594 |
+
|
| 595 |
if __name__ == "__main__":
|
| 596 |
main()
|