YanBoChen commited on
Commit
5fb5e09
·
1 Parent(s): 2f35ee2

Update query file references for full evaluation and improve user prompts in evaluation scripts (before optimized_general_pipeline)

Browse files
evaluation/direct_llm_evaluator.py CHANGED
@@ -448,8 +448,8 @@ if __name__ == "__main__":
448
  query_file = sys.argv[1]
449
  else:
450
  # Default to evaluation/single_test_query.txt for consistency
451
- # TODO: Change to pre_user_query_evaluate.txt for full evaluation
452
- query_file = Path(__file__).parent / "pre_user_query_evaluate.txt"
453
 
454
  if not os.path.exists(query_file):
455
  print(f"❌ Query file not found: {query_file}")
 
448
  query_file = sys.argv[1]
449
  else:
450
  # Default to evaluation/single_test_query.txt for consistency
451
+ # TODO: Change to pre_user_query_evaluate.txt for full evaluation, user_query.txt for formal evaluation
452
+ query_file = Path(__file__).parent / "user_query.txt"
453
 
454
  if not os.path.exists(query_file):
455
  print(f"❌ Query file not found: {query_file}")
evaluation/fixed_judge_evaluator.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Fixed version of metric5_6_llm_judge_evaluator.py with batch processing
4
+ Splits large evaluation requests into smaller batches to avoid API limits
5
+ """
6
+
7
+ import sys
8
+ import os
9
+ import json
10
+ import time
11
+ import glob
12
+ from pathlib import Path
13
+ from datetime import datetime
14
+ from typing import Dict, List, Any
15
+ import re
16
+
17
+ # Add src directory to path
18
+ sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
19
+
20
+ from llm_clients import llm_Llama3_70B_JudgeClient
21
+
22
+ class FixedLLMJudgeEvaluator:
23
+ """
24
+ Fixed LLM Judge Evaluator with batch processing for large evaluations
25
+ """
26
+
27
+ def __init__(self, batch_size: int = 2):
28
+ """
29
+ Initialize with configurable batch size
30
+
31
+ Args:
32
+ batch_size: Number of queries to evaluate per batch (default: 2)
33
+ """
34
+ self.judge_llm = llm_Llama3_70B_JudgeClient()
35
+ self.evaluation_results = []
36
+ self.batch_size = batch_size
37
+ print(f"✅ Fixed LLM Judge Evaluator initialized with batch_size={batch_size}")
38
+
39
+ def load_systems_outputs(self, systems: List[str]) -> Dict[str, List[Dict]]:
40
+ """Load outputs from multiple systems for comparison"""
41
+ results_dir = Path(__file__).parent / "results"
42
+ system_files = {}
43
+
44
+ for system in systems:
45
+ if system == "rag":
46
+ pattern = str(results_dir / "medical_outputs_[0-9]*.json")
47
+ elif system == "direct":
48
+ pattern = str(results_dir / "medical_outputs_direct_*.json")
49
+ else:
50
+ pattern = str(results_dir / f"medical_outputs_{system}_*.json")
51
+
52
+ print(f"🔍 Searching for {system} with pattern: {pattern}")
53
+ output_files = glob.glob(pattern)
54
+ print(f"🔍 Found files for {system}: {output_files}")
55
+
56
+ if not output_files:
57
+ raise FileNotFoundError(f"No output files found for system: {system}")
58
+
59
+ # Use most recent file
60
+ latest_file = max(output_files, key=os.path.getctime)
61
+ print(f"📁 Using latest file for {system}: {latest_file}")
62
+
63
+ with open(latest_file, 'r', encoding='utf-8') as f:
64
+ data = json.load(f)
65
+ system_files[system] = data['medical_outputs']
66
+
67
+ return system_files
68
+
69
+ def create_batch_evaluation_prompt(self, batch_queries: List[Dict], system_names: List[str]) -> str:
70
+ """
71
+ Create evaluation prompt for a small batch of queries
72
+
73
+ Args:
74
+ batch_queries: Small batch of queries (2-3 queries)
75
+ system_names: Names of systems being compared
76
+
77
+ Returns:
78
+ Formatted evaluation prompt
79
+ """
80
+ prompt_parts = [
81
+ "MEDICAL AI EVALUATION - BATCH ASSESSMENT",
82
+ "",
83
+ f"You are evaluating {len(system_names)} medical AI systems on {len(batch_queries)} queries.",
84
+ "Rate each response on a scale of 1-10 for:",
85
+ "1. Clinical Actionability: Can healthcare providers immediately act on this advice?",
86
+ "2. Clinical Evidence Quality: Is the advice evidence-based and follows medical standards?",
87
+ "",
88
+ "SYSTEMS:"
89
+ ]
90
+
91
+ for i, system in enumerate(system_names, 1):
92
+ if system == "rag":
93
+ prompt_parts.append(f"SYSTEM {i} (RAG): Uses medical guidelines + LLM")
94
+ elif system == "direct":
95
+ prompt_parts.append(f"SYSTEM {i} (Direct): Uses LLM only without external guidelines")
96
+ else:
97
+ prompt_parts.append(f"SYSTEM {i} ({system.upper()}): {system} medical AI system")
98
+
99
+ prompt_parts.extend([
100
+ "",
101
+ "QUERIES TO EVALUATE:",
102
+ ""
103
+ ])
104
+
105
+ # Add each query with all system responses
106
+ for i, query_batch in enumerate(batch_queries, 1):
107
+ query = query_batch['query']
108
+ category = query_batch['category']
109
+
110
+ prompt_parts.extend([
111
+ f"=== QUERY {i} ({category.upper()}) ===",
112
+ f"Patient Query: {query}",
113
+ ""
114
+ ])
115
+
116
+ # Add each system's response
117
+ for j, system in enumerate(system_names, 1):
118
+ advice = query_batch[f'{system}_advice']
119
+
120
+ # Truncate very long advice to avoid token limits
121
+ if len(advice) > 1500:
122
+ advice = advice[:1500] + "... [truncated for evaluation]"
123
+
124
+ prompt_parts.extend([
125
+ f"SYSTEM {j} Response: {advice}",
126
+ ""
127
+ ])
128
+
129
+ prompt_parts.extend([
130
+ "RESPONSE FORMAT (provide exactly this format):",
131
+ ""
132
+ ])
133
+
134
+ # Add response format template
135
+ for i in range(1, len(batch_queries) + 1):
136
+ for j, system in enumerate(system_names, 1):
137
+ prompt_parts.append(f"Query {i} System {j}: Actionability=X, Evidence=Y")
138
+
139
+ return '\n'.join(prompt_parts)
140
+
141
+ def parse_batch_evaluation_response(self, response_text: str, batch_queries: List[Dict], system_names: List[str]) -> List[Dict]:
142
+ """Parse evaluation response for a batch of queries"""
143
+ results = []
144
+ lines = response_text.strip().split('\n')
145
+
146
+ for line in lines:
147
+ # Parse format: "Query X System Y: Actionability=Z, Evidence=W"
148
+ match = re.search(r'Query\s+(\d+)\s+System\s+(\d+):\s*Actionability\s*=\s*(\d+(?:\.\d+)?),?\s*Evidence\s*=\s*(\d+(?:\.\d+)?)', line, re.IGNORECASE)
149
+
150
+ if match:
151
+ query_num = int(match.group(1)) - 1
152
+ system_num = int(match.group(2)) - 1
153
+ actionability = float(match.group(3))
154
+ evidence = float(match.group(4))
155
+
156
+ if (0 <= query_num < len(batch_queries) and
157
+ 0 <= system_num < len(system_names) and
158
+ 1 <= actionability <= 10 and
159
+ 1 <= evidence <= 10):
160
+
161
+ result = {
162
+ "query": batch_queries[query_num]['query'],
163
+ "category": batch_queries[query_num]['category'],
164
+ "system_type": system_names[system_num],
165
+ "actionability_score": actionability / 10, # Normalize to 0-1
166
+ "evidence_score": evidence / 10, # Normalize to 0-1
167
+ "evaluation_success": True,
168
+ "timestamp": datetime.now().isoformat()
169
+ }
170
+ results.append(result)
171
+
172
+ return results
173
+
174
+ def evaluate_systems_in_batches(self, systems: List[str]) -> Dict[str, List[Dict]]:
175
+ """
176
+ Evaluate multiple systems using batch processing
177
+
178
+ Args:
179
+ systems: List of system names to compare
180
+
181
+ Returns:
182
+ Dict with results for each system
183
+ """
184
+ print(f"🚀 Starting batch evaluation for systems: {systems}")
185
+
186
+ # Load system outputs
187
+ systems_outputs = self.load_systems_outputs(systems)
188
+
189
+ # Verify all systems have same number of queries
190
+ query_counts = [len(outputs) for outputs in systems_outputs.values()]
191
+ if len(set(query_counts)) > 1:
192
+ print(f"⚠️ Warning: Systems have different query counts: {dict(zip(systems, query_counts))}")
193
+
194
+ total_queries = min(query_counts)
195
+ print(f"📊 Evaluating {total_queries} queries across {len(systems)} systems...")
196
+
197
+ # Prepare combined queries for batching
198
+ combined_queries = []
199
+ system_outputs_list = list(systems_outputs.values())
200
+
201
+ for i in range(total_queries):
202
+ batch_query = {
203
+ 'query': system_outputs_list[0][i]['query'],
204
+ 'category': system_outputs_list[0][i]['category']
205
+ }
206
+
207
+ # Add advice from each system
208
+ for j, system_name in enumerate(systems):
209
+ batch_query[f'{system_name}_advice'] = systems_outputs[system_name][i]['medical_advice']
210
+
211
+ combined_queries.append(batch_query)
212
+
213
+ # Process in small batches
214
+ all_results = []
215
+ num_batches = (total_queries + self.batch_size - 1) // self.batch_size
216
+
217
+ for batch_num in range(num_batches):
218
+ start_idx = batch_num * self.batch_size
219
+ end_idx = min(start_idx + self.batch_size, total_queries)
220
+ batch_queries = combined_queries[start_idx:end_idx]
221
+
222
+ print(f"\n📦 Processing batch {batch_num + 1}/{num_batches} (queries {start_idx + 1}-{end_idx})...")
223
+
224
+ try:
225
+ # Create batch evaluation prompt
226
+ batch_prompt = self.create_batch_evaluation_prompt(batch_queries, systems)
227
+
228
+ print(f"📝 Batch prompt created ({len(batch_prompt)} characters)")
229
+ print(f"🔄 Calling judge LLM for batch {batch_num + 1}...")
230
+
231
+ # Call LLM for this batch
232
+ eval_start = time.time()
233
+ response = self.judge_llm.batch_evaluate(batch_prompt)
234
+ eval_time = time.time() - eval_start
235
+
236
+ # Extract response text
237
+ response_text = response.get('content', '') if isinstance(response, dict) else str(response)
238
+
239
+ print(f"✅ Batch {batch_num + 1} completed in {eval_time:.2f}s")
240
+ print(f"📄 Response length: {len(response_text)} characters")
241
+
242
+ # Parse batch response
243
+ batch_results = self.parse_batch_evaluation_response(response_text, batch_queries, systems)
244
+ all_results.extend(batch_results)
245
+
246
+ print(f"📊 Batch {batch_num + 1}: {len(batch_results)} evaluations parsed")
247
+
248
+ # Small delay between batches to avoid rate limiting
249
+ if batch_num < num_batches - 1:
250
+ time.sleep(2)
251
+
252
+ except Exception as e:
253
+ print(f"❌ Batch {batch_num + 1} failed: {e}")
254
+ # Continue with next batch rather than stopping
255
+ continue
256
+
257
+ # Group results by system
258
+ results_by_system = {}
259
+ for system in systems:
260
+ results_by_system[system] = [r for r in all_results if r['system_type'] == system]
261
+
262
+ self.evaluation_results.extend(all_results)
263
+
264
+ return results_by_system
265
+
266
+ def save_comparison_results(self, systems: List[str], filename: str = None) -> str:
267
+ """Save comparison evaluation results"""
268
+ if filename is None:
269
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
270
+ systems_str = "_vs_".join(systems)
271
+ filename = f"judge_evaluation_comparison_{systems_str}_{timestamp}.json"
272
+
273
+ results_dir = Path(__file__).parent / "results"
274
+ results_dir.mkdir(exist_ok=True)
275
+ filepath = results_dir / filename
276
+
277
+ # Calculate statistics
278
+ successful_results = [r for r in self.evaluation_results if r['evaluation_success']]
279
+
280
+ if successful_results:
281
+ actionability_scores = [r['actionability_score'] for r in successful_results]
282
+ evidence_scores = [r['evidence_score'] for r in successful_results]
283
+
284
+ overall_stats = {
285
+ "average_actionability": sum(actionability_scores) / len(actionability_scores),
286
+ "average_evidence": sum(evidence_scores) / len(evidence_scores),
287
+ "successful_evaluations": len(successful_results),
288
+ "total_queries": len(self.evaluation_results)
289
+ }
290
+ else:
291
+ overall_stats = {
292
+ "average_actionability": 0.0,
293
+ "average_evidence": 0.0,
294
+ "successful_evaluations": 0,
295
+ "total_queries": len(self.evaluation_results)
296
+ }
297
+
298
+ # System-specific results
299
+ detailed_system_results = {}
300
+ for system in systems:
301
+ system_results = [r for r in successful_results if r.get('system_type') == system]
302
+ if system_results:
303
+ detailed_system_results[system] = {
304
+ "results": system_results,
305
+ "query_count": len(system_results),
306
+ "avg_actionability": sum(r['actionability_score'] for r in system_results) / len(system_results),
307
+ "avg_evidence": sum(r['evidence_score'] for r in system_results) / len(system_results)
308
+ }
309
+ else:
310
+ detailed_system_results[system] = {
311
+ "results": [],
312
+ "query_count": 0,
313
+ "avg_actionability": 0.0,
314
+ "avg_evidence": 0.0
315
+ }
316
+
317
+ # Save results
318
+ results_data = {
319
+ "category_results": {}, # Would need category analysis
320
+ "overall_results": overall_stats,
321
+ "timestamp": datetime.now().isoformat(),
322
+ "comparison_metadata": {
323
+ "systems_compared": systems,
324
+ "comparison_type": "multi_system_batch",
325
+ "batch_size": self.batch_size,
326
+ "timestamp": datetime.now().isoformat()
327
+ },
328
+ "detailed_system_results": detailed_system_results
329
+ }
330
+
331
+ with open(filepath, 'w', encoding='utf-8') as f:
332
+ json.dump(results_data, f, indent=2, ensure_ascii=False)
333
+
334
+ print(f"📊 Comparison evaluation results saved to: {filepath}")
335
+ return str(filepath)
336
+
337
+
338
+ def main():
339
+ """Main execution function"""
340
+ print("🧠 Fixed OnCall.ai LLM Judge Evaluator - Batch Processing Version")
341
+
342
+ if len(sys.argv) < 2:
343
+ print("Usage: python fixed_judge_evaluator.py [system1,system2,...]")
344
+ print("Examples:")
345
+ print(" python fixed_judge_evaluator.py rag,direct")
346
+ print(" python fixed_judge_evaluator.py rag,direct --batch-size 3")
347
+ return 1
348
+
349
+ # Parse systems
350
+ systems_arg = sys.argv[1]
351
+ systems = [s.strip() for s in systems_arg.split(',')]
352
+
353
+ # Parse batch size
354
+ batch_size = 2
355
+ if "--batch-size" in sys.argv:
356
+ batch_idx = sys.argv.index("--batch-size")
357
+ if batch_idx + 1 < len(sys.argv):
358
+ batch_size = int(sys.argv[batch_idx + 1])
359
+
360
+ print(f"🎯 Systems to evaluate: {systems}")
361
+ print(f"📦 Batch size: {batch_size}")
362
+
363
+ try:
364
+ # Initialize evaluator
365
+ evaluator = FixedLLMJudgeEvaluator(batch_size=batch_size)
366
+
367
+ # Run batch evaluation
368
+ results = evaluator.evaluate_systems_in_batches(systems)
369
+
370
+ # Save results
371
+ results_file = evaluator.save_comparison_results(systems)
372
+
373
+ # Print summary
374
+ print(f"\n✅ Fixed batch evaluation completed!")
375
+ print(f"📊 Results saved to: {results_file}")
376
+
377
+ # Show system comparison
378
+ for system, system_results in results.items():
379
+ if system_results:
380
+ avg_actionability = sum(r['actionability_score'] for r in system_results) / len(system_results)
381
+ avg_evidence = sum(r['evidence_score'] for r in system_results) / len(system_results)
382
+ print(f" 🏥 {system.upper()}: Actionability={avg_actionability:.3f}, Evidence={avg_evidence:.3f} ({len(system_results)} queries)")
383
+ else:
384
+ print(f" ❌ {system.upper()}: No successful evaluations")
385
+
386
+ return 0
387
+
388
+ except Exception as e:
389
+ print(f"❌ Fixed judge evaluation failed: {e}")
390
+ return 1
391
+
392
+
393
+ if __name__ == "__main__":
394
+ exit(main())
evaluation/latency_evaluator.py CHANGED
@@ -796,8 +796,8 @@ if __name__ == "__main__":
796
  query_file = sys.argv[1]
797
  else:
798
  # Default to evaluation/single_test_query.txt for initial testing
799
- # TODO: Change to pre_user_query_evaluate.txt for full evaluation
800
- query_file = Path(__file__).parent / "pre_user_query_evaluate.txt"
801
 
802
  if not os.path.exists(query_file):
803
  print(f"❌ Query file not found: {query_file}")
 
796
  query_file = sys.argv[1]
797
  else:
798
  # Default to evaluation/single_test_query.txt for initial testing
799
+ # TODO: Change to pre_user_query_evaluate.txt for full evaluation, user_query.txt for formal evaluation
800
+ query_file = Path(__file__).parent / "user_query.txt"
801
 
802
  if not os.path.exists(query_file):
803
  print(f"❌ Query file not found: {query_file}")
evaluation/user_query.txt CHANGED
@@ -1,34 +1,14 @@
1
- 以下是九個以「我在問你」口吻設計的快速諮詢 prompts,分為三類,每類三題:
2
 
3
 
4
- 1.
5
- Diagnosis-Focused
6
- 60-year-old patient with hypertension history, sudden chest pain. What are possible causes and how to assess?
7
 
8
- 2.
9
- Treatment-Focused
10
- Suspected acute ischemic stroke. Tell me the next steps to take
11
 
12
- 3.
13
- 20 y/f , porphyria, sudden seizure. What are possible causes and complete management workflow?
14
 
15
- (測試時可以先用這三題看結果,如果要debug、調整完,再用下面的)
16
- ---
17
-
18
- ### 一、Diagnosis-Focused(診斷為主)
19
-
20
- 1. I have a 68-year-old man with atrial fibrillation presenting with sudden slurred speech and right-sided weakness. what are the possible diagnoses, and how would you evaluate them?
21
- 2. A 40-year-old woman reports fever, urinary frequency, and dysuria. what differential diagnoses should I consider, and which tests would you order?
22
- 3. A 50-year-old patient has progressive dyspnea on exertion and orthopnea over two weeks. what are the likely causes, and what diagnostic steps should I take?
23
-
24
- ### 二、Treatment-Focused(治療為主)
25
-
26
- 4. ECG shows a suspected acute STEMI. what immediate interventions should I initiate in the next five minutes?
27
- 5. I have a patient diagnosed with bacterial meningitis. What empiric antibiotic regimen and supportive measures should I implement?
28
- 6. A patient is in septic shock with BP 80/50 mmHg and HR 120 bpm—what fluid resuscitation and vasopressor strategy would you recommend?
29
-
30
- ### 三、Mixed(診斷+治療綜合)
31
-
32
- 7. A 75-year-old diabetic presents with a non-healing foot ulcer and fever—what differential for osteomyelitis, diagnostic workup, and management plan do you suggest?
33
- 8. A 60-year-old COPD patient has worsening dyspnea and hypercapnia on ABG. How would you confirm the diagnosis, and what is your stepwise treatment approach?
34
- 9. A 28-year-old woman is experiencing postpartum hemorrhage. what are the possible causes, what immediate resuscitation steps should I take, and how would you proceed with definitive management?
 
 
1
 
2
 
3
+ 1.diagnosis: I have a 68-year-old man with atrial fibrillation presenting with sudden slurred speech and right-sided weakness. what are the possible diagnoses, and how would you evaluate them?
4
+ 2.diagnosis: A 40-year-old woman reports fever, urinary frequency, and dysuria. what differential diagnoses should I consider, and which tests would you order?
5
+ 3.diagnosis: A 50-year-old patient has progressive dyspnea on exertion and orthopnea over two weeks. what are the likely causes, and what diagnostic steps should I take?
6
 
7
+ 4.treatment: ECG shows a suspected acute STEMI. what immediate interventions should I initiate in the next five minutes?
8
+ 5.treatment: I have a patient diagnosed with bacterial meningitis. What empiric antibiotic regimen and supportive measures should I implement?
9
+ 6.treatment: A patient is in septic shock with BP 80/50 mmHg and HR 120 bpm—what fluid resuscitation and vasopressor strategy would you recommend?
10
 
 
 
11
 
12
+ 7.mixed/complicated: A 75-year-old diabetic presents with a non-healing foot ulcer and fever—what differential for osteomyelitis, diagnostic workup, and management plan do you suggest?
13
+ 8.mixed/complicated: A 60-year-old COPD patient has worsening dyspnea and hypercapnia on ABG. How would you confirm the diagnosis, and what is your stepwise treatment approach?
14
+ 9.mixed/complicated: A 28-year-old woman is experiencing postpartum hemorrhage. what are the possible causes, what immediate resuscitation steps should I take, and how would you proceed with definitive management?