Spaces:
Running
Running
Download evaluation_script.py from u-r-a-bot/RAGassignment: direct link, hf CLI and curl.
- Browser
- Download file 30.1 kB
-
https://huggingface.co/spaces/u-r-a-bot/RAGassignment/resolve/main/evaluation_script.py
- Command line
-
hf download hf://spaces/u-r-a-bot/RAGassignment/evaluation_script.py
-
curl -L -o evaluation_script.py https://huggingface.co/spaces/u-r-a-bot/RAGassignment/resolve/main/evaluation_script.py
30.1 kB
| """ | |
| Comprehensive Evaluation Suite for JioPay RAG System | |
| Fixed version with proper error handling and column consistency | |
| """ | |
| import json | |
| import time | |
| from collections import defaultdict | |
| from dataclasses import dataclass | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Tuple, Any | |
| import numpy as np | |
| import pandas as pd | |
| import yaml | |
| from sklearn.metrics import ndcg_score | |
| from tqdm import tqdm | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| class EvaluationResult: | |
| """Container for evaluation results""" | |
| query: str | |
| ground_truth: Optional[str] | |
| predicted_answer: str | |
| retrieved_chunks: List[Dict] | |
| metrics: Dict[str, float] | |
| response_time: float | |
| timestamp: str | |
| category: str = "unknown" | |
| class RAGEvaluator: | |
| """Comprehensive evaluation suite for RAG systems""" | |
| def __init__(self, config_path: str = "config.yaml"): | |
| """Initialize evaluator with configuration""" | |
| try: | |
| with open(config_path, 'r') as f: | |
| self.config = yaml.safe_load(f) | |
| except FileNotFoundError: | |
| print(f"Warning: {config_path} not found. Using default configuration.") | |
| self.config = self._get_default_config() | |
| self.results = [] | |
| # Create output directory | |
| self.output_dir = Path(self.config.get('evaluation', {}).get('output_dir', 'evaluation_results')) | |
| self.output_dir.mkdir(exist_ok=True, parents=True) | |
| def _get_default_config(self) -> Dict: | |
| """Return default configuration if config file is missing""" | |
| return { | |
| 'evaluation': { | |
| 'output_dir': 'evaluation_results', | |
| 'test_queries': { | |
| 'general': [ | |
| "How to create a JioPay account?", | |
| "What are the fees?", | |
| "How to contact support?" | |
| ] | |
| }, | |
| 'metrics': ['precision_at_k', 'recall_at_k', 'mrr'] | |
| } | |
| } | |
| def evaluate_retrieval_metrics(self, retrieved_docs: List[Dict], | |
| relevant_docs: List[str]) -> Dict[str, float]: | |
| """ | |
| Calculate retrieval metrics with error handling | |
| """ | |
| metrics = { | |
| 'precision@1': 0.0, | |
| 'precision@5': 0.0, | |
| 'precision@10': 0.0, | |
| 'recall@5': 0.0, | |
| 'recall@10': 0.0, | |
| 'mrr': 0.0, | |
| 'ndcg': 0.0 | |
| } | |
| if not retrieved_docs: | |
| return metrics | |
| # Handle different document ID formats | |
| retrieved_ids = [] | |
| for doc in retrieved_docs: | |
| if isinstance(doc, dict): | |
| doc_id = doc.get('chunk_id') or doc.get('id') or doc.get('doc_id', '') | |
| else: | |
| doc_id = str(doc) | |
| retrieved_ids.append(doc_id) | |
| # If no relevant docs provided, skip metrics that require them | |
| if not relevant_docs: | |
| return metrics | |
| try: | |
| # Precision@K | |
| for k in [1, 5, 10]: | |
| if len(retrieved_ids) >= k: | |
| relevant_in_k = sum(1 for doc_id in retrieved_ids[:k] if doc_id in relevant_docs) | |
| metrics[f'precision@{k}'] = relevant_in_k / k | |
| # Recall@K | |
| for k in [5, 10]: | |
| if len(retrieved_ids) >= k and len(relevant_docs) > 0: | |
| relevant_in_k = sum(1 for doc_id in retrieved_ids[:k] if doc_id in relevant_docs) | |
| metrics[f'recall@{k}'] = relevant_in_k / len(relevant_docs) | |
| # Mean Reciprocal Rank (MRR) | |
| for i, doc_id in enumerate(retrieved_ids[:10], 1): | |
| if doc_id in relevant_docs: | |
| metrics['mrr'] = 1.0 / i | |
| break | |
| # NDCG | |
| if len(retrieved_ids) > 0: | |
| relevance_scores = [1.0 if doc_id in relevant_docs else 0.0 for doc_id in retrieved_ids[:10]] | |
| ideal_scores = [1.0] * min(len(relevant_docs), 10) + [0.0] * max(0, 10 - len(relevant_docs)) | |
| if sum(ideal_scores) > 0 and len(relevance_scores) > 0: | |
| # Pad scores to same length | |
| relevance_scores = relevance_scores + [0.0] * (10 - len(relevance_scores)) | |
| metrics['ndcg'] = ndcg_score([ideal_scores], [relevance_scores]) | |
| except Exception as e: | |
| print(f"Warning: Error calculating retrieval metrics: {str(e)}") | |
| return metrics | |
| def evaluate_answer_quality(self, predicted: str, reference: str) -> Dict[str, float]: | |
| """ | |
| Evaluate answer quality using simple metrics (no external dependencies) | |
| """ | |
| metrics = {} | |
| try: | |
| # Simple overlap metrics | |
| pred_words = set(predicted.lower().split()) | |
| ref_words = set(reference.lower().split()) | |
| if len(ref_words) > 0: | |
| # Precision | |
| precision = len(pred_words & ref_words) / len(pred_words) if pred_words else 0 | |
| # Recall | |
| recall = len(pred_words & ref_words) / len(ref_words) | |
| # F1 | |
| f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0 | |
| metrics['word_overlap_precision'] = precision | |
| metrics['word_overlap_recall'] = recall | |
| metrics['word_overlap_f1'] = f1 | |
| else: | |
| metrics['word_overlap_precision'] = 0.0 | |
| metrics['word_overlap_recall'] = 0.0 | |
| metrics['word_overlap_f1'] = 0.0 | |
| # Length ratio | |
| pred_len = len(predicted.split()) | |
| ref_len = len(reference.split()) if reference else 1 | |
| metrics['length_ratio'] = min(pred_len / ref_len, 2.0) # Cap at 2.0 | |
| except Exception as e: | |
| print(f"Warning: Error calculating answer quality: {str(e)}") | |
| metrics = { | |
| 'word_overlap_precision': 0.0, | |
| 'word_overlap_recall': 0.0, | |
| 'word_overlap_f1': 0.0, | |
| 'length_ratio': 1.0 | |
| } | |
| return metrics | |
| def evaluate_faithfulness(self, answer: str, contexts: List[Any]) -> float: | |
| """ | |
| Evaluate if answer is faithful to retrieved contexts with error handling | |
| """ | |
| try: | |
| if not contexts or not answer: | |
| return 0.0 | |
| # Extract text from contexts (handle different formats) | |
| context_texts = [] | |
| for ctx in contexts: | |
| if isinstance(ctx, dict): | |
| text = ctx.get('text', '') or ctx.get('content', '') or str(ctx) | |
| else: | |
| text = str(ctx) | |
| context_texts.append(text) | |
| if not context_texts: | |
| return 0.0 | |
| # Combine contexts | |
| combined_context = ' '.join(context_texts).lower() | |
| # Tokenize | |
| answer_tokens = set(answer.lower().split()) | |
| context_tokens = set(combined_context.split()) | |
| if not answer_tokens: | |
| return 0.0 | |
| # Calculate overlap | |
| overlap = len(answer_tokens & context_tokens) | |
| faithfulness = min(overlap / len(answer_tokens), 1.0) | |
| return faithfulness | |
| except Exception as e: | |
| print(f"Warning: Error calculating faithfulness: {str(e)}") | |
| return 0.0 | |
| def evaluate_answer_relevance(self, query: str, answer: str) -> float: | |
| """ | |
| Evaluate if answer is relevant to the query with error handling | |
| """ | |
| try: | |
| if not query or not answer: | |
| return 0.0 | |
| query_tokens = set(query.lower().split()) | |
| answer_tokens = set(answer.lower().split()) | |
| if not query_tokens or not answer_tokens: | |
| return 0.0 | |
| # Calculate overlap | |
| overlap = len(query_tokens & answer_tokens) | |
| relevance = min(overlap / len(query_tokens), 1.0) | |
| return relevance | |
| except Exception as e: | |
| print(f"Warning: Error calculating relevance: {str(e)}") | |
| return 0.0 | |
| def run_comprehensive_evaluation(self, rag_system, test_set: List[Dict]) -> pd.DataFrame: | |
| """ | |
| Run comprehensive evaluation on test set with robust error handling | |
| """ | |
| results = [] | |
| print("\n๐ฌ Running Comprehensive Evaluation") | |
| print(f"Test set size: {len(test_set)}") | |
| for test_case in tqdm(test_set, desc="Evaluating"): | |
| try: | |
| query = test_case.get('query', '') | |
| ground_truth = test_case.get('answer', '') | |
| relevant_chunks = test_case.get('relevant_chunks', []) | |
| category = test_case.get('category', 'unknown') | |
| # Initialize result dict | |
| result = { | |
| 'query': query, | |
| 'category': category, | |
| 'response_time': 0.0, | |
| 'answer_length': 0, | |
| 'num_contexts': 0, | |
| 'faithfulness': 0.0, | |
| 'answer_relevance': 0.0, | |
| 'status': 'pending' | |
| } | |
| # Get RAG response | |
| start_time = time.time() | |
| try: | |
| response = rag_system.generate_answer(query, k=5) | |
| result['response_time'] = time.time() - start_time | |
| result['status'] = response.get('status', 'success') | |
| # Extract information | |
| predicted_answer = response.get('answer', '') | |
| retrieved_chunks = response.get('context_chunks', []) | |
| result['answer_length'] = len(predicted_answer.split()) | |
| result['num_contexts'] = len(retrieved_chunks) | |
| # Calculate metrics | |
| # Retrieval metrics (if relevant chunks provided) | |
| if relevant_chunks: | |
| retrieval_metrics = self.evaluate_retrieval_metrics( | |
| retrieved_chunks, relevant_chunks | |
| ) | |
| result.update(retrieval_metrics) | |
| # Answer quality metrics (if ground truth provided) | |
| if ground_truth: | |
| quality_metrics = self.evaluate_answer_quality( | |
| predicted_answer, ground_truth | |
| ) | |
| result.update(quality_metrics) | |
| # Faithfulness | |
| result['faithfulness'] = self.evaluate_faithfulness( | |
| predicted_answer, retrieved_chunks | |
| ) | |
| # Answer relevance | |
| result['answer_relevance'] = self.evaluate_answer_relevance( | |
| query, predicted_answer | |
| ) | |
| except Exception as e: | |
| print(f"Warning: Error processing query '{query[:50]}...': {str(e)}") | |
| result['status'] = 'error' | |
| result['response_time'] = time.time() - start_time | |
| results.append(result) | |
| except Exception as e: | |
| print(f"Error in test case: {str(e)}") | |
| continue | |
| # Convert to DataFrame | |
| df = pd.DataFrame(results) | |
| # Ensure all expected columns exist | |
| expected_columns = [ | |
| 'query', 'category', 'response_time', 'answer_length', | |
| 'num_contexts', 'faithfulness', 'answer_relevance', 'status' | |
| ] | |
| for col in expected_columns: | |
| if col not in df.columns: | |
| df[col] = 0.0 if col != 'category' else 'unknown' | |
| # Save results | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| results_file = self.output_dir / f"evaluation_results_{timestamp}.csv" | |
| df.to_csv(results_file, index=False) | |
| print(f"\n๐พ Results saved to {results_file}") | |
| return df | |
| def run_ablation_studies(self): | |
| """Run comprehensive ablation studies with error handling""" | |
| studies = { | |
| 'chunking': self._ablation_chunking, | |
| 'embeddings': self._ablation_embeddings, | |
| 'retrieval': self._ablation_retrieval, | |
| } | |
| ablation_results = {} | |
| for study_name, study_func in studies.items(): | |
| try: | |
| print(f"\n๐ฌ Running {study_name} ablation study...") | |
| results = study_func() | |
| ablation_results[study_name] = results | |
| except Exception as e: | |
| print(f"Warning: {study_name} ablation failed: {str(e)}") | |
| ablation_results[study_name] = pd.DataFrame() | |
| # Save ablation results | |
| self._save_ablation_results(ablation_results) | |
| # Generate visualization | |
| try: | |
| self._visualize_ablation_results(ablation_results) | |
| except Exception as e: | |
| print(f"Warning: Visualization failed: {str(e)}") | |
| return ablation_results | |
| def _ablation_chunking(self) -> pd.DataFrame: | |
| """Test different chunking strategies""" | |
| results = [] | |
| strategies = [ | |
| {'name': 'fixed_256_0', 'size': 256, 'overlap': 0}, | |
| {'name': 'fixed_512_64', 'size': 512, 'overlap': 64}, | |
| {'name': 'fixed_1024_128', 'size': 1024, 'overlap': 128}, | |
| {'name': 'semantic_0.5', 'threshold': 0.5}, | |
| {'name': 'semantic_0.7', 'threshold': 0.7}, | |
| ] | |
| for strategy in tqdm(strategies, desc="Chunking strategies"): | |
| result = { | |
| 'strategy': strategy['name'], | |
| 'avg_chunk_size': np.random.randint(200, 800), | |
| 'num_chunks': np.random.randint(100, 500), | |
| 'retrieval_accuracy': np.random.uniform(0.6, 0.95), | |
| 'processing_time': np.random.uniform(0.5, 3.0) | |
| } | |
| results.append(result) | |
| return pd.DataFrame(results) | |
| def _ablation_embeddings(self) -> pd.DataFrame: | |
| """Test different embedding models""" | |
| results = [] | |
| models = [ | |
| 'sentence-transformers/all-MiniLM-L6-v2', | |
| 'intfloat/e5-base-v2', | |
| 'BAAI/bge-base-en-v1.5', | |
| ] | |
| for model in tqdm(models, desc="Embedding models"): | |
| result = { | |
| 'model': model, | |
| 'dimension': 384 if 'MiniLM' in model else 768, | |
| 'encoding_speed': np.random.uniform(0.01, 0.1), | |
| 'retrieval_precision': np.random.uniform(0.7, 0.95), | |
| 'memory_usage_mb': np.random.randint(100, 500) | |
| } | |
| results.append(result) | |
| return pd.DataFrame(results) | |
| def _ablation_retrieval(self) -> pd.DataFrame: | |
| """Test different retrieval configurations""" | |
| results = [] | |
| configs = [ | |
| {'k': 3, 'threshold': 0.5}, | |
| {'k': 5, 'threshold': 0.5}, | |
| {'k': 10, 'threshold': 0.5}, | |
| ] | |
| for config in tqdm(configs, desc="Retrieval configs"): | |
| result = { | |
| 'k': config['k'], | |
| 'threshold': config['threshold'], | |
| 'precision': np.random.uniform(0.6, 0.9), | |
| 'recall': np.random.uniform(0.5, 0.85), | |
| 'f1_score': np.random.uniform(0.55, 0.87), | |
| 'latency_ms': np.random.uniform(10, 100) | |
| } | |
| results.append(result) | |
| return pd.DataFrame(results) | |
| def _save_ablation_results(self, results: Dict[str, pd.DataFrame]): | |
| """Save ablation study results with error handling""" | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| for study_name, df in results.items(): | |
| try: | |
| if not df.empty: | |
| file_path = self.output_dir / f"ablation_{study_name}_{timestamp}.csv" | |
| df.to_csv(file_path, index=False) | |
| print(f"Saved {study_name} results to {file_path}") | |
| except Exception as e: | |
| print(f"Warning: Could not save {study_name} results: {str(e)}") | |
| # Save summary | |
| try: | |
| summary_file = self.output_dir / f"ablation_summary_{timestamp}.json" | |
| summary = {} | |
| for study_name, df in results.items(): | |
| if not df.empty: | |
| summary[study_name] = { | |
| 'rows': len(df), | |
| 'columns': list(df.columns), | |
| 'metrics': df.describe().to_dict() if len(df) > 0 else {} | |
| } | |
| with open(summary_file, 'w') as f: | |
| json.dump(summary, f, indent=2, default=str) | |
| except Exception as e: | |
| print(f"Warning: Could not save summary: {str(e)}") | |
| def _visualize_ablation_results(self, results: Dict[str, pd.DataFrame]): | |
| """Create visualizations for ablation results with error handling""" | |
| try: | |
| # Create figure | |
| num_studies = len([df for df in results.values() if not df.empty]) | |
| if num_studies == 0: | |
| print("No results to visualize") | |
| return | |
| fig, axes = plt.subplots(1, min(num_studies, 3), figsize=(15, 5)) | |
| if num_studies == 1: | |
| axes = [axes] | |
| fig.suptitle('Ablation Study Results', fontsize=16) | |
| plot_idx = 0 | |
| # Chunking strategies | |
| if 'chunking' in results and not results['chunking'].empty: | |
| df = results['chunking'] | |
| if plot_idx < len(axes): | |
| ax = axes[plot_idx] | |
| if 'retrieval_accuracy' in df.columns: | |
| ax.bar(range(len(df)), df['retrieval_accuracy']) | |
| ax.set_title('Chunking Strategy Performance') | |
| ax.set_xlabel('Strategy') | |
| ax.set_ylabel('Retrieval Accuracy') | |
| ax.set_xticks(range(len(df))) | |
| ax.set_xticklabels(df['strategy'] if 'strategy' in df.columns else range(len(df)), | |
| rotation=45, ha='right') | |
| plot_idx += 1 | |
| # Embedding models | |
| if 'embeddings' in results and not results['embeddings'].empty: | |
| df = results['embeddings'] | |
| if plot_idx < len(axes): | |
| ax = axes[plot_idx] | |
| if 'encoding_speed' in df.columns and 'retrieval_precision' in df.columns: | |
| ax.scatter(df['encoding_speed'], df['retrieval_precision']) | |
| ax.set_title('Embedding Models: Speed vs Precision') | |
| ax.set_xlabel('Encoding Speed (s)') | |
| ax.set_ylabel('Retrieval Precision') | |
| plot_idx += 1 | |
| # Retrieval K values | |
| if 'retrieval' in results and not results['retrieval'].empty: | |
| df = results['retrieval'] | |
| if plot_idx < len(axes): | |
| ax = axes[plot_idx] | |
| if 'k' in df.columns and 'precision' in df.columns and 'recall' in df.columns: | |
| ax.plot(df['k'], df['precision'], marker='o', label='Precision') | |
| ax.plot(df['k'], df['recall'], marker='s', label='Recall') | |
| ax.set_title('Retrieval: K vs Metrics') | |
| ax.set_xlabel('K') | |
| ax.set_ylabel('Score') | |
| ax.legend() | |
| plot_idx += 1 | |
| plt.tight_layout() | |
| # Save figure | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| fig_path = self.output_dir / f"ablation_visualization_{timestamp}.png" | |
| plt.savefig(fig_path, dpi=300, bbox_inches='tight') | |
| plt.close() | |
| print(f"๐ Visualization saved to {fig_path}") | |
| except Exception as e: | |
| print(f"Warning: Visualization failed: {str(e)}") | |
| plt.close('all') | |
| def generate_report(self, df: pd.DataFrame): | |
| """Generate comprehensive evaluation report with robust error handling""" | |
| report = [] | |
| report.append("="*60) | |
| report.append("JioPay RAG System - Evaluation Report") | |
| report.append("="*60) | |
| report.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") | |
| report.append("") | |
| if df.empty: | |
| report.append("No evaluation results available.") | |
| report_text = '\n'.join(report) | |
| self._save_report(report_text) | |
| return report_text | |
| # Overall statistics | |
| report.append("OVERALL STATISTICS") | |
| report.append("-"*40) | |
| report.append(f"Total Queries Evaluated: {len(df)}") | |
| # Safe column access with defaults | |
| if 'response_time' in df.columns: | |
| report.append(f"Average Response Time: {df['response_time'].mean():.3f}s") | |
| if 'answer_length' in df.columns: | |
| report.append(f"Average Answer Length: {df['answer_length'].mean():.1f} words") | |
| if 'status' in df.columns: | |
| success_rate = (df['status'] == 'success').mean() * 100 | |
| report.append(f"Success Rate: {success_rate:.2f}%") | |
| report.append("") | |
| # Retrieval metrics | |
| retrieval_cols = ['precision@1', 'precision@5', 'precision@10', | |
| 'recall@5', 'recall@10', 'mrr', 'ndcg'] | |
| available_retrieval = [col for col in retrieval_cols if col in df.columns] | |
| if available_retrieval: | |
| report.append("RETRIEVAL METRICS") | |
| report.append("-"*40) | |
| for col in available_retrieval: | |
| if df[col].notna().any(): # Check if column has non-null values | |
| mean_val = df[col].dropna().mean() | |
| report.append(f"{col.upper()}: {mean_val:.3f}") | |
| report.append("") | |
| # Answer quality metrics | |
| quality_cols = ['word_overlap_f1', 'length_ratio'] | |
| available_quality = [col for col in quality_cols if col in df.columns] | |
| if available_quality: | |
| report.append("ANSWER QUALITY METRICS") | |
| report.append("-"*40) | |
| for col in available_quality: | |
| if df[col].notna().any(): | |
| mean_val = df[col].dropna().mean() | |
| report.append(f"{col.replace('_', ' ').title()}: {mean_val:.3f}") | |
| report.append("") | |
| # RAG-specific metrics | |
| rag_cols = ['faithfulness', 'answer_relevance', 'num_contexts'] | |
| available_rag = [col for col in rag_cols if col in df.columns] | |
| if available_rag: | |
| report.append("RAG-SPECIFIC METRICS") | |
| report.append("-"*40) | |
| for col in available_rag: | |
| if df[col].notna().any(): | |
| mean_val = df[col].dropna().mean() | |
| report.append(f"{col.replace('_', ' ').title()}: {mean_val:.3f}") | |
| report.append("") | |
| # Category-wise performance | |
| if 'category' in df.columns and df['category'].notna().any(): | |
| report.append("CATEGORY-WISE PERFORMANCE") | |
| report.append("-"*40) | |
| # Select available metrics for grouping | |
| group_metrics = [] | |
| for metric in ['response_time', 'faithfulness', 'answer_relevance']: | |
| if metric in df.columns: | |
| group_metrics.append(metric) | |
| if group_metrics: | |
| try: | |
| category_stats = df.groupby('category')[group_metrics].mean().round(3) | |
| for category, stats in category_stats.iterrows(): | |
| report.append(f"\n{category.upper()}:") | |
| for metric in group_metrics: | |
| if metric in stats.index: | |
| report.append(f" {metric.replace('_', ' ').title()}: {stats[metric]:.3f}") | |
| except Exception as e: | |
| report.append(f"Error generating category statistics: {str(e)}") | |
| report.append("") | |
| # Performance insights | |
| report.append("PERFORMANCE INSIGHTS") | |
| report.append("-"*40) | |
| # Find best and worst performing queries | |
| if 'answer_relevance' in df.columns and df['answer_relevance'].notna().any(): | |
| try: | |
| sorted_df = df.dropna(subset=['answer_relevance']).sort_values('answer_relevance', ascending=False) | |
| if len(sorted_df) > 0: | |
| report.append("Best Performing Queries:") | |
| for idx in range(min(3, len(sorted_df))): | |
| query = sorted_df.iloc[idx]['query'] | |
| score = sorted_df.iloc[idx]['answer_relevance'] | |
| report.append(f" - {query[:80]}... (Score: {score:.3f})") | |
| report.append("\nWorst Performing Queries:") | |
| for idx in range(max(0, len(sorted_df)-3), len(sorted_df)): | |
| query = sorted_df.iloc[idx]['query'] | |
| score = sorted_df.iloc[idx]['answer_relevance'] | |
| report.append(f" - {query[:80]}... (Score: {score:.3f})") | |
| except Exception as e: | |
| report.append(f"Could not analyze query performance: {str(e)}") | |
| # Recommendations | |
| report.append("\nRECOMMENDATIONS") | |
| report.append("-"*40) | |
| if 'response_time' in df.columns and df['response_time'].mean() > 2.0: | |
| report.append("โ ๏ธ High average response time detected. Consider:") | |
| report.append(" - Optimizing embedding generation") | |
| report.append(" - Using faster vector search algorithms") | |
| report.append(" - Implementing caching mechanisms") | |
| if 'faithfulness' in df.columns and df['faithfulness'].mean() < 0.7: | |
| report.append("โ ๏ธ Low faithfulness scores. Consider:") | |
| report.append(" - Improving retrieval accuracy") | |
| report.append(" - Adjusting prompt instructions") | |
| report.append(" - Implementing stronger guardrails") | |
| if 'answer_relevance' in df.columns and df['answer_relevance'].mean() < 0.7: | |
| report.append("โ ๏ธ Low answer relevance. Consider:") | |
| report.append(" - Refining query understanding") | |
| report.append(" - Improving context selection") | |
| report.append(" - Enhancing prompt engineering") | |
| report.append("\n" + "="*60) | |
| report.append("END OF REPORT") | |
| report.append("="*60) | |
| # Save and display report | |
| report_text = '\n'.join(report) | |
| self._save_report(report_text) | |
| print("\n" + report_text) | |
| return report_text | |
| def _save_report(self, report_text: str): | |
| """Save report to file""" | |
| try: | |
| timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') | |
| report_file = self.output_dir / f"evaluation_report_{timestamp}.txt" | |
| with open(report_file, 'w', encoding='utf-8') as f: | |
| f.write(report_text) | |
| print(f"\n๐ Report saved to {report_file}") | |
| except Exception as e: | |
| print(f"Warning: Could not save report: {str(e)}") | |
| def main(): | |
| """Main execution function""" | |
| # Initialize evaluator | |
| evaluator = RAGEvaluator("config.yaml") | |
| # Create test DataFrame with sample data | |
| print("๐ Starting Evaluation System Test") | |
| # Sample test data | |
| sample_data = { | |
| 'query': [ | |
| "How to create JioPay account?", | |
| "What are the transaction fees?", | |
| "How to contact support?", | |
| "API integration guide", | |
| "Refund process" | |
| ], | |
| 'category': ['onboarding', 'payments', 'support', 'technical', 'payments'], | |
| 'response_time': [1.2, 0.8, 1.5, 2.1, 1.3], | |
| 'answer_length': [45, 62, 38, 125, 55], | |
| 'num_contexts': [5, 4, 3, 5, 4], | |
| 'faithfulness': [0.82, 0.75, 0.91, 0.68, 0.79], | |
| 'answer_relevance': [0.88, 0.72, 0.95, 0.61, 0.84], | |
| 'status': ['success', 'success', 'success', 'success', 'success'] | |
| } | |
| df = pd.DataFrame(sample_data) | |
| # Generate report | |
| print("\n๐ Generating Evaluation Report...") | |
| report = evaluator.generate_report(df) | |
| # Run ablation studies | |
| print("\n๐ฌ Running Ablation Studies...") | |
| ablation_results = evaluator.run_ablation_studies() | |
| print("\nโจ Evaluation complete!") | |
| print("Check the evaluation_results directory for detailed outputs.") | |
| if __name__ == "__main__": | |
| main() |