Local retrieval-augmented generation with BM25 ranking and source citations. Zero dependencies.
Inspired by the RAG/knowledge platforms that dominate AI tooling today (Dify, Firecrawl, LlamaIndex). This is an original, dependency-free implementation — no vendored code, no service, no API key.
documents -> paragraph-aware chunking -> BM25 index -> grounded answer + [file:line] citations
- Chunking keeps paragraph boundaries and line numbers, with configurable overlap.
- BM25 (Okapi, k1/b tunable) is implemented from scratch — no search library.
- Citations are mandatory: every answer names the exact source lines it used.
- Bring your own model: pass any
answer_fncallable; the default is extractive and works offline. - Portable index:
to_dict/from_dictround-trip to JSON.
python -m rag index ./docs --out rag-index.json
python -m rag ask "How do I make tomato soup?" --index rag-index.json
python -m rag ask "basil" --jsonfrom rag import BM25Index, answer, chunk_text
index = BM25Index(synonyms={"tomato": ["tomatoes"]})
index.add(chunk_text(open("notes.md").read(), source="notes.md"))
result = answer(index, "What does the guide say about tomatoes?")
print(result["answer"], result["sources"])
# With your own LLM:
result = answer(index, "...", answer_fn=my_llm_callable)No model means no hallucination, no API key and no network. When you do plug in a model, it receives only the retrieved passages with citations, so the answer stays grounded.
python -m unittest discover -s tests # 16 tests, no dependenciesMIT licensed.