KeenWoo commited on
Commit
f5ded32
·
verified ·
1 Parent(s): bab2b13

Delete evaluate.py

Browse files
Files changed (1) hide show
  1. evaluate.py +0 -446
evaluate.py DELETED
@@ -1,446 +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
- Respond with a single JSON object containing a float score from 0.0 to 1.0.
62
- - 1.0: The generated answer is factually correct and aligns perfectly with the ground truth.
63
- - 0.7: The generated answer is partially correct but misses key information or contains minor inaccuracies.
64
- - 0.0: The generated answer is factually incorrect or contradicts the ground truth.
65
-
66
- --- DATA TO EVALUATE ---
67
- GROUND_TRUTH_ANSWER:
68
- {ground_truth_answer}
69
-
70
- GENERATED_ANSWER:
71
- {generated_answer}
72
- ---
73
- Return a single JSON object with your score:
74
- {{
75
- "correctness_score": <float>
76
- }}
77
- """
78
-
79
-
80
-
81
-
82
-
83
- test_fixtures = []
84
-
85
- def load_test_fixtures():
86
- """Loads fixtures into the test_fixtures list."""
87
- global test_fixtures
88
- test_fixtures = []
89
- env_path = os.environ.get("TEST_FIXTURES_PATH", "").strip()
90
-
91
- # --- START: DEFINITIVE FIX ---
92
- # The old code used a relative path, which is unreliable.
93
- # This new code builds an absolute path to the fixture file based on
94
- # the location of this (evaluate.py) script.
95
- # script_dir = Path(__file__).parent
96
- # default_fixture_file = script_dir / "small_test_cases_v10.jsonl"
97
- # candidates = [env_path] if env_path else [str(default_fixture_file)]
98
-
99
- # --- END: DEFINITIVE FIX ---
100
- # candidates = [env_path] if env_path else ["conversation_test_fixtures_v10.jsonl"]
101
- candidates = [env_path] if env_path else ["small_test_cases_v10.jsonl"]
102
-
103
- path = next((p for p in candidates if p and os.path.exists(p)), None)
104
- if not path:
105
- print("Warning: No test fixtures file found for evaluation.")
106
- return
107
-
108
- if "small_test_cases_v10.jsonl" in path:
109
- # Use the corrected v10 file if available
110
- # if "conversation_test_fixtures_v10.jsonl" in path:
111
- print(f"Using corrected test fixtures: {path}")
112
-
113
- with open(path, "r", encoding="utf-8") as f:
114
- for line in f:
115
- try:
116
- test_fixtures.append(json.loads(line))
117
- except json.JSONDecodeError:
118
- print(f"Skipping malformed JSON line in {path}")
119
- print(f"Loaded {len(test_fixtures)} fixtures for evaluation from {path}")
120
-
121
-
122
- def evaluate_nlu_tags(expected: Dict[str, Any], actual: Dict[str, Any], tag_key: str, expected_key_override: str = None) -> Dict[str, float]:
123
- lookup_key = expected_key_override or tag_key
124
- expected_raw = expected.get(lookup_key, [])
125
- expected_set = set(expected_raw if isinstance(expected_raw, list) else [expected_raw]) if expected_raw and expected_raw != "None" else set()
126
- actual_raw = actual.get(tag_key, [])
127
- actual_set = set(actual_raw if isinstance(actual_raw, list) else [actual_raw]) if actual_raw and actual_raw != "None" else set()
128
- if not expected_set and not actual_set:
129
- return {"precision": 1.0, "recall": 1.0, "f1_score": 1.0}
130
- true_positives = len(expected_set.intersection(actual_set))
131
- precision = true_positives / len(actual_set) if actual_set else 0.0
132
- recall = true_positives / len(expected_set) if expected_set else 0.0
133
- f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0.0
134
- return {"precision": precision, "recall": recall, "f1_score": f1_score}
135
-
136
- def _parse_judge_json(raw_str: str) -> dict | None:
137
- try:
138
- start_brace = raw_str.find('{')
139
- end_brace = raw_str.rfind('}')
140
- if start_brace != -1 and end_brace > start_brace:
141
- json_str = raw_str[start_brace : end_brace + 1]
142
- return json.loads(json_str)
143
- return None
144
- except (json.JSONDecodeError, AttributeError):
145
- return None
146
-
147
- # --- NEW: helpers for categorisation and error-class labelling ---
148
- def _categorize_test(test_id: str) -> str:
149
- tid = (test_id or "").lower()
150
- if "synonym" in tid: return "synonym"
151
- if "multi_fact" in tid or "multi-hop" in tid or "multihop" in tid: return "multi_fact"
152
- if "omission" in tid: return "omission"
153
- if "hallucination" in tid: return "hallucination"
154
- if "time" in tid or "temporal" in tid: return "temporal"
155
- if "context" in tid: return "context_disambig"
156
- return "baseline"
157
-
158
- def _classify_error(gt: str, gen: str) -> str:
159
- import re
160
- gt = (gt or "").strip().lower()
161
- gen = (gen or "").strip().lower()
162
- if not gen:
163
- return "empty"
164
- if not gt:
165
- return "hallucination" if gen else "empty"
166
- if gt in gen:
167
- return "paraphrase"
168
- gt_tokens = set([t for t in re.split(r'\W+', gt) if t])
169
- gen_tokens = set([t for t in re.split(r'\W+', gen) if t])
170
- overlap = len(gt_tokens & gen_tokens) / max(1, len(gt_tokens))
171
- if overlap >= 0.3:
172
- return "omission"
173
- return "contradiction"
174
-
175
- ## NEW
176
- # In evaluate.py
177
- def run_comprehensive_evaluation(
178
- vs_general: FAISS,
179
- vs_personal: FAISS,
180
- nlu_vectorstore: FAISS,
181
- config: Dict[str, Any],
182
- storage_path: Path # <-- ADD THIS PARAMETER
183
- ):
184
- global test_fixtures
185
- if not test_fixtures:
186
- # The return signature is now back to 3 items.
187
- return "No test fixtures loaded.", [], []
188
-
189
- vs_personal_test = None
190
- personal_context_docs = []
191
- personal_context_file = "sample_data/1 Complaints of a Dutiful Daughter.txt"
192
-
193
- if os.path.exists(personal_context_file):
194
- print(f"Found personal context file for evaluation: '{personal_context_file}'")
195
- with open(personal_context_file, "r", encoding="utf-8") as f:
196
- content = f.read()
197
- doc = Document(page_content=content, metadata={"source": os.path.basename(personal_context_file)})
198
- personal_context_docs.append(doc)
199
- else:
200
- print(f"WARNING: Personal context file not found at '{personal_context_file}'. Factual tests will likely fail.")
201
-
202
- vs_personal_test = build_or_load_vectorstore(
203
- personal_context_docs,
204
- index_path="tmp/eval_personal_index",
205
- is_personal=True
206
- )
207
- print(f"Successfully created temporary personal vectorstore with {len(personal_context_docs)} document(s) for this evaluation run.")
208
-
209
- def _norm(label: str) -> str:
210
- label = (label or "").strip().lower()
211
- return "factual_question" if "factual" in label else label
212
-
213
- print("Starting comprehensive evaluation...")
214
- results: List[Dict[str, Any]] = []
215
- total_fixtures = len(test_fixtures)
216
- print(f"\n🚀 STARTING EVALUATION on {total_fixtures} test cases...")
217
-
218
- for i, fx in enumerate(test_fixtures):
219
- test_id = fx.get("test_id", "N/A")
220
- print(f"--- Processing Test Case {i+1}/{total_fixtures}: ID = {test_id} ---")
221
-
222
- turns = fx.get("turns") or []
223
- api_chat_history = [{"role": t.get("role"), "content": t.get("text")} for t in turns]
224
- query = next((t["content"] for t in reversed(api_chat_history) if (t.get("role") or "user").lower() == "user"), "")
225
- if not query: continue
226
-
227
- print(f'Query: "{query}"')
228
-
229
- ground_truth = fx.get("ground_truth", {})
230
- expected_route = _norm(ground_truth.get("expected_route", "caregiving_scenario"))
231
- expected_tags = ground_truth.get("expected_tags", {})
232
- actual_route = _norm(route_query_type(query))
233
- route_correct = (actual_route == expected_route)
234
-
235
- actual_tags: Dict[str, Any] = {}
236
- if "caregiving_scenario" in actual_route:
237
- actual_tags = detect_tags_from_query(
238
- query, nlu_vectorstore=nlu_vectorstore,
239
- behavior_options=config["behavior_tags"], emotion_options=config["emotion_tags"],
240
- topic_options=config["topic_tags"], context_options=config["context_tags"],
241
- )
242
-
243
- behavior_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_behaviors")
244
- emotion_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_emotion")
245
- topic_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_topics")
246
- context_metrics = evaluate_nlu_tags(expected_tags, actual_tags, "detected_contexts")
247
-
248
- final_tags = {}
249
- if "caregiving_scenario" in actual_route:
250
- final_tags = {
251
- "scenario_tag": (actual_tags.get("detected_behaviors") or [None])[0],
252
- "emotion_tag": actual_tags.get("detected_emotion"),
253
- "topic_tag": (actual_tags.get("detected_topics") or [None])[0],
254
- "context_tags": actual_tags.get("detected_contexts", [])
255
- }
256
-
257
- current_test_role = fx.get("test_role", "patient")
258
- rag_chain = make_rag_chain(
259
- vs_general,
260
- vs_personal_test,
261
- role=current_test_role,
262
- for_evaluation=True
263
- )
264
-
265
- t0 = time.time()
266
- response = answer_query(rag_chain, query, query_type=actual_route, chat_history=api_chat_history, **final_tags)
267
- latency_ms = round((time.time() - t0) * 1000.0, 1)
268
- answer_text = response.get("answer", "ERROR")
269
- ground_truth_answer = ground_truth.get("ground_truth_answer")
270
-
271
- category = _categorize_test(test_id)
272
- error_class = _classify_error(ground_truth_answer, answer_text)
273
-
274
- expected_sources_set = set(map(str, ground_truth.get("expected_sources", [])))
275
- raw_sources = response.get("sources", [])
276
- actual_sources_set = set(map(str, raw_sources if isinstance(raw_sources, (list, tuple)) else [raw_sources]))
277
-
278
- print("\n" + "-"*20 + " SOURCE EVALUATION " + "-"*20)
279
- print(f" - Expected: {sorted(list(expected_sources_set))}")
280
- print(f" - Actual: {sorted(list(actual_sources_set))}")
281
-
282
- true_positives = expected_sources_set.intersection(actual_sources_set)
283
- false_positives = actual_sources_set - expected_sources_set
284
- false_negatives = expected_sources_set - actual_sources_set
285
-
286
- if not false_positives and not false_negatives:
287
- print(" - Result: ✅ Perfect Match!")
288
- else:
289
- if false_positives:
290
- print(f" - 🔻 False Positives (hurts precision): {sorted(list(false_positives))}")
291
- if false_negatives:
292
- print(f" - 🔻 False Negatives (hurts recall): {sorted(list(false_negatives))}")
293
- print("-"*59 + "\n")
294
-
295
- context_precision, context_recall = 0.0, 0.0
296
- if expected_sources_set or actual_sources_set:
297
- tp = len(expected_sources_set.intersection(actual_sources_set))
298
- if len(actual_sources_set) > 0: context_precision = tp / len(actual_sources_set)
299
- if len(expected_sources_set) > 0: context_recall = tp / len(expected_sources_set)
300
- elif not expected_sources_set and not actual_sources_set:
301
- context_precision, context_recall = 1.0, 1.0
302
-
303
-
304
- faithfulness = 0.0
305
- hallucination_rate = 0.0
306
- source_docs = response.get("source_documents", [])
307
- if source_docs and "ERROR" not in answer_text:
308
- context_blob = "\n---\n".join([doc.page_content for doc in source_docs])
309
- judge_msg = FAITHFULNESS_JUDGE_PROMPT.format(query=query, answer=answer_text, sources=context_blob)
310
- try:
311
- if context_blob.strip():
312
- raw = call_llm([{"role": "user", "content": judge_msg}], temperature=0.0)
313
- data = _parse_judge_json(raw)
314
- if data:
315
- denom = data.get("supported", 0) + data.get("contradicted", 0) + data.get("not_enough_info", 0)
316
- if denom > 0:
317
- faithfulness = round(data.get("supported", 0) / denom, 3)
318
- hallucination_rate = 1.0 - faithfulness
319
- elif data.get("ignored", 0) > 0:
320
- faithfulness = 1.0
321
- hallucination_rate = 0.0
322
-
323
- except Exception as e:
324
- print(f"ERROR during faithfulness judging: {e}")
325
-
326
-
327
- # TURN DEBUG on Answer Correctness
328
- # print("\n" + "-"*20 + " ANSWER & CORRECTNESS EVALUATION " + "-"*20)
329
- # print(f" - Ground Truth Answer: {ground_truth_answer}")
330
- # print(f" - Generated Answer: {answer_text}")
331
- # print("-" * 59)
332
-
333
- answer_correctness_score = 0.0
334
- if ground_truth_answer and "ERROR" not in answer_text:
335
- try:
336
- judge_msg = ANSWER_CORRECTNESS_JUDGE_PROMPT.format(ground_truth_answer=ground_truth_answer, generated_answer=answer_text)
337
- print(f" - Judge Prompt Sent:\n{judge_msg}")
338
- raw_correctness = call_llm([{"role": "user", "content": judge_msg}], temperature=0.0)
339
- print(f" - Judge Raw Response: {raw_correctness}")
340
- correctness_data = _parse_judge_json(raw_correctness)
341
- if correctness_data and "correctness_score" in correctness_data:
342
- answer_correctness_score = float(correctness_data["correctness_score"])
343
- print(f" - Final Score: {answer_correctness_score}")
344
- else:
345
- # answer_correctness_score = 0.0
346
- print(f" - NO Correctness Data Score: {answer_correctness_score}")
347
- except Exception as e:
348
- print(f"ERROR during answer correctness judging: {e}")
349
-
350
-
351
- sources_pretty = ", ".join(sorted(s)) if (s:=actual_sources_set) else ""
352
- results.append({
353
- "test_id": fx.get("test_id", "N/A"), "title": fx.get("title", "N/A"),
354
- "route_correct": "✅" if route_correct else "❌", "expected_route": expected_route, "actual_route": actual_route,
355
- "behavior_f1": f"{behavior_metrics['f1_score']:.2f}", "emotion_f1": f"{emotion_metrics['f1_score']:.2f}",
356
- "topic_f1": f"{topic_metrics['f1_score']:.2f}", "context_f1": f"{context_metrics['f1_score']:.2f}",
357
- "generated_answer": answer_text, "sources": sources_pretty, "source_count": len(actual_sources_set),
358
- "context_precision": context_precision, "context_recall": context_recall,
359
- "faithfulness": faithfulness, "hallucination_rate": hallucination_rate,
360
- "answer_correctness": answer_correctness_score,
361
- "category": category, "error_class": error_class,
362
- "latency_ms": latency_ms
363
- })
364
-
365
- df = pd.DataFrame(results)
366
- summary_text, table_rows, headers = "No valid test fixtures found to evaluate.", [], []
367
-
368
- if not df.empty:
369
- # Add "hallucination_rate" to this list of columns to ensure it is not dropped.
370
- cols = [
371
- "test_id", "title", "route_correct", "expected_route", "actual_route",
372
- "behavior_f1", "emotion_f1", "topic_f1", "context_f1",
373
- "generated_answer", "sources", "source_count",
374
- "context_precision", "context_recall",
375
- "faithfulness", "hallucination_rate",
376
- "answer_correctness",
377
- "category", "error_class", "latency_ms",
378
- ]
379
- df = df[[c for c in cols if c in df.columns]]
380
-
381
- # --- START OF MODIFICATION ---
382
- pct = df["route_correct"].value_counts(normalize=True).get("✅", 0) * 100
383
- to_f = lambda s: pd.to_numeric(s, errors="coerce")
384
-
385
- # Calculate the mean for the NLU F1 scores
386
- bf1_mean = to_f(df["behavior_f1"]).mean() * 100
387
- ef1_mean = to_f(df["emotion_f1"]).mean() * 100
388
- tf1_mean = to_f(df["topic_f1"]).mean() * 100
389
- cf1_mean = to_f(df["context_f1"]).mean() * 100
390
-
391
- # Calculate the mean for Faithfulness
392
- faith_mean = to_f(df["faithfulness"]).mean() * 100
393
- # --- CHANGE 6: Calculate the mean for the new metric ---
394
- halluc_mean = to_f(df["hallucination_rate"]).mean() * 100
395
-
396
- rag_with_sources_pct = (df["source_count"] > 0).mean() * 100 if "source_count" in df else 0
397
-
398
- # Add the NLU metrics to the summary f-string
399
- # Choose to use Hallucination - **RAG: Faithfulness**: {faith_mean:.1f}%
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 Answers w/ Sources**: {rag_with_sources_pct:.1f}%
409
- - **RAG: Hallucination Rate**: {halluc_mean:.1f}% (Lower is better)
410
- - **RAG: Answer Correctness (LLM-judge)**: {(to_f(df["answer_correctness"]).mean() * 100):.1f}%
411
- - **RAG: Avg Latency (ms)**: {to_f(df["latency_ms"]).mean():.1f}
412
- """
413
- # --- END OF MODIFICATION ---
414
- print(summary_text)
415
-
416
- df_display = df.rename(columns={"context_precision": "Ctx. Precision", "context_recall": "Ctx. Recall"})
417
- table_rows = df_display.values.tolist()
418
- headers = df_display.columns.tolist()
419
-
420
- # --- NEW: per-category averages ---
421
- try:
422
- cat_means = df.groupby("category")["answer_correctness"].mean().reset_index()
423
- print("\n📊 Correctness by Category:")
424
- print(cat_means.to_string(index=False))
425
- except Exception as e:
426
- print(f"WARNING: Could not compute category breakdown: {e}")
427
-
428
- # --- NEW: confusion-style matrix ---
429
- try:
430
- confusion = pd.crosstab(df.get("category", []), df.get("error_class", []),
431
- rownames=["Category"], colnames=["Error Class"], dropna=False)
432
- print("\n📊 Error Class Distribution by Category:")
433
- print(confusion.to_string())
434
- except Exception as e:
435
- print(f"WARNING: Could not build confusion matrix: {e}")
436
- # END
437
-
438
- else:
439
- summary_text = "No valid test fixtures found to evaluate."
440
- table_rows, headers = [], []
441
-
442
-
443
- return summary_text, table_rows, headers
444
- # return summary_text, table_rows
445
-
446
- ## END