Skip to content

< CollectionsAll the RAGs · 25 of 42 ·124 · Level 03, RAG

Build a RAPTOR Tree and Search It Collapsed

medium · implement · RAG

Build a RAPTOR tree over a document's chunks, then search every level of it at once. Implement build_tree(chunks, cluster, summarize) and retrieve(nodes, query, budget). cluster(texts) returns groups of positions in texts (positions in that list, not node ids; a position may sit in two groups); summarize(prompt) is the model and returns a string.

  1. Leaves. Chunk i becomes node {"id": i, "level": 0, "text": chunks[i], "children": []}. The leaves are the first layer.
  2. Rounds. While the layer has more than one node, call cluster on its texts. If that gives as many groups as the layer has nodes, or more, stop. Otherwise each group, in order, puts one node in the next layer.
  3. A group of one carries its node up as it is: no model call, no new node.
  4. A larger group becomes a new node: the next id, level the round number (1 for the first round, whatever its members' levels), children the members' ids in group order, and as text the stripped reply to SUMMARY_PROMPT.format(texts=...), the members' texts joined by a blank line.
  5. Return every node, in id order.
  6. retrieve scores every node, at every level, with similarity(query, node text), best first (ties: lower id first), skips those scoring 0, and takes nodes while their total count_tokens stays within budget, stopping at the first that does not fit. It returns their ids.

The catch. A clustering does not always shrink the layer. When every node lands alone, or overlapping groups are as many as the nodes, another round builds the same layer again and the loop never ends: check before any model call. And a lone node goes up unchanged, because a summary of one passage is a paraphrase that costs a call and puts a near copy into the index.