Search Tutorials
--Ads--RAPTOR: Recursive Summarization Trees
Retrieve at multiple levels of abstraction with a tree of cluster summaries.
Chunk-based retrieval sees documents only at one level of detail: the chunk. A question like "What does our employee handbook say about time off in general?" is answered by no single chunk; it needs a summary of many. RAPTOR (Recursive Abstractive Processing for Tree-Organized Retrieval, Sarthi et al., 2024) builds a tree of summaries above the chunks, so retrieval can pick the right level of abstraction for each question.
How RAPTOR builds the tree
- Start with the chunks (level 0) and embed them.
- Cluster chunks with similar embeddings. Clusters often cut across documents, grouping everything about, say, leave rules.
- Summarise each cluster with an LLM. The summaries become level 1.
- Embed the summaries, cluster them and summarise again. Repeat until only one or a few nodes remain.
The original paper uses UMAP dimensionality reduction with Gaussian mixture models, which allow a chunk to belong to more than one cluster. The version below uses k-means for simplicity; the idea is the same.
Building the tree
pip install scikit-learn
import numpy as np
from sklearn.cluster import KMeans
from rag_helpers import ask, embed
def summarise(texts: list[str]) -> str:
joined = "\n\n---\n\n".join(texts)
return ask("Write a summary (under 200 words) of the passages below that keeps the key "
f"facts, numbers and names, and states the common topic.\n\n{joined}", max_tokens=600)
def build_raptor_tree(chunks: list[str], cluster_size: int = 6, max_levels: int = 3) -> list[dict]:
nodes = [{"text": c, "level": 0} for c in chunks]
current = chunks
for level in range(1, max_levels + 1):
if len(current) <= 2:
break
n_clusters = max(2, len(current) // cluster_size)
labels = KMeans(n_clusters=n_clusters, n_init="auto", random_state=0).fit_predict(embed(current))
summaries = []
for c in range(n_clusters):
members = [current[i] for i in np.where(labels == c)[0]]
if members:
summaries.append(summarise(members))
nodes += [{"text": s, "level": level} for s in summaries]
print(f"level {level}: {len(summaries)} summaries")
current = summaries
return nodes
Retrieving from the tree
The paper compared two strategies and found the simpler one works best:
- Tree traversal: start at the top, pick the best nodes at each level and descend.
- Collapsed tree: put all nodes from all levels into one index and run normal top-k search. Broad questions naturally match summaries; detailed questions match chunks.
class RaptorRetriever:
def __init__(self, nodes: list[dict]):
self.nodes = nodes
self.vectors = embed([n["text"] for n in nodes])
def search(self, query: str, budget_chars: int = 8000) -> list[dict]:
scores = self.vectors @ embed(query, query=True)[0]
picked, used = [], 0
for i in np.argsort(-scores): # fill a context budget, best first
node = self.nodes[i]
if used + len(node["text"]) > budget_chars:
continue
picked.append({**node, "score": float(scores[i])})
used += len(node["text"])
return picked
retriever = RaptorRetriever(build_raptor_tree(chunks))
for hit in retriever.search("What does the handbook say about time off in general?")[:4]:
print(hit["level"], round(hit["score"], 3), hit["text"][:80])
Using a character (or token) budget rather than a fixed k matters here, because summaries and chunks have different lengths.
When RAPTOR helps
- Long documents and books, where questions are about themes, plots or overall arguments.
- Collections with spread-out information, where an answer requires combining facts from many chunks.
- Mixed question types: users ask both "what is X?" and "give me an overview of Y".
The costs are an LLM summary call per cluster at indexing time and more complex updates: when documents change, affected branches of the tree must be rebuilt. For collections that change daily, rebuilding the tree periodically (for example nightly) is a practical compromise.
Both add summaries above the chunk level. RAPTOR groups text by semantic similarity; GraphRAG groups entities by their relationships. RAPTOR is simpler to build; GraphRAG is better at relationship questions.
Key takeaways
- RAPTOR recursively clusters and summarises chunks into a tree of increasing abstraction.
- Collapsed-tree retrieval indexes all levels together and lets the question pick the level.
- Fill a context budget instead of a fixed k, since node lengths differ.
- It helps for overview questions over long documents; updates require rebuilding branches.