yugandhartamire/rag_bench_pipeline
๐ RAG Pipeline with TRACe Evaluation
A complete Retrieval-Augmented Generation (RAG) system with comprehensive evaluation using TRACe metrics (Relevance, Utilization, Completeness, Adherence). Built with Gradio for easy deployment to Hugging Face Spaces.
โจ Features
- ๐ Multiple Retrieval Methods: Dense (vector similarity) and Sparse (BM25)
- ๐ฏ Advanced Reranking: FlashRank with multiple repacking strategies
- ๐ค Multiple LLM Providers: Groq and OpenRouter support
- ๐ TRACe Metrics: Complete evaluation with Relevance, Utilization, Completeness, and Adherence
- ๐จ Gradio Interface: User-friendly web UI with multiple tabs
- ๐ Batch Processing: Process multiple queries with checkpoint support
- ๐ API Key Rotation: Automatic rate limit handling
- ๐พ Results Export: Download evaluation results as CSV
๐๏ธ Architecture
rag_pipeline/
โโโ app/
โ โโโ config.py # Configuration management
โ โโโ data_loader.py # Dataset loading utilities
โ โโโ llm_manager.py # LLM provider management
โ โโโ rag/ # Core RAG components
โ โ โโโ embeddings.py # HuggingFace embeddings
โ โ โโโ retrievers.py # BM25 & Vector retrievers
โ โ โโโ reranker.py # FlashRank reranking
โ โ โโโ pipeline.py # Main RAG pipeline
โ โ โโโ evaluator.py # TRACe metrics evaluation
โ โโโ utils/ # Utility functions
โ โ โโโ text_processing.py # Text splitting & keying
โ โ โโโ metrics.py # Metrics computation
โ โ โโโ helpers.py # Error handling
โ โโโ ui/ # Gradio interface
โ โโโ gradio_app.py # Multi-tab UI
โโโ app.py # Application entry point
โโโ config.yaml # Default configuration
โโโ requirements.txt # Python dependencies
โโโ README.md # This file๐ Quick Start
Local Installation
- Clone the repository
git clone <your-repo-url>
cd rag_pipeline- Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies
pip install -r requirements.txt- Set up API keys
Create a .env file or set environment variables:
export GROQ_API_KEY="your_groq_api_key"
export OPENROUTER_API_KEY="your_openrouter_api_key"- Run the application
python app.pyThe application will be available at http://localhost:7860
๐ Deploy to Hugging Face Spaces
Method 1: Direct Upload
- Create a new Space on Hugging Face
- Choose Gradio as the SDK
- Upload all project files
- Add your API keys in Settings โ Repository secrets:
GROQ_API_KEYOPENROUTER_API_KEY
Method 2: Git Integration
- Create a new Space with Git enabled
- Clone your Space repository:
git clone https://huggingface.co/spaces/<your-username>/<your-space-name>- Copy project files and push:
cp -r rag_pipeline/* <your-space-name>/
cd <your-space-name>
git add .
git commit -m "Initial commit"
git push๐ Usage Guide
Tab 1: Configuration โ๏ธ
- Dataset Configuration
- Enter Hugging Face dataset name (e.g.,
rungalileo/ragbench) - Select split (train/validation/test)
- Set sample size (-1 for all)
- Chunking Settings
- Chunk size: 400 (recommended)
- Chunk overlap: 80 (recommended)
- Retrieval Configuration
- Embedding model:
BAAI/bge-small-en-v1.5 - Retriever type: Dense or Sparse
- Top K: Number of documents to retrieve
- Reranking Settings
- Ranking model:
ms-marco-MiniLM-L-12-v2 - Rerank K: Final number of documents
- Repacking strategy: sides or reverse
- LLM Configuration
- Provider: Groq or OpenRouter
- Generator model:
llama-3.1-8b-instant - Judge model:
llama-3.3-70b-versatile
- API Keys
- Enter comma-separated API keys for rate limit handling
- Click Load Dataset & Initialize Pipeline
Tab 2: Single Query ๐
- Enter your question
- Choose:
- Run Query: Get answer without evaluation
- Run Query + Evaluation: Full TRACe metrics evaluation
- View retrieved documents, generated answer, and metrics
Tab 3: Batch Evaluation ๐
- Set number of samples to process
- Click Start Batch Processing
- Monitor progress in real-time
- Download results as CSV
Tab 4: Results Analysis ๐
- Upload batch results CSV
- View summary statistics
- Analyze metrics distribution
๐ TRACe Metrics Explained
Relevance Score
Fraction of context sentences that are relevant to the question.
- Formula:
relevant_sentences / total_context_sentences - Range: 0.0 to 1.0
Utilization Score
Fraction of context sentences actually used in the response.
- Formula:
utilized_sentences / total_context_sentences - Range: 0.0 to 1.0
Completeness Score
How well the response covers all relevant information.
- Formula:
(relevant โฉ utilized) / relevant_sentences - Range: 0.0 to 1.0
Adherence Score
Whether the response is fully supported by context.
- Boolean: True/False
- Continuous: Fraction of supported sentences
๐ง Configuration Options
Retriever Types
Dense (Vector Similarity)
- Uses semantic embeddings
- Better for conceptual matches
- Requires embedding model
Sparse (BM25)
- Uses lexical matching
- Better for exact term matches
- Faster, no embedding needed
Repacking Strategies
Sides
- Places most relevant docs at beginning and end
- Leverages attention bias in LLMs
Reverse
- Least to most relevant order
- Alternative ordering strategy
๐ค API Key Management
The system supports multiple API keys for each provider to handle rate limits:
# In Configuration tab, enter comma-separated keys:
groq_keys = "key1,key2,key3"
openrouter_keys = "key1,key2"The system automatically rotates keys when rate limits are hit.
๐ฆ Dependencies
Key libraries:
gradio- Web interfacelangchain- LLM orchestrationsentence-transformers- Embeddingsflashrank- Rerankingrank-bm25- Sparse retrievaldatasets- HuggingFace datasets
See `requirements.txt` for complete list.
๐ Troubleshooting
Rate Limit Errors
- Add multiple API keys (comma-separated)
- System will automatically rotate
Memory Issues
- Reduce sample size
- Use smaller embedding models
- Reduce chunk size
Slow Processing
- Use sparse retrieval (BM25)
- Reduce rerank_k value
- Use smaller models
๐ Example Datasets
Compatible with datasets from Hugging Face with this structure:
{
"id": "unique_id",
"question": "Your question here?",
"documents": ["passage1", "passage2", ...],
"dataset_name": "dataset_name"
}Tested datasets:
rungalileo/ragbench(recommended)- Custom datasets with similar structure
๐ ๏ธ Development
Adding New Retrievers
Edit `app/rag/retrievers.py`:
class CustomRetriever:
def invoke(self, query: str, k: int) -> List[Document]:
# Your implementation
passAdding New Metrics
Edit `app/utils/metrics.py`:
def compute_custom_metric(judge_output, context):
# Your implementation
return score๐ License
MIT License - feel free to use for your projects!
๐ Acknowledgments
- Built with LangChain
- Uses FlashRank for reranking
- Evaluation based on TRACe metrics
- Interface powered by Gradio
๐ง Contact
For issues and questions, please open an issue on GitHub.
Made with โค๏ธ for the RAG community
