Skip to content

AnkitKumarxcodes/metarag-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

35 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MetaRAG SDK β€” Intelligent Pipeline Selection Engine

Python PyPI Ollama License Status


MetaRAG is an open-source engine that takes the guesswork out of RAG pipeline design. Instead of manually tuning chunking strategies, retrieval backends, and rerankers β€” MetaRAG benchmarks them all and routes every query to the configuration that actually performs best on your data.

Think of it as AutoML, but for RAG.



πŸ“Œ Table of Contents


πŸ€” Why MetaRAG

Every team building a RAG system faces the same unsolved problem:

Which chunking strategy should I use?
Which retrieval method works best for my documents?
How do I know if my pipeline is actually good?
What happens when a different query type breaks everything?

Current tools make you answer these questions manually β€” every time, for every project.

Tool Build RAG Evaluate Compare Auto-Select Learn
LangChain βœ… ❌ ❌ ❌ ❌
LlamaIndex βœ… ❌ ❌ ❌ ❌
RAGAS ❌ βœ… ❌ ❌ ❌
MetaRAG βœ… βœ… βœ… βœ… βœ…

MetaRAG owns the entire RAG workflow β€” from raw documents to evaluated, auto-selected, continuously improving answers. No LangChain dependency in the core β€” the retrieval and chunking logic is hand-built on top of numpy, pandas, and rank-bm25 only.


πŸ— Architecture

                        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                        β”‚              USER INTERFACE              β”‚
                        β”‚   MetaRAG(docs, embeddings, generator)   β”‚
                        β”‚            .fit()  .ask()                β”‚
                        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                          β”‚
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚                    METARAG CORE                  β”‚
                 β”‚                                                  β”‚
                 β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
    Documents ──►│   β”‚  Loader  │───►│ Chunker  │──►│ Embeddingsβ”‚   β”‚
                 β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜   β”‚
                 β”‚                                        β”‚         β”‚
                 β”‚                              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”  β”‚
                 β”‚                              β”‚  Vector Databaseβ”‚ β”‚
                 β”‚                              β”‚ InMemoryβ”‚Chroma β”‚ β”‚
                 β”‚                              β”‚      β”‚ FAISS   β”‚ β”‚
                 β”‚                              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜  β”‚
                 β”‚                                        β”‚         β”‚
                 β”‚                              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”  β”‚
                 β”‚                              β”‚   Retrievers   β”‚  β”‚
                 β”‚                              β”‚ BM25 β”‚ Dense   β”‚  β”‚
                 β”‚                              β”‚ Hybrid β”‚ MMR   β”‚  β”‚
                 β”‚                              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜  β”‚
                 β”‚                                        β”‚         β”‚
    Query ──────►│   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”  β”‚
                 β”‚   β”‚  Router  │──────────────► β”‚   Pipelines  β”‚   β”‚
                 β”‚   β”‚ (cold-   β”‚               β”‚Straightβ”‚MQueryβ”‚   β”‚
                 β”‚   β”‚  start β†’ β”‚               β”‚Rerankedβ”‚Full  β”‚   β”‚
                 β”‚   β”‚  learned)β”‚               β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜   β”‚
                 β”‚   β””β”€β”€β”€β”€β–²β”€β”€β”€β”€β”€β”˜                        β”‚          β”‚
                 β”‚        β”‚                     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”   β”‚
                 β”‚        β”‚                     β”‚   Evaluator   β”‚   β”‚
                 β”‚        β”‚                     β”‚  (5 metrics)  β”‚   β”‚
                 β”‚        β”‚                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜   β”‚
                 β”‚        β”‚                              β”‚          β”‚
                 β”‚        └────────── benchmark() β”€β”€β”€β”€β”€β”€β”€β”˜          β”‚
                 β”‚              trains router from win-rates        β”‚
                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                          β”‚
                                                    β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
                                                    β”‚   Answer   β”‚
                                                    β”‚textβ”‚score  β”‚
                                                    β”‚pipelineβ”‚ms β”‚
                                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🧩 Components

πŸ“‚ Document Loader

Loads any supported document type automatically β€” no configuration needed. Optional-dependency formats are skipped gracefully with one summary line, not a crash.

from metarag import DocumentLoader

loader = DocumentLoader("./data")                # folder (recursive)
loader = DocumentLoader("./data/contract.pdf")   # single file
docs   = loader.load()
Format Support
PDF βœ… (pip install metarag-sdk[pdf])
TXT βœ…
DOCX βœ… (pip install metarag-sdk[docx])
HTML βœ… (pip install metarag-sdk[html])
CSV βœ…
JSON βœ…
Markdown βœ…
Nested directories βœ…

βœ‚οΈ Chunker

Six strategies. One interface. All zero-dependency and free β€” no embedding or LLM calls in any of them.

from metarag import Chunker

chunker = Chunker(strategy="recursive")      # sensible default
chunks  = chunker.chunk_documents(docs, cache_dir=".metarag/cache/chunks")
Strategy Best For
fixed Quick baseline
recursive General purpose ⭐
sentence Conversational text
semantic Loosely topic-grouped text
sliding_window Overlap-heavy retrieval
markdown Structured docs β€” splits on headers, keeps them in metadata

πŸ—„ Vector Database

In-memory by default (zero dependencies). Chroma and FAISS as drop-in swaps.

from metarag import InMemoryVectorDB, ChromaVectorDB, FAISSVectorDB

db = InMemoryVectorDB()                              # zero-dep default
db = ChromaVectorDB(persist_directory=".metarag/index")
db = FAISSVectorDB()

db.build(chunks, embeddings)   # embeddings computed beforehand, once
db.search(query_embedding, k=4)
db.add(new_chunks, new_embeddings)

πŸ” Retrievers

Four retrieval strategies, all returning (chunk, score) pairs directly β€” no separate "with score" call needed.

from metarag import BM25Retriever, DenseRetriever, HybridRetriever, MMRRetriever

bm25   = BM25Retriever(chunks)                              # keyword
dense  = DenseRetriever(chunks, embeddings, vector_db)       # semantic
hybrid = HybridRetriever(chunks, embeddings, vector_db, alpha=0.5)  # combined
mmr    = MMRRetriever(chunks, embeddings, vector_db)          # diverse

results = hybrid.retrieve("your query", k=4)   # [(chunk, score), ...]

MMR is hand-implemented β€” vectorized relevance scoring plus greedy diversity selection, no sklearn dependency.


βš™οΈ Pipelines

fit() assembles pipelines automatically from your configured retrievers β€” you don't wire these by hand for the default flow.

from metarag import MetaRAG

rag = MetaRAG(docs="./data", embeddings=embeddings, generator=generator)
rag.fit()

rag.pipeline_graph()   # prints the actual stage graph for every built pipeline
Pipeline What it does
straight Retrieve only β€” one per built retriever (bm25, dense, hybrid, mmr)
multiquery Expand the query into variants, retrieve on all, merge
reranked Hybrid retrieval, then cross-encoder reranking (needs sentence-transformers)
full MultiQuery + Reranking combined

Every pipeline ends in a Deduplicator pass and returns a common result shape (query, chunks, pipeline).


πŸ€– Generator

Bring any object with a .generate(prompt) -> str method β€” MetaRAG duck-types it, no base class required.

from metarag import OllamaGenerator   # built-in convenience wrapper

generator = OllamaGenerator(model="mistral")   # free, local
# or bring your own: any object exposing .generate(prompt)

answer = rag.ask("What is the main topic of this document?")
print(answer.text)          # the answer
print(answer.pipeline)      # which pipeline the router picked
print(answer.score)         # composite evaluation score
print(answer.latency_ms)    # end-to-end latency

πŸ“Š Evaluator

Five metrics, one composite score. Zero LLM calls β€” pure embedding similarity and lexical overlap, so it runs in milliseconds on whatever embedding model you're already using.

from metarag import Evaluator

evaluator = Evaluator(embedding_model=embeddings, preset="balanced")  # or "precision" / "recall"
result = evaluator.evaluate(answer)

print(result.faithfulness)   # cosine(answer, retrieved context) β€” grounded?
print(result.relevancy)      # cosine(query, answer) β€” on-topic?
print(result.precision_avg)  # avg cosine(query, each chunk) β€” chunks useful?
print(result.coverage)       # query-term overlap in retrieved chunks
print(result.redundancy)     # avg pairwise chunk similarity (lower is better)
print(result.composite)      # preset-weighted combination β€” drives the router

No OpenAI. No cloud API required β€” evaluation runs entirely on your own embedding model.


πŸ”€ Router

Two modes, one class. Cold-start rules from the moment fit() finishes; win-rate-driven learned thresholds once you've run benchmark().

from metarag import Router

router = Router()
pipeline_name = router.route(features)   # features = merged corpus + query + probe signals
# β†’ "hybrid"

Cold-start signals (before any benchmark() run):

Signal Example condition Pipeline Selected
High similarity, low redundancy clean, well-matched corpus reranked
Numeric-heavy or short-doc corpus logs, FAQs, structured records straight / hybrid
Weak retrieval (low similarity) vague or under-specified query multiquery
High redundancy in top chunks repetitive corpus mmr
Noisy, OCR-heavy corpus scanned documents hybrid
Long or operator-heavy query "compare X and Y" multiquery

Once benchmark() trains the router, its default becomes whichever pipeline actually won the most queries, and refinement rules can only override that toward a different pipeline if it has real supporting win-rate evidence β€” never a hardcoded guess.


⚑ Quickstart

Installation

pip install metarag-sdk

Optional components install on top as needed β€” see docs/installation.md for the full list ([pdf], [chroma], [faiss], [nltk], [rerank], [ollama], or [all]).

Setup Ollama (free, local β€” optional)

# install from ollama.com, then pull models
ollama pull mistral             # generation
ollama pull nomic-embed-text    # embeddings

Build and Ask

from metarag import MetaRAG, CachedEmbeddings, OllamaGenerator

embeddings = CachedEmbeddings(...)

rag = MetaRAG(
    docs="./data",
    embeddings=embeddings,
    generator=OllamaGenerator(model="mistral"),
)

rag.fit()

Example output

Files Loaded        : 8
Documents Extracted : 101
Chunks Generated     : 333
Vector Index Built
Pipelines Built      : 7
answer = rag.ask("What is the main topic of this document?")
print(answer.text)

Benchmark Every Pipeline

queries = [
    "Summarize the document.",
    "What are the key findings?",
    "List important numbers.",
]

results = rag.benchmark(queries, retrieval_only=True)

Example output

Benchmark Rows      : 595
Benchmark CSV Saved
Router Thresholds Saved
rag.leaderboard()
rag.dashboard()
rag.report()

Example output

=========================================================================================
PIPELINE       PREC   COVER  REDUND  SCORE    LATENCY
=========================================================================================
reranked        0.84   0.79   0.12    0.84      1240ms
multiquery      0.81   0.76   0.15    0.82       890ms
hybrid          0.74   0.71   0.18    0.76       340ms
mmr             0.71   0.69   0.09    0.73       290ms
dense           0.69   0.65   0.21    0.68       230ms
bm25            0.63   0.60   0.24    0.61       120ms
straight        0.60   0.58   0.26    0.58       110ms
=========================================================================================

πŸ† Best pipeline: reranked (score=0.84)
πŸ”€ Router would pick: reranked
rag.save()

πŸ” Pipeline Selection

MetaRAG does not commit to one pipeline. Every query gets routed to whichever configuration actually performs best on your data.

User asks a question
        β”‚
        β–Ό
Router extracts features
  (corpus profile + query profile + one cheap probe retrieval)
        β”‚
        β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚  Trained?                               β”‚
   β”‚   NO  β†’ cold-start rule-based routing    β”‚
   β”‚   YES β†’ win-rate-driven learned routing  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β”‚
        β–Ό
  Selected pipeline retrieves chunks
        β”‚
        β–Ό
  Generator produces Answer
        β”‚
        β–Ό
  Evaluator scores it (composite)
        β”‚
        β–Ό
  benchmark() β†’ train() feeds the router real win-rate evidence over time

πŸ“ Evaluation

MetaRAG uses a single fast, zero-LLM-call evaluation tier by default β€” every metric is either embedding cosine similarity or lexical overlap, so it costs milliseconds regardless of which embedding model you're using.

Faithfulness   β†’  cosine(answer, retrieved context) β€” is it grounded?
Relevancy      β†’  cosine(query, answer) β€” does it address the question?
Precision      β†’  cosine(query, each chunk) β€” max / avg / std
Coverage       β†’  query-term overlap inside the retrieved chunks
Redundancy     β†’  avg pairwise chunk similarity (lower is better)
Composite      β†’  preset-weighted combination β€” drives the router

Three built-in presets weight these differently:

Preset Best for
balanced General RAG, internal docs
precision Security logs, anomaly detection β€” penalizes redundancy and latency harder
recall Research and summarization β€” weights coverage highest

No OpenAI. No cloud API. Runs entirely on your own embedding model.


πŸ€– Supported Models

MetaRAG doesn't hardcode any specific model β€” any object satisfying EmbeddingInterface (.embed_query() / .embed_documents()) or GeneratorInterface (.generate()) works. These are the options most commonly used in testing:

Embeddings

Model Provider Cost
nomic-embed-text Ollama (local) Free
all-MiniLM-L6-v2 HuggingFace Free
BAAI/bge-small-en HuggingFace Free
text-embedding-3-small OpenAI Paid

Generation

Model Provider Cost
mistral Ollama (local) Free
llama3 Ollama (local) Free
llama3-8b-8192 Groq API Free tier
gpt-4o-mini OpenAI Paid

CachedEmbeddings wraps any embedding model with a local disk cache automatically β€” repeat runs against the same corpus skip re-embedding entirely.


πŸ—Ί Roadmap

v0.1 β€” Foundation βœ…

  • Document loader β€” PDF, HTML, DOCX, CSV, JSON, Markdown
  • 6 chunking strategies with a unified interface
  • Vector database β€” InMemory, Chroma, FAISS
  • 4 retrieval strategies β€” BM25, Dense, Hybrid, hand-coded MMR
  • Pipeline composition β€” MultiQuery, Reranker, Full
  • 5-metric evaluator with preset weighting

v0.2 β€” Intelligence βœ…

  • MetaRAG top-level class β€” fit(), ask(), benchmark(), leaderboard()
  • Backend-agnostic core β€” LangChain removed, hard deps reduced to numpy / pandas / rank-bm25
  • Corpus / Query / Probe profilers feeding a merged router feature dict
  • Trained router β€” cold-start rules β†’ win-rate-driven learned thresholds
  • benchmark() β€” per-query winners across every built pipeline

v0.3 β€” Toolkit & Observability (current)

  • Observability suite β€” pipeline_graph(), dashboard(), report(), inspect(), trace()
  • Router persistence β€” save() / load() / update_router_thresholds()
  • defaults.py single-source-of-truth config, with sweep-ready list values
  • SklearnRouterAdapter β€” plug in any .predict()-style model as the router
  • Comprehensive test suite
  • pip install metarag-sdk β€” packaged release
  • RAGTuner β€” automated hyperparameter sweep across DEFAULTS list values
  • CLI β€” metarag fit ./data, metarag ask "question"
  • Experiment-tracking view β€” compare runs beyond raw benchmark.csv

πŸ”­ Future Scope

πŸ€– Agentic Workflow (v1.0)

MetaRAG will support agentic execution β€” where the system can loop, retry with a different pipeline if confidence is low, and handle multi-hop questions that require multiple retrieval steps.

query β†’ retrieve β†’ evaluate
                      β”‚
               score < 0.6?
                      β”‚
              retry with different pipeline
                      β”‚
               score >= 0.6?
                      β”‚
                return answer

This turns MetaRAG from a pipeline selector into a self-correcting retrieval agent.

🌐 REST API (v1.5)

A FastAPI layer that exposes MetaRAG over HTTP β€” enabling any platform or language to use it.

POST /upload       # index a document set
POST /ask          # get an answer
GET  /leaderboard  # pipeline scores
GET  /history       # query history

Designed for organisations that cannot install Python directly β€” they just call the API.

🏒 Platform Integrations (v2.0)

Native integrations with where organisations actually work:

MetaRAG for Notion       β†’  query your Notion workspace
MetaRAG for Confluence   β†’  search your team's knowledge base
MetaRAG for SharePoint   β†’  enterprise document intelligence
MetaRAG for Slack        β†’  answer questions from channel history

🧠 Continuous Learning (v2.5)

A full training pipeline that learns from real usage:

Every ask() + score  β†’  training data
Periodic retraining   β†’  smarter router
Domain adaptation     β†’  legal, medical, code β€” tuned per org
Human feedback loop    β†’  thumbs up/down improves quality

The router goes from cold-start rules β†’ win-rate thresholds β†’ sklearn classifier β†’ fine-tuned model, automatically, as data accumulates.

☁️ MetaRAG Cloud (v3.0)

A hosted layer for organisations that don't want to manage infrastructure β€” upload documents, ask questions via a chat interface, see the pipeline leaderboard, no terminal or Python setup required.


πŸ“ Project Structure

metarag/
β”‚
β”œβ”€β”€ metarag.py            High-level framework β€” MetaRAG class
β”œβ”€β”€ defaults.py           Shared, single-source-of-truth configuration
β”‚
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ loader.py
β”‚   β”œβ”€β”€ chunking.py
β”‚   β”œβ”€β”€ embeddings.py
β”‚   β”œβ”€β”€ vector_db.py
β”‚   └── retriever.py
β”‚
β”œβ”€β”€ pipelines/
β”‚   β”œβ”€β”€ generator.py
β”‚   └── pipeline.py
β”‚
β”œβ”€β”€ Evaluator/
β”‚   β”œβ”€β”€ evaluator.py
β”‚   β”œβ”€β”€ scorer.py
β”‚   └── metrics.py
β”‚
β”œβ”€β”€ router/
β”‚   β”œβ”€β”€ router.py
β”‚   β”œβ”€β”€ router_interface.py
β”‚   β”œβ”€β”€ query_profiler.py
β”‚   β”œβ”€β”€ corpus_profiler.py
β”‚   └── probe_profiler.py
β”‚
β”œβ”€β”€ examples/
β”‚   β”œβ”€β”€ loader_demo.py
β”‚   β”œβ”€β”€ chunker_demo.py
β”‚   β”œβ”€β”€ embeddings_demo.py
β”‚   β”œβ”€β”€ retriever_demo.py
β”‚   β”œβ”€β”€ vector_db_demo.py
β”‚   β”œβ”€β”€ pipeline_demo.py
β”‚   └── metarag_demo.py
β”‚
β”œβ”€β”€ tests/
β”‚
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ index.md
β”‚   β”œβ”€β”€ installation.md
β”‚   β”œβ”€β”€ quickstart.md
β”‚   β”œβ”€β”€ architecture.md
β”‚   β”œβ”€β”€ api.md
β”‚   β”œβ”€β”€ contracts.md
β”‚   β”œβ”€β”€ data_types.md
β”‚   └── examples.md
β”‚
β”œβ”€β”€ assets/
β”œβ”€β”€ README.md
β”œβ”€β”€ LICENSE
β”œβ”€β”€ pyproject.toml
└── requirements-dev.txt

🀝 Contributing

MetaRAG is in active development. Contributions welcome in any of these areas:

  • New retrieval strategies
  • New chunking strategies
  • New evaluation metrics
  • RAGTuner β€” hyperparameter sweep implementation
  • CLI tool
  • Integration connectors (Notion, Confluence, Slack)
  • Documentation and examples
git clone https://github.com/AnkitKumarxcodes/metarag-sdk.git
cd metarag-sdk

python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate

pip install -e .
pip install -r requirements-dev.txt

Run the test suite before opening a PR:

pytest

πŸ“„ License

MIT License β€” free to use, modify, and distribute.


Built with the belief that RAG quality should be automatic, measurable, and continuously improving.

⭐ Star this repo if MetaRAG saves you time

About

MetaRAG is an open-source engine that takes the guesswork out of RAG pipeline design. Instead of manually tuning chunking strategies, retrieval backends, and rerankers, MetaRAG benchmarks them against your own queries and routes each one to whichever configuration actually performs best on your data.

Topics

Resources

License

Stars

1 star

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages