Module 4 · Next-generation RAG architectures

GraphRAG: knowledge graphs and community summaries

6 min read

Some questions are not about a passage, but about relationships or about the corpus as a whole: "Which products are made in Germany?", "What are the main themes of the complaints?". No passage search can answer them: the information is scattered across dozens of documents, and none contains it in full. GraphRAG builds a knowledge graph from the corpus and queries it. This lesson explains its principle, its implementation in Prism, and above all its cost.

The principle

GraphRAG, popularized by a Microsoft research project, adds three steps to indexing:

passages ─(LLM)─► entities & relations ─► graph ─(Louvain)─► communities ─(LLM)─► summaries
  1. Extraction: an LLM reads each passage and extracts its entities (products, suppliers, countries, policies) and their relations (MANUFACTURES, COVERS, COMPATIBLE_WITH).
  2. Communities: a community detection algorithm (Louvain or Leiden) groups densely connected entities.
  3. Summaries: an LLM summarizes each community.

And two search modes:

  • Local: start from the entities mentioned in the question, explore their neighborhood in the graph, retrieve the passages that mention them.
  • Global: each community summary partially answers the question (map), then the best answers are synthesized (reduce).

Extraction, with structured output

class Entity(BaseModel):
    name: str = Field(description="Nom canonique : « Chaise Axis » plutôt que « la chaise »")
    type: str = Field(description="PRODUIT, FOURNISSEUR, PAYS, POLITIQUE, SERVICE ou AUTRE")


class Relation(BaseModel):
    source: str
    target: str
    label: str = Field(description="Verbe court en majuscules : FABRIQUE, COMPATIBLE_AVEC, COUVRE…")

(The descriptions, in French like the corpus, ask for a canonical name — "Axis chair" rather than "the chair" —, an entity type, and a short uppercase verb as the relation label.) Structured output guarantees a valid object on every call. The real difficulty lies elsewhere: entity resolution. "The Axis chair", "Axis", "CHAIR-7" and "the ergonomic chair" are the same thing; if extraction turns them into four nodes, the graph fragments and its communities lose their meaning. The "canonical name" instruction helps; in production, a merging step is added (by name and embedding similarity, or from a reference list of your products).

The graph and its communities

for chunk in chunks:
    prompt = EXTRACT.format(chunk_id=chunk.id, text=chunk.text)
    extraction = llm.structured("extract_graph", Extraction, prompt)
    for entity in extraction.entities:
        kg.graph.add_node(entity.name, type=entity.type)
        kg.mentions.setdefault(entity.name, set()).add(chunk.id)
    for rel in extraction.relations:
        if rel.source in kg.graph and rel.target in kg.graph:
            kg.graph.add_edge(rel.source, rel.target, label=rel.label)
# Louvain : regroupe les entités densément reliées entre elles. Graine fixe = résultats reproductibles.
groups = nx.community.louvain_communities(kg.graph, seed=42) if kg.graph.number_of_edges() else []

The mentions dictionary links each entity to the passages that cite it: it is the bridge between the graph and the text. Relations whose endpoint was not extracted as an entity are ignored, so as not to create untyped nodes. Louvain runs with a fixed seed, for reproducible results.

In offline mode, Prism's fake extraction produces a small graph that shows the mechanics: 14 entities, 12 relations, 4 communities, one of which groups "Allemagne, Bureau Lift, Chaise Axis, Ergoform, Garantie, Roulettes CASTER-M" (Germany, the Lift desk, the Axis chair, the manufacturer Ergoform, warranty, CASTER-M casters). With Claude, the graph is much richer.

Local search starts from the question's entities:

seeds = [e for e in kg.graph.nodes if e.lower() in lowered or e.lower().split()[-1] in lowered]
scope = set(seeds) | {n for s in seeds for n in kg.graph.neighbors(s)}

For « Qui fabrique la chaise Axis ? » (who makes the Axis chair?), the "Chaise Axis" entity leads to its neighbor "Ergoform", hence to the suppliers passage — even if that passage does not contain the word "makes" in the question's form. Entity matching is deliberately simple here (name matching); embeddings of entity names are often used to make it robust.

Global search is a map-reduce over the summaries:

for community in kg.communities:
    prompt = f"Résumé d'un groupe d'informations :\n{community.summary}\n\nQuestion : {question}"
    p = llm.structured("global_map", Partial, prompt)
    if p.answer and p.score > 0:
        partials.append(p)
best = sorted(partials, key=lambda p: p.score, reverse=True)[:top]

Each community gives a partial answer and a usefulness score; only the best are synthesized.

The cost, which decides everything

StepLLM callsFor 100,000 passages
ExtractionOne per passage100,000 calls
Community summariesOne per community (often over several levels)Thousands
Global searchOne per queried community + the synthesisDozens per question
UpdatesRe-extraction of modified passages, recomputation of affected communitiesVariable, complex

GraphRAG indexing typically costs orders of magnitude more than vector indexing, and global search is slow. Lighter variants exist (graphs built without community summaries, extraction by smaller models, global search limited to top-level communities), but the principle remains expensive.

When to use it

SituationGraphRAG useful?
Factual questions about one passageNo: hybrid search + re-ranking is enough and costs far less
Synthesis questions over the whole corpus ("main themes", "trends")Yes: global search is designed for this
Questions that follow relationships ("which products from supplier X have a warranty longer than 3 years?")Yes, or a relational database if the data is structured
Highly changing corpusHard: updating the graph is expensive

One question to ask first: do these relationships already exist somewhere? If products, their suppliers and their warranties are in your database, an SQL query (or an SQL tool given to an agent, lesson 4.2) is more accurate and cheaper than a graph extracted by an LLM from texts that describe that same data.

Key takeaways

  • GraphRAG extracts entities and relations, groups entities into communities, summarizes them.
  • Local search: neighborhood of the question's entities; global search: map-reduce over the summaries.
  • Entity resolution (one canonical name per object) makes the graph's quality.
  • Indexing and global search are very expensive: reserve GraphRAG for synthesis and relationship questions.
  • If the relationships already exist in a structured database, query it directly.

Practice

  1. Run examples/04_graphrag.py offline, then with an API key: compare the number of entities, relations and communities.
  2. Spot duplicate entities in the real graph (same object, different names) and write a merging step.
  3. Ask "What are the suppliers and their countries?" to hybrid search and to global search: which one answers completely?

Resources