AI Hints
Home›RAG Tutorial›Graphs and Images
RAG · Lesson 91 of 120

GraphRAG

Entities and links.

⏱ 2 min read▶ Video at 1:29:22🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Some questions are about connections. Tell me everything about the Volt Pro needs facts from the price list, the manual, the error codes, and the warranty. GraphRAG links pages through the things they mention, called entities.

GraphRAG
From the video: GraphRAG
  • Questions about connections
  • Facts on many pages
  • Link through entities

A tiny knowledge graph

Entities is a short list of things we care about. We link each entity to every chunk that mentions it, using a networkx graph. To answer a question about the Volt Pro, we follow its links. Run it. The Volt Pro links to chunks from several pages.

graph.pypython
import networkx as nx
from rag_kit import load_docs, make_chunks

chunks = make_chunks(load_docs())
entities = ["Volt Pro", "York", "Leeds", "E05"]

graph = nx.Graph()
for i, c in enumerate(chunks):
    for e in entities:
        if e in c["text"]:
            graph.add_edge(e, i)

linked = sorted({chunks[i]["source"] for i in graph.neighbors("Volt Pro")})
print("Volt Pro links to:", linked)
print("York links to:    ", sorted({chunks[i]["source"] for i in graph.neighbors("York")}))
Output
Volt Pro links to: ['ebike_errors.md', 'price_list_2025.md', 'price_list_2026.md']
York links to:     ['rentals.md', 'stores.md']
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

GraphRAG in practice

Real GraphRAG uses a model to extract entities and relations from every chunk. It also summarises groups of related entities. That helps with broad questions, like what are the main themes, but it's costly to build.

keyvalue
Entitiesextracted by a model
Relationslinks between them
Good forbroad questions
Costhigh to build

Summary

GraphRAG links chunks through shared entities, so one question can gather facts from many pages. Next, images.

Key takeaways
  • Entities
  • Links
  • Gather across pages
Next up: Multimodal RAG — images too