143 lines
4.7 KiB
Python
143 lines
4.7 KiB
Python
"""Evaluate GraphRAG responses with DeepEval."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from main import ask_question, get_or_build_graph
|
|
|
|
|
|
DEFAULT_DATASET = Path(__file__).with_name("evaluation_dataset.json")
|
|
|
|
|
|
def load_questions(path: Path) -> list[dict[str, str]]:
|
|
with path.open("r", encoding="utf-8") as file:
|
|
data = json.load(file)
|
|
if not isinstance(data, list):
|
|
raise ValueError("Evaluation dataset must be a JSON array")
|
|
return [item for item in data if isinstance(item, dict)]
|
|
|
|
|
|
def configure_deepeval_llm() -> None:
|
|
"""Map the project's OpenAI-compatible settings to DeepEval's defaults."""
|
|
api_key = os.getenv("UNIVERSITY_API_KEY")
|
|
if api_key:
|
|
os.environ.setdefault("OPENAI_API_KEY", api_key)
|
|
|
|
base_url = os.getenv("UNIVERSITY_BASE_URL")
|
|
if base_url:
|
|
os.environ.setdefault(
|
|
"OPENAI_BASE_URL",
|
|
base_url.removesuffix("/chat/completions").rstrip("/"),
|
|
)
|
|
os.environ.setdefault("OPENAI_MODEL_NAME", os.getenv("UNIVERSITY_MODEL", "model2"))
|
|
os.environ.setdefault(
|
|
"DEEPEVAL_PER_ATTEMPT_TIMEOUT_SECONDS_OVERRIDE",
|
|
os.getenv("DEEPEVAL_TIMEOUT", "180"),
|
|
)
|
|
|
|
|
|
def evaluate_case(test_case: Any, metrics: list[Any]) -> dict[str, Any]:
|
|
results: dict[str, Any] = {}
|
|
for metric in metrics:
|
|
metric.measure(test_case)
|
|
name = metric.__class__.__name__
|
|
results[name] = {
|
|
"score": metric.score,
|
|
"reason": metric.reason,
|
|
"success": metric.is_successful(),
|
|
}
|
|
return results
|
|
|
|
|
|
def run_evaluation(dataset_path: Path, output_path: Path, rebuild: bool = False):
|
|
configure_deepeval_llm()
|
|
from deepeval.metrics import (
|
|
AnswerRelevancyMetric,
|
|
ContextualRelevancyMetric,
|
|
FaithfulnessMetric,
|
|
)
|
|
from deepeval.test_case import LLMTestCase
|
|
|
|
graph = get_or_build_graph(force_rebuild=rebuild)
|
|
rows = load_questions(dataset_path)
|
|
test_cases = []
|
|
for item in rows:
|
|
question = str(item.get("question", "")).strip()
|
|
if not question:
|
|
continue
|
|
response = ask_question(graph, question)
|
|
contexts = [
|
|
line.strip()
|
|
for line in (response.evidence or "").splitlines()
|
|
if line.strip()
|
|
]
|
|
actual_output = str(response.answer or "").strip()
|
|
if not actual_output:
|
|
raise RuntimeError(
|
|
f"GraphRAG returned an empty answer for evaluation question: {question!r}"
|
|
)
|
|
case_kwargs = {
|
|
"input": question,
|
|
"actual_output": actual_output,
|
|
"retrieval_context": contexts,
|
|
}
|
|
ground_truth = str(item.get("ground_truth", "")).strip()
|
|
if ground_truth:
|
|
case_kwargs["expected_output"] = ground_truth
|
|
test_cases.append(LLMTestCase(**case_kwargs))
|
|
|
|
if not test_cases:
|
|
raise ValueError("Evaluation dataset contains no valid questions")
|
|
|
|
metrics = [
|
|
FaithfulnessMetric(threshold=0.5, async_mode=False),
|
|
AnswerRelevancyMetric(threshold=0.5, async_mode=False),
|
|
ContextualRelevancyMetric(threshold=0.5, async_mode=False),
|
|
]
|
|
evaluations = []
|
|
for test_case in test_cases:
|
|
if not test_case.retrieval_context:
|
|
print(
|
|
f"Warning: no graph context was retrieved for {test_case.input!r}; "
|
|
"faithfulness and contextual relevancy may be low."
|
|
)
|
|
evaluations.append(
|
|
{
|
|
"input": test_case.input,
|
|
"actual_output": test_case.actual_output,
|
|
"retrieval_context": test_case.retrieval_context,
|
|
"expected_output": getattr(test_case, "expected_output", None),
|
|
"metrics": evaluate_case(test_case, metrics),
|
|
}
|
|
)
|
|
|
|
output = {
|
|
"framework": "deepeval",
|
|
"metrics": [metric.__class__.__name__ for metric in metrics],
|
|
"evaluations": evaluations,
|
|
}
|
|
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
output_path.write_text(
|
|
json.dumps(output, ensure_ascii=False, indent=2),
|
|
encoding="utf-8",
|
|
)
|
|
print(f"Saved DeepEval evaluation to {output_path}")
|
|
return output
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description="Evaluate GraphRAG answers with DeepEval")
|
|
parser.add_argument("--dataset", type=Path, default=DEFAULT_DATASET)
|
|
parser.add_argument("--output", type=Path, default=Path("evaluation_results.json"))
|
|
parser.add_argument("--rebuild", action="store_true")
|
|
return parser.parse_args()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
args = parse_args()
|
|
run_evaluation(args.dataset, args.output, args.rebuild)
|