Skip to main content

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

Initialize a RAGAS evaluator for a specific RAG architecture.
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
Instance Attributes:
  • 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 evaluation
  • rag_name - Descriptive name of the RAG system
  • rag_type - RAG type identifier
  • llm_model - Default LLM model name (initially “gpt-4o”)
  • performance_metadata - List storing execution metrics per query
Example:

set_models

Update the LLM model used by the evaluator.
str
New LLM model name (e.g., “gpt-4o”, “claude-3-5-sonnet”)
str
New embeddings model name (currently not used in implementation)
Example:

load_test_queries

Load test queries from the obstetric dataset.
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 question
  • ground_truth (str) - The expected answer
Example:

prepare_dataset

Prepare RAGAS dataset format by executing RAG queries and collecting results.
List[Dict]
required
List of test query dictionaries with “question” and “ground_truth” keys
Dataset
RAGAS-compatible HuggingFace Dataset with columns:
  • question - User queries
  • answer - RAG-generated answers
  • contexts - Retrieved context chunks
  • ground_truth - Expected answers
Side Effects:
  • Populates self.performance_metadata with execution metrics
  • Prints progress information for each query
  • Handles errors gracefully and continues processing
Example:

evaluate_rag

Evaluate RAG using RAGAS metrics with automatic fallback to synchronous mode.
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
Behavior:
  • 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
Example:

display_results

Display evaluation results in a formatted console output.
required
Evaluation results from evaluate_rag()
Output Format:
  • Individual metric scores (0-1 scale)
  • Average score across all metrics
  • Performance assessment (Excellent/Good/Needs improvement/Significant improvements needed)
Example:
Sample Output:

save_results

Save evaluation results to JSON file or return as dictionary.
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
Output Structure:
Example:

run_evaluation

Execute complete evaluation pipeline with the obstetric dataset. Returns: Evaluation results object Pipeline Steps:
  1. Load test queries from obstetric dataset
  2. Prepare RAGAS dataset by executing RAG queries
  3. Run RAGAS evaluation with configured metrics
  4. Display formatted results
  5. Save results to JSON file
Example:
Console Output:

run_multi_model_evaluation

Run evaluation for the current RAG type against multiple LLM models.
list
List of model keys from MODELS_REGISTRY. If None, tests all registered models.
Behavior:
  • 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
Output File: ragas_multimodel_{rag_type}_{timestamp}.json Example:
Output Structure:

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
Behavior:
  • Calculates mean value for each metric and stores as instance attribute
  • Provides to_pandas() method for DataFrame access
  • Compatible with downstream result processing pipelines
Example:

Helper Functions

evaluate_rewriter_rag

Evaluate Rewriter RAG specifically with optional analysis export.
bool
default:"False"
Export detailed analysis files (CSV, charts) using export_ragas_analysis utility
bool
default:"False"
Enable debug output
Example:

evaluate_hybrid_rag

Evaluate Hybrid RAG (BM25 + Semantic) specifically.
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
Example:

evaluate_hybrid_rrf_rag

Evaluate Hybrid RAG with Reciprocal Rank Fusion.
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
Example:

evaluate_hyde_rag

Evaluate HyDE RAG (Hypothetical Documents) specifically.
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
Example:

evaluate_simple_rag

Evaluate Simple Semantic RAG specifically.
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
Example:

evaluate_pageindex_rag

Evaluate PageIndex RAG specifically.
bool
default:"False"
Export detailed analysis files
bool
default:"False"
Enable debug output
Example:

evaluate_both_rags

Evaluate both original RAG systems sequentially (Rewriter and Hybrid).
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
Example:

evaluate_all_rags

Evaluate all 6 RAG systems sequentially with comprehensive comparison report.
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”)
Behavior:
  • 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
Output Files:
  • Individual: ragas_evaluation_{rag_type}_{timestamp}.json
  • Comparison: ragas_comparison_all_rags_{timestamp}.json
Example:

run_all_models_all_rags_evaluation

Comprehensive evaluation: ALL RAG types against ALL LLM models.
bool
default:"False"
Export detailed analysis files (currently not used in this function)
bool
default:"False"
Enable debug output
Behavior:
  • 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
Output File: ragas_comprehensive_all_rags_all_models_{timestamp}.json Example:
Console Output:

DATA_GT Dataset

Built-in obstetric and pregnancy-specific evaluation dataset with 10 ground truth questions. Structure:
Topics Covered:
  • 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
Language: Spanish (Colombian clinical guidelines) Usage:

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:
Available Flags:
  • --export or -e - Export detailed analysis files
  • --debug or -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
Example costs per 10-question evaluation:
  • 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 Metrics
Solution: Automatically handled by fallback mechanism. 2. Model Not Found
Solution: Use valid model keys from MODELS_REGISTRY. 3. Query Execution Failure
Solution: Individual query failures are logged but don’t stop evaluation. 4. Unsupported RAG Type
Solution: Use one of the 6 supported RAG types.

Dependencies

Required Packages:
  • ragas - RAGAS evaluation framework
  • datasets - HuggingFace datasets library
  • pandas - Data manipulation
  • numpy - Numerical operations
Internal Dependencies:
  • src.rag.* - RAG system implementations
  • src.common.model_provider - LLM model management
  • src.common.pricing - Cost tracking utilities
  • src.common.utils - Analysis export utilities

See Also