StageRAG is a lightweight, production-ready RAG framework designed to give you precise control over the speed-versus-accuracy trade-off. It allows you to build high-factuality applications while gracefully managing uncertainty in LLM responses.
You must request access to both Llama models:
pip install huggingface-hub
huggingface-cli login
# Enter your HuggingFace token when prompted
Get your token from: https://huggingface.co/settings/tokens
git clone https://github.com/darrencxl0301/StageRAG.git
cd StageRAG
# Install main dependencies
pip install -r requirements.txt
# Install in development mode
pip install -e .
# Setup the packages
python setup.py
python scripts/download_data.py
This downloads the sample dataset from darren0301/domain-mix-qa-1k to data/data.jsonl.
from datasets import load_dataset
import json
dataset = load_dataset("darren0301/domain-mix-qa-1k")
with open("data/data.jsonl", "w") as f:
for item in dataset["train"]:
json.dump({"conversations": item["conversations"]}, f)
f.write("\n")
Create a JSONL file with this format:
{"conversations": [{"role": "user", "content": "What is EPF?"}, {"role": "assistant", "content": "EPF is the Employees Provident Fund..."}]}
{"conversations": [{"role": "user", "content": "How to apply for leave?"}, {"role": "assistant", "content": "To apply for leave..."}]}
# Basic usage (CPU)
python demo/interactive_demo.py --rag_dataset data/data.jsonl
# With GPU and 4-bit quantization (recommended)
python demo/interactive_demo.py --rag_dataset data/data.jsonl --use_4bit --device cuda
Interactive Commands:
mode speed - Switch to speed mode (3-step)mode precision - Switch to precision mode (4-step)cache stats - View cache performancesearch <query> - Test RAG retrievalquit or q - Exitpython demo/basic_usage.py --rag_dataset data/data.jsonl
from stagerag import StageRAGSystem
import argparse
# Setup configuration
args = argparse.Namespace(
rag_dataset='data/data.jsonl',
device='cuda',
use_4bit=True,
cache_size=1000,
temperature=0.7,
top_p=0.85,
max_new_tokens=512,
max_seq_len=2048,
disable_rag=False,
rag_threshold=0.3,
seed=42
)
# Initialize system
system = StageRAGSystem(args)
# Process query
result = system.process_query(
"What are the EPF contribution rates?",
mode="speed"
)
print(f"Answer: {result['answer']}")
print(f"Confidence: {result['confidence']['overall_confidence']:.3f}")
print(f"Time: {result['processing_time']:.2f}s")
# Install test dependencies
pip install pytest pytest-cov
# Run all tests
pytest tests/ -v
# Run specific test files
pytest tests/test_cache.py -v
pytest tests/test_confidence.py -v
pytest tests/test_rag.py -v
# Run with detailed output
pytest tests/test_cache.py -vv
# Run with coverage report
pytest tests/ --cov=stagerag --cov-report=html
| Argument | Default | Description |
|---|---|---|
--rag_dataset | Required | Path to JSONL knowledge base |
--device | cuda | Device to use (cuda/cpu) |
--use_4bit | False | Enable 4-bit quantization |
--cache_size | 1000 | LRU cache size |
--temperature | 0.7 | Sampling temperature (0.0-1.0) |
--top_p | 0.85 | Top-p nucleus sampling |
--max_new_tokens | 512 | Max tokens to generate |
--disable_rag | False | Disable RAG retrieval |
Edit stagerag/config.py to adjust confidence evaluation:
weights = {
'retrieval': 0.25, # RAG retrieval quality
'basic_quality': 0.25, # Answer structure/length
'relevance': 0.25, # Keyword relevance
'uncertainty': 0.25 # Uncertainty detection
}
StageRAG/
├── stagerag/ # Main package
│ ├── __init__.py # Package exports
│ ├── main.py # StageRAGSystem class
│ ├── cache.py # LRU cache implementation
│ ├── confidence.py # Confidence evaluator
│ ├── rag.py # RAG retrieval system
│ ├── prompts.py # Prompt templates
│ └── config.py # Configuration dataclasses
├── demo/ # Usage examples
│ ├── interactive_demo.py
│ └── basic_usage.py
├── scripts/ # Utility scripts
│ └── download_data.py # HuggingFace dataset downloader
├── tests/ # Test suite
│ ├── test_cache.py
│ ├── test_confidence.py
│ └── test_rag.py
├── data/ # Knowledge base (created on first run)
│ └── data.jsonl
├── requirements.txt # Production dependencies
├── requirements-dev.txt # Development dependencies
├── setup.py # Package configuration
└── README.md
User Input → [1B] Normalize → [3B] RAG Filter → [1B] Generate Answer → Response
User Input → [1B] Normalize → [3B] RAG Retrieve → [3B] Synthesize → [3B] Final Answer → Response
| Mode | Avg Time | Avg Confidence | Use Case |
|---|---|---|---|
| Speed | 3.3s | 0.72 | Real-time chat |
| Precision | 7.8s | 0.83 | Complex queries, critical decisions |
Tested on NVIDIA RTX 3090 GPU with 4-bit quantization
Sample dataset: darren0301/domain-mix-qa-1k
Contains 1,000 domain-specific Q&A pairs covering:
Contributions are welcome! Please:
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
@software{stagerag2024,
author = {Darren Chai Xin Lun},
title = {StageRAG: A Framework for Building Hallucination-Resistant RAG Applications},
year = {2024},
url = {https://github.com/darrencxl0301/StageRAG},
note = {Dataset: https://huggingface.co/datasets/darren0301/domain-mix-qa-1k}
}
Darren Chai Xin Lun
⭐ If you find this project helpful, please give it a star!
14 commits
Python
100.0%
StageRAG is a lightweight, production-ready RAG framework designed to give you precise control over the speed-versus-accuracy trade-off. It allows you to build high-factuality applications while gracefully managing uncertainty in LLM responses.
You must request access to both Llama models:
pip install huggingface-hub
huggingface-cli login
# Enter your HuggingFace token when prompted
Get your token from: https://huggingface.co/settings/tokens
git clone https://github.com/darrencxl0301/StageRAG.git
cd StageRAG
# Install main dependencies
pip install -r requirements.txt
# Install in development mode
pip install -e .
# Setup the packages
python setup.py
python scripts/download_data.py
This downloads the sample dataset from darren0301/domain-mix-qa-1k to data/data.jsonl.
from datasets import load_dataset
import json
dataset = load_dataset("darren0301/domain-mix-qa-1k")
with open("data/data.jsonl", "w") as f:
for item in dataset["train"]:
json.dump({"conversations": item["conversations"]}, f)
f.write("\n")
Create a JSONL file with this format:
{"conversations": [{"role": "user", "content": "What is EPF?"}, {"role": "assistant", "content": "EPF is the Employees Provident Fund..."}]}
{"conversations": [{"role": "user", "content": "How to apply for leave?"}, {"role": "assistant", "content": "To apply for leave..."}]}
# Basic usage (CPU)
python demo/interactive_demo.py --rag_dataset data/data.jsonl
# With GPU and 4-bit quantization (recommended)
python demo/interactive_demo.py --rag_dataset data/data.jsonl --use_4bit --device cuda
Interactive Commands:
mode speed - Switch to speed mode (3-step)mode precision - Switch to precision mode (4-step)cache stats - View cache performancesearch <query> - Test RAG retrievalquit or q - Exitpython demo/basic_usage.py --rag_dataset data/data.jsonl
from stagerag import StageRAGSystem
import argparse
# Setup configuration
args = argparse.Namespace(
rag_dataset='data/data.jsonl',
device='cuda',
use_4bit=True,
cache_size=1000,
temperature=0.7,
top_p=0.85,
max_new_tokens=512,
max_seq_len=2048,
disable_rag=False,
rag_threshold=0.3,
seed=42
)
# Initialize system
system = StageRAGSystem(args)
# Process query
result = system.process_query(
"What are the EPF contribution rates?",
mode="speed"
)
print(f"Answer: {result['answer']}")
print(f"Confidence: {result['confidence']['overall_confidence']:.3f}")
print(f"Time: {result['processing_time']:.2f}s")
# Install test dependencies
pip install pytest pytest-cov
# Run all tests
pytest tests/ -v
# Run specific test files
pytest tests/test_cache.py -v
pytest tests/test_confidence.py -v
pytest tests/test_rag.py -v
# Run with detailed output
pytest tests/test_cache.py -vv
# Run with coverage report
pytest tests/ --cov=stagerag --cov-report=html
| Argument | Default | Description |
|---|---|---|
--rag_dataset | Required | Path to JSONL knowledge base |
--device | cuda | Device to use (cuda/cpu) |
--use_4bit | False | Enable 4-bit quantization |
--cache_size | 1000 | LRU cache size |
--temperature | 0.7 | Sampling temperature (0.0-1.0) |
--top_p | 0.85 | Top-p nucleus sampling |
--max_new_tokens | 512 | Max tokens to generate |
--disable_rag | False | Disable RAG retrieval |
Edit stagerag/config.py to adjust confidence evaluation:
weights = {
'retrieval': 0.25, # RAG retrieval quality
'basic_quality': 0.25, # Answer structure/length
'relevance': 0.25, # Keyword relevance
'uncertainty': 0.25 # Uncertainty detection
}
StageRAG/
├── stagerag/ # Main package
│ ├── __init__.py # Package exports
│ ├── main.py # StageRAGSystem class
│ ├── cache.py # LRU cache implementation
│ ├── confidence.py # Confidence evaluator
│ ├── rag.py # RAG retrieval system
│ ├── prompts.py # Prompt templates
│ └── config.py # Configuration dataclasses
├── demo/ # Usage examples
│ ├── interactive_demo.py
│ └── basic_usage.py
├── scripts/ # Utility scripts
│ └── download_data.py # HuggingFace dataset downloader
├── tests/ # Test suite
│ ├── test_cache.py
│ ├── test_confidence.py
│ └── test_rag.py
├── data/ # Knowledge base (created on first run)
│ └── data.jsonl
├── requirements.txt # Production dependencies
├── requirements-dev.txt # Development dependencies
├── setup.py # Package configuration
└── README.md
User Input → [1B] Normalize → [3B] RAG Filter → [1B] Generate Answer → Response
User Input → [1B] Normalize → [3B] RAG Retrieve → [3B] Synthesize → [3B] Final Answer → Response
| Mode | Avg Time | Avg Confidence | Use Case |
|---|---|---|---|
| Speed | 3.3s | 0.72 | Real-time chat |
| Precision | 7.8s | 0.83 | Complex queries, critical decisions |
Tested on NVIDIA RTX 3090 GPU with 4-bit quantization
Sample dataset: darren0301/domain-mix-qa-1k
Contains 1,000 domain-specific Q&A pairs covering:
Contributions are welcome! Please:
git checkout -b feature/amazing-feature)git commit -m 'Add amazing feature')git push origin feature/amazing-feature)This project is licensed under the MIT License - see the LICENSE file for details.
@software{stagerag2024,
author = {Darren Chai Xin Lun},
title = {StageRAG: A Framework for Building Hallucination-Resistant RAG Applications},
year = {2024},
url = {https://github.com/darrencxl0301/StageRAG},
note = {Dataset: https://huggingface.co/datasets/darren0301/domain-mix-qa-1k}
}
Darren Chai Xin Lun
⭐ If you find this project helpful, please give it a star!
14 commits
Python
100.0%