GraphRAG: Merge the Graph, Answer the Global Question
Merge per-chunk extractions into a graph, then answer a global question map-reduce style over community summaries. Implement merge(extractions) and global_answer(question, summaries, model, budget). An extraction is {"chunk": id, "entities": [{"name", "description"}], "relationships": [{"source", "target"}]}, each relationship naming entities of that chunk.
- Key every name: lowercase it, turn each run of characters other than
a-zand0-9into one space, drop the words inSUFFIXES, join the rest with one space. - Entities:
{key: {"name": first spelling seen, stripped, "descriptions": [...], "chunks": [...]}}. Add each stripped, non-empty description and each chunk id once, in the order first seen. - Edges:
{(a, b): weight}witha < bthe two keys. Each relationship adds 1. One whose ends share a key is dropped.mergereturns(entities, edges). - Map: one
model(MAP_PROMPT.format(question=..., summary=...))call per summary, in order;read_map(reply)gives(score, answer). - Rank: drop answers scoring 0, then best score first; ties keep summary order.
- Pack: take answers in that order while their total
count_tokensstays withinbudget, stopping at the first that does not fit. - Reduce: one call with
REDUCE_PROMPT.format(question=..., answers=...), the packed answers joined by a blank line; return the stripped reply. If nothing was packed, returnNO_ANSWERand make no reduce call.
The catch. Chunks name the same thing differently: Northwind Labs, northwind labs, Northwind Labs, Inc.. Keyed apart, they make three nodes, the graph splits, and each community report sees a third of the story. Keyed together, a relationship between two of those spellings is a node pointing at itself: no edge.