Overview
The RAGAS Evaluator module provides comprehensive evaluation capabilities for RAG systems using the RAGAS (Retrieval-Augmented Generation Assessment) framework. It supports multiple RAG architectures, various LLM models, and generates detailed performance metrics and cost analysis. Module Path:src/evaluation/ragas_evaluator.py
Key Features
- Multiple RAG Support: Evaluate Simple, HyDE, Rewriter, Hybrid, Hybrid-RRF, and PageIndex RAG systems
- RAGAS Metrics: Faithfulness, Answer Relevancy, Context Precision, and Context Recall
- Multi-Model Evaluation: Compare performance across different LLM models
- Performance Tracking: Token usage, execution time, and cost analysis
- Obstetric Dataset: Built-in specialized medical dataset with 10 ground truth questions
- Comprehensive Reporting: JSON export with detailed question-by-question analysis
RAGASEvaluator Class
The main orchestrator class for RAG evaluation workflows.Constructor
str
default:"rewriter"
RAG architecture to evaluate. Supported values:
"simple"- Simple Semantic RAG"hybrid"- Hybrid RAG (BM25 + Semantic)"hybrid-rrf"- Hybrid RAG with Reciprocal Rank Fusion"hyde"- HyDE RAG (Hypothetical Documents)"rewriter"- Multi-Query Rewriter RAG"pageindex"- PageIndex RAG
bool
default:"False"
Enable debug output for detailed logging and error traces
metrics- List of RAGAS metric objects (faithfulness, answer_relevancy, context_precision, context_recall)results_dir- Path to results directory (project_root/results)query_function- RAG-specific query function for evaluationrag_name- Descriptive name of the RAG systemrag_type- RAG type identifierllm_model- Default LLM model name (initially “gpt-4o”)performance_metadata- List storing execution metrics per query
set_models
str
New LLM model name (e.g., “gpt-4o”, “claude-3-5-sonnet”)
str
New embeddings model name (currently not used in implementation)
load_test_queries
bool
default:"True"
Whether to use the built-in obstetric dataset (currently the only option)
List[Dict]
List of query dictionaries, each containing:
question(str) - The test questionground_truth(str) - The expected answer
prepare_dataset
List[Dict]
required
List of test query dictionaries with “question” and “ground_truth” keys
Dataset
RAGAS-compatible HuggingFace Dataset with columns:
question- User queriesanswer- RAG-generated answerscontexts- Retrieved context chunksground_truth- Expected answers
- Populates
self.performance_metadatawith execution metrics - Prints progress information for each query
- Handles errors gracefully and continues processing
evaluate_rag
Dataset
required
Prepared RAGAS dataset with questions, answers, contexts, and ground truth
Dict[str, Any]
Evaluation results object with metric scores. Can be accessed as:
- Object attributes (e.g.,
results.faithfulness) - Via
to_pandas()method for DataFrame conversion
- Executes RAGAS evaluation with 8 parallel workers
- Disables per-call timeouts for Python 3.14+ compatibility
- Automatically detects all-NaN results and falls back to synchronous evaluation
- Handles async context issues gracefully
display_results
required
Evaluation results from
evaluate_rag()- Individual metric scores (0-1 scale)
- Average score across all metrics
- Performance assessment (Excellent/Good/Needs improvement/Significant improvements needed)
save_results
required
Evaluation results from
evaluate_rag()str
Output filename. If not provided, generates timestamped filename
bool
default:"False"
If True, returns dictionary instead of saving to file
str
LLM model name to include in metadata
Union[Path, Dict, None]
- File path if saved to disk
- Dictionary if
return_data_only=True - None if no results or error occurred
run_evaluation
- Load test queries from obstetric dataset
- Prepare RAGAS dataset by executing RAG queries
- Run RAGAS evaluation with configured metrics
- Display formatted results
- Save results to JSON file
run_multi_model_evaluation
list
List of model keys from MODELS_REGISTRY. If None, tests all registered models.
- Iterates through each model in the list
- Creates custom LLM instances for each model
- Wraps RAG query functions to use the custom model
- Collects results from all models
- Generates consolidated multi-model report
ragas_multimodel_{rag_type}_{timestamp}.json
Example:
SyncEvaluationResult Class
Lightweight wrapper for synchronous evaluation results, compatible with RAGAS result format.Constructor
pd.DataFrame
required
DataFrame containing metric scores for each evaluation sample
List[Any]
required
List of RAGAS metric objects used in evaluation
- Calculates mean value for each metric and stores as instance attribute
- Provides
to_pandas()method for DataFrame access - Compatible with downstream result processing pipelines
Helper Functions
evaluate_rewriter_rag
bool
default:"False"
Export detailed analysis files (CSV, charts) using export_ragas_analysis utility
bool
default:"False"
Enable debug output
evaluate_hybrid_rag
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
evaluate_hybrid_rrf_rag
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
evaluate_hyde_rag
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
evaluate_simple_rag
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
evaluate_pageindex_rag
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
evaluate_both_rags
bool
default:"False"
Export detailed analysis files for both systems
bool
default:"False"
Enable debug output
Dict
Dictionary with keys “rewriter” and “hybrid” containing respective results
evaluate_all_rags
bool
default:"False"
Export detailed analysis files for all systems
bool
default:"False"
Enable debug output
Dict
Dictionary with keys for each RAG type (“simple”, “hyde”, “rewriter”, “hybrid”, “hybrid-rrf”, “pageindex”)
- Evaluates all 6 RAG systems in sequence
- Generates individual result files for each RAG
- Creates consolidated comparison report with best performer analysis
- Includes 2-second pause between evaluations
- Individual:
ragas_evaluation_{rag_type}_{timestamp}.json - Comparison:
ragas_comparison_all_rags_{timestamp}.json
run_all_models_all_rags_evaluation
bool
default:"False"
Export detailed analysis files (currently not used in this function)
bool
default:"False"
Enable debug output
- Tests all 6 RAG types with all models in MODELS_REGISTRY
- Total evaluations: 6 RAGs × N models
- Generates comprehensive consolidated report
- Provides progress indicators and success statistics
ragas_comprehensive_all_rags_all_models_{timestamp}.json
Example:
DATA_GT Dataset
Built-in obstetric and pregnancy-specific evaluation dataset with 10 ground truth questions. Structure:- Prenatal care scheduling and timing
- Risk assessment protocols
- Clinical evaluation tools (Herrera & Hurtado scale)
- Postpartum depression screening
- Weight gain recommendations by BMI
- VBAC (Vaginal Birth After Cesarean) probabilities
- Nausea and vomiting treatment options
RAGAS Metrics
The evaluator uses four fundamental RAGAS metrics:Faithfulness
Measures whether the answer is factually consistent with the retrieved contexts. Score range: 0-1 (higher is better). Calculation: Checks if claims in the answer can be inferred from the contexts without hallucination.Answer Relevancy
Measures how relevant the answer is to the original question. Score range: 0-1 (higher is better). Calculation: Uses embeddings to compute semantic similarity between question and answer.Context Precision
Measures the proportion of relevant contexts in the retrieved set. Score range: 0-1 (higher is better). Calculation: Evaluates whether retrieved contexts are actually useful for answering the question.Context Recall
Measures whether all necessary information from ground truth is present in retrieved contexts. Score range: 0-1 (higher is better). Calculation: Checks if ground truth answer can be derived from the retrieved contexts.Result Format
Single RAG Evaluation
Multi-Model Comparison
Comprehensive All RAGs All Models
Command-Line Usage
The module can be executed directly from the command line:--exportor-e- Export detailed analysis files--debugor-d- Enable debug output
Complete Usage Example
Performance Considerations
Execution Time
- Single RAG evaluation: ~3-5 minutes for 10 questions
- Multi-model evaluation: ~5-10 minutes per model
- All RAGs evaluation: ~20-30 minutes total
- Comprehensive (all RAGs × all models): 1-2 hours depending on number of models
Cost Implications
Evaluation costs depend on:- LLM model pricing (input/output tokens)
- Number of RAG queries
- Retrieved context length
- Answer generation length
- GPT-4o: ~$0.04-0.06
- Claude-3.5-Sonnet: ~$0.05-0.08
- GPT-3.5-turbo: ~$0.01-0.02
Async vs Sync Mode
The evaluator automatically handles async context issues:- Default: Async evaluation with 8 workers (faster)
- Fallback: Synchronous evaluation with 1 worker (more stable)
- Trigger: All-NaN metrics or async exceptions
Error Handling
Common Issues
1. All-NaN MetricsDependencies
Required Packages:ragas- RAGAS evaluation frameworkdatasets- HuggingFace datasets librarypandas- Data manipulationnumpy- Numerical operations
src.rag.*- RAG system implementationssrc.common.model_provider- LLM model managementsrc.common.pricing- Cost tracking utilitiessrc.common.utils- Analysis export utilities
See Also
- Evaluation Overview - Comprehensive evaluation system guide
- Model Provider - LLM model configuration and management
- RAG Systems - Documentation for all RAG implementations
- Pricing - Cost tracking and analysis utilities
