KeenWoo commited on
Commit
9e6c5a6
·
verified ·
1 Parent(s): f651cbc

Delete evaluate.py

Browse files
Files changed (1) hide show
  1. evaluate.py +0 -453
evaluate.py DELETED
@@ -1,453 +0,0 @@
1
- # evaluate.py
2
-
3
- import os
4
- import json
5
- import time
6
- import re # <-- ADD THIS IMPORT
7
- import pandas as pd
8
- from typing import List, Dict, Any
9
- from pathlib import Path
10
-
11
- # --- Imports from the main application ---
12
- # In evaluate.py
13
-
14
- try:
15
- from alz_companion.agent import (
16
- make_rag_chain, route_query_type, detect_tags_from_query,
17
- answer_query, call_llm, build_or_load_vectorstore
18
- )
19
- from alz_companion.prompts import FAITHFULNESS_JUDGE_PROMPT
20
- from langchain_community.vectorstores import FAISS
21
- # --- Also move this import inside the try block for consistency ---
22
- from langchain.schema import Document
23
-
24
- except ImportError:
25
- # --- START: FALLBACK DEFINITIONS ---
26
- class FAISS:
27
- def __init__(self): self.docstore = type('obj', (object,), {'_dict': {}})()
28
- def add_documents(self, docs): pass
29
- def save_local(self, path): pass
30
- @classmethod
31
- def from_documents(cls, docs, embeddings=None): return cls()
32
-
33
- class Document:
34
- def __init__(self, page_content, metadata=None):
35
- self.page_content = page_content
36
- self.metadata = metadata or {}
37
-
38
- def make_rag_chain(*args, **kwargs): return lambda q, **k: {"answer": f"(Eval Fallback) You asked: {q}", "sources": []}
39
- def route_query_type(q, **kwargs): return "general_conversation"
40
- def detect_tags_from_query(*args, **kwargs): return {}
41
- def answer_query(chain, q, **kwargs): return chain(q, **kwargs)
42
- def call_llm(*args, **kwargs): return "{}"
43
-
44
- # --- ADD FALLBACK DEFINITION FOR THE MISSING FUNCTION ---
45
- def build_or_load_vectorstore(docs, index_path, is_personal=False):
46
- return FAISS()
47
- # --- END OF ADDITION ---
48
-
49
- FAITHFULNESS_JUDGE_PROMPT = ""
50
- print("WARNING: Could not import from alz_companion. Evaluation functions will use fallbacks.")
51
- # --- END: FALLBACK DEFINITIONS ---
52
-
53
-
54
- # --- LLM-as-a-Judge Prompt for Answer Correctness ---
55
- ANSWER_CORRECTNESS_JUDGE_PROMPT = """You are an expert evaluator. Your task is to assess the factual correctness of a generated answer against a ground truth answer.
56
-
57
- - GROUND_TRUTH_ANSWER: This is the gold-standard, correct answer.
58
- - GENERATED_ANSWER: This is the answer produced by the AI model.
59
-
60
- Evaluate if the GENERATED_ANSWER is factually aligned with the GROUND_TRUTH_ANSWER. Ignore minor differences in phrasing, tone, or structure. The key is factual accuracy.
61
-
62
- Respond with a single JSON object containing a float score from 0.0 to 1.0.
63
- - 1.0: The generated answer is factually correct and aligns perfectly with the ground truth.
64
- - 0.5: The generated answer is partially correct but misses key information or contains minor inaccuracies.
65
- - 0.0: The generated answer is factually incorrect or contradicts the ground truth.
66
-
67
- --- DATA TO EVALUATE ---
68
- GROUND_TRUTH_ANSWER:
69
- {ground_truth_answer}
70
-
71
- GENERATED_ANSWER:
72
- {generated_answer}
73
- ---
74
-
75
- Return a single JSON object with your score:
76
- {{
77
- "correctness_score": <float>
78
- }}
79
- """
80
-
81
- test_fixtures = []
82
-
83
- def load_test_fixtures():
84
- """Loads fixtures into the test_fixtures list."""
85
- global test_fixtures
86
- test_fixtures = []
87
- env_path = os.environ.get("TEST_FIXTURES_PATH", "").strip()
88
- candidates = [env_path] if env_path else ["conversation_test_fixtures_v10.jsonl", "conversation_test_fixtures_v8.jsonl"]
89
- path = next((p for p in candidates if p and os.path.exists(p)), None)
90
- if not path:
91
- print("Warning: No test fixtures file found for evaluation.")
92
- return
93
-
94
- # Use the corrected v10 file if available
95
- if "conversation_test_fixtures_v10.jsonl" in path:
96
- print(f"Using corrected test fixtures: {path}")
97
-
98
- with open(path, "r", encoding="utf-8") as f:
99
- for line in f:
100
- try:
101
- test_fixtures.append(json.loads(line))
102
- except json.JSONDecodeError:
103
- print(f"Skipping malformed JSON line in {path}")
104
- print(f"Loaded {len(test_fixtures)} fixtures for evaluation from {path}")
105
-
106
- def evaluate_nlu_tags(expected: Dict[str, Any], actual: Dict[str, Any], tag_key: str, expected_key_override: str = None) -> Dict[str, float]:
107
- lookup_key = expected_key_override or tag_key
108
- expected_raw = expected.get(lookup_key, [])
109
- expected_set = set(expected_raw if isinstance(expected_raw, list) else [expected_raw]) if expected_raw and expected_raw != "None" else set()
110
- actual_raw = actual.get(tag_key, [])
111
- actual_set = set(actual_raw if isinstance(actual_raw, list) else [actual_raw]) if actual_raw and actual_raw != "None" else set()
112
- if not expected_set and not actual_set:
113
- return {"precision": 1.0, "recall": 1.0, "f1_score": 1.0}
114
- true_positives = len(expected_set.intersection(actual_set))
115
- precision = true_positives / len(actual_set) if actual_set else 0.0
116
- recall = true_positives / len(expected_set) if expected_set else 0.0
117
- f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0.0
118
- return {"precision": precision, "recall": recall, "f1_score": f1_score}
119
-
120
- def _parse_judge_json(raw_str: str) -> dict | None:
121
- try:
122
- start_brace = raw_str.find('{')
123
- end_brace = raw_str.rfind('}')
124
- if start_brace != -1 and end_brace > start_brace:
125
- json_str = raw_str[start_brace : end_brace + 1]
126
- return json.loads(json_str)
127
- return None
128
- except (json.JSONDecodeError, AttributeError):
129
- return None
130
-
131
- # --- NEW: helpers for categorisation and error-class labelling ---
132
- def _categorize_test(test_id: str) -> str:
133
- tid = (test_id or "").lower()
134
- if "synonym" in tid: return "synonym"
135
- if "multi_fact" in tid or "multi-hop" in tid or "multihop" in tid: return "multi_fact"
136
- if "omission" in tid: return "omission"
137
- if "hallucination" in tid: return "hallucination"
138
- if "time" in tid or "temporal" in tid: return "temporal"
139
- if "context" in tid: return "context_disambig"
140
- return "baseline"
141
-
142
- def _classify_error(gt: str, gen: str) -> str:
143
- import re
144
- gt = (gt or "").strip().lower()
145
- gen = (gen or "").strip().lower()
146
- if not gen:
147
- return "empty"
148
- if not gt:
149
- return "hallucination" if gen else "empty"
150
- if gt in gen:
151
- return "paraphrase"
152
- gt_tokens = set([t for t in re.split(r'\W+', gt) if t])
153
- gen_tokens = set([t for t in re.split(r'\W+', gen) if t])
154
- overlap = len(gt_tokens & gen_tokens) / max(1, len(gt_tokens))
155
- if overlap >= 0.3:
156
- return "omission"
157
- return "contradiction"
158
-
159
- ## NEW
160
- # In evaluate.py
161
- def run_comprehensive_evaluation(
162
- vs_general: FAISS,
163
- vs_personal: FAISS,
164
- nlu_vectorstore: FAISS,
165
- vs_playbook: FAISS, # <-- Add the new parameter here
166
- config: Dict[str, Any],
167
- storage_path: Path # <-- ADD THIS PARAMETER
168
- ):
169
- # --- START: ULTIMATE SANITY CHECK ---
170
- print("\n" + "#"*20 + " SANITY CHECK: STATE OF 'vs_personal' AT EXECUTION " + "#"*20)
171
- if vs_personal and hasattr(vs_personal.docstore, '_dict'):
172
- all_docs = list(vs_personal.docstore._dict.values())
173
- doc_count = len(all_docs)
174
- print(f" - The 'vs_personal' object received by this function contains {doc_count} document(s).")
175
- print(" - LISTING DOCUMENT SOURCES:")
176
- if not all_docs:
177
- print(" - The docstore is empty.")
178
- else:
179
- for i, doc in enumerate(all_docs):
180
- source = doc.metadata.get('source', 'N/A')
181
- print(f" - Document #{i+1}: source='{source}'")
182
- else:
183
- print(" - CRITICAL FAILURE: The 'vs_personal' object received is None or invalid.")
184
- print("#"*90 + "\n")
185
- # --- END: ULTIMATE SANITY CHECK ---
186
-
187
- global test_fixtures
188
- if not test_fixtures:
189
- # The return signature is now back to 3 items.
190
- return "No test fixtures loaded.", [], []
191
-
192
- # --- START OF FIX ---
193
- # We will now use the 'vs_personal' passed directly from the main application.
194
- # The entire block that created a temporary 'vs_personal_test' has been REMOVED.
195
- print("\n--- Using live personal vectorstore for FQ/MH tests ---")
196
- if vs_personal and hasattr(vs_personal.docstore, '_dict'):
197
- print(f"Personal vectorstore contains {len(vs_personal.docstore._dict)} documents.")
198
- else:
199
- print("WARNING: Personal vectorstore from main app is empty or invalid.")
200
- # --- END OF FIX ---
201
-
202
- def _norm(label: str) -> str:
203
- label = (label or "").strip().lower()
204
- return "factual_question" if "factual" in label else label
205
-
206
- print("Starting comprehensive evaluation...")
207
- results: List[Dict[str, Any]] = []
208
- total_fixtures = len(test_fixtures)
209
- print(f"\n🚀 STARTING EVALUATION on {total_fixtures} test cases...")
210
-
211
- for i, fx in enumerate(test_fixtures):
212
- test_id = fx.get("test_id", "N/A")
213
- print(f"--- Processing Test Case {i+1}/{total_fixtures}: ID = {test_id} ---")
214
-
215
- turns = fx.get("turns") or []
216
- api_chat_history = [{"role": t.get("role"), "content": t.get("text")} for t in turns]
217
- query = next((t["content"] for t in reversed(api_chat_history) if (t.get("role") or "user").lower() == "user"), "")
218
- if not query: continue
219
-
220
- print(f'Query: "{query}"')
221
-
222
- ground_truth = fx.get("ground_truth", {})
223
- expected_route = _norm(ground_truth.get("expected_route", "caregiving_scenario"))
224
- expected_tags = ground_truth.get("expected_tags", {})
225
- actual_route = _norm(route_query_type(query))
226
- route_correct = (actual_route == expected_route)
227
-
228
- actual_tags: Dict[str, Any] = {}
229
- if "caregiving_scenario" in actual_route:
230
- actual_tags = detect_tags_from_query(
231
- query, nlu_vectorstore=nlu_vectorstore,
232
- behavior_options=config["behavior_tags"], emotion_options=config["emotion_tags"],
233
- topic_options=config["topic_tags"], context_options=config["context_tags"],
234
- )
235
-
236
- behavior_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_behaviors")
237
- emotion_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_emotion")
238
- topic_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_topics")
239
- context_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_contexts")
240
-
241
- # --- DEFINITIVE BUG FIX for Tag Extraction ---
242
- final_tags = {}
243
- if "caregiving_scenario" in actual_route:
244
- behaviors = actual_tags.get("detected_behaviors")
245
- topics = actual_tags.get("detected_topics")
246
-
247
- primary_behavior = None
248
- if isinstance(behaviors, list) and behaviors:
249
- primary_behavior = behaviors[0]
250
- elif isinstance(behaviors, str) and behaviors != "None":
251
- primary_behavior = behaviors
252
-
253
- primary_topic = None
254
- if isinstance(topics, list) and topics:
255
- primary_topic = topics[0]
256
- elif isinstance(topics, str) and topics != "None":
257
- primary_topic = topics
258
-
259
- final_tags = {
260
- "scenario_tag": primary_behavior,
261
- "emotion_tag": actual_tags.get("detected_emotion"),
262
- "topic_tag": primary_topic,
263
- "context_tags": actual_tags.get("detected_contexts", [])
264
- }
265
- # --- END OF BUG FIX ---
266
-
267
-
268
- current_test_role = fx.get("test_role", "patient")
269
- rag_chain = make_rag_chain(
270
- vs_general,
271
- vs_personal, # Use the temporary, correctly populated personal store
272
- vs_playbook, # <-- Pass the playbook to the chain inside the test
273
- role=current_test_role,
274
- for_evaluation=True
275
- )
276
-
277
- t0 = time.time()
278
- response = answer_query(rag_chain, query, query_type=actual_route, chat_history=api_chat_history, **final_tags)
279
- latency_ms = round((time.time() - t0) * 1000.0, 1)
280
- answer_text = response.get("answer", "ERROR")
281
- ground_truth_answer = ground_truth.get("ground_truth_answer")
282
-
283
- category = _categorize_test(test_id)
284
- error_class = _classify_error(ground_truth_answer, answer_text)
285
-
286
- expected_sources_set = set(map(str, ground_truth.get("expected_sources", [])))
287
- raw_sources = response.get("sources", [])
288
- actual_sources_set = set(map(str, raw_sources if isinstance(raw_sources, (list, tuple)) else [raw_sources]))
289
-
290
- print("\n" + "-"*20 + " SOURCE EVALUATION " + "-"*20)
291
- print(f" - Expected: {sorted(list(expected_sources_set))}")
292
- print(f" - Actual: {sorted(list(actual_sources_set))}")
293
-
294
- true_positives = expected_sources_set.intersection(actual_sources_set)
295
- false_positives = actual_sources_set - expected_sources_set
296
- false_negatives = expected_sources_set - actual_sources_set
297
-
298
- if not false_positives and not false_negatives:
299
- print(" - Result: ✅ Perfect Match!")
300
- else:
301
- if false_positives:
302
- print(f" - 🔻 False Positives (hurts precision): {sorted(list(false_positives))}")
303
- if false_negatives:
304
- print(f" - 🔻 False Negatives (hurts recall): {sorted(list(false_negatives))}")
305
- print("-"*59 + "\n")
306
-
307
- context_precision, context_recall = 0.0, 0.0
308
- if expected_sources_set or actual_sources_set:
309
- tp = len(expected_sources_set.intersection(actual_sources_set))
310
- if len(actual_sources_set) > 0: context_precision = tp / len(actual_sources_set)
311
- if len(expected_sources_set) > 0: context_recall = tp / len(expected_sources_set)
312
- elif not expected_sources_set and not actual_sources_set:
313
- context_precision, context_recall = 1.0, 1.0
314
-
315
- print("\n" + "-"*20 + " ANSWER & CORRECTNESS EVALUATION " + "-"*20)
316
- print(f" - Ground Truth Answer: {ground_truth_answer}")
317
- print(f" - Generated Answer: {answer_text}")
318
- print("-" * 59)
319
-
320
- answer_correctness_score = None
321
- if ground_truth_answer and "ERROR" not in answer_text:
322
- try:
323
- judge_msg = ANSWER_CORRECTNESS_JUDGE_PROMPT.format(ground_truth_answer=ground_truth_answer, generated_answer=answer_text)
324
- print(f" - Judge Prompt Sent:\n{judge_msg}")
325
- raw_correctness = call_llm([{"role": "user", "content": judge_msg}], temperature=0.0)
326
- print(f" - Judge Raw Response: {raw_correctness}")
327
- correctness_data = _parse_judge_json(raw_correctness)
328
- if correctness_data and "correctness_score" in correctness_data:
329
- answer_correctness_score = float(correctness_data["correctness_score"])
330
- print(f" - Final Score: {answer_correctness_score}")
331
- except Exception as e:
332
- print(f"ERROR during answer correctness judging: {e}")
333
-
334
-
335
- faithfulness = None
336
- hallucination_rate = None # <-- CHANGE 1: New variable name
337
- source_docs = response.get("source_documents", [])
338
-
339
- if source_docs and "ERROR" not in answer_text:
340
- context_blob = "\n---\n".join([doc.page_content for doc in source_docs])
341
- judge_msg = FAITHFULNESS_JUDGE_PROMPT.format(query=query, answer=answer_text, sources=context_blob)
342
- try:
343
- if context_blob.strip():
344
- raw = call_llm([{"role": "user", "content": judge_msg}], temperature=0.0)
345
- data = _parse_judge_json(raw)
346
- if data:
347
- denom = data.get("supported", 0) + data.get("contradicted", 0) + data.get("not_enough_info", 0)
348
- if denom > 0:
349
- faithfulness = round(data.get("supported", 0) / denom, 3)
350
- # Numerator is the sum of unsupported sentences
351
- hallucinated_sentences = data.get("contradicted", 0) + data.get("not_enough_info", 0)
352
- hallucination_rate = round(hallucinated_sentences / denom, 3) # <-- CHANGE 2: New formula
353
- elif data.get("ignored", 0) > 0:
354
- faithfulness = 1.0
355
- # If all sentences are ignored (e.g., pure empathy), hallucination is 0
356
- hallucination_rate = 0.0 # <-- CHANGE 3: A score of 0 is better here
357
- except Exception as e:
358
- print(f"ERROR during faithfulness judging: {e}")
359
-
360
- sources_pretty = ", ".join(sorted(s)) if (s:=actual_sources_set) else ""
361
- results.append({
362
- "test_id": fx.get("test_id", "N/A"), "title": fx.get("title", "N/A"),
363
- "route_correct": "✅" if route_correct else "❌", "expected_route": expected_route, "actual_route": actual_route,
364
- "behavior_f1": f"{behavior_metrics['f1_score']:.2f}", "emotion_f1": f"{emotion_metrics['f1_score']:.2f}",
365
- "topic_f1": f"{topic_metrics['f1_score']:.2f}", "context_f1": f"{context_metrics['f1_score']:.2f}",
366
- "generated_answer": answer_text, "sources": sources_pretty, "source_count": len(actual_sources_set),
367
- "latency_ms": latency_ms,
368
- "faithfulness": faithfulness, "hallucination_rate": hallucination_rate, # <-- CHANGE 4: Use the new key
369
- "context_precision": context_precision, "context_recall": context_recall,
370
- "answer_correctness": answer_correctness_score,
371
- "category": category,
372
- "error_class": error_class
373
- })
374
-
375
- df = pd.DataFrame(results)
376
- summary_text, table_rows, headers = "No valid test fixtures found to evaluate.", [], []
377
-
378
- if not df.empty:
379
- # --- CHANGE 5: Update the column list ---
380
- cols = ["test_id", "title", "route_correct", "expected_route", "actual_route", "context_precision", "context_recall", "hallucination_rate", "faithfulness", "answer_correctness", "behavior_f1", "emotion_f1", "topic_f1", "context_f1", "source_count", "latency_ms", "sources", "generated_answer", "category", "error_class"]
381
- df = df[[c for c in cols if c in df.columns]]
382
-
383
- # --- START OF MODIFICATION ---
384
- pct = df["route_correct"].value_counts(normalize=True).get("✅", 0) * 100
385
- to_f = lambda s: pd.to_numeric(s, errors="coerce")
386
-
387
- # Calculate the mean for the NLU F1 scores
388
- bf1_mean = to_f(df["behavior_f1"]).mean() * 100
389
- ef1_mean = to_f(df["emotion_f1"]).mean() * 100
390
- tf1_mean = to_f(df["topic_f1"]).mean() * 100
391
- cf1_mean = to_f(df["context_f1"]).mean() * 100
392
-
393
- # Calculate the mean for Faithfulness
394
- faith_mean = to_f(df["faithfulness"]).mean() * 100
395
-
396
- # --- CHANGE 6: Calculate the mean for the new metric ---
397
- halluc_mean = to_f(df["hallucination_rate"]).mean() * 100
398
-
399
- # --- CHANGE 7: Update the summary f-string ---
400
- summary_text = f"""## Evaluation Summary
401
- - **Routing Accuracy**: {pct:.2f}%
402
- - **Behaviour F1 (avg)**: {bf1_mean:.2f}%
403
- - **Emotion F1 (avg)**: {ef1_mean:.2f}%
404
- - **Topic F1 (avg)**: {tf1_mean:.2f}%
405
- - **Context F1 (avg)**: {cf1_mean:.2f}%
406
- - **RAG: Context Precision**: {(to_f(df["context_precision"]).mean() * 100):.1f}%
407
- - **RAG: Context Recall**: {(to_f(df["context_recall"]).mean() * 100):.1f}%
408
- - **RAG: Hallucination Rate**: {halluc_mean:.1f}% (Lower is better)
409
- - **RAG: Faithfulness**: {faith_mean:.1f}%
410
- - **RAG: Answer Correctness (LLM-judge)**: {(to_f(df["answer_correctness"]).mean() * 100):.1f}%"""
411
- # --- END OF MODIFICATION ---
412
-
413
-
414
- df_display = df.rename(columns={"context_precision": "Ctx. Precision", "context_recall": "Ctx. Recall"})
415
- table_rows = df_display.values.tolist()
416
- headers = df_display.columns.tolist()
417
-
418
-
419
- output_path = "evaluation_results.csv"
420
- df.to_csv(output_path, index=False, encoding="utf-8")
421
- print(f"Evaluation results saved to {output_path}")
422
-
423
- log_path = storage_path / "evaluation_log.txt"
424
- with open(log_path, "w", encoding="utf-8") as logf:
425
- logf.write("===== Detailed Evaluation Run =====\n")
426
- df_string = df.to_string(index=False)
427
- logf.write(df_string)
428
- logf.write("\n\n")
429
-
430
- try:
431
- cat_means = df.groupby("category")["answer_correctness"].mean().reset_index()
432
- print("\n📊 Correctness by Category:")
433
- print(cat_means.to_string(index=False))
434
- logf.write("\n📊 Correctness by Category:\n")
435
- logf.write(cat_means.to_string(index=False))
436
- logf.write("\n")
437
- except Exception as e:
438
- print(f"WARNING: Could not compute category breakdown: {e}")
439
-
440
- try:
441
- confusion = pd.crosstab(df["category"], df["error_class"], rownames=["Category"], colnames=["Error Class"], dropna=False)
442
- print("\n📊 Error Class Distribution by Category:")
443
- print(confusion.to_string())
444
- logf.write("\n📊 Error Class Distribution by Category:\n")
445
- logf.write(confusion.to_string())
446
- logf.write("\n")
447
- except Exception as e:
448
- print(f"WARNING: Could not build confusion matrix: {e}")
449
-
450
- return summary_text, table_rows, headers
451
- # return summary_text, table_rows
452
-
453
- ## END