🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Knowledge Graphs Meet LLMs: Graph RAG and Beyond

đŸŸĸ Free Lesson

Knowledge Graphs with LLMs

Vectors find similar text. Graphs answer questions that require several connected facts at once.

Graph RAG

Prerequisites

  • !Triples, entities and relations
  • !Vector retrieval and embeddings
  • !Multi-hop reasoning as a question type

What You'll Learn

  • 1State what a graph knows that a vector index cannot represent
  • 2Extract and normalize triples from unstructured text with an LLM
  • 3Run multi-hop queries that plain RAG answers incorrectly
  • 4Decide when graph structure is worth its maintenance cost

Two memory systems, two strengths

A vector index answers "what text resembles this query". That is a similarity question, and similarity is not the same as connection. When someone asks which suppliers serve factories that ship to a region under a new tariff, the answer is not a passage somewhere in the corpus — it is a path through three relations, each of which may be documented in a different document entirely.

A knowledge graph represents facts as triples: a subject, a predicate, an object. Acme partners with Northwind; Northwind ships to Ontario; Ontario just imposed a tariff. Each fact is small, addressable and independently verifiable, and questions about their composition become graph traversals rather than retrieval guesses.

Language models and graphs correct each other's weaknesses. The model is fluent but ungrounded: it can narrate a plausible relationship that no document supports. The graph is precise but rigid: it cannot interpret a novel phrasing or fill a gap that was never extracted. Used together, the graph constrains what the model may claim, and the model supplies the interpretation the graph cannot — parsing messy text into triples and turning traversals into prose.

There is also an organizational benefit. A graph makes the factual surface area of a domain explicit and reviewable. Stakeholders can look at the relation vocabulary and the entity list and tell you where it is wrong, which is not something anyone can do with an opaque embedding space. That reviewability is often what turns a research prototype into a system a compliance team will approve.

Extracting triples from messy text

Extraction is a schema problem before it is a model problem. Define the relation vocabulary you will accept in advance — worksFor, suppliesTo, locatedIn — and constrain the model to emit only those, rather than letting it invent predicates that fragment the graph into synonyms of each other.

python
import json
from openai import OpenAI

ALLOWED_RELATIONS = {
    "worksFor", "foundedBy", "locatedIn", "suppliesTo",
    "partnersWith", "competesWith", "reportsTo", "investsIn",
}

client = OpenAI()

def extract_triples(document_text):
    """Emit normalized triples constrained to a fixed relation set."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        messages=[
            {
                "role": "system",
                "content": "Extract facts as JSON triples with keys subject, "
                           "predicate, object. Use ONLY these predicates: "
                           + ", ".join(sorted(ALLOWED_RELATIONS))
                           + ". Emit an empty list if nothing qualifies.",
            },
            {"role": "user", "content": document_text},
        ],
        response_format={"type": "json_object"},
    )
    payload = json.loads(response.choices[0].message.content)
    triples = []
    for t in payload.get("triples", []):
        if t.get("predicate") not in ALLOWED_RELATIONS:
            continue
        triples.append({
            "subject": normalize_name(t["subject"]),
            "predicate": t["predicate"],
            "object": normalize_name(t["object"]),
            "source": document_text[:200],
            "confidence": float(t.get("confidence", 0.5)),
        })
    return triples

def normalize_name(name):
    """Collapse surface variants so the same entity keeps one node."""
    return " ".join(name.strip().lower().split())

Carry provenance on every triple. A fact without a source document cannot be cited, audited or retracted, and systems that drop provenance during extraction find themselves unable to answer the first question a skeptical user asks: where did that come from?

Identity resolution decides whether the graph works

The failure mode that ruins knowledge graphs is not bad extraction — it is the same real-world entity appearing as three nodes. Acme Corp, ACME Corporation and Acme Corp. must resolve to one node, or every query under-retrieves because the facts are scattered across near-duplicates.

python
def resolve_entities(candidates, threshold=0.86):
    """Greedy clustering of surface forms into canonical entities."""
    canonical = []
    for cand in candidates:
        best, best_score = None, 0.0
        for node in canonical:
            score = name_similarity(cand, node["aliases"])
            if score > best_score:
                best, best_score = node, score
        if best is not None and best_score >= threshold:
            best["aliases"].add(cand)
        else:
            canonical.append({"id": f"e{len(canonical)}", "aliases": {cand}})
    return canonical

Deterministic rules handle most of it: strip corporate suffixes, fold case and punctuation, match on known identifiers when they exist. Embedding similarity handles the rest, but only above a conservative threshold — merging two distinct companies is far more damaging than leaving two aliases separate, because a bad merge silently corrupts every query that touches the merged node.

Keep a review queue for proposed merges rather than applying them automatically at scale. When a merge is confirmed, every edge attached to the absorbed node must be rewritten to the canonical one, and that rewrite has to be transactional — a half-applied merge leaves the graph in a state no query planner expects.

Graph RAG for multi-hop questions

Plain retrieval fails multi-hop questions because no single chunk contains the answer. Graph RAG retrieves by traversal: start from entities mentioned in the question, walk the relevant relations, and give the model both the path and the source documents so it can write a grounded answer.

python
def graph_rag(question, graph, retriever, max_hops=3):
    """Retrieve a subgraph around question entities, then answer with citations."""
    entities = link_entities(question)
    subgraph = graph.expand(entities, hops=max_hops, limit=25)

    context_lines = [
        f"{e['subject']} -[{e['predicate']}]-> {e['object']} "
        f"(source: {e['source_id']})"
        for e in subgraph
    ]
    passages = retriever.search(question, k=4)

    prompt = (
        "Answer using ONLY the facts below. Cite the fact ids you used. "
        "If the facts do not contain the answer, say so explicitly.\n\n"
        "FACTS:\n" + "\n".join(context_lines) +
        "\n\nPASSAGES:\n" + "\n".join(p["text"] for p in passages) +
        f"\n\nQUESTION: {question}"
    )
    return client.chat.completions.create(
        model="gpt-4o-mini",
        temperature=0,
        messages=[{"role": "user", "content": prompt}],
    ).choices[0].message.content

The instruction to cite fact ids is doing real work. It forces the model to bind each claim to a specific edge, which makes unsupported assertions both harder to write and easy to verify by checking the cited ids against the graph.

Grounding answers against the graph

Verification closes the loop. After generation, parse the cited fact ids and confirm they exist and actually support the sentence they are attached to. Claims with no citation are flagged; citations whose edges do not entail the claim are flagged too.

CheckCatchesAction on failure
Citation existsHallucinated fact idsRegenerate or refuse
Edge supports claimMisquoted or overstated factsRewrite the sentence
Recency of edgeStale facts surviving updatesRe-retrieve and retry
Confidence thresholdWeak extractions entering answersDrop the edge from context
Contradiction scanConflicting edges in the graphEscalate for review

Contradiction detection deserves special attention because graphs accumulate conflicts: one document says a person left a company in March, another from June still lists them. Store temporal validity on edges and prefer the most recent, but surface unresolved conflicts rather than silently picking a winner.

Storage choices and when to skip the graph

You do not need a dedicated graph database to start. The table below maps common scales to workable options, and the honest advice is that the simplest option meeting your needs will be maintained by the team you actually have.

ScaleWorkable storeTrade-off
Under 100k edgesRelational tables or JSONSimplest operations, limited traversal speed
Millions of edgesDedicated graph databaseFast multi-hop queries, new operational surface
Mixed workloadsGraph plus vector storeTwo systems to keep in sync
Exploratory analysisIn-memory graph libraryFast iteration, no persistence guarantees

Skip the graph entirely when questions rarely need more than one fact at a time, when the corpus changes faster than triples can be refreshed, or when nobody owns the schema. A mediocre graph that drifts out of date produces answers that are confidently wrong — worse than a vector search that merely misses. Build one when multi-hop questions are a real and recurring need, and start with a narrow relation vocabulary you can maintain.

Whatever store you choose, plan the refresh path before the initial load. Documents arrive continuously, extractions occasionally contradict each other, and edges go stale. A pipeline that can re-extract a source document and replace every edge it produced — rather than appending blindly — keeps the graph reconcilable with the corpus that supposedly justifies it.

âš ī¸Schema drift is the silent killer

Without a fixed predicate vocabulary and an owner for it, every extraction run invents slightly different relations. Constrain predicates at extraction time and review the distribution monthly.

Common Mistakes

Letting the model invent its own predicates during extraction

Fix: Constrain to a fixed relation vocabulary and drop anything outside it at write time.

Skipping entity resolution because extraction demos looked clean

Fix: Cluster aliases conservatively and review merges — a bad merge corrupts every query that touches the node.

Generating answers from the graph without requiring citations

Fix: Require fact ids per claim and verify each cited edge still exists and supports the sentence.

Best Practices

  • Carry provenance and timestamps on every triple you store
  • Prefer a narrow, well-owned relation vocabulary over an expressive one
  • Combine graph paths with text passages so the model can phrase and cite
  • Use graph RAG specifically for multi-hop questions; keep plain vector search for the rest
  • Store temporal validity so stale edges lose to fresher ones automatically

Key Takeaways

  • Graphs answer composition questions that similarity search cannot
  • Extraction needs a fixed relation vocabulary and provenance on every edge
  • Identity resolution quality determines whether multi-hop queries find anything
  • Citation verification turns generation into a checkable claim rather than a plausible one
  • Maintenance cost is the real price of a graph — build one only for recurring multi-hop needs
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement