An extensible, abstract framework for building Retrieval-Augmented Generation (RAG) systems with unlimited technique possibilities
Project description
RAGLib
An extensible, abstract framework for building Retrieval-Augmented Generation (RAG) systems with unlimited technique possibilities.
RAGLib provides a unified, registry-based architecture that allows you to discover, compose, and extend RAG techniques dynamically. Whether you're prototyping with built-in implementations or integrating cutting-edge research, RAGLib adapts to your needs.
โจ Core Philosophy
RAGLib is designed around abstraction and extensibility:
- ๐๏ธ Abstract Interface: All techniques implement the same
RAGTechnique.apply()contract - ๐ Dynamic Discovery: Find and use techniques through the central
TechniqueRegistry - ๐งฉ Infinite Extensibility: Add new techniques without modifying core library code
- ๐ Adapter Pattern: Swap implementations from fallback to production with zero code changes
- ๐ฆ Plugin Ecosystem: Distribute and discover techniques as standalone packages
๐ Key Features
- ๐ง Unified API: Every technique, from chunking to generation, uses the same interface
- ๐๏ธ Registry System: Dynamically discover, register, and compose techniques
- ๐งฉ Modular Architecture: Mix and match any combination of techniques
- ๐ Plugin Framework: Easy extensibility with automatic plugin discovery
- โก Production Ready: Seamless transition from prototypes to production systems
- ๐ Built-in Benchmarking: Evaluate and compare technique performance
- ๐ Self-Documenting: Auto-generated documentation from technique metadata
๐ฏ Quick Start
Installation
pip install rag-techlib
# For optional dependencies
pip install rag-techlib[faiss] # Advanced embeddings and vector search
pip install rag-techlib[llm] # LLM integration
pip install rag-techlib[dev] # Development tools
pip install rag-techlib[all] # Everything
Registry-Driven Usage
The power of RAGLib lies in its registry system - discover and use techniques dynamically:
from raglib.registry import TechniqueRegistry
from raglib.schemas import Document
# Discover available techniques
print("Available techniques:", list(TechniqueRegistry.list().keys()))
# Get techniques by category
chunkers = TechniqueRegistry.find_by_category("chunking")
retrievers = TechniqueRegistry.find_by_category("retrieval")
# Load any technique dynamically
ChunkerClass = TechniqueRegistry.get("fixed_size_chunker")
RetrieverClass = TechniqueRegistry.get("dense_retriever")
# Use with consistent interface
chunker = ChunkerClass(chunk_size=256, overlap=20)
retriever = RetrieverClass()
# All techniques use the same apply() method
documents = [Document(id="1", text="Your content here...")]
chunks_result = chunker.apply(documents)
retrieval_result = retriever.apply(query="search query", corpus=chunks_result.payload)
Configuration-Driven Pipelines
Build entire RAG systems from configuration:
from raglib.pipelines import Pipeline
# Define pipeline from configuration
pipeline_config = [
("chunker", "semantic_chunker", {"similarity_threshold": 0.8}),
("retriever", "dense_retriever", {"top_k": 5}),
("reranker", "mmr", {"lambda_param": 0.7}),
("generator", "llm_generator", {"temperature": 0.7})
]
# Build pipeline dynamically
pipeline_steps = []
for name, technique_name, params in pipeline_config:
TechniqueClass = TechniqueRegistry.get(technique_name)
technique = TechniqueClass(**params)
pipeline_steps.append(technique)
pipeline = Pipeline(pipeline_steps)
# Run the complete RAG system
result = pipeline.run("What is machine learning?")
๐งฉ Extensible Architecture
Adding Custom Techniques
RAGLib's registry system makes adding new techniques trivial:
from raglib.core import RAGTechnique, TechniqueMeta, TechniqueResult
from raglib.registry import TechniqueRegistry
@TechniqueRegistry.register
class MyCustomRetriever(RAGTechnique):
meta = TechniqueMeta(
name="my_custom_retriever",
category="retrieval",
description="My innovative retrieval technique",
version="1.0.0"
)
def __init__(self, custom_param=None):
super().__init__(self.meta)
self.custom_param = custom_param
def apply(self, query, corpus, **kwargs):
# Your custom logic here
results = self._my_retrieval_logic(query, corpus)
return TechniqueResult(
success=True,
payload={"hits": results}
)
# Technique is automatically available in registry
retriever = TechniqueRegistry.get("my_custom_retriever")(custom_param="value")
Plugin Development
Create distributable technique packages:
# In your plugin package
from raglib.core import RAGTechnique, TechniqueMeta
from raglib.registry import TechniqueRegistry
@TechniqueRegistry.register
class AdvancedSemanticRetriever(RAGTechnique):
meta = TechniqueMeta(
name="advanced_semantic_retriever",
category="retrieval",
description="State-of-the-art semantic retrieval",
dependencies=["transformers", "faiss-gpu"]
)
def apply(self, query, corpus, **kwargs):
# Advanced implementation
pass
# Users can install and use immediately:
# pip install your-raglib-plugin
# from raglib.registry import TechniqueRegistry
# retriever = TechniqueRegistry.get("advanced_semantic_retriever")()
๐ Built-in Technique Categories
RAGLib provides production-ready implementations across all RAG components:
๐จ Document Processing
- Content-Aware Chunking: Content-aware chunking that respects text structure and natural boundaries
- Document-Specific Chunking: Document-specific chunking that adapts to document type
- Fixed Size Chunking: Fixed-size text chunking with overlap support
- Document-Specific Chunking: Parent document retrieval with small-to-large chunk mapping
- Propositional Chunking: Propositional chunking based on semantic propositions
- Recursive Chunking: Recursive chunking with hierarchical text splitting
- Semantic Chunking: Semantic similarity-based chunking with configurable embedder
- Sentence Window Chunking: Sentence-based windowing with configurable window size and overlap
๐ Information Retrieval
- BM25 Retrieval: Classical sparse retrieval (simple and production variants)
- Dense Retrieval: Vector-based semantic search with adapter support
- Hybrid Retrieval: Combine multiple retrieval strategies
๐ฏ Result Refinement
- MMR Reranking: Balance relevance and diversity
- Cross-Encoder Reranking: Pairwise relevance scoring
- Custom Rerankers: Easily add domain-specific reranking logic
๐ฌ Response Generation
- LLM Generation: Flexible text generation with adapter support
- HyDE: Query expansion using hypothetical document generation
- Template Generation: Structured response formatting
๐ง System Components
- Pipeline Orchestration: Chain techniques with error handling
- Fusion-in-Decoder: Advanced multi-context generation
- Adapter Interfaces: Seamless integration with external libraries
All categories support both fallback implementations (for prototyping) and production adapters (for deployment).
๐ Adapter System
Seamlessly transition from development to production:
# Development: Use built-in fallbacks
retriever = TechniqueRegistry.get("dense_retriever")() # Uses DummyEmbedder
# Production: Plug in real implementations
from sentence_transformers import SentenceTransformer
from your_vector_db import ProductionVectorStore
class RealEmbedder:
def __init__(self):
self.model = SentenceTransformer('all-MiniLM-L6-v2')
def embed(self, texts):
return self.model.encode(texts)
retriever = TechniqueRegistry.get("dense_retriever")(
embedder=RealEmbedder(),
vectorstore=ProductionVectorStore()
)
# Same interface, production performance
result = retriever.apply(query="search query", corpus=documents)
๐ Benchmarking & Evaluation
from raglib.benchmark import BenchmarkHarness
# Evaluate any technique
retriever = TechniqueRegistry.get("bm25")()
harness = BenchmarkHarness()
results = harness.run_benchmark(
technique=retriever,
dataset_path="evaluation_data.jsonl",
metrics=["precision", "recall", "f1"]
)
print(f"F1 Score: {results['metrics']['f1']:.3f}")
๐ Documentation
- Getting Started - Installation and first steps
- Techniques Guide - Complete technique catalog
- API Reference - Detailed API documentation
- Plugin Development - Creating custom techniques
- Benchmarking Guide - Evaluation framework
๐ ๏ธ Development
Setup
git clone https://github.com/your-org/raglib.git
cd raglib
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
pip install -e .[dev]
Testing
# Run all tests
pytest
# Run tests with coverage
pytest --cov=raglib
# Run only fast tests
pytest -m "not slow"
# Run by category
pytest -m unit # Unit tests
pytest -m integration # Integration tests
Code Quality
# Linux/macOS
make format # Format code
make lint # Run linting
make type-check # Type checking
make all-checks # All quality checks
# Windows
.\build.ps1 format
.\build.ps1 lint
.\build.ps1 type-check
Documentation
# Generate technique index
make docs-generate # Linux/macOS
.\build.ps1 docs-generate # Windows
# Build and serve docs
mkdocs serve # Development server
mkdocs build # Build static site
๐ค Contributing
We welcome contributions! RAGLib thrives on community-contributed techniques and improvements.
How to Contribute
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-technique) - Add your technique following our Contributing Guide
- Include comprehensive tests
- Ensure all quality checks pass
- Submit a pull request
Contribution Types
- ๐งฌ New Techniques: Add novel RAG techniques to the registry
- ๐ง Adapters: Create integrations with external libraries
- ๐ Benchmarks: Contribute evaluation datasets and metrics
- ๐ Documentation: Improve guides, examples, and API docs
- ๐ Bug Fixes: Help maintain code quality
- โก Performance: Optimize existing implementations
See CONTRIBUTING.md for detailed guidelines.
๐ฏ Why RAGLib?
For Researchers
- ๐ฌ Rapid Prototyping: Test new ideas without infrastructure overhead
- ๐ Standardized Evaluation: Compare techniques fairly with built-in benchmarks
- ๐ Easy Reproduction: Deterministic fallbacks ensure reproducible results
- ๐ฆ Simple Distribution: Share techniques as plugins
For Engineers
- ๐๏ธ Production Ready: Seamless transition from prototype to production
- ๐ง Flexible Integration: Adapter pattern works with any external library
- ๐ Scalable Architecture: Registry system handles growing technique libraries
- ๐ก๏ธ Robust Error Handling: Graceful fallbacks prevent system failures
For Teams
- ๐ค Collaborative Development: Registry enables parallel technique development
- ๐ Configuration Management: Build systems from declarative configs
- ๐ Discovery: Find and evaluate techniques without code diving
- ๐ Self-Documenting: Metadata-driven documentation stays current
๐ Community & Ecosystem
- GitHub Discussions: Share ideas and get help
- Plugin Registry: Discover community-contributed techniques
- Research Papers: Implementations of latest RAG research
- Industry Examples: Production-tested technique combinations
๐ Roadmap
- Multi-modal Support: Image and audio RAG techniques
- Distributed Computing: Scale to massive document collections
- AutoRAG: Automatic technique selection and optimization
- Visual Pipeline Builder: GUI for technique composition
- Enterprise Features: Advanced monitoring and deployment tools
๐ License
MIT License
Copyright (c) 2025 RAGLib Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
๐ Citation
If you use RAGLib in your research, please cite:
@software{raglib,
title = {RAGLib: An Extensible Framework for Retrieval-Augmented Generation},
author = {RAGLib Contributors},
year = {2025},
url = {https://github.com/Mohammadshamlawi/raglib},
note = {An abstract, registry-based library for building RAG systems}
}
RAGLib - Building the future of Retrieval-Augmented Generation, one technique at a time.
๐ Website: https://rag-techlib.readthedocs.io
๐ Issues: https://github.com/Mohammadshamlawi/raglib/issues
๐ฌ Discussions: https://github.com/Mohammadshamlawi/raglib/discussions
๐ฆ PyPI: https://pypi.org/project/rag-techlib/
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file rag_techlib-1.4.0.tar.gz.
File metadata
- Download URL: rag_techlib-1.4.0.tar.gz
- Upload date:
- Size: 124.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
77b770bd9d1a5776678b6f2344c76ed97f0a031b04f10e37acf8382e2bf7c279
|
|
| MD5 |
6b71c7211da27e322bcbfc6e4aba7717
|
|
| BLAKE2b-256 |
f8d742d05d7691976d18ef81e37b38bed90a6a45b2df17ec3efe8f075c6d351c
|
File details
Details for the file rag_techlib-1.4.0-py3-none-any.whl.
File metadata
- Download URL: rag_techlib-1.4.0-py3-none-any.whl
- Upload date:
- Size: 56.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c0b0dd9a4d61a3ceb31534579302a17575ba2567d84ec10fdd1484aebc686e8e
|
|
| MD5 |
84846492585410dc9571d0e380f452f5
|
|
| BLAKE2b-256 |
c05b10073ed54a5f7162c0fd42265b8dcb2ed21e0a100fbd4a4375f54c3fdddd
|