Information Extraction
Prerequisites
- !Named entity recognition and BIO tagging
- !Relational schemas and primary keys
- !Classification metrics on imbalanced pairs
What You'll Learn
- 1Design a target schema that downstream systems can consume without cleanup
- 2Extract relations by classifying candidate pairs with type constraints
- 3Force LLM extraction into a validated schema with a retry policy
- 4Resolve mentions to canonical entities and route uncertain tuples to review
Structure is a schema decision before it is a modelling one
Information extraction fails at the design stage more often than at the algorithm stage. The question is never "can we find facts in text" but "what exactly do we write into which table, and what happens when the text is ambiguous or the fact is only implied".
Most outputs fall into a small number of shapes. A record mirrors a document's fields â a contract clause, a form â and suits documents that follow a template. A triple (subject, relation, object) captures isolated facts and composes into a knowledge graph, but forces every relation into a closed vocabulary. An event frame carries a trigger, participants, time and location, and handles the temporality that triples discard. A link simply attaches a document to an existing entity ID, which is often all a search or filtering feature really needs.
| Output shape | Best for | Cost of a wrong entry | Requires |
|---|---|---|---|
| Field records | Templates, forms, filings | Localized | Stable layout |
| Triples | Graphs, link traversal | Spreads through reasoning | Closed relation set |
| Event frames | News, contracts, incidents | Misdates and misattribution | Temporal modelling |
| Entity links | Search, filtering, dashboards | Duplicates and orphans | Canonical ID registry |
Write the schema with the consumer in mind: name each field's owner, define what null means, and decide whether contradictory facts from two documents are two rows or one row with provenance. Extraction that ignores provenance becomes unauditable within a quarter, because nobody can say which document produced a disputed value.
Relations: classify pairs, not sentences
A sentence may hold several entities and several relations; framing the task as pair classification makes the output count predictable. Candidate generation proposes entity pairs, a classifier decides the relation, and type constraints throw away impossible combinations before the classifier ever runs.
import re
from dataclasses import dataclass
@dataclass(frozen=True)
class Mention:
text: str
start: int
end: int
etype: str # "PERSON", "ORG", "LOC", "PRODUCT", ...
TYPE_RULES = {
("ORG", "LOC"): {"headquartered_in", "operates_in"},
("PERSON", "ORG"): {"works_for", "founded", "acquired_by"},
("ORG", "ORG"): {"acquired_by", "partners_with", "subsidiary_of"},
("PRODUCT", "ORG"): {"manufactured_by"},
}
def extract_relations(text: str, mentions: list[Mention],
classify) -> list[dict]:
"""classify(a: Mention, b: Mention, sentence: str) -> (relation, conf)."""
spans = re.split(r"(?<=[.!?])\s+", text)
results = []
for sent in spans:
in_sentence = [m for m in mentions
if sent.find(m.text) != -1 or m.text in sent]
for i, a in enumerate(in_sentence):
for b in in_sentence[i + 1:]:
allowed = TYPE_RULES.get((a.etype, b.etype), set())
allowed |= TYPE_RULES.get((b.etype, a.etype), set())
if not allowed:
continue # impossible pair: skip early
rel, conf = classify(a, b, sent)
if rel not in allowed:
continue # type system says no
if conf < 0.60:
continue # below review threshold
results.append({
"subject": a.text,
"relation": rel,
"object": b.text,
"confidence": round(conf, 3),
"evidence": sent.strip(),
})
return results
Two details carry disproportionate weight. Filtering by type rules before classification removes most false positives cheaply, because a person cannot be headquartered in a city under your relation vocabulary. And storing the evidence sentence with every triple means review, audit and correction become one lookup instead of a re-extraction project.
Events: triggers, arguments and time
Event extraction adds a dimension that triples handle badly. A trigger verb or noun ("acquired", "filed", "announced") anchors the event, arguments fill participant roles, and temporal expressions pin it in time â usually relative to the document date rather than absolute.
The recurring trap is argument attachment: "A agreed to buy B from C for $2 billion last year" yields a buyer, a target, a seller, a price and a time, and a model that extracts roles without checking who did what to whom will happily swap seller and target. Mitigations are structural rather than architectural: require every argument to be a span from the sentence, require the temporal expression to be resolved against the document date with an explicit rule, and drop events with missing required arguments instead of filling defaults. An incomplete event row is honest; a confident wrong one corrupts everything downstream that joins on it.
LLM extraction with a validated schema
For unstructured text without a template, prompting an LLM with a JSON schema gets you far â provided you validate the output and treat failures as a retryable condition rather than a silent pass.
import json
import re
REQUIRED = {"subject", "relation", "object", "evidence"}
ALLOWED_RELATIONS = {"works_for", "founded", "headquartered_in",
"acquired_by", "partners_with", "manufactured_by"}
def parse_extraction(raw: str, max_retries: int = 2) -> list[dict]:
"""Parse and validate model output; retry once with the error attached."""
attempt, feedback = 0, ""
while attempt <= max_retries:
text = raw if attempt == 0 else call_model(feedback)
attempt += 1
match = re.search(r"\{[\s\S]*\}|\[[\s\S]*\]", text)
if not match:
feedback = "Response contained no JSON. Return JSON only."
continue
try:
payload = json.loads(match.group(0))
except json.JSONDecodeError as err:
feedback = f"Invalid JSON: {err}. Return JSON only."
continue
records = payload if isinstance(payload, list) else [payload]
valid = []
problems = []
for r in records:
missing = REQUIRED - set(r)
if missing:
problems.append(f"missing keys: {sorted(missing)}")
continue
if r["relation"] not in ALLOWED_RELATIONS:
problems.append(f"relation '{r['relation']}' not in vocabulary")
continue
if r["evidence"] not in text:
problems.append("evidence is not a substring of the source")
continue
valid.append({k: str(r[k]) for k in REQUIRED})
if not problems:
return valid
feedback = ("Previous output had problems: "
+ "; ".join(problems[:3]))
return [] # give up rather than ingest unvalidated rows
def call_model(feedback: str) -> str:
"""Placeholder for the actual prompt call carrying the error message."""
return f"{{'error': 're-prompt with {feedback}'}}"
Three validation rules do the heavy lifting: relations must come from the closed vocabulary, evidence must be a literal substring of the source (which the model can usually satisfy and confabulation cannot), and required keys must be present. Failures are re-prompted with the specific error â a much higher recovery rate than a generic "try again" â and persistent failures are dropped and logged rather than forced through.
đĄEvidence-substring as a cheap factuality gate
Requiring extracted evidence to appear verbatim in the source is not a full factuality check, but it is a remarkably effective one: fabricated quotes, invented figures and rewritten clause text all fail it immediately, at no cost beyond a string search.
Entity resolution: mentions are not things
"IBM", "International Business Machines", "Big Blue" and "IBM Corp." are one entity in your registry and four strings in your text. Resolution runs in two steps: block candidates by normalized keys (lowercase, strip legal suffixes, compare token sets), then score pairwise similarity using names, co-occurring attributes such as domain and location, and any external identifiers. Above a confident threshold, merge; in the middle band, queue for review; below it, keep separate.
Log every merge and every rejection. Merges that later prove wrong are expensive to undo once joins have run, so prefer a reversible identifier â two mentions map to a candidate cluster that can be split â over an eager primary key assignment. Deduplication applies to facts as well as entities: the same triple extracted from three documents should carry three provenance records and one graph edge, not three edges that triple your traversal cost.
Ambiguity, negation and modality belong in the schema
Raw triples cannot express that a fact was denied, hedged or reported second-hand, and text is full of exactly those mentions. "The merger was denied" is not a merger. "Revenue may exceed $10 million" is not a revenue figure, and "sources say the CEO plans to step down" is an attributed claim rather than a resignation. Systems that ignore this pollute their graph with statements the source never made, and the pollution is invisible until someone reasons over it.
Three fields absorb most of the problem. A polarity flag marks negated mentions, which should either be stored with the flag or dropped. A modality value distinguishes facts from plans, rumours and hypotheticals, letting consumers decide what they are willing to act on. A provenance record names the source document, the publication date and the entity that asserted the claim, which is what turns "when did we learn this" into an answerable query.
Negation scope deserves special attention because it is easy to detect and easy to mishandle: scope usually extends to the end of the clause, and coordination ("did not approve or fund") makes naive window rules wrong. When a mention sits inside a negated clause, prefer suppressing the tuple over tagging it with a flag your consumers will forget to check â a missing fact is corrected on demand, a wrong fact quietly shapes every downstream decision.
The human loop and how to measure it
Extraction quality is measured at the tuple level: a prediction counts only when subject, relation and object all match, which is stricter than per-field accuracy and closer to what consumers feel. Report micro-F1 across all relations plus macro-F1 across relation types, because rare relations vanish in the micro average while carrying disproportionate business value.
Review effort should follow uncertainty. Sample everything below the confidence floor, a fraction of the band above it, and a random slice of high-confidence output to catch systematic errors that confidence does not reflect â a model that is consistently wrong about one relation type is confidently wrong, and only random auditing exposes it. Track agreement between reviewers as well; disagreement on a tuple usually means the schema allowed two readings, which is a design defect to fix rather than a case to adjudicate.
Common Mistakes
Extracting facts without recording which document produced them
Fix: Store provenance and evidence spans with every tuple so disputes are one lookup away from resolution
Letting an LLM return free-form objects when a closed vocabulary exists
Fix: Validate relations against the vocabulary and retry with the specific error attached
Treating string mentions as canonical entities
Fix: Resolve to cluster IDs with reversible merges and review the middle-similarity band
Reporting per-field accuracy instead of tuple-level F1
Fix: Score subject, relation and object jointly, and report macro-F1 so rare relations stay visible
Best Practices
- Design the schema with the consuming system and its null semantics first
- Apply type constraints before classification so impossible pairs never reach the model
- Keep evidence spans â for review, for audits, and as a free factuality gate
- Score pair similarity in a middle band for human review rather than forcing a merge decision
- Audit a random slice of high-confidence output weekly; consistent errors look confident
Key Takeaways
- Extraction begins with a schema the consumer can use, including null semantics and provenance
- Pair classification with type constraints beats sentence-level relation detection for predictable output
- Schema validation with an evidence-substring check converts LLM output into ingestible, auditable rows
- Mentions are strings; entities are registry entries â resolution needs reversible merges and a review band
- Measure tuple-level and macro-F1, and audit confident output, because systematic errors arrive with high confidence