Vectorless RAG is a way to answer questions from long documents without chunking them, without an embedding model and without a vector database. Instead, you build a tree of the document’s sections (like the contents page of a textbook) and let a language model walk that tree to the right section, the same way you would flip to the right chapter before an exam. In this tutorial you will build a complete vectorless RAG project in Python, in the style of PageIndex, and run it on your own study notes.
This project is for BTech, MCA and MTech students who want a modern AI final-year or mini project that goes further than a “chat with PDF” demo. You will build a section tree from Markdown or PDF notes, a pluggable LLM navigator that runs on a local model through Ollama (or a deterministic mock for tests), answers with page-level citations, and an evaluation script that compares your vectorless retriever with a classic BM25 baseline on a 36-question student-notes dataset. Everything runs offline, and all 119 pytest tests pass without a model, an API key or a GPU. The complete source code is free on GitHub under the MIT License.
Table of Contents
What Is Vectorless RAG?
RAG (retrieval-augmented generation) means you first retrieve the part of a document that answers a question and then let a language model generate an answer from it. The usual recipe is vector RAG: split the document into fixed-size chunks, turn each chunk into an embedding vector, store the vectors in a vector database and return the chunks whose vectors are closest to the question.
Vectorless RAG keeps the retrieve-then-generate idea but changes how retrieval works:
- Index: instead of chunks and vectors, the index is a tree of sections. Each node has a title, a page range and a short summary.
- Retrieve: instead of a similarity search, a language model reasons over the tree. It reads the top-level titles and summaries, picks the most promising branch, and repeats until it reaches a section.
- Answer: only the chosen section text goes to the model, and the answer cites the section and page it came from.
Think of how you revise. You do not read random 500-word slices of your Operating Systems notes. You open the contents page, go to “Deadlocks”, then to “Banker’s Algorithm”. Vectorless RAG teaches a model to do exactly that.
What You Will Build
The project is a Python package called vectorless_rag with a command-line tool called vrag:
| Command / module | What it does |
|---|---|
vrag index notes.md | Builds the section tree from Markdown or PDF notes and saves it as JSON (the vectorless index). |
vrag tree notes.md | Prints the tree: section ids, titles and page ranges, optionally with summaries. |
vrag ask notes.md "question" | Navigates the tree with a mock or Ollama model and prints the path, the answer and the citation. |
vrag bm25 notes.md "question" | The baseline: classic 120-word chunks ranked with Okapi BM25. |
vrag eval | Runs 36 questions on three sets of notes and compares vectorless RAG with BM25. |
TreeNavigator (Python API) | Use the retriever inside your own Flask app, chatbot or project. |

Why Vectorless RAG Is Trending in 2026
On 14 November 2026 VectifyAI introduced the new PageIndex Agent, which it describes as “vectorless, OCR-free, multimodal RAG”. It builds a tree of each document’s sections “like a table of contents” and lets the agent navigate it to the right pages, with no embeddings and no vector database. The company reports 99.0% accuracy on its 100-question financial QA benchmark, up from 96.3% for its previous version. Later in November the open-source PageIndex 0.7.5 release added a local mode that “needs no server, no vector DB, no PageIndex API key”.
Students noticed. KWS Trends data for India (updated 19 November 2026) lists “vectorless rag” and “pageindex vectorless rag” as Breakout rising searches under RAG, with “pageindex rag” up 2,650% and “rag evaluation” up 110%. Overall RAG searches in India are up 44% compared with the previous 12 months.
The idea itself is simple. The original PageIndex article (19 September 2025) lists the main weaknesses of vector RAG: similarity is not the same as relevance, hard chunking cuts sections in half, retrieval ignores chat history, and in-document references like “see Appendix G” get lost. A tree of sections fixes several of these at once. You do not need the commercial product to learn the technique. A clean, small implementation is enough for a strong project, and that is what you will build here.
Vectorless RAG does not mean “no retrieval”. It means retrieval by reasoning over the document’s own structure instead of by vector similarity.
Vector RAG vs Vectorless RAG
| Vector RAG | Vectorless RAG (tree) | |
|---|---|---|
| Index | Chunk embeddings in a vector database | A JSON tree: title, page range and summary per section |
| Retrieval | Top-k nearest vectors | LLM picks branches level by level |
| Needs | Embedding model, vector DB, chunk size tuning | Headings or bookmarks, and an LLM |
| Explainable? | A similarity score | A readable path: Contents → Transactions → Concurrency Control |
| Citations | Chunk number | Section id and page range |
| Weak spot | Paraphrased or structural questions, broken context | Bad or missing headings, many LLM calls on very deep trees |
| Best for | Short, unstructured text such as FAQs and chats | Textbooks, lab manuals, theses, reports, legal and financial documents |
Tech Stack and Prerequisites
- Python 3.10 to 3.13 on Windows, macOS or Linux. The core package uses only the standard library.
- Ollama (optional) to run a local model. The examples use qwen2.5-coder:3b, which runs on a normal laptop CPU. Any small instruct model works.
- pypdf (optional) to read PDF notes.
- pytest, pytest-cov and ruff for tests and linting.
- Basic Python: classes, dataclasses, recursion and JSON. If you can write a recursive tree traversal, you can build this.
Project File Structure
Vectorless-RAG-Python/
├── vectorless_rag/
│ ├── text.py # tokeniser, tiny stemmer, extractive summaries
│ ├── tree.py # Node, Page, DocumentTree (JSON save/load, page roll-up)
│ ├── parsers.py # Markdown + PDF (bookmarks or numbered headings) -> tree
│ ├── llm.py # OllamaLLM, MockLLM, ScriptedLLM, get_llm()
│ ├── navigator.py # TreeNavigator: prompts, JSON parsing, tree search, answers
│ ├── bm25.py # fixed-size chunking + Okapi BM25 baseline
│ ├── evaluate.py # metrics, summary table, JSON/Markdown reports
│ └── cli.py # vrag index | tree | ask | bm25 | eval
├── data/
│ ├── notes/ # operating-systems.md, dbms.md, computer-networks.md
│ └── questions.jsonl # 36 questions with gold section + evidence phrase
├── examples/quickstart.py
├── tests/ # 119 offline tests + a tiny PDF writer for fixtures
├── .github/workflows/ci.yml
├── pyproject.toml
└── README.md
Step-by-Step: Build Vectorless RAG in Python
Step 1: Set Up the Project
git clone https://github.com/GetProjectsIdea/Vectorless-RAG-Python.git
cd Vectorless-RAG-Python
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e ".[dev]" # pytest, ruff and pypdf
pytest # 119 passed
The package has no required dependencies, so it also installs on college lab machines with slow internet. pypdf is only needed for PDF notes.
Step 2: Model the Section Tree
Everything starts with one small data class. A Node is one section of your notes. It knows its own text, its page range and its children, and it can return the text of its whole subtree:
@dataclass
class Node:
node_id: str
title: str
level: int
start_page: int
end_page: int
text: str = ""
summary: str = ""
children: list[Node] = field(default_factory=list)
@property
def pages(self) -> str:
if self.start_page == self.end_page:
return f"p. {self.start_page}"
return f"pp. {self.start_page}-{self.end_page}"
@property
def is_leaf(self) -> bool:
return not self.children
def walk(self) -> Iterator[Node]:
yield self
for child in self.children:
yield from child.walk()
def full_text(self) -> str:
"""Own text plus the text of every descendant, in reading order."""
parts = [self.text] if self.text.strip() else []
for child in self.children:
body = child.full_text()
parts.append(f"{child.title}\n{body}" if body else child.title)
return "\n\n".join(p for p in parts if p.strip())
DocumentTree wraps the root node and the page texts. Its finalize() method rolls page ranges up from children to parents (so “3 Deadlocks” becomes pp. 4-5 when its last subsection is on page 5) and writes a summary for every node. The tree saves to plain JSON, so your vectorless index is a small, human-readable file instead of a vector database.
Step 3: Parse Markdown and PDF Notes into a Tree
Markdown headings (#, ##, ###) become tree levels. Page numbers come from <!-- page 5 --> markers or form feeds, or from a word count when the notes have neither. The builder uses a stack, which is a classic data structures exercise:
for i in range(start_line, len(lines)):
page, text = lines[i]
if i in heading_at:
raw_level, t = heading_at[i]
while len(stack) > 1 and stack[-1][0] >= raw_level:
stack.pop()
current = new_child(stack[-1][1], raw_level, t, page)
stack.append((raw_level, current))
continue
if not text.strip() and not body[current.node_id]:
continue
if current is root and text.strip() and not root.children:
current = new_child(root, 1, "Introduction", page)
stack.append((min((x[1] for x in found), default=1), current))
body[current.node_id].append((page, text))
For PDFs, the parser uses the PDF bookmarks (the outline you see in a PDF reader’s sidebar) when the file has them. Otherwise it detects numbered headings such as 2.3 Round Robin in the page text with a regular expression. Both paths feed the same builder, so Markdown and PDF notes give the same kind of tree:
PDF_HEADING = re.compile(r"^(\d{1,2}(?:\.\d{1,2}){0,3})\.?\s+([A-Z][A-Za-z0-9 ,:;&()'/+-]{2,80})$")
Run vrag tree data/notes/operating-systems.md and you get 18 sections over 7 pages, each with an id like [3.2], a title and a page range.
Step 4: Write Summaries the Navigator Can Read
The navigator never sees full sections while it is choosing. It only sees titles, page ranges and summaries, so summaries matter a lot. The project writes a deterministic extractive summary: the first sentence or two of the section plus its most frequent keywords. For a parent node, the keywords come from its whole subtree. That way “4 Memory Management” advertises words like paging, frames and replacement even though they only appear in its subsections:
if not node.summary:
basis = node.text if count_words(node.text) >= 12 else node.full_text()
node.summary = summarize(basis, summary_words)
if node.children:
# A parent's keywords describe its whole subtree, so the navigator can
# see that "Belady" lives somewhere under "Memory Management".
head = node.summary.split(" Keywords: ")[0]
kw = keywords(node.full_text(), 10)
node.summary = (head + " " if head else "") + "Keywords: " + ", ".join(kw) + "."
A good upgrade for your project report is to let the LLM write these summaries once at index time. You only pay that cost once per document.
Step 5: Plug In an LLM (Ollama or a Mock)
The navigator talks to any object with a complete(prompt, json_mode) method. That one-method interface is what makes the project testable. There are three implementations:
- OllamaLLM calls a local model through Ollama’s
/api/generateendpoint using onlyurllib, withtemperature 0and JSON mode. - MockLLM reads the same prompts and makes choices with simple keyword overlap. It is deterministic, so CI results never change.
- ScriptedLLM replays canned replies so unit tests can force any navigation path, including bad model output.
def payload(self, prompt: str, json_mode: bool = False) -> dict:
body = {
"model": self.model,
"prompt": prompt,
"stream": False,
"options": {"temperature": self.temperature, "num_ctx": self.num_ctx},
}
if json_mode:
body["format"] = "json"
return body
def complete(self, prompt: str, json_mode: bool = False) -> str:
data = json.dumps(self.payload(prompt, json_mode)).encode()
req = urllib.request.Request(
self.host + "/api/generate", data=data, headers={"Content-Type": "application/json"}, method="POST"
)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
reply = json.loads(resp.read().decode())
except (urllib.error.URLError, TimeoutError, OSError) as exc:
raise LLMError(f"Cannot reach Ollama at {self.host} ({exc}). Is `ollama serve` running?") from exc
if "error" in reply:
raise LLMError(f"Ollama error: {reply['error']}")
return str(reply.get("response", ""))
Step 6: Navigate the Tree with the LLM
This is the heart of vectorless RAG. At each node the navigator shows the model only the children: id, title, page range, summary and subsection names. It asks for JSON such as {"selected": ["4"], "reason": "..."}, follows up to two branches, and stops at leaf sections. A budget on LLM calls keeps deep trees cheap:
def _visit(self, node: Node, question: str, history: list[str] | None, result: Retrieval) -> None:
if len(result.nodes) >= self.max_results:
return
if node.is_leaf:
if node not in result.nodes:
result.nodes.append(node)
return
if result.llm_calls >= self.max_calls:
# Out of budget: keep the whole subtree as context rather than guessing deeper.
if node is not self.tree.root and node not in result.nodes:
result.nodes.append(node)
return
valid = [c.node_id for c in node.children]
reply = self.llm.complete(self.choose_prompt(question, node, history), json_mode=True)
result.llm_calls += 1
ids, reason = selected_ids(reply, valid, self.max_select, {c.node_id: c.title for c in node.children})
result.steps.append(Step(node.node_id, node.title, valid, ids, reason))
if not ids:
if node is not self.tree.root and node.text.strip() and node not in result.nodes:
result.nodes.append(node) # the parent's own text is the best we have
return
for cid in ids:
child = next(c for c in node.children if c.node_id == cid)
self._visit(child, question, history, result)
Small local models do not always follow instructions. Sometimes they copy the example id from the prompt, answer with a section title instead of an id, or wrap the JSON in chatty text. parse_json_reply() and selected_ids() handle all of these cases: they pull out the first JSON object, map a title back to its id, and map a deeper id like 2.3 to its parent candidate 2. Each case has its own test.

Step 7: Answer with Citations
After navigation, the selected sections (capped at 1,500 words) go into an answer prompt that says “answer using ONLY the notes below”. The model returns JSON with an answer and the section ids it used. The navigator checks those ids against the sections it actually retrieved, so the model cannot invent a source:
def answer(self, question: str, history: list[str] | None = None) -> Answer:
retrieval = self.retrieve(question, history)
if not retrieval.nodes:
return Answer(question, "I could not find a relevant section in these notes.", [], retrieval)
prompt = ANSWER_PROMPT.format(question=question, context=self.context(retrieval.nodes))
reply = self.llm.complete(prompt, json_mode=True)
retrieval.llm_calls += 1
data = parse_json_reply(reply)
text = str(data.get("answer") or reply).strip()
valid = {n.node_id for n in retrieval.nodes}
sources = (
[str(s) for s in data.get("sources", []) if str(s) in valid]
if isinstance(data.get("sources"), list)
else []
)
if not sources and data.get("sources") is None:
sources = [n.node_id for n in retrieval.nodes]
return Answer(question, text, sources, retrieval)
Step 8: Build the BM25 Baseline
A project with a benchmark is much stronger in a viva than one without. The baseline is the classic RAG recipe: 120-word chunks with a 30-word overlap, ranked with Okapi BM25, a keyword ranking formula used by search engines for decades. It is about 40 lines of plain Python:
class BM25:
"""Okapi BM25 over pre-tokenised documents."""
def __init__(self, docs: list[list[str]], k1: float = 1.5, b: float = 0.75):
self.k1, self.b = k1, b
self.docs = docs
self.tf = [Counter(d) for d in docs]
self.lengths = [len(d) for d in docs]
self.avgdl = (sum(self.lengths) / len(docs)) if docs else 0.0
df: Counter[str] = Counter()
for d in docs:
df.update(set(d))
n = len(docs)
self.idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
def score(self, query: list[str], index: int) -> float:
tf, dl = self.tf[index], self.lengths[index]
s = 0.0
for t in query:
f = tf.get(t, 0)
if not f:
continue
denom = f + self.k1 * (1 - self.b + self.b * dl / (self.avgdl or 1))
s += self.idf.get(t, 0.0) * f * (self.k1 + 1) / denom
return s
def top(self, query: list[str], k: int = 3) -> list[tuple[int, float]]:
scores = [(i, self.score(query, i)) for i in range(len(self.docs))]
scores.sort(key=lambda x: (-x[1], x[0]))
return scores[:k]
Step 9: Evaluate on Student Notes
The dataset has three sets of revision notes (Operating Systems, DBMS and Computer Networks) and 36 questions. Each question stores the gold section and a short evidence phrase copied from the notes. Retrieval counts as a hit when that phrase appears in the retrieved text. 17 questions are direct (they use the same words as the notes) and 19 are paraphrased, for example “Which method moves the read head like a lift going up and down?” for the SCAN elevator algorithm:
{"id": "os-12", "doc": "operating-systems.md", "type": "paraphrased", "question": "Which method moves the read head like a lift going up and down?", "section": "5.2 Disk Scheduling", "evidence": "also called the elevator algorithm"}
A test checks that every evidence phrase really exists inside its gold section, so the dataset cannot silently go wrong when you edit the notes.
Run It: Installation, Demo and Tests
Print the tree and ask a question offline with the mock navigator:
vrag tree data/notes/operating-systems.md
vrag ask data/notes/operating-systems.md "How do we stop low-importance jobs from never getting the processor?"
Now switch to a real local model. Install Ollama, pull a small model, and add two flags:
ollama pull qwen2.5-coder:3b
vrag ask data/notes/dbms.md "How does holding exclusive locks until commit help?" \
--llm ollama --model qwen2.5-coder:3b
vrag ask data/notes/dbms.md "What does 2NF remove?" --llm ollama --model qwen2.5-coder:3b --json

Use your own notes by passing any .md, .txt or .pdf file, or use the Python API:
from vectorless_rag import TreeNavigator, get_llm, parse_path
tree = parse_path("my-dbms-notes.pdf")
nav = TreeNavigator(tree, get_llm("ollama", model="qwen2.5-coder:3b"))
ans = nav.answer("What does 2NF remove?")
print(ans.text)
print(ans.retrieval.citations()) # ['[3.1] 3.1 1NF, 2NF and 3NF (p. 3)']
Finally, run the tests. All 119 tests run offline: parsers (including real PDFs written by a tiny PDF generator in the test folder), the tree, JSON parsing of messy model replies, navigation paths with scripted replies, a fake Ollama HTTP server, BM25, the evaluation metrics and every CLI command. GitHub Actions runs them on Python 3.10, 3.11, 3.12 and 3.13.
pytest -v
ruff check .

Benchmark Results: Vectorless RAG vs BM25
Run the benchmark yourself with vrag eval (mock, offline) or vrag eval --llm ollama --model qwen2.5-coder:3b -v. Hit@1 means the evidence is in the first retrieved section or chunk. These are the results on the 36 questions:
| Retriever | Hit@1 (all) | Direct | Paraphrased | Words sent to the LLM | LLM calls |
|---|---|---|---|---|---|
| Vectorless tree, mock navigator | 64% | 88% | 42% | 71 | 2.1 |
| Vectorless tree, qwen2.5-coder:3b (Ollama) | 69% | 94% | 47% | 62 | 2.1 |
| BM25, 120-word chunks (top 3) | 75% | 88% | 63% | 348 | 0 |

What the numbers say, honestly:
- On direct questions, vectorless RAG with a 3B local model opened the exact right section 94% of the time, against 88% for BM25’s top chunk.
- It sent about 5.7x less text to the answering model (62 words on average against 348). On a long textbook that saving grows, because the tree narrows chapter, then section, while top-k chunks stay the same size.
- On paraphrased questions, small models still struggle. A 3B model often opens a neighbouring section, for example “TCP” instead of “Congestion Control”, so BM25 top-3 found the evidence more often (63% at hit@1).
- BM25 top-3 covers about a third of each short note file, so its “evidence somewhere in context” score is generous. That would not hold on a 300-page book.
- The mock navigator is purely lexical. It exists to make the pipeline deterministic in CI, not to win benchmarks.
That is a fair, report-ready conclusion: vectorless RAG gives precise, explainable, cheap-to-store retrieval, and its accuracy depends on summary quality and model strength. Trying a bigger model, LLM-written summaries or a hybrid with BM25 is a ready-made experiment for your project report.
When Should You Use Vectorless RAG?
| Use vectorless RAG when… | Prefer vector or keyword RAG when… |
|---|---|
| The document has real structure: chapters, sections, numbered headings | The text is flat: chats, tweets, short FAQs |
| You need explainable answers with section and page citations | You need millisecond search over millions of short items |
| You cannot or do not want to run an embedding model and vector DB | You cannot afford several LLM calls per question |
| Questions ask about a topic that matches a section | Questions need facts scattered across many sections |
In practice many teams combine the two, for example BM25 to shortlist branches and an LLM to decide between them. Because the retriever in this project sits behind a small interface, you can try that without touching the parser.
Learning Outcomes for Your Project Report
- How RAG works end to end, and the trade-offs between vector, keyword and vectorless retrieval
- Tree data structures in practice: stack-based parsing, recursion, page roll-up and JSON serialisation
- Prompt design for structured output, and defensive parsing of real model replies
- Dependency injection: one LLM interface with real, mock and scripted implementations
- Information retrieval basics: tokenising, stemming, IDF and Okapi BM25
- Designing an evaluation dataset, metrics such as hit@1, and reporting results honestly
- Testing and CI: offline tests, a fake HTTP server, generated PDF fixtures and a Python version matrix
Future Scope
- LLM-written node summaries at index time, then compare accuracy with the extractive ones
- Follow in-document references such as “see Section 3.2” with a jump move
- Multi-document search: a library tree where the first choice is the subject or the book
- Hybrid retrieval: BM25 over node summaries to shortlist branches before the LLM decides
- A Flask or Streamlit web page that highlights the navigation path on the tree
- Conversation memory: pass earlier questions to the navigator (the
historyargument already exists) - Run the benchmark on a real textbook PDF with bookmarks and publish the results
Frequently Asked Questions
What is vectorless RAG in simple words?
Vectorless RAG is retrieval-augmented generation without embeddings or a vector database. You build a tree of a document’s sections with titles, page ranges and summaries, and a language model navigates that tree to the section that answers the question, like using a textbook’s contents page.
Is vectorless RAG better than vector RAG?
It depends on the document. For structured documents such as textbooks, manuals and reports it gives precise, explainable answers with page citations and needs no vector database. For flat, short or unstructured text, vector or keyword search is usually faster and simpler. Many systems combine both.
Do I need a GPU or an API key for this project?
No. The core package uses only the Python standard library. You can run everything with the offline mock navigator, and for real answers a small model such as qwen2.5-coder:3b runs on a laptop CPU through Ollama. No paid API is required.
Can I use my own PDF notes?
Yes. Install the pdf extra with pip install -e “.[pdf]” and pass the PDF to vrag tree or vrag ask. The parser uses the PDF bookmarks when they exist and otherwise detects numbered headings such as 2.3 Round Robin.
How is this different from PageIndex?
PageIndex is a product and open-source library by VectifyAI that popularised tree-based, reasoning-driven retrieval. This project is a small, independent educational implementation of the same idea, written from scratch so you can read every line, test it offline and extend it for a college project.
Can I submit this as my final-year project?
Yes. The code is MIT licensed. Add one feature from the future scope list, explain the tree, the navigator and the benchmark in your report, and show the demo and the 119 passing tests in your viva. The source is on GitHub.
Download the Source Code
The complete project (tree builder, Markdown and PDF parsers, LLM backends, tree navigator, BM25 baseline, evaluation script, student-notes dataset, 119 tests and CI) is on GitHub: GetProjectsIdea/Vectorless-RAG-Python. It is released under the MIT License, so you can use this vectorless RAG project for coursework, college projects and your own experiments.
Related Projects on GetProjects
- Gemini student assistant in Python: a notes summariser and campus FAQ chatbot built on classic chunk-based RAG, a good comparison for this project
- Local AI coding assistant in Python with Ollama: more practice running local models
- Create your own search engine: the keyword-search side of retrieval
- How to build an MCP server in Python: expose your vectorless retriever as a tool for AI assistants
- 50 major project ideas for BTech CSE and MCA students
- AI PhD thesis topics 2026: research directions in retrieval and LLM reasoning
References
- PageIndex: Introducing the new PageIndex Agent (vectorless, OCR-free, multimodal RAG) (14 Nov 2026)
- KWS Trends: rag search volume and trends in India (updated 19 Nov 2026)
- VectifyAI/PageIndex release 0.7.5 (Nov 2026) and the PageIndex GitHub repository
- PageIndex: Next-generation vectorless, reasoning-based RAG (19 Sep 2025)
- Ollama API: generate a response
- Okapi BM25 (Wikipedia) and pypdf documentation
Conclusion
You have built a complete vectorless RAG system in Python: a section tree from Markdown or PDF notes, an LLM navigator that walks it like a student reading a contents page, answers with page citations, and an honest benchmark against BM25. There are no embeddings, no vector database and no paid API, and every part is tested offline. Clone the repository, point vrag at your own semester notes, and see which questions your tree answers best. Happy coding!