Build a RAPTOR Tree and Search It Collapsed
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.
- Leaves. Chunk
ibecomes node{"id": i, "level": 0, "text": chunks[i], "children": []}. The leaves are the first layer. - Rounds. While the layer has more than one node, call
clusteron 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. - A group of one carries its node up as it is: no model call, no new node.
- A larger group becomes a new node: the next id,
levelthe round number (1 for the first round, whatever its members' levels),childrenthe members' ids in group order, and astextthe stripped reply toSUMMARY_PROMPT.format(texts=...), the members' texts joined by a blank line. - Return every node, in id order.
retrievescores every node, at every level, withsimilarity(query, node text), best first (ties: lower id first), skips those scoring 0, and takes nodes while their totalcount_tokensstays withinbudget, 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.