Meilisearch

Raptor RAG explained: A full guide to hierarchical retrieval

Learn what RAPTOR RAG is, how it differs from other RAG methods, and how to implement it in Python.

Maya Shin

Maya Shin

Head of Marketing @ Meilisearch·@mayya_shin·LinkedIn

·22 min read
Raptor RAG explained: A full guide to hierarchical retrieval

Share the article

In 2024, researchers at Stanford published a new standard for chunking and organization called Recursive Abstractive Processing for Tree-Organized Retrieval (RAPTOR).

RAPTOR changes the way retrieval-augmented generation (RAG) works with chunked documents. Instead of creating chunks and storing them randomly, RAPTOR creates a hierarchical tree structure of chunks, categorizes them, and writes summaries for each group.

RAPTOR gives users more precise answers because hierarchical summaries contain high-level information that LLMs can search.

More precise details are contained in each 'leaf' of the tree. To find answers, the LLM searches summaries and then drills down into the data contained in branches and leaves.

This is especially useful for long-document benchmarks such as QASPER, where answers often depend on information spread across multiple sections.

Here's how to effectively use RAPTOR in your RAG systems.

What is RAPTOR RAG?

RAPTOR RAG changes how document chunks are organized for large-language-model processing. Instead of chunking documents into individual sections, RAPTOR RAG stores the chunks as a tree.

Imagine that you have several chunks for a dozen documents. RAPTOR RAG takes the chunks and organizes them by category.

The categories contain detailed information (represented by each category's expanded branches and their leaves, which further describe the information), and the hierarchy of each category includes a detailed summary.

Detailed summaries make it easier for large language models (LLMs) to find information to answer a user's query. An LLM can find information using an abstract summary or drill down into more detailed data, searching the branches and clustered 'leaves' attached to them.

Because chunked data is organized into a tree, using RAPTOR RAG also improves the accuracy of query answers.

An LLM first searches a small number of category summaries and then explores further into the tree.

When chunked data is organized properly, it improves the speed and performance of LLM queries.

The number of summaries in a RAPTOR RAG depends on the number of documents in your data silos.

A RAPTOR tree structure: raw leaf chunks at the bottom, cluster summaries in the middle layers, and a single abstract summary at the root

How does RAPTOR differ from GraphRAG, CRAG, and other advanced RAG methods?

RAPTOR was introduced to solve problems with simple chunking and data indexing. It's one of the many ways chunked data can be organized and used with LLM queries.

Here is a comparison table that highlights the pros and cons of each technique:

Comparison of RAPTOR RAG against naive RAG, GraphRAG, CRAG, and other advanced RAG methods, listing the strengths and weaknesses of each

What problems does RAPTOR RAG solve?

RAPTOR RAG primarily addresses latency and accuracy of large document chunks.

Chunking data can be done using short phrases or long paragraphs. Each chunk size has its advantages and disadvantages.

Small chunks offer better accuracy, but they add latency.

Larger chunks are better with latency, but the longer the chunks, the higher the probability of introducing hallucinations.

Both of these problems are better solved with the improved organization that RAPTOR RAG offers.

With a RAPTOR RAG strategy, queries no longer search through scattered data or rely only on flat retrieval when semantic meaning is distributed across multiple documents. It's a better strategy overall if your core data spans multiple long documents.

RAPTOR RAG:

  • Answers questions where answers span multiple documents
  • Helps when you can't decide if large or small chunks are necessary

How does RAPTOR RAG work?

RAPTOR RAG works in five steps: chunking, generating embeddings, clustering similar chunks, creating cluster similarities, and building a recursive tree.

Each iteration builds a more abstract view of the layers below it, but these abstractions improve query performance.

The RAPTOR index construction pipeline: chunk documents, embed the chunks, cluster them, summarize each cluster, then repeat to build the next layer

Step #1: Chunking documents

Sending an LLM an entire PDF to parse isn't optimal for token usage, which in turn affects the costs of running AI agents and RAG.

Instead, chunking breaks PDF data into components.

In RAPTOR RAG, chunking can be done in three ways:

  • Fixed size: Phrases contain the same number of characters
  • Recursive: Chunks are based on words and paragraphs
  • Semantics: Cuts up documents based on word meaning, context, and semantic similarity

Here is sample code for chunking:

python
# ── Approach 1: simple fixed-size chunking by hand ──
def fixed_chunk(text: str, size: int = 400, overlap: int = 50) -> list[str]:
    chunks = []
    start = 0
    while start < len(text):
        end = start + size
        chunks.append(text[start:end])
        start = end - overlap          # step back to create overlap
    return chunks


# ── Approach 2: recursive chunking with LangChain (recommended) ──
from langchain.text_splitter import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=400,        # target size in characters
    chunk_overlap=50,      # overlap between consecutive chunks
    separators=["\n\n", "\n", ". ", " ", ""],  # try these boundaries in order
)

document = """Your long business document text goes here...
It might span many paragraphs, sections, and pages.
The splitter will break it on paragraph and sentence
boundaries before ever cutting mid-word."""

chunks = splitter.split_text(document)

for i, chunk in enumerate(chunks):
    print(f"--- Chunk {i} ({len(chunk)} chars) ---")
    print(chunk)

Step #2: Generating embeddings

Chunks are stored in a vector database, which converts them into numerical representations.

The numerical representation is a score used to assess answer accuracy. A higher score indicates that the chunk is a better response to a specific query.

Chunks are embedded using SBERT (Sentence Bidirectional Encoder Representations from Transformers) forming the leaf nodes of the tree structure.

You can also use OpenAI embeddings if you want hosted embeddings instead of a local sentence-transformers model.

Here is sample code:

python
# ── Option A: local embeddings, free, runs on your machine ──
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")   # 384-dimensional vectors

chunks = [
    "Our return window is 30 days from purchase.",
    "Store hours are 9am to 6pm, Monday through Friday.",
]

embeddings = model.encode(chunks)
print(embeddings.shape)        # (2, 384) -- two chunks, 384 numbers each
print(embeddings[0][:5])       # peek at the first 5 values of chunk 1


# ── Comparing meaning: cosine similarity ──
from sentence_transformers.util import cos_sim

query = model.encode("How long do I have to return something?")
scores = cos_sim(query, embeddings)[0]
print(scores)                  # higher score = closer in meaning
# the return-policy chunk scores far higher than the store-hours chunk,
# even though the query shares almost no words with it


# ── Option B: hosted API embeddings (OpenAI), paid, higher quality ──
from openai import OpenAI

client = OpenAI()              # reads your API key from the environment

response = client.embeddings.create(
    model="text-embedding-3-small",   # 1,536-dimensional vectors
    input=chunks,
)
api_embeddings = [item.embedding for item in response.data]
print(len(api_embeddings[0]))  # 1536

Step #3: Clustering similar chunks

Now it's time to build the hierarchy based on the vector database. This relates to hierarchical clustering, but RAPTOR's soft assignments allow chunks to appear in multiple groups rather than forcing each chunk into a single branch.

The chunks are scored, so RAPTOR goes through them, groups similar values, and summarizes them.

RAPTOR uses a soft clustering algorithm via Gaussian Mixture Models (GMMs) which allows a chunk to belong to more than one cluster at once. The overlap avoids accuracy loss from missing words that might add context.

Here is sample code:

python
import numpy as np
import umap
from sklearn.mixture import GaussianMixture

# embeddings: a (n_chunks, dim) array from Step 2
embeddings = np.random.rand(50, 384)   # stand-in for real chunk vectors

# ── 1. Reduce dimensionality with UMAP ──
reducer = umap.UMAP(
    n_neighbors=15,        # how much local vs. global structure to preserve
    n_components=10,       # reduce from 384 dims down to 10
    metric="cosine",       # match the similarity measure used for embeddings
)
reduced = reducer.fit_transform(embeddings)

# ── 2. Choose the number of clusters via BIC ──
def best_cluster_count(data, max_k=10):
    best_k, best_bic = 1, np.inf
    for k in range(1, max_k + 1):
        gmm = GaussianMixture(n_components=k, random_state=42)
        gmm.fit(data)
        bic = gmm.bic(data)        # lower is better
        if bic < best_bic:
            best_k, best_bic = k, bic
    return best_k

k = best_cluster_count(reduced)
print(f"Chosen number of clusters: {k}")

# ── 3. Fit the GMM and get SOFT assignments ──
gmm = GaussianMixture(n_components=k, random_state=42)
gmm.fit(reduced)

probs = gmm.predict_proba(reduced)     # (n_chunks, k) probability matrix

# a chunk belongs to every cluster where its probability clears a threshold
THRESHOLD = 0.10
clusters = {c: [] for c in range(k)}
for chunk_idx, row in enumerate(probs):
    for cluster_idx, p in enumerate(row):
        if p >= THRESHOLD:
            clusters[cluster_idx].append(chunk_idx)

for c, members in clusters.items():
    print(f"Cluster {c}: chunks {members}")

Step #4: Creating cluster summaries

Once clustered, similar chunks can be summarized.

Since RAPTOR RAG uses a hierarchy, the cluster summaries at the top end of the tree are very few. The iteration summaries, as RAG works its way up the tree, become increasingly abstract.

The best LLMs for this step are Gemini 2.5 Flash, GPT-4o-mini, and Claude Haiku 4.5.

Here is sample code:

python
from openai import OpenAI

client = OpenAI()

SUMMARY_PROMPT = """You are summarizing a cluster of related text passages \
from a company's documents. Write a concise summary that captures the key \
information and themes shared across these passages. Preserve specific facts, \
but remove redundancy.

Passages:
{passages}

Summary:"""


def summarize_cluster(chunk_texts: list[str]) -> str:
    """Condense one cluster of chunks into a single summary node."""
    joined = "\n\n---\n\n".join(chunk_texts)
    response = client.chat.completions.create(
        model="gpt-4o-mini",          # cheap model is fine for summarization
        messages=[
            {"role": "user", "content": SUMMARY_PROMPT.format(passages=joined)}
        ],
        temperature=0.2,              # low temp = consistent, factual summaries
    )
    return response.choices[0].message.content.strip()


def build_layer(clusters: dict[int, list[int]], chunk_texts: list[str]) -> list[str]:
    """Turn every cluster into one summary, producing the next layer up."""
    summaries = []
    for cluster_id, member_indices in clusters.items():
        passages = [chunk_texts[i] for i in member_indices]
        summary = summarize_cluster(passages)
        summaries.append(summary)
        print(f"Cluster {cluster_id}: {len(passages)} chunks -> 1 summary")
    return summaries


# ── The recursive loop that builds the whole tree ──
def build_raptor_tree(chunk_texts, embed_fn, cluster_fn, max_layers=4):
    tree = [chunk_texts]              # layer 0 = the raw leaves
    current = chunk_texts

    for layer in range(max_layers):
        if len(current) <= 1:        # reached a single root node
            break
        embeddings = embed_fn(current)          # Step 2
        clusters   = cluster_fn(embeddings)     # Step 3
        current    = build_layer(clusters, current)   # Step 4
        tree.append(current)
        print(f"--- Built layer {layer + 1}: {len(current)} summary nodes ---")

    return tree

Step #5: Building the recursive tree

Step four builds the layers, but step five organizes the tree into its hierarchy.

Each summary has a parent-child relationship. The parent is the more abstract summarization, and each branch below it is the child node.

A node contains its text, its embedding vector, its layer number, and references to its children.

Here is sample code to illustrate:

python
from dataclasses import dataclass, field

@dataclass
class Node:
    id: int
    text: str                       # raw chunk OR summary
    embedding: list[float]
    layer: int                      # 0 = leaves, higher = more abstract
    child_ids: list[int] = field(default_factory=list)


def assemble_tree(layers_of_text, layers_of_embeddings, layers_of_clusters):
    """Turn the per-layer output of Step 4 into linked Node objects."""
    nodes: dict[int, Node] = {}
    next_id = 0
    prev_layer_ids: list[int] = []

    for layer_num, (texts, embeddings) in enumerate(
        zip(layers_of_text, layers_of_embeddings)
    ):
        current_layer_ids = []
        for i, (text, emb) in enumerate(zip(texts, embeddings)):
            # link this summary to the child nodes it was built from
            child_ids = []
            if layer_num > 0:
                member_indices = layers_of_clusters[layer_num - 1][i]
                child_ids = [prev_layer_ids[m] for m in member_indices]

            nodes[next_id] = Node(
                id=next_id, text=text, embedding=emb,
                layer=layer_num, child_ids=child_ids,
            )
            current_layer_ids.append(next_id)
            next_id += 1

        prev_layer_ids = current_layer_ids
    return nodes


def store_collapsed_tree(nodes: dict[int, Node], collection):
    """Flatten ALL nodes from ALL layers into one vector index."""
    collection.add(
        ids        = [str(n.id) for n in nodes.values()],
        embeddings = [n.embedding for n in nodes.values()],
        documents  = [n.text for n in nodes.values()],
        metadatas  = [
            {
                "layer": n.layer,
                "child_ids": ",".join(map(str, n.child_ids)),
                "is_leaf": n.layer == 0,
            }
            for n in nodes.values()
        ],
    )
    print(f"Stored {len(nodes)} nodes across all layers in one index.")

How to implement RAPTOR RAG in Python

Implementing a RAPTOR RAG takes several steps, but you can perform each one in Python.

You'll need a document storage location, a vector store, your LLM of choice, and the infrastructure to run the Python code.

The following sections provide the Python code for each step, but the code can be combined to run all steps as a single process.

The complete RAPTOR RAG system architecture, from document ingestion and tree construction through to hierarchical retrieval and answer generation

Step #1: Load and chunk the documents

The chunking step takes documents and segments them into words or characters. These chunks are also known as the leaves in the hierarchy.

Here is the step in Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 1 -- Chunking
# ──────────────────────────────────────────────────────────────────────────────
def chunk_text(text: str, size: int = 400, overlap: int = 50) -> list[str]:
    """Split raw text into overlapping chunks.

    For production, prefer LangChain's RecursiveCharacterTextSplitter, which
    respects paragraph/sentence boundaries. This hand-rolled version keeps the
    dependency list short and shows the core idea.
    """
    chunks, start = [], 0
    while start < len(text):
        end = start + size
        chunk = text[start:end].strip()
        if chunk:
            chunks.append(chunk)
        start = end - overlap
    return chunks

Step #2: Transform chunks into vectors for semantic comparison

Step two takes the chunks created in step one and creates the vectors.

A vector database converts the chunks and provides a numerical value representing the confidence in their relevance to the query. This value determines if the chunk becomes a part of the query answer.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 2 -- Embedding (swappable: local model by default)
# ──────────────────────────────────────────────────────────────────────────────
class Embedder:
    """Wraps a local sentence-transformers model.

    To use an API instead, replace `encode` with a call to your provider
    (OpenAI, Voyage, Cohere, Gemini). The ONLY rule: use the same embedder
    for leaves, summaries, AND queries, or the vectors won't be comparable.
    """

    def __init__(self, model_name: str = "all-MiniLM-L6-v2"):
        self.model = SentenceTransformer(model_name)

    def encode(self, texts: list[str]) -> np.ndarray:
        return np.asarray(self.model.encode(texts, show_progress_bar=False))

Step #3: Group similar chunks before summarizing them

Step three takes similar chunks from step two and clusters them. This step is necessary for step four so that the clustered chunks can be summarized.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 3 -- Clustering (UMAP dimensionality reduction -> soft GMM)
# ──────────────────────────────────────────────────────────────────────────────
def cluster_embeddings(
    embeddings: np.ndarray,
    threshold: float = 0.10,
    max_k: int = 10,
    random_state: int = 42,
) -> list[list[int]]:
    """Return a list of clusters; each cluster is a list of node indices.

    Soft clustering means a node can appear in more than one cluster.
    """
    n = len(embeddings)
    if n <= 2:
        return [list(range(n))]  # too few to cluster meaningfully

    # Reduce dimensions so the GMM behaves well in low-dimensional space.
    n_components = min(10, n - 1)
    reduced = umap.UMAP(
        n_neighbors=min(15, n - 1),
        n_components=n_components,
        metric="cosine",
        random_state=random_state,
    ).fit_transform(embeddings)

    # Pick the cluster count that minimizes BIC (balances fit vs. complexity).
    best_k, best_bic, best_gmm = 1, np.inf, None
    for k in range(1, min(max_k, n) + 1):
        gmm = GaussianMixture(n_components=k, random_state=random_state)
        gmm.fit(reduced)
        bic = gmm.bic(reduced)
        if bic < best_bic:
            best_k, best_bic, best_gmm = k, bic, gmm

    # Soft assignment: a node joins every cluster it clears the threshold for.
    probs = best_gmm.predict_proba(reduced)
    clusters: list[list[int]] = [[] for _ in range(best_k)]
    for idx, row in enumerate(probs):
        assigned = [c for c, p in enumerate(row) if p >= threshold]
        if not assigned:                       # ensure every node lands somewhere
            assigned = [int(np.argmax(row))]
        for c in assigned:
            clusters[c].append(idx)

    return [c for c in clusters if c]           # drop empties

Step #4: Generate cluster summaries

Here, we use an LLM to condense the clustered chunks from step three and create a summary.

The first summary becomes the parent node to the leaves below.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 4 -- Summarization (swappable: local or API)
# ──────────────────────────────────────────────────────────────────────────────
SUMMARY_PROMPT = (
    "Summarize the following related passages into a single concise summary. "
    "Preserve specific facts and key themes; remove redundancy.\n\n"
    "Passages:\n{passages}\n\nSummary:"
)


def make_openai_summarizer(model: str = "gpt-4o-mini") -> Callable[[list[str]], str]:
    """Return a summarizer backed by the OpenAI API.

    RAPTOR summarization is an offline batch job -- run it through a cheap model
    (and ideally the Batch API) to keep costs down.
    """
    from openai import OpenAI
    client = OpenAI()

    def summarize(passages: list[str]) -> str:
        joined = "\n\n---\n\n".join(passages)
        resp = client.chat.completions.create(
            model=model,
            messages=[{"role": "user",
                       "content": SUMMARY_PROMPT.format(passages=joined)}],
            temperature=0.2,
        )
        return resp.choices[0].message.content.strip()

    return summarize


def naive_summarizer(passages: list[str]) -> str:
    """Zero-dependency fallback so the tree builds without any LLM.

    Replace this with `make_openai_summarizer()` (or a local Llama/Mistral via
    Ollama) for real summaries. This just truncates+joins as a placeholder.
    """
    joined = " ".join(passages)
    return joined[:500] + ("..." if len(joined) > 500 else "")

Step #5: Build the recursive tree

This step recursively moves up the tree to create parent-node summaries and organizes the data into a hierarchy of branches and leaves.

The most important part of this step is linking the nodes together to create relationships between them.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 5 -- Recursive tree construction + collapsed storage
# ──────────────────────────────────────────────────────────────────────────────
class RaptorTree:
    def __init__(
        self,
        embedder: Embedder,
        summarizer: Callable[[list[str]], str] = naive_summarizer,
        max_layers: int = 4,
    ):
        self.embedder = embedder
        self.summarizer = summarizer
        self.max_layers = max_layers
        self.nodes: dict[int, Node] = {}
        self._next_id = 0

    def _add_node(self, text: str, embedding: np.ndarray,
                  layer: int, child_ids: list[int]) -> Node:
        node = Node(self._next_id, text, embedding, layer, child_ids)
        self.nodes[self._next_id] = node
        self._next_id += 1
        return node

    def build(self, documents: list[str]) -> None:
        """Build the full tree from a list of raw documents."""
        # ---- Layer 0: leaves ----
        leaf_texts: list[str] = []
        for doc in documents:
            leaf_texts.extend(chunk_text(doc))                  # Step 1

        embeddings = self.embedder.encode(leaf_texts)           # Step 2
        current_layer = [
            self._add_node(t, e, 0, [])
            for t, e in zip(leaf_texts, embeddings)
        ]
        print(f"Layer 0: {len(current_layer)} leaf chunks")

        # ---- Higher layers: cluster -> summarize -> embed -> repeat ----
        for layer in range(1, self.max_layers + 1):
            if len(current_layer) <= 1:
                break

            layer_embeddings = np.array([n.embedding for n in current_layer])
            clusters = cluster_embeddings(layer_embeddings)     # Step 3

            if len(clusters) >= len(current_layer):
                break  # no consolidation happening; stop growing

            next_layer: list[Node] = []
            for cluster in clusters:
                members = [current_layer[i] for i in cluster]
                summary = self.summarizer([m.text for m in members])   # Step 4
                summary_emb = self.embedder.encode([summary])[0]        # Step 2 again
                parent = self._add_node(
                    summary, summary_emb, layer, [m.id for m in members]
                )
                next_layer.append(parent)

            current_layer = next_layer
            print(f"Layer {layer}: {len(current_layer)} summary nodes")

    # ---- Step 5 storage: collapse ALL layers into one flat pool ----
    def collapsed_nodes(self) -> list[Node]:
        """Every node from every layer, treated as equal retrieval candidates."""
        return list(self.nodes.values())

Step #6: Store tree nodes in a vector database

Step six writes every node into a vector database, where each node is stored, along with its text and metadata.

At this point, the tree is ready for queries. Building the tree is expensive, so it's done as few times as possible.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 6 -- Persist the collapsed tree into a vector database (Chroma)
# ──────────────────────────────────────────────────────────────────────────────
import chromadb


def store_tree(tree: RaptorTree, collection_name: str = "raptor_tree"):
    """Write every node from every layer into one Chroma collection.

    Chroma persists to disk, so the expensive tree only gets built once.
    Note: metadata values must be scalars, so child_ids is joined into a
    string and split back out on read.
    """
    client = chromadb.PersistentClient(path="./raptor_db")

    # Start clean so re-running doesn't duplicate nodes.
    try:
        client.delete_collection(collection_name)
    except Exception:
        pass
    collection = client.create_collection(collection_name)

    nodes = tree.collapsed_nodes()
    collection.add(
        ids=[str(n.id) for n in nodes],
        embeddings=[n.embedding.tolist() for n in nodes],
        documents=[n.text for n in nodes],
        metadatas=[
            {
                "layer": n.layer,
                "child_ids": ",".join(map(str, n.child_ids)),
                "is_leaf": n.layer == 0,
            }
            for n in nodes
        ],
    )
    print(f"Stored {len(nodes)} nodes across all layers in '{collection_name}'.")
    return collection

Step #7: Implement hierarchical retrieval

Building the tree starts at the last child node, but retrieval starts at the top of the tree at the first summarization.

As an answer is processed, the retrieval system goes down the hierarchy based on the summaries until it reaches the last leaf nodes.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 7 -- Hierarchical (tree-traversal) retrieval
# ──────────────────────────────────────────────────────────────────────────────
def retrieve_traversal(
    tree: RaptorTree,
    query: str,
    top_per_layer: int = 2,
) -> list[Node]:
    """Walk the tree top-down, keeping the best nodes at each layer.

    Unlike collapsed retrieval (which searches all nodes at once), this
    descends the hierarchy: at each layer it only considers the CHILDREN
    of the nodes it already selected one layer up.
    """
    q_emb = tree.embedder.encode([query])[0]

    # Group nodes by layer so we can walk from the top down.
    by_layer: dict[int, list[Node]] = {}
    for node in tree.nodes.values():
        by_layer.setdefault(node.layer, []).append(node)

    top_layer = max(by_layer)
    selected: list[Node] = []

    # Start with every node in the most abstract layer.
    candidates = by_layer[top_layer]

    for layer in range(top_layer, -1, -1):
        if not candidates:
            break

        # Score this layer's candidates and keep the best handful.
        scored = sorted(
            candidates,
            key=lambda n: cosine_sim(q_emb, n.embedding),
            reverse=True,
        )
        kept = scored[:top_per_layer]
        selected.extend(kept)

        # Descend: next layer's candidates are the CHILDREN of what we kept.
        child_ids = [cid for n in kept for cid in n.child_ids]
        candidates = [tree.nodes[cid] for cid in child_ids]

    return selected

Step #8: Generate the final response

Step eight takes the nodes retrieved in step seven, inputs the text into a prompt alongside the user's question, and asks an LLM to write the answer.

This is the retrieval step that users see when they type a question.

Here is the Python code:

python
# ──────────────────────────────────────────────────────────────────────────────
# Step 8 -- Generate the final answer from retrieved context
# ──────────────────────────────────────────────────────────────────────────────
def answer(tree: RaptorTree, query: str, top_per_layer: int = 2) -> str:
    """Full RAG: retrieve context from the tree, then ask an LLM.

    Shown with OpenAI; swap for any LLM. Falls back to just returning the
    retrieved context if no API key is configured.
    """
    context_nodes = retrieve_traversal(tree, query, top_per_layer)
    context = "\n\n".join(
        f"[layer {n.layer}] {n.text}" for n in context_nodes
    )

    try:
        from openai import OpenAI
        client = OpenAI()
        resp = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{
                "role": "user",
                "content": (
                    "Answer the question using only the context below. "
                    "If the answer isn't there, say so.\n\n"
                    f"Context:\n{context}\n\nQuestion: {query}"
                ),
            }],
            temperature=0.2,
        )
        return resp.choices[0].message.content.strip()
    except Exception as e:
        return f"[No LLM configured: {e}]\n\nRetrieved context:\n{context}"

What are RAPTOR RAG's limitations and known failure modes?

RAPTOR RAG has several advantages, but it has limitations you should learn about before you decide to implement it.

These few disadvantages might change the way you design your system to overcome them:

  • Cost: Because building the tree is expensive, it can be a limitation for businesses on a budget. Every summarization is a call to an LLM, so large trees cost more, especially if you need to rebuild the tree often.
  • Errors can chain: Each summary builds on the next summary. If the LLM hallucinates in one summary, the errors will propagate to the next parent summary.
  • Constant updates to dynamic data: If your source data changes frequently, you must rebuild the tree. This can be time-consuming and cost more than necessary. Businesses might prefer to use RAPTOR RAG on documents that change infrequently or stay static.
  • Cluster errors: If chunking produces errors, they will persist in the summaries. As with other chunking procedures, it's important to review chunks to ensure there were no errors. This can be done with quality assurance and sampling chunks before moving on to the next step.
  • Too complex for simple queries: RAPTOR RAG is best for answers that require integrating data from multiple documents. Using it on simple queries will unnecessarily waste LLM tokens and AI budgets.
  • Document ingestion errors: If your Python script throws an error when ingesting and chunking documents, the RAPTOR RAG system loses context. Without relevant context, the system can hallucinate and return incomplete and inaccurate answers.

How can Meilisearch power the retrieval layer in a RAPTOR pipeline?

RAPTOR's indexing produces a multi-level tree of text nodes.

Meilisearch runs keyword and semantic search together and merges them into a single ranked list.

At search time, it runs both keyword and semantic search in parallel, then merges the results using its ranking rules, which sort matches into buckets by criteria such as typo count, word proximity, and attribute importance.

This is important in a RAPTOR tree because the two node types reward different retrieval styles.

Running both at once means a single query can retrieve the correct node, whether the answer lives in a leaf or in an abstract summary.

Meilisearch's hybrid search capabilities (combining semantic vector search with full-text keyword matching) make it a strong fit for the collapsed-tree retrieval strategy, where all nodes across tree levels are queried simultaneously.

Build RAG systems that can see the whole document

RAPTOR RAG is a good option when your retrieval system needs to answer complex questions across long documents, multiple sections, or scattered pieces of context.

Instead of forcing an LLM to work from isolated chunks, RAPTOR gives it a layered view of the information: broad summaries at the top, detailed chunks at the bottom, and a path between the two.

It is not the right fit for every RAG system, especially if your data changes constantly or your queries are simple.

But when users need detailed answers from large, interconnected knowledge bases, RAPTOR gives you a more organized way to retrieve the right information.

Power RAPTOR retrieval with Meilisearch

Meilisearch can support the retrieval layer in a RAPTOR pipeline by helping you search across both summary nodes and leaf-level chunks. Its hybrid search capabilities combine keyword and semantic search, so users can find the right answer whether their query matches the exact wording of a document or the broader meaning of a summary.

Try Meilisearch

Maya Shin

Maya Shin

Head of Marketing @ Meilisearch

Related articles