TAI BUI
Back to curriculum
BuildPython

Relation Extraction & Knowledge Graph Construction

NER found the entities. Entity linking anchored them. Relation extraction draws the edges between them. A knowledge graph is the sum of nodes, edges, and their provenance.

TIME: ~60 minutesPREREQUISITES: Phase 5 · 06 (NER), Phase 5 · 24 (Coreference Resolution), Phase 5 · 25 (Entity Linking)

Learning Objectives

  • Convert a sentence into (subject, relation, object) triples and explain how aggregated triples become a queryable knowledge graph.
  • Compare rule/pattern-based, supervised-classifier, and generative-LLM relation extraction, and pick the right one for a given precision/recall target.
  • Apply the AEVS (Anchor-Extraction-Verification-Supplement) pipeline to catch hallucinated triples, and explain why span verification alone doesn't catch a wrong relation between two real spans.
  • Canonicalize open-IE relations onto a closed ontology (e.g. Wikidata property ids) and explain why this step, not the extractor, eats most of the engineering budget.
  • Identify the production pitfalls that break a relation-extraction pipeline: missing coreference, unlinked entity surface forms, missing temporal qualifiers, and domain mismatch.

The Problem

An analyst reads: "Tim Cook became CEO of Apple in 2011." That one sentence hides four facts:

  • (Tim Cook, role, CEO)
  • (Tim Cook, employer, Apple)
  • (Tim Cook, start_date, 2011)
  • (Apple, type, Organization)

Relation extraction (RE) turns free text into structured triples: (subject, relation, object). Aggregate those triples across a corpus and you have a knowledge graph. Aggregate and query them and you have a reasoning substrate for RAG, analytics, or compliance audits.

Here's the 2026 problem: LLMs extract relations enthusiastically. Too enthusiastically. They hallucinate triples the source text never supported, and without provenance you can't tell a real triple from a plausible fiction. The 2026 answer is AEVS-style anchor-and-verify pipelines.

Warm-up0/3
1. NER tags "Tim Cook" and "Apple" as two separate entities in a sentence. What has NER not told you yet?Warm-up
2. In the text "Maria founded the firm. She sold it later.", who does the word "She" refer back to?Warm-up
3. A system must decide whether the mention "Jaguar" in a news story means the animal or the car brand by pointing it at one knowledge-base entry. What is this task called?Warm-up
Check: The Problem0/3
1. What is the atomic unit of a knowledge graph?Define
2. In relation extraction, what is a knowledge graph?Define
3. How many facts does the lesson find hidden in "Tim Cook became CEO of Apple in 2011."?Apply

The Concept

Triple form. (subject_entity, relation_type, object_entity). Relations come from a closed ontology (Wikidata properties, FIBO, UMLS) or an open set, OpenIE (Open Information Extraction)-style, where anything goes.

Text → triples → knowledge graph

Three extraction approaches.

  1. Rule / pattern-based. Hearst patterns: "X such as Y" → (Y, isA, X). Plus hand-crafted regex. Brittle, precise, explainable.
  2. Supervised classifier. Given two entity mentions in a sentence, predict the relation from a fixed set. Trained on TACRED, ACE, KBP. Standard 2015–2022.
  3. Generative LLM. Prompt the model to emit triples. Works out of the box, but needs provenance or it hallucinates plausible-looking junk.

AEVS (Anchor-Extraction-Verification-Supplement, 2026). The current hallucination-mitigation framework:

  • Anchor. Identify every entity span and relation-phrase span with exact positions.
  • Extract. Generate triples linked to anchor spans.
  • Verify. Match each triple element back to the source text; reject anything unsupported.
  • Supplement. A coverage pass ensures no anchored span is dropped.

Hallucinations drop sharply, though the pipeline costs more compute. The upside: it's auditable.

The open-vs-closed tradeoff.

  • Closed ontology. A fixed property list, like Wikidata's 11,000+ properties. Predictable and easy to query, but effectively closed to new relations.
  • Open IE. Any verbal phrase becomes a relation. Recall is high, precision is low, and the output is messy to query.

Production KGs usually mix both: open IE for discovery, then canonicalize relations onto a closed ontology before merging into the main graph.

Check: The Concept0/13
1. What are the three extraction approaches the lesson names for relation extraction?Define
2. Which datasets does the lesson name as the training sets for the standard 2015-2022 supervised relation classifiers?Define
3. What is Open IE?Define
4. What is a closed ontology?Define
5. What does AEVS stand for in 2026 relation extraction?Define
6. What is provenance for a triple?Define
7. What is distant supervision?Define
8. Why must each triple carry source provenance (doc id + span)?Explain
9. Which choice trades open IE recall for graph queryability?Explain
10. What does the Supplement step of AEVS do?Explain
11. How does a supervised relation classifier differ from a generative LLM extractor?Explain
12. An AEVS pipeline checks that a triple's subject span and object span both match the source text exactly, and the triple passes. What can still be wrong with it?Analyze
13. You are building a knowledge graph from scratch and do not yet know which relations the corpus contains. Which approach fits?Design

Build It

Step 1: pattern-based extraction

python
PATTERNS = [
    (r"(?P<s>[A-Z]\w+) (?:is|was) (?:a|an|the) (?P<o>[A-Z]?\w+)", "isA"),
    (r"(?P<s>[A-Z]\w+) (?:is|was) born in (?P<o>\w+)", "bornIn"),
    (r"(?P<s>[A-Z]\w+) works? (?:at|for) (?P<o>[A-Z]\w+)", "worksAt"),
    (r"(?P<s>[A-Z]\w+) founded (?P<o>[A-Z]\w+)", "founded"),
]

See code/main.py for the full toy extractor. Hearst patterns still ship in domain-specific pipelines because they are debuggable.

Step 2: supervised relation classification

REBEL (Babelscape) is the standard open-weights baseline for this approach: a seq2seq model that reads text and generates triples already tagged with Wikidata property ids, fine-tuned on distant-supervision data. Load it like any other Hugging Face checkpoint:

python
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
 
tok = AutoTokenizer.from_pretrained("Babelscape/rebel-large")
model = AutoModelForSeq2SeqLM.from_pretrained("Babelscape/rebel-large")
 
text = "Tim Cook was born in Alabama. He later became CEO of Apple."
encoded = tok(text, return_tensors="pt", truncation=True)
output = model.generate(**encoded, max_length=200)
triples = tok.batch_decode(output, skip_special_tokens=False)

Step 3: LLM-prompted extraction with anchoring

python
prompt = f"""Extract (subject, relation, object) triples from the text.
For each triple, include the exact character span in the source text.
 
Text: {text}
 
Output JSON:
[{{"subject": {{"text": "...", "span": [start, end]}},
   "relation": "...",
   "object": {{"text": "...", "span": [start, end]}}}}, ...]
 
Only include triples fully supported by the text. No inference beyond what is stated.
"""

Verify every returned span against the source. Reject anything where text[start:end] != triple_entity. This is the AEVS "verify" step in its minimal form.

Step 4: canonicalize onto a closed ontology

python
RELATION_MAP = {
    "is the CEO of": "P169",       # "chief executive officer"
    "was born in":   "P19",         # "place of birth"
    "founded":        "P112",       # "founded by" (inverted subject/object)
    "works at":       "P108",       # "employer"
}
 
 
def canonicalize(relation):
    rel_low = relation.lower().strip()
    if rel_low in RELATION_MAP:
        return RELATION_MAP[rel_low]
    return None   # drop unmapped open relations or route to manual review

Canonicalization is often 60-80% of the engineering work. Budget for it.

Step 5: build a small graph and query

python
triples = extract(text)
graph = {}
for s, r, o in triples:
    graph.setdefault(s, []).append((r, o))
 
 
def neighbors(node, relation=None):
    return [(r, o) for r, o in graph.get(node, []) if relation is None or r == relation]
 
 
print(neighbors("Tim Cook", relation="P108"))    # -> [(P108, Apple)]

This is the atom of every RAG-over-KG system. Scale it with RDF triple stores (Blazegraph, Virtuoso), property graphs (Neo4j), or vector-augmented graph stores.

Check: Build It0/9
1. What does canonicalization of relations do?Define
2. What is REBEL?Define
3. Why do Hearst-style patterns still ship in domain-specific pipelines despite being brittle?Explain
4. With the lesson's PATTERNS list, what does the "founded" pattern produce for the sentence "Marie founded Acme"?Apply
5. With the lesson's "worksAt" pattern, what happens on the sentence "He works at Apple"?Apply
6. With the lesson's RELATION_MAP, what does canonicalize(" Was Born In ") return?Apply
7. RELATION_MAP sends "founded" to P112, noted as "founded by" with subject and object inverted. What must the mapping do with (Marie, founded, Acme)?Apply
8. With graph = {"Tim Cook": [("P108", "Apple"), ("P19", "Alabama")]} and the lesson's neighbors function, what does neighbors("Tim Cook", relation="P19") return?Apply
9. The text is "Tim Cook was born in Alabama." and an LLM returns the subject "Tim Cook" with span [0, 7]. What does the lesson's verify step do?Apply

Pitfalls

  • Coreference before RE. In "He founded Apple," RE needs to know who "he" is first. Run coref before extraction (lesson 24).
  • Entity canonicalization. "Apple Inc" and "Apple" must resolve to the same node, which means entity linking runs first too (lesson 25).
  • Hallucinated triples. LLMs emit triples the text does not support. Enforce span verification.
  • Relation canonicalization drift. Open IE relations are inconsistent: "was born in," "came from," "is a native of." Collapse them to canonical ids or the graph is unqueryable.
  • Temporal errors. "Tim Cook is CEO of Apple" is true today and would have been false in 2005. Many relations are time-bounded, so use qualifiers (P580 start time, P582 end time in Wikidata).
  • Domain mismatch. REBEL trained on Wikipedia. Legal, medical, and scientific text often need domain-fine-tuned RE models.
Check: Pitfalls0/7
1. What distinct pitfall does 'entity canonicalization' name, separate from relation canonicalization?Define
2. Why does relation extraction usually need coreference resolution first?Explain
3. Your knowledge graph stores (Tim Cook, role, CEO) with no time qualifier. Two years after he steps down, what happens to that fact?Analyze
4. You run REBEL on a batch of legal contracts and precision drops far below its published Wikipedia benchmark numbers. What's the most likely cause, per the lesson?Analyze
5. A query for people born in Alabama misses people whose edge reads "is a native of" instead of "was born in". Which gap caused this?Analyze
6. A graph has two nodes, "Apple" and "Apple Inc", each holding part of the company's edges. Which upstream stage should have prevented this?Analyze
7. Your graph must record where each person has worked over a career. Which design fits?Design

Use It

The 2026 stack:

SituationPick
Fast production, general domainREBEL or a generative LLM extractor (LlamaPred-style) with Wikidata canonicalization
Domain-specific (biomed, legal)SciREX-style domain fine-tune + custom ontology
LLM-prompted, audited outputAEVS pipeline: anchor → extract → verify → supplement
High-volume news IEPattern-based + supervised hybrid
Building a KG from scratchOpen IE + manual canonicalization pass
Temporal KGExtract with qualifiers (start/end time, point in time)

The integration pattern: NER → coref → entity linking → relation extraction → ontology mapping → graph load. Every stage is a potential quality gate.

Check: Use It0/2
1. Which stage order does the lesson give for the full pipeline, and why does relation extraction sit where it does?Explain
2. You must extract relations from biomedical papers, and REBEL was trained on Wikipedia. Which approach fits?Design

Ship It

Save as outputs/skill-re-designer.md:

markdown
---
name: re-designer
description: Design a relation extraction pipeline with provenance and canonicalization.
version: 1.0.0
phase: 5
lesson: 26
tags: [nlp, relation-extraction, knowledge-graph]
---
 
Given a corpus (domain, language, volume) and downstream use (KG-RAG, analytics, compliance), output:
 
1. Extractor. Pattern-based / supervised / LLM / AEVS hybrid. Reason tied to precision vs recall target.
2. Ontology. Closed property list (Wikidata / domain) or open IE with canonicalization pass.
3. Provenance. Every triple carries source char-span + doc id. Non-negotiable for audit.
4. Merge strategy. Canonical entity id + relation id + temporal qualifiers; dedup policy.
5. Evaluation. Precision / recall on 200 hand-labelled triples + hallucination-rate on LLM-extracted sample.
 
Refuse any LLM-based RE pipeline without span verification (source provenance). Refuse open-IE output flowing into a production graph without canonicalization. Flag pipelines with no temporal qualifier on time-bounded relations (employer, spouse, position).
Check: Ship It0/1
1. A compliance team wants triples extracted by an LLM, and every fact must be traceable in an audit. Which design fits?Design
Author's Note

The part of this pipeline that eats the calendar is never the extractor. It's the mapping step: taking whatever verb phrase an LLM or REBEL handed you and deciding which Wikidata property it actually means. I've watched a team spend two weeks tuning a relation classifier and then burn six weeks arguing over whether "joined" and "hired by" collapse to the same P108 edge. Budget for canonicalization like it's the real project, not a cleanup step at the end.

The other trap is trusting a triple because the span check passed. Verification catches an LLM inventing a (Tim Cook, employer, Google) triple out of thin air. It does not catch the LLM correctly identifying two real spans and connecting them with the wrong relation. Span-matching is necessary, not sufficient. Read a sample of "verified" triples by hand before you trust the pipeline in production.

Exercises

  1. Easy. Run the pattern extractor in code/main.py on 5 news-article sentences. Hand-check precision.
  2. Medium. Use REBEL (or a small LLM) on the same sentences. Compare triples. Which extractor has higher precision? Higher recall?
  3. Hard. Build the AEVS pipeline: extract with LLM + verify spans against source. Measure hallucination rate before vs after the verify step on 50 Wikipedia-style sentences.

Key Terms

TermWhat people sayWhat it actually means
TripleSubject-relation-object(s, r, o) tuple that is the atomic unit of a KG.
Open IEExtract anythingOpen-vocabulary relation phrases; high recall, low precision.
Closed ontologyFixed schemaBounded set of relation types (Wikidata, UMLS, FIBO).
CanonicalizationNormalize everythingMap surface names / relations to canonical ids.
AEVSGrounded extractionAnchor-Extraction-Verification-Supplement pipeline (2026).
ProvenanceSource-of-truth linkEvery triple carries a doc id + char-span to its source.
Distant supervisionCheap labelsAlign text with an existing KG to create training data.

Further Reading

Code

Ships With