Skip to content

< CollectionsAll the RAGs · 26 of 42 ·125 · Level 03, RAG

GraphRAG: Merge the Graph, Answer the Global Question

medium · implement · RAG

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.

  1. Key every name: lowercase it, turn each run of characters other than a-z and 0-9 into one space, drop the words in SUFFIXES, join the rest with one space.
  2. 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.
  3. Edges: {(a, b): weight} with a < b the two keys. Each relationship adds 1. One whose ends share a key is dropped. merge returns (entities, edges).
  4. Map: one model(MAP_PROMPT.format(question=..., summary=...)) call per summary, in order; read_map(reply) gives (score, answer).
  5. Rank: drop answers scoring 0, then best score first; ties keep summary order.
  6. Pack: take answers in that order while their total count_tokens stays within budget, stopping at the first that does not fit.
  7. 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, return NO_ANSWER and 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.