GraphRAG in Python: Knowledge Graphs for Document QA

Standard RAG fails on synthesis questions. GraphRAG builds a knowledge graph and runs community detection first. Build one from scratch in Python with networkx.

Cover Image for GraphRAG in Python: Knowledge Graphs for Document QA

You have a collection of papers and want to describe the themes running through all of them. Finding a few closely matching passages may help with a specific factual question, but a broad synthesis needs evidence spread across the collection. GraphRAG organises that evidence through relationships between entities, giving a document-question-answering system another way to assemble context.

The GraphRAG approach scores higher than naive RAG on comprehensiveness and diversity for synthesis questions in the paper's evaluation, while naive RAG scores higher on directness. We build entity communities and their summaries in Python, separating the work done during indexing from the summaries consulted when a question arrives.

Community summaries let a query draw on relationships across the collection. We trace their construction and combine them into an answer with a working implementation.

For a clinical evaluation of graph-based retrieval, see our BMJ Digital Health & AI study of RAG and GraphRAG in chronic kidney disease, published in November 2026 with Joshua Au Yeung and Elham Asgari. The study commentary explains the findings from simulated patient cases. The tutorial below illustrates community-based retrieval on a small document collection and does not reproduce the clinical system.

Let's Build It

Click the badge to follow along in an interactive notebook:

Open In Colab

Here is what the graph construction looks like as entities and edges are added and communities are coloured:

Graph construction animation: entity nodes appear, edges are drawn, then community colour clusters emerge

The code below is a complete, self-contained implementation. It uses a hardcoded ML corpus so you do not need to download anything, and it calls the OpenAI API for entity extraction and report generation. You will need an OPENAI_API_KEY.

import os
import json
import textwrap
import networkx as nx
import community as community_louvain  # pip install python-louvain
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# ─── Corpus ───────────────────────────────────────────────────────────────────

CORPUS = [
    """Transformer models use self-attention to relate all positions in a sequence
    simultaneously. The attention mechanism computes query, key, and value projections,
    then applies scaled dot-product attention. BERT introduced bidirectional
    pre-training, while GPT models use causal (left-to-right) attention masks.""",

    """Large language models are typically trained with the next-token prediction
    objective on massive text corpora. GPT-4 and Claude use reinforcement learning
    from human feedback (RLHF) to align model outputs with human preferences.
    Constitutional AI from Anthropic adds a self-critique step before RLHF.""",

    """Retrieval-augmented generation (RAG) combines a dense retrieval system with
    a generative language model. A query is encoded into an embedding, the nearest
    chunks are retrieved from a vector store such as FAISS or Pinecone, and the
    context is prepended to the LLM prompt. RAG reduces hallucination and allows
    knowledge to be updated without retraining.""",

    """Knowledge graphs represent facts as (subject, predicate, object) triples.
    Neo4j is a popular property graph database. SPARQL is used to query RDF graphs.
    Entity linking maps surface mentions to canonical graph nodes, and relation
    extraction populates the graph from unstructured text.""",

    """Quantisation reduces model size by representing weights in lower precision.
    INT8 and INT4 are common targets. GPTQ applies one-shot post-training
    quantisation using approximate second-order information. AWQ activates
    weight quantisation to preserve salient weights. Both methods keep accuracy
    close to the full-precision baseline.""",

    """The KV cache stores the key and value tensors from previous attention
    computations so they need not be recomputed at each decoding step. This trades
    memory for compute. For a 70B-parameter model with long contexts, the KV cache
    can exceed the size of the model weights themselves, making it a primary
    bottleneck for batch throughput.""",

    """Community detection algorithms partition graph nodes into groups with dense
    internal connections. The Louvain algorithm optimises modularity greedily.
    Leiden improves on Louvain by guaranteeing well-connected communities and
    avoiding poorly connected splits. Both algorithms are widely used for
    social network analysis and knowledge graph clustering.""",

    """Vector databases such as Weaviate, Qdrant, and Chroma store dense embeddings
    and support approximate nearest-neighbour search via HNSW or IVF indexing.
    They underpin semantic search, recommendation engines, and RAG pipelines.
    Hybrid search combines dense retrieval with sparse BM25 scoring.""",
]

# ─── Step 1: Entity and relationship extraction ────────────────────────────────

EXTRACTION_PROMPT = """You are an information-extraction assistant.
Given a text passage, extract all named entities and the relationships between them.

Return ONLY valid JSON with this exact structure:
{
  "entities": [
    {"name": "...", "type": "...", "description": "..."}
  ],
  "relationships": [
    {"source": "...", "target": "...", "description": "...", "strength": 0.0}
  ]
}

Rules:
- "type" should be one of: MODEL, TECHNIQUE, CONCEPT, TOOL, ALGORITHM, METRIC
- "strength" is a float from 0 to 1 indicating how strongly the entities are related
- Entity names should be canonical (e.g. "GPT-4" not "it")
- Only include relationships explicitly supported by the text
"""

def extract_entities_and_relationships(chunk: str) -> dict:
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": EXTRACTION_PROMPT},
            {"role": "user", "content": f"Text:\n{chunk}"},
        ],
        response_format={"type": "json_object"},
        temperature=0,
    )
    return json.loads(response.choices[0].message.content)

print("Extracting entities and relationships from each chunk...")
extractions = [extract_entities_and_relationships(chunk) for chunk in CORPUS]

for i, ext in enumerate(extractions):
    n_ent = len(ext.get("entities", []))
    n_rel = len(ext.get("relationships", []))
    print(f"  Chunk {i+1}: {n_ent} entities, {n_rel} relationships")

# ─── Step 2: Build the graph ──────────────────────────────────────────────────

G = nx.Graph()

for ext in extractions:
    for entity in ext.get("entities", []):
        name = entity["name"]
        if name not in G:
            G.add_node(name, type=entity["type"], description=entity["description"])
        else:
            # Merge descriptions if node already exists
            existing = G.nodes[name].get("description", "")
            if entity["description"] not in existing:
                G.nodes[name]["description"] = existing + " " + entity["description"]

    for rel in ext.get("relationships", []):
        src, tgt = rel["source"], rel["target"]
        if src in G and tgt in G:
            if G.has_edge(src, tgt):
                # Accumulate strength
                G[src][tgt]["strength"] = min(
                    1.0, G[src][tgt]["strength"] + rel["strength"]
                )
            else:
                G.add_edge(src, tgt, description=rel["description"],
                           strength=rel["strength"])

print(f"\nGraph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")

# ─── Step 3: Community detection (Louvain) ────────────────────────────────────

partition = community_louvain.best_partition(G, weight="strength", random_state=42)

# Group nodes by community id
from collections import defaultdict
communities = defaultdict(list)
for node, comm_id in partition.items():
    communities[comm_id].append(node)

print(f"\nCommunities detected: {len(communities)}")
for comm_id, members in communities.items():
    print(f"  Community {comm_id}: {', '.join(members)}")

# ─── Step 4: Community report generation ─────────────────────────────────────

REPORT_PROMPT = """You are summarising a community of related AI/ML concepts from a knowledge graph.

Given the list of entities (with descriptions) and their relationships, write a concise community report.
Return ONLY valid JSON:
{
  "title": "...",
  "summary": "...",
  "key_themes": ["...", "..."],
  "most_important_entities": ["...", "..."]
}
"""

def generate_community_report(comm_id: int, members: list[str]) -> dict:
    entity_lines = []
    for node in members:
        desc = G.nodes[node].get("description", "")
        entity_lines.append(f"- {node} ({G.nodes[node].get('type', 'CONCEPT')}): {desc}")

    rel_lines = []
    for u, v, data in G.edges(data=True):
        if u in members or v in members:
            rel_lines.append(f"- {u} -> {v}: {data.get('description', '')}")

    content = "Entities:\n" + "\n".join(entity_lines)
    if rel_lines:
        content += "\n\nRelationships:\n" + "\n".join(rel_lines)

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": REPORT_PROMPT},
            {"role": "user", "content": content},
        ],
        response_format={"type": "json_object"},
        temperature=0,
    )
    report = json.loads(response.choices[0].message.content)
    report["community_id"] = comm_id
    report["members"] = members
    return report

print("\nGenerating community reports...")
community_reports = [
    generate_community_report(cid, members)
    for cid, members in communities.items()
]

for report in community_reports:
    print(f"\n[Community {report['community_id']}] {report['title']}")
    print(f"  Summary: {report['summary'][:120]}...")
    print(f"  Key themes: {', '.join(report['key_themes'])}")

# ─── Step 5: Global search (map-reduce) ───────────────────────────────────────

MAP_PROMPT = """You are analysing a community report to help answer a user query.

If this report is relevant to the query, extract the key points that address it.
Return ONLY valid JSON:
{
  "relevant": true,
  "key_points": ["...", "..."],
  "relevance_score": 0.0
}
If not relevant: {"relevant": false, "key_points": [], "relevance_score": 0.0}
"""

REDUCE_PROMPT = """You are synthesising partial answers from multiple community reports
to answer a user's question comprehensively.

Produce a well-structured, thorough answer. Avoid repetition. Cite the community titles
where relevant.
"""

def global_search(query: str, reports: list[dict]) -> str:
    print(f"\nGlobal search: '{query}'")

    # Map step: rate each report for relevance
    relevant_points = []
    for report in reports:
        report_text = (
            f"Title: {report['title']}\n"
            f"Summary: {report['summary']}\n"
            f"Key themes: {', '.join(report['key_themes'])}\n"
            f"Important entities: {', '.join(report['most_important_entities'])}"
        )
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": MAP_PROMPT},
                {"role": "user", "content": f"Query: {query}\n\nReport:\n{report_text}"},
            ],
            response_format={"type": "json_object"},
            temperature=0,
        )
        result = json.loads(response.choices[0].message.content)
        if result.get("relevant") and result.get("relevance_score", 0) > 0.3:
            relevant_points.append({
                "community": report["title"],
                "points": result["key_points"],
                "score": result["relevance_score"],
            })
            print(f"  Relevant: {report['title']} (score={result['relevance_score']:.2f})")
        else:
            print(f"  Skipped:  {report['title']}")

    # Reduce step: synthesise
    if not relevant_points:
        return "No relevant communities found for this query."

    context = "\n\n".join(
        f"From '{p['community']}':\n" + "\n".join(f"- {pt}" for pt in p["points"])
        for p in sorted(relevant_points, key=lambda x: -x["score"])
    )

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": REDUCE_PROMPT},
            {"role": "user", "content": f"Query: {query}\n\nPartial answers:\n{context}"},
        ],
        temperature=0.3,
    )
    return response.choices[0].message.content

answer = global_search(
    "What are the main techniques for making LLMs more efficient and cost-effective?",
    community_reports,
)
print("\n=== Final Answer ===")
print(textwrap.fill(answer, width=80))

Running this on the 8-chunk corpus, you should see output like:

Graph: 34 nodes, 28 edges

Communities detected: 4
  Community 0: Transformer, BERT, GPT-4, self-attention, RLHF, Constitutional AI...
  Community 1: RAG, FAISS, Pinecone, knowledge graph, Neo4j, SPARQL...
  Community 2: quantisation, GPTQ, AWQ, INT8, INT4...
  Community 3: KV cache, community detection, Leiden, Louvain, vector database...

Generating community reports...
[Community 0] Language Model Architectures and Alignment
[Community 1] Retrieval and Knowledge Graph Systems
[Community 2] Model Compression via Quantisation
[Community 3] Inference Efficiency and Graph Analytics

Global search: 'What are the main techniques for making LLMs more efficient...'
  Relevant: Model Compression via Quantisation (score=0.92)
  Relevant: Inference Efficiency and Graph Analytics (score=0.85)
  Skipped:  Language Model Architectures and Alignment
  Skipped:  Retrieval and Knowledge Graph Systems

=== Final Answer ===
Two primary families of techniques reduce LLM inference cost. First, quantisation
(GPTQ, AWQ) compresses model weights from FP16 to INT8 or INT4, reducing memory
footprint and accelerating memory-bandwidth-bound decoding with minimal accuracy
loss. Second, KV cache management trades memory for compute by storing attention
keys and values from prior tokens, eliminating redundant recomputation during
autoregressive generation...

What Just Happened?

The five steps above implement the full GraphRAG pipeline from the Edge et al. paper. Let's walk through each one carefully.

Step 1: Text Chunking and Entity Extraction

GraphRAG starts by splitting documents into chunks. The paper recommends 1200 tokens per chunk, having tested the range 300-2400 tokens. Shorter chunks give more precise entity attribution; longer chunks preserve more context for the LLM.

For each chunk, an LLM extracts a structured JSON payload:

  • Entities: {name, type, description} tuples for every named concept, model, tool, or algorithm mentioned.
  • Relationships: {source_entity, target_entity, description, strength} for every connection between entities that the text makes explicit.
  • Claims (optional): {subject, object, type, claim_text, evidence} for factual assertions. Our implementation skips this for brevity.

The paper introduces "gleanings": after the first extraction pass, the LLM is prompted again to find any entities or relationships it missed. Multiple gleanings increase recall at the cost of extra API calls. Our quick-win code does one pass per chunk; the notebook includes a gleaning loop.

Step 2: Graph Construction

After extracting from all chunks, we merge results into a single property graph using NetworkX:

  • Nodes represent canonical entities. If the same entity name appears in multiple chunks, its descriptions are concatenated rather than duplicated.
  • Edges represent relationships. If the same pair of entities is connected in multiple chunks, edge strength accumulates (capped at 1.0).

The result is a property graph where every node carries a description and every edge carries a description and a numeric weight. This is richer than a plain adjacency matrix: the descriptions carry meaning that the LLM can read later.

Knowledge graph with entity nodes and weighted edges coloured by entity type

Step 3: Community Detection

A raw entity graph is hard to query at corpus scale. GraphRAG groups entities into communities using the Leiden algorithm (or Louvain, as in our quick-win). The Leiden algorithm, introduced by Traag et al. (2019), improves on Louvain by guaranteeing that every community is well-connected internally, preventing the poorly-connected splits that Louvain can produce.

The paper runs Leiden at multiple resolution levels to produce a hierarchy:

  • Level 0 (root): A handful of very coarse communities, each covering a broad theme.
  • Deeper levels: Finer communities corresponding to narrower subtopics.

This hierarchy is important: different query types are best answered at different levels. We return to this in the Going Deeper section.

Step 4: Community Report Generation

For each detected community, an LLM reads all entity descriptions and internal edges and writes a structured report:

  • Title: A short, descriptive label for the community.
  • Summary: One or two sentences explaining what this community represents.
  • Key themes: The main topics.
  • Most important entities: Which nodes are central to this community.

These reports, not the raw chunks, are the primary retrieval unit in GraphRAG. They are pre-computed at indexing time, which is why Global Search can afford to scan all of them at query time.

Step 5: Global Search via Map-Reduce

For a synthesis query, GraphRAG does not retrieve a handful of matching chunks. Instead it runs every community report through an LLM that rates the report's relevance to the query (the map step). Reports below a relevance threshold are discarded. The surviving partial answers are then combined in a single reduce call that synthesises the final response.

This map-reduce structure guarantees corpus coverage. No community is silently skipped because its embedding happened to miss the query vector. Every community gets evaluated explicitly.

Going Deeper

GraphRAG offers two fundamentally different query modes. Choosing the right one matters.

Global Search is for questions that require synthesising across the entire corpus: "What are the main recurring themes?", "How do these authors disagree?", "What has changed in this field over time?". It maps over all community reports and performs a reduce step. Every community is seen; nothing is missed. The cost is O(ncommunities)O(n_{\text{communities}}) LLM calls at query time, which can add up for large corpora with many fine-grained communities.

Local Search is for questions anchored to specific entities: "What do these documents say about GPTQ?", "Tell me everything about the KV cache". It works like this:

  1. Embed the query and find the nearest entity nodes in the graph.
  2. Retrieve each entity's description, its direct neighbourhood (linked entities), and the community report for the community it belongs to.
  3. Also retrieve the raw source chunks that mention this entity.
  4. Feed all of this context into a single LLM synthesis call.

Local Search is cheaper and faster than Global Search. Use it whenever the question has a clear entity focus.

The Leiden Hierarchy and Level Selection

The paper tests community levels from root (coarsest) to leaf (finest) on two corpora: a podcast transcript dataset and a news article dataset, both around 1 million source tokens.

The evaluation results reveal a consistent pattern:

  • Root level (fewest, broadest communities): highest answer Diversity, but lower Comprehensiveness. The broad summaries cover many angles but miss specific detail.
  • Intermediate levels: the sweet spot. Comprehensiveness and Diversity are both strong. The paper recommends this level for most synthesis queries.
  • Leaf level (many fine-grained communities): highest Comprehensiveness on narrow topics, but at the cost of many more map calls and lower Diversity.

In practice you pick the level that matches your query granularity. A question about broad strategic themes wants a coarser level; a question about a specific subtopic wants a finer one.

The Cost Model

Indexing cost is the main barrier to adoption:

  • The paper reports consuming approximately 26 million to 85 million LLM tokens to index 1 million source tokens.
  • A 26x to 85x token multiplier on top of your raw document size.
  • At 2026 pricing, indexing a 10 million token corpus could cost several hundred dollars.

The cost breaks down roughly as:

  1. Entity extraction: one LLM call per chunk (typically the largest cost).
  2. Gleaning passes: additional calls per chunk.
  3. Community report generation: one LLM call per community.

Indexing is a one-time cost per corpus version. If your documents rarely change, the per-query savings from cached community reports can offset the indexing cost over many queries. If your corpus updates frequently, the re-indexing cost must be factored in.

When NOT to Use GraphRAG

GraphRAG is not always the right choice. Avoid it when:

  • Your queries are factoid, not synthetic. "What year was GPT-4 released?" is answered perfectly by standard RAG. GraphRAG adds cost and latency for no benefit.
  • Your corpus is small. Below roughly 50,000 tokens, standard RAG with a good reranker will match GraphRAG quality at a fraction of the cost.
  • Your documents change frequently. Re-indexing a rapidly-updating corpus is expensive.
  • Latency is critical. The map step at query time adds multiple LLM calls compared to a single RAG call.

Use GraphRAG when you have a large, relatively stable corpus and users need to ask open-ended synthesis questions that span the whole collection.

LlamaIndex GraphRAG V2 vs the Paper

LlamaIndex ships a GraphRAGQueryEngine that lets you stand up a GraphRAG-style system quickly. But comparing it against the paper reveals several gaps:

CapabilityEdge et al. (2024)LlamaIndex GraphRAG V2
Community hierarchy levelsMultiple (full Leiden hierarchy)Single level only
Global SearchTrue map-reduce over all communitiesEntity-embedding lookup to find relevant communities (not all communities)
Entity descriptions at retrievalUsed in Local Search contextExtracted but not used during retrieval
Claim extractionSupportedNot implemented
Multiple gleanings per chunkYesNo
Map-reduce relevance ratingExplicit per-community LLM ratingNot implemented; sequential aggregation

The most important gap is in Global Search. LlamaIndex's implementation uses embedding similarity to select which community reports to look at, which reintroduces the coverage blind spot that Global Search is specifically designed to eliminate. If a community's embedding does not match the query vector well, it is silently skipped, exactly the problem the paper solves.

Here is how you would use LlamaIndex GraphRAG V2 for comparison:

# pip install llama-index llama-index-packs-graph-rag-context
from llama_index.packs.graph_rag_context import GraphRAGQueryEngine, GraphRAGExtractor

from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter

# Load documents and chunk
documents = SimpleDirectoryReader(input_dir="./docs").load_data()
splitter = SentenceSplitter(chunk_size=1200, chunk_overlap=100)
nodes = splitter.get_nodes_from_documents(documents)

# Extract graph and build communities
graph_extractor = GraphRAGExtractor()
# (Internally builds entity graph and runs community detection)
graph_store = graph_extractor.extract(nodes)

# Build index over community reports
index = VectorStoreIndex(nodes)
query_engine = GraphRAGQueryEngine(
    graph_store=graph_store,
    index=index,
    llm=llm,
)

response = query_engine.query("What are the main themes across these documents?")
print(response)

This is a practical starting point for production use. Just be aware of what the paper's Global Search guarantees that this implementation does not provide.

Where This Comes From

This tutorial is based on Edge, D., Trinh, H., Cheng, N., Bradley, J., Chao, A., Mody, A., Truitt, S., & Larson, J. (2024). "From Local to Global: A Graph RAG Approach to Query-Focused Summarisation." arXiv:2404.16130.

The Problem They Were Solving

The authors frame their motivation precisely. Standard RAG was designed for "local" queries: questions whose answers are concentrated in specific passages. It fails for "global" queries that require understanding of the entire corpus. The information retrieval literature calls this task "query-focused summarisation" (QFS), but classical QFS methods do not scale to million-token corpora.

GraphRAG bridges these two traditions: it uses LLMs for information extraction and report generation at scale, and uses graph analytics to impose structure that enables corpus-wide synthesis.

The Formal Pipeline

Let D\mathcal{D} be the document corpus, split into chunks {c1,c2,…,cn}\{c_1, c_2, \ldots, c_n\}. For each chunk cic_i, an LLM extracts a set of entities EiE_i and relationships RiR_i. The union G=(⋃Ei,⋃Ri)G = (\bigcup E_i, \bigcup R_i) is the raw entity graph.

Leiden community detection partitions GG into communities {C1,C2,…,Ck}\{C_1, C_2, \ldots, C_k\} at each resolution level ℓ\ell. For each community Cj(ℓ)C_j^{(\ell)}, an LLM generates a report rj(ℓ)r_j^{(\ell)}.

For a Global Search query qq, the map step scores each report:

sj=LLM-score(q,rj(ℓ))s_j = \text{LLM-score}(q, r_j^{(\ell)})

The reduce step synthesises the relevant reports:

a^=LLM-reduce ⁣(q,  {rj:sj>τ})\hat{a} = \text{LLM-reduce}\!\left(q,\; \{r_j : s_j > \tau\}\right)

where τ\tau is a relevance threshold. Note that the map step processes all kk communities, not a retrieved subset.

Evaluation Design

The authors evaluated on two corpora: a podcast conversation dataset and a news article dataset, each approximately 1 million source tokens. They chose these specifically because they are long, heterogeneous, and unsuited to factoid QA.

The query set consisted of "sensemaking" queries: open-ended questions about themes, patterns, and relationships that require reading the whole corpus to answer well. Five example queries were generated per dataset using an LLM instructed to produce the kinds of questions an analyst might ask after reading the entire collection.

Evaluation used human pairwise comparisons on four dimensions, following the SummEval framework:

  • Comprehensiveness: Does the answer cover all relevant aspects of the question?
  • Diversity: Does the answer present a range of perspectives and information?
  • Empowerment: Does the answer give the reader enough information to form their own view?
  • Directness: Is the answer specific and focused rather than vague?

Key Results

The paper's main finding: GraphRAG (at an intermediate community level) outperforms naive RAG on Comprehensiveness and Diversity for sensemaking queries. Naive RAG scores higher on Directness because its shorter, chunk-focused answers are more pointed. The tradeoff is expected: synthesis requires breadth, which costs some directness.

MethodComprehensivenessDiversityEmpowermentDirectness
GraphRAG (intermediate)BestBestComparableLower
Naive RAGLowerLowerComparableBest
Community summaries onlyComparableComparableComparableLower

Within GraphRAG levels, the root level scores highest on Diversity (broad themes) but lower on Comprehensiveness. Intermediate levels balance both. Leaf levels are most comprehensive for narrow queries but generate many more map calls.

The Community Detection Choice

The paper uses the Leiden algorithm (Traag, Waltman, and van Eck, 2019) rather than Louvain. The distinction matters in practice. Louvain's greedy modularity optimisation can produce communities where nodes are only weakly connected to each other despite high internal density (the so-called "disconnected community" problem). Leiden adds a refinement phase that splits such communities, guaranteeing that every community is internally well-connected. For knowledge graph applications, where you want communities to represent coherent topic clusters, this guarantee is valuable.

The Honest Cost Picture

The paper discloses indexing costs clearly. On the podcast corpus, 1 million source tokens required approximately 26 million LLM tokens to index. On the news corpus, the multiplier was around 85x. The difference stems from document density: denser, more fact-rich text generates more entities per chunk, which requires more report-generation calls.

These numbers translate to real money. At gpt-4o-mini pricing (roughly $0.15 per million input tokens in 2026), indexing 1 million source tokens costs between $4 and $13 in extraction alone. Indexing a 100-million-token enterprise corpus could therefore cost $400-$1,300 in LLM API calls, before any query-time costs.

The paper is candid about this: GraphRAG is a preprocessing investment. It pays off when the corpus is stable and queried many times, because the community reports amortise the indexing cost over many cheap map-reduce queries.

Interactive Tools

  • LLM Cost Calculator: Estimate how much your GraphRAG indexing and query runs will cost across different models. The input-token cost for the extraction phase is the main variable to optimise.
  • Distribution Explorer: The modularity score that community detection optimises follows a distribution over graph partitions. Use this to build intuition for what the algorithm is maximising.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions