CoolFace
Apppublic

yugandhartamire/rag_bench_pipeline

sourceHugging Facemitupdated 2mo agoView on Hugging Face
0likes
App README

๐Ÿš€ 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

  1. 1.Clone the repository
bash
git clone <your-repo-url>
cd rag_pipeline
  1. 1.Create virtual environment
bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. 1.Install dependencies
bash
pip install -r requirements.txt
  1. 1.Set up API keys

Create a .env file or set environment variables:

bash
export GROQ_API_KEY="your_groq_api_key"
export OPENROUTER_API_KEY="your_openrouter_api_key"
  1. 1.Run the application
bash
python app.py

The application will be available at http://localhost:7860

๐ŸŒ Deploy to Hugging Face Spaces

Method 1: Direct Upload

  1. 1.Create a new Space on Hugging Face
  2. 2.Choose Gradio as the SDK
  3. 3.Upload all project files
  4. 4.Add your API keys in Settings โ†’ Repository secrets:
  5. 5.GROQ_API_KEY
  6. 6.OPENROUTER_API_KEY

Method 2: Git Integration

  1. 1.Create a new Space with Git enabled
  2. 2.Clone your Space repository:
bash
git clone https://huggingface.co/spaces/<your-username>/<your-space-name>
  1. 1.Copy project files and push:
bash
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 โš™๏ธ

  1. 1.Dataset Configuration
  2. 2.Enter Hugging Face dataset name (e.g., rungalileo/ragbench)
  3. 3.Select split (train/validation/test)
  4. 4.Set sample size (-1 for all)
  1. 1.Chunking Settings
  2. 2.Chunk size: 400 (recommended)
  3. 3.Chunk overlap: 80 (recommended)
  1. 1.Retrieval Configuration
  2. 2.Embedding model: BAAI/bge-small-en-v1.5
  3. 3.Retriever type: Dense or Sparse
  4. 4.Top K: Number of documents to retrieve
  1. 1.Reranking Settings
  2. 2.Ranking model: ms-marco-MiniLM-L-12-v2
  3. 3.Rerank K: Final number of documents
  4. 4.Repacking strategy: sides or reverse
  1. 1.LLM Configuration
  2. 2.Provider: Groq or OpenRouter
  3. 3.Generator model: llama-3.1-8b-instant
  4. 4.Judge model: llama-3.3-70b-versatile
  1. 1.API Keys
  2. 2.Enter comma-separated API keys for rate limit handling
  3. 3.Click Load Dataset & Initialize Pipeline

Tab 2: Single Query ๐Ÿ”

  1. 1.Enter your question
  2. 2.Choose:
  3. 3.Run Query: Get answer without evaluation
  4. 4.Run Query + Evaluation: Full TRACe metrics evaluation
  5. 5.View retrieved documents, generated answer, and metrics

Tab 3: Batch Evaluation ๐Ÿ“Š

  1. 1.Set number of samples to process
  2. 2.Click Start Batch Processing
  3. 3.Monitor progress in real-time
  4. 4.Download results as CSV

Tab 4: Results Analysis ๐Ÿ“ˆ

  1. 1.Upload batch results CSV
  2. 2.View summary statistics
  3. 3.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:

python
# 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 interface
  • โ€”langchain - LLM orchestration
  • โ€”sentence-transformers - Embeddings
  • โ€”flashrank - Reranking
  • โ€”rank-bm25 - Sparse retrieval
  • โ€”datasets - 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:

python
{
    "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`:

python
class CustomRetriever:
    def invoke(self, query: str, k: int) -> List[Document]:
        # Your implementation
        pass

Adding New Metrics

Edit `app/utils/metrics.py`:

python
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