Multi-Document RAG: PDFs, Word Files and More

Answer questions across many documents and formats with per-source metadata, filters and citations.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 7 · Lesson 6 of 8 · Intermediate

Multi-Document RAG: PDFs, Word Files and More

Answer questions across many documents and formats with per-source metadata, filters and citations.

Real knowledge bases are folders full of mixed files: PDFs, Word documents, Markdown notes and web exports. Questions often need several of them at once ("Compare the 2025 and 2026 travel policies"), and users need to know which document each fact came from. This lesson builds a multi-document, multi-format RAG application with per-source metadata, document filters, source diversity and clear citations.

What you will learn

  • How to load PDFs, Word files and text files into one index with consistent metadata
  • How to filter retrieval to selected documents
  • How to keep results diverse across documents
  • How to cite document names, pages and sections in answers

Prerequisites

pip install chromadb pypdf python-docx sentence-transformers anthropic

Step 1: One loader for several formats

Every chunk records its source file, a human-readable document title, and a location (page for PDFs, section heading for Word files):

multi_doc_rag.py
from pathlib import Path

import chromadb
import docx
from pypdf import PdfReader
from rag_helpers import ask, embed

def pdf_units(path: Path):
    for number, page in enumerate(PdfReader(path).pages, start=1):
        yield page.extract_text() or "", f"page {number}"

def docx_units(path: Path):
    section, buffer = "Introduction", []
    for para in docx.Document(path).paragraphs:
        if para.style.name.lower().startswith("heading") and para.text.strip():
            if buffer:
                yield "\n".join(buffer), section
            section, buffer = para.text.strip(), []
        elif para.text.strip():
            buffer.append(para.text.strip())
    if buffer:
        yield "\n".join(buffer), section

def text_units(path: Path):
    yield path.read_text(encoding="utf-8", errors="replace"), "full text"

LOADERS = {".pdf": pdf_units, ".docx": docx_units, ".txt": text_units, ".md": text_units}

def split(text: str, size: int = 1000):
    words, current = text.split(), []
    for w in words:
        current.append(w)
        if len(" ".join(current)) > size:
            yield " ".join(current)
            current = current[-30:]                     # ~30 words of overlap
    if current:
        yield " ".join(current)

Step 2: Index the folder

db = chromadb.PersistentClient(path="multi_doc_db")
col = db.get_or_create_collection("library", metadata={"hnsw:space": "cosine"})

def index_folder(folder: str) -> None:
    for path in sorted(Path(folder).rglob("*")):
        loader = LOADERS.get(path.suffix.lower())
        if not loader:
            continue
        source, title = path.as_posix(), path.stem.replace("-", " ").title()
        col.delete(where={"source": source})
        ids, texts, metas = [], [], []
        for unit_text, location in loader(path):
            for piece in split(unit_text):
                ids.append(f"{source}:{len(ids)}")
                texts.append(f"[{title} - {location}]\n{piece}")      # contextual header
                metas.append({"source": source, "title": title, "location": location,
                              "type": path.suffix.lstrip(".")})
        if texts:
            col.add(ids=ids, documents=texts, metadatas=metas, embeddings=embed(texts).tolist())
            print(f"{title}: {len(texts)} chunks")

Step 3: Retrieve with document filters and diversity

Two problems appear with many documents: one long document can fill all the top slots, and users sometimes want to ask about specific documents only. Fetch more candidates than needed, cap the chunks per document, and support an optional list of documents:

def retrieve(question: str, k: int = 6, per_doc: int = 2, titles: list[str] | None = None) -> list[dict]:
    where = {"title": {"$in": titles}} if titles else None
    res = col.query(query_embeddings=embed(question, query=True).tolist(), n_results=k * 4, where=where)
    hits, counts = [], {}
    for text, meta, dist in zip(res["documents"][0], res["metadatas"][0], res["distances"][0]):
        if counts.get(meta["source"], 0) < per_doc:
            hits.append({"text": text, "meta": meta, "score": 1 - dist})
            counts[meta["source"]] = counts.get(meta["source"], 0) + 1
        if len(hits) == k:
            break
    return hits

Step 4: Answer with document-level citations

def answer(question: str, titles: list[str] | None = None) -> str:
    hits = retrieve(question, titles=titles)
    sources = "\n\n".join(
        f'<source id="{n}" document="{h["meta"]["title"]}" location="{h["meta"]["location"]}">\n{h["text"]}\n</source>'
        for n, h in enumerate(hits, start=1))
    return ask(f"<sources>\n{sources}\n</sources>\n\n"
               "Answer using only the sources. After each fact cite [id]. When documents disagree, "
               "say which document says what. If the answer is missing, say so.\n\n"
               f"Question: {question}", effort="medium")

if __name__ == "__main__":
    index_folder("library")
    print(answer("How did the hotel limit change between the 2025 and 2026 travel policies?"))
Travel Policy 2025: 12 chunks
Travel Policy 2026: 14 chunks
Employee Handbook: 41 chunks
The 2025 policy capped hotels in metro cities at 5,000 rupees per night [1], while the 2026
policy raises this to 6,000 rupees [2]. The limit for other cities is 4,000 rupees in both [2][3].

Without the per-document cap, the 41-chunk handbook could crowd out one of the two policies the question is actually about.

Tips for larger libraries

  • Document-level metadata (department, year, version, status) enables filters such as "only current policies".
  • Document routing: for questions naming a document, extract the name and filter (Self-Query Retrieval).
  • Comparisons: decompose "compare A and B" into one retrieval per document (Query Decomposition).
  • Old .doc files: convert to .docx or PDF first.

Common errors and troubleshooting

  • Chroma metadata error: metadata values must be strings, numbers or booleans; do not store lists or None.
  • Empty PDF pages: scanned pages need OCR (Parsing Complex Documents).
  • Wrong document cited: make sure the citation label in each source block matches the metadata, and keep the contextual header in the chunk text.

Key takeaways

  • Normalise every format into chunks with source, title and location metadata.
  • Cap chunks per document to keep results diverse, and allow filtering to chosen documents.
  • Cite document names and locations, and tell the model how to report disagreements.

Frequently asked questions

Should every document have its own collection?

Usually not: one collection with a document field supports filtering and cross-document questions. Separate collections make sense for strict tenant isolation.

How do I answer "summarise all documents" questions?

Retrieval of a few chunks cannot cover everything; use per-document summaries, RAPTOR or long-context approaches (RAPTOR).

Practice exercises

  1. Add a year field parsed from file names and a "latest version only" filter.
  2. Return a list of documents consulted below each answer, with the number of chunks used from each.

Related tutorials