Back to Tutorials
LLM Application Development
Advanced

Knowledge Graphs and LLMs: Follow the Links

A small model turns a company wiki into a graph. Compare it with the truth, repair it with a schema, then answer questions that need two or three linked facts, by search and by walking the graph.

11 minInteractive: drag, click and try things as you read


RAG finds the pages that look most like your question and hands them to a model. That works when one page holds the answer. Ask “which projects would be affected by a security flaw in decimalplus?” and the answer is spread across pages that never mention each other: decimalplus is used by ledgerkit, ledgerkit is used by Atlas. A knowledge graph stores facts as links between things, so you can follow them. Here you’ll build one from a small company wiki with a language model, then answer 18 questions both ways. When the answer is a chain of facts spread over several pages, follow the links instead of searching for look-alikes.

A knowledge graph is a set of entities, the things you care about, joined by relations. Each fact is a triple: subject, relation, object, such as (Atlas, uses, ledgerkit) or (ledgerkit, depends_on, decimalplus). Once facts are stored that way, questions become walks: start at decimalplus, follow “depends on” backwards to every library that needs it, then “uses” backwards to every project.

Our test bed is Larkspur, a made-up software company with 30 short wiki pages: six projects, twelve libraries, four teams, eight people and three offices. Each page describes one of them in plain sentences, the way people actually write: “Atlas uses ledgerkit for currency maths and chartly for its charts.” To turn pages into a graph, we asked Qwen3-1.7B, a small open model, to read each page and list its facts as triples, using only nine relations: uses, built_by, depends_on, maintained_by, leads, member_of, works_in, based_in, and does (what a project or library is for). Because we wrote the wiki, we know the true graph behind it: 57 links.

Predict first

How many of the 57 true links does the 1.7-billion-parameter model extract correctly from the 30 pages?

Try it
The company and its wiki were written for this explainer. The extracted facts are exactly what Qwen3-1.7B wrote, run offline, with names matched to the wiki’s spelling (ignoring case and “the”). Click a name to see its facts.

A wrong-way fact can be worse than a missing one: given “Data team is built by Compass.”, the model answered that Compass is built by Compass. The fix doesn’t need a better model. Every relation joins two particular kinds of thing: built_by goes from a project to a team, maintained_by from a library to a person. Check each extracted fact against that list, called a schema: keep it if its two ends are the right kinds, flip it if they’re the wrong way round, and drop it if it fits neither. That’s a few lines of code. Switch the figure to “Checked against the schema”: 50 right links, 2 wrong and 7 missing, from 36 right, 30 wrong and 21 missing. Check extracted facts against a schema of what can link to what: it’s cheap, and it fixed most of the model’s mistakes.

Ask both ways#

Now the questions. Six need one fact (“Who leads the Mobile team?”), eight need two linked facts (“Who leads the team that builds Ember?”), and four need three or more (“Which team leads should hear about a bug in httpkit?”). Each question goes to the same model two ways. Vector search embeds the question and hands over the 3 or 6 most similar pages. The graph walk finds the names the question mentions, follows every link out from them for 1 to 4 steps, or hops, and hands over the facts it passed, as plain sentences.

Predict first

“Which projects would be affected by a security flaw in decimalplus?” Search hands the model the 3 pages most like the question. What does it answer?

Try it
The pages are ranked in your browser by the similarity of their embeddings (all-MiniLM-L6-v2) to the question’s, and the graph walk runs in your browser on the extracted graph. The answers are Qwen3-1.7B’s, run offline on exactly these pages and facts, and graded in your browser: right means every item named and nothing extra of the same kind.

The table under the figure sums up all 18 questions. Search is hard to beat for one fact: 6 of 6, because the page that answers it looks like the question. With two linked facts it got 1 of 8, and with three or more, none. The graph as extracted helped with two facts (4 of 8 at 2 hops) but lost two of the one-fact questions to its backwards links. The schema-checked graph did best: 5 of 6, and 6 of 8 two-fact questions at 3 hops. Questions that need three or more facts stayed hard: the walk puts every fact in front of the model, but a 1.7B model still has to chain them in its head, and it often names some of the answers but not all. More hops isn’t always better, either: at 4 hops the checked graph hands over two-thirds of all its facts, on average, and two-fact answers drop to 3 of 8. A graph walk gets the linked facts in front of the model; for long chains, let code do the walking.

When it’s worth it#

A graph is worth building when your questions are about how things connect: what depends on what, who reports to whom, which supplier feeds which product. It costs something:

  • Extraction: a model call for every page, again whenever a page changes, and a check against a schema, as you saw.
  • Names: the same thing must get the same name everywhere. We matched “Data” to “Data team” and ignored “the”; real documents need more of this, called entity resolution.
  • Choosing hops: too few and the answer is out of reach; too many and the model drowns in facts.

For questions answered by one page, plain search is simpler and did better here. Between the two, you can also let a model search more than once, rewriting its query from what the first search found. And for broad questions about a whole collection (“what are the main themes?”), Microsoft’s GraphRAG goes further: it groups the graph into communities of related entities and summarises each one in advance.

In code#

For questions that are really queries, such as “everything that depends on X”, you don’t need a model at query time at all. With the facts in a graph library such as networkx (pip install networkx), the walk is a function call:

import networkx as nx

# facts as (subject, relation, object): in practice, extracted by a model and checked
facts = [
    ("Atlas", "uses", "ledgerkit"), ("Atlas", "uses", "chartly"), ("Atlas", "built_by", "Payments team"),
    ("Compass", "uses", "chartly"), ("Compass", "uses", "tablestream"), ("Compass", "built_by", "Data team"),
    ("Drift", "uses", "ledgerkit"), ("Drift", "uses", "mlcore"), ("Drift", "built_by", "Data team"),
    ("ledgerkit", "depends_on", "decimalplus"), ("tablestream", "depends_on", "decimalplus"),
    ("mlcore", "depends_on", "tablestream"), ("chartly", "depends_on", "colorwheel"),
]
G = nx.MultiDiGraph()
for s, r, o in facts:
    G.add_edge(s, o, relation=r)

def uses_of(lib):
    """Everything that depends on lib, directly or through other libraries."""
    deps = nx.DiGraph((s, o) for s, o, r in G.edges(data="relation") if r in ("uses", "depends_on"))
    return nx.ancestors(deps, lib)

def built_by(n):
    return [o for _, o, r in G.out_edges(n, data="relation") if r == "built_by"]

projects = sorted(n for n in uses_of("decimalplus") if built_by(n))  # projects are what teams build
print("Projects affected by a flaw in decimalplus:", projects)
teams = sorted({t for p in projects for t in built_by(p)})
print("Teams to tell:", teams)
print("The path from Drift:", nx.shortest_path(G, "Drift", "decimalplus"))
# Projects affected by a flaw in decimalplus: ['Atlas', 'Compass', 'Drift']
# Teams to tell: ['Data team', 'Payments team']
# The path from Drift: ['Drift', 'ledgerkit', 'decimalplus']

The model’s job then shrinks to two things it’s good at: pulling facts out of text, once, when pages change, and turning the facts a query finds into a readable answer.

What to remember

  • A knowledge graph stores facts as links between things, so a question that spans several pages becomes a walk from one name to the next.
  • A small model extracted 36 of 57 true links and wrote 30 wrong ones, many of them backwards; checking each fact against a schema left 50 right and only 2 wrong.
  • Search answered one-fact questions best but only 1 of 8 two-fact ones; a walk through the checked graph got 6 of 8, and for long chains a graph query beats asking the model.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.