""" Metrics calculation for RAG evaluation """ from typing import List, Dict, Any, Optional, Set from abc import ABC, abstractmethod import re def _tokenize(text: str) -> Set[str]: """ Tokenize text supporting both Chinese and English For Chinese: Extract individual characters For English: Split by whitespace and punctuation For mixed: Combine both approaches Args: text: Input text Returns: Set of tokens """ if not text: return set() text = text.lower() # For Chinese or mixed content, extract characters # Match Chinese characters chinese_chars = set(re.findall(r'[\u4e00-\u9fff]', text)) # For English and other languages, split by non-word characters # This handles English words and numbers english_words = set(re.findall(r'\b\w+\b', text)) # Combine both return chinese_chars | english_words class Metric(ABC): """Abstract base class for metrics""" @abstractmethod def calculate(self, **kwargs) -> float: """ Calculate metric score Returns: Metric score (0.0 to 1.0) """ pass class ContextRecall(Metric): """ Context Recall: Measures how many relevant contexts were retrieved Formula: |retrieved ∩ ground_truth| / |ground_truth| """ def calculate( self, retrieved_contexts: List[str], ground_truth_contexts: List[str] ) -> float: """ Calculate context recall Args: retrieved_contexts: List of retrieved context IDs/texts ground_truth_contexts: List of ground truth context IDs/texts Returns: Recall score (0.0 to 1.0) """ if not ground_truth_contexts: return 0.0 # Convert to sets for intersection retrieved_set = set(retrieved_contexts) ground_truth_set = set(ground_truth_contexts) # Calculate intersection intersection = retrieved_set & ground_truth_set recall = len(intersection) / len(ground_truth_set) return recall class ContextPrecision(Metric): """ Context Precision: Measures how many retrieved contexts are relevant Formula: |retrieved ∩ ground_truth| / |retrieved| """ def calculate( self, retrieved_contexts: List[str], ground_truth_contexts: List[str] ) -> float: """ Calculate context precision Args: retrieved_contexts: List of retrieved context IDs/texts ground_truth_contexts: List of ground truth context IDs/texts Returns: Precision score (0.0 to 1.0) """ if not retrieved_contexts: return 0.0 # Convert to sets for intersection retrieved_set = set(retrieved_contexts) ground_truth_set = set(ground_truth_contexts) # Calculate intersection intersection = retrieved_set & ground_truth_set precision = len(intersection) / len(retrieved_set) return precision class MRR(Metric): """ Mean Reciprocal Rank: Measures the rank of the first relevant context Formula: 1 / rank_of_first_relevant_context """ def calculate( self, retrieved_contexts: List[str], ground_truth_contexts: List[str] ) -> float: """ Calculate MRR Args: retrieved_contexts: Ordered list of retrieved context IDs/texts ground_truth_contexts: List of ground truth context IDs/texts Returns: MRR score (0.0 to 1.0) """ if not retrieved_contexts or not ground_truth_contexts: return 0.0 ground_truth_set = set(ground_truth_contexts) # Find rank of first relevant context for rank, context in enumerate(retrieved_contexts, start=1): if context in ground_truth_set: return 1.0 / rank return 0.0 class NDCG(Metric): """ Normalized Discounted Cumulative Gain Measures ranking quality with position discount """ def calculate( self, retrieved_contexts: List[str], ground_truth_contexts: List[str], k: Optional[int] = None ) -> float: """ Calculate NDCG@k Args: retrieved_contexts: Ordered list of retrieved context IDs/texts ground_truth_contexts: List of ground truth context IDs/texts k: Cut-off rank (if None, use all retrieved contexts) Returns: NDCG score (0.0 to 1.0) """ if not retrieved_contexts or not ground_truth_contexts: return 0.0 if k is None: k = len(retrieved_contexts) ground_truth_set = set(ground_truth_contexts) # Calculate DCG dcg = 0.0 for i, context in enumerate(retrieved_contexts[:k], start=1): relevance = 1.0 if context in ground_truth_set else 0.0 dcg += relevance / (i + 1) # log2(i+1) simplified # Calculate IDCG (ideal DCG) # IDCG should consider at most k relevant documents at top positions idcg = 0.0 max_relevant = min(len(ground_truth_contexts), k) for i in range(1, max_relevant + 1): idcg += 1.0 / (i + 1) if idcg == 0.0: return 0.0 ndcg = dcg / idcg return ndcg class Faithfulness(Metric): """ Faithfulness: Measures if the answer is faithful to the contexts Uses RAGAS faithfulness metric """ def calculate( self, question: str, answer: str, contexts: List[str] ) -> float: """ Calculate faithfulness score Args: question: Question text answer: Generated answer contexts: Retrieved contexts Returns: Faithfulness score (0.0 to 1.0) """ # TODO: Integrate with RAGAS faithfulness metric # For now, simple heuristic: check if answer contains context keywords if not answer or not contexts: return 0.0 # Tokenize answer and contexts answer_tokens = _tokenize(answer) context_text = ' '.join(contexts) context_tokens = _tokenize(context_text) if not answer_tokens: return 0.0 overlap = answer_tokens & context_tokens faithfulness = len(overlap) / len(answer_tokens) return min(faithfulness, 1.0) class AnswerRelevancy(Metric): """ Answer Relevancy: Measures if the answer is relevant to the question Uses RAGAS answer relevancy metric """ def calculate( self, question: str, answer: str ) -> float: """ Calculate answer relevancy score Args: question: Question text answer: Generated answer Returns: Relevancy score (0.0 to 1.0) """ # TODO: Integrate with RAGAS answer relevancy metric # For now, simple heuristic: check keyword overlap if not question or not answer: return 0.0 # Tokenize question and answer question_tokens = _tokenize(question) answer_tokens = _tokenize(answer) if not question_tokens: return 0.0 # Calculate overlap overlap = question_tokens & answer_tokens relevancy = len(overlap) / len(question_tokens) return min(relevancy, 1.0) class Correctness(Metric): """ Correctness: Measures if the answer is correct compared to ground truth Uses RAGAS correctness metric """ def calculate( self, answer: str, ground_truth_answer: str ) -> float: """ Calculate correctness score Args: answer: Generated answer ground_truth_answer: Ground truth answer Returns: Correctness score (0.0 to 1.0) """ # TODO: Integrate with RAGAS correctness metric # For now, simple heuristic: word overlap if not answer or not ground_truth_answer: return 0.0 # Tokenize answers answer_tokens = _tokenize(answer) ground_truth_tokens = _tokenize(ground_truth_answer) if not ground_truth_tokens: return 0.0 overlap = answer_tokens & ground_truth_tokens correctness = len(overlap) / len(ground_truth_tokens) return min(correctness, 1.0) class MetricsCalculator: """Calculator for all evaluation metrics""" def __init__(self): self.context_recall = ContextRecall() self.context_precision = ContextPrecision() self.mrr = MRR() self.ndcg = NDCG() self.faithfulness = Faithfulness() self.answer_relevancy = AnswerRelevancy() self.correctness = Correctness() def calculate_all( self, question: str, retrieved_contexts: List[str], generated_answer: str, ground_truth_contexts: List[str], ground_truth_answer: str ) -> Dict[str, float]: """ Calculate all metrics Args: question: Question text retrieved_contexts: Retrieved context IDs/texts generated_answer: Generated answer ground_truth_contexts: Ground truth context IDs/texts ground_truth_answer: Ground truth answer Returns: Dictionary of metric scores """ metrics = {} # Retrieval metrics metrics['context_recall'] = self.context_recall.calculate( retrieved_contexts=retrieved_contexts, ground_truth_contexts=ground_truth_contexts ) metrics['context_precision'] = self.context_precision.calculate( retrieved_contexts=retrieved_contexts, ground_truth_contexts=ground_truth_contexts ) metrics['mrr'] = self.mrr.calculate( retrieved_contexts=retrieved_contexts, ground_truth_contexts=ground_truth_contexts ) metrics['ndcg'] = self.ndcg.calculate( retrieved_contexts=retrieved_contexts, ground_truth_contexts=ground_truth_contexts ) # Generation metrics metrics['faithfulness'] = self.faithfulness.calculate( question=question, answer=generated_answer, contexts=retrieved_contexts ) metrics['answer_relevancy'] = self.answer_relevancy.calculate( question=question, answer=generated_answer ) metrics['correctness'] = self.correctness.calculate( answer=generated_answer, ground_truth_answer=ground_truth_answer ) return metrics