AI Hints
Home›RAG Tutorial›Tables, Databases and Long Documents
RAG · Lesson 90 of 120

Long Documents

Summaries as an index.

⏱ 2 min read▶ Video at 1:28:25🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

With hundreds of long documents, chunk search can get noisy. One fix is a two level index. First, find the right document using short summaries. Then search chunks inside that document only.

Long Documents
From the video: Long Documents
  • Many long documents
  • Find the document first
  • Then search inside

Summaries first

The model writes a one sentence summary of every page. We index the summaries, with the page name. A question first finds the best page by its summary. Then we search chunks from that page only. Run it. The summary search picks the finance page, and the chunk search finds the payment options.

summaries.pypython
from rag_kit import load_docs, make_chunks, Index
from llm import llm

docs = load_docs()
summaries = [{"source": d["source"],
              "text": llm.invoke(f"Summarise this page in one sentence:\n{d['text']}").text}
             for d in docs]

q = "Can I pay for a bike monthly?"
page = Index(summaries).search(q, 1)[0][1]["source"]
inside = Index([c for c in make_chunks(docs) if c["source"] == page])
print("page: ", page)
print("chunk:", inside.search(q, 1)[0][1]["text"][:60])
Output
page:  finance.md
chunk: You can spread the cost of any bike over £400 with our finan
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()

Summaries are made once, when indexing. They help most with many long documents, on different topics. LangChain's multi vector retriever stores summaries and chunks together.

keyvalue
Madeonce, at indexing
Best formany long documents
Level 1find the document
Level 2search inside it

Summary

Search summaries to pick the document, then search chunks inside it. Next, GraphRAG.

Key takeaways
  • Summaries
  • Pick the document
  • Search inside
Next up: GraphRAG — entities and links