Module 4 of 6 · 50 minutes

Information extraction

Extraction turns free text into fields you can count, join and act on. Pick the simplest method that works — and validate everything.

By · Last updated

Learning objectives

  • Use regular expressions to extract well-defined patterns
  • Explain named entity recognition
  • Extract structured JSON with an LLM
  • Validate and ground extracted values
  • Extract with a schema instead of free-form JSON
  • Score an extractor field by field against hand-checked answers
Setup: the data and models from earlier modules (runs automatically when you press Run on any cell)
Python · setupimport random
import re
import numpy as np
import pandas as pd

random.seed(7)
templates = {
    "delivery": ["My parcel arrived {d} days late and the box was crushed",
                 "Delivery took {d} days and the courier left it in the rain",
                 "Still waiting for my order after {d} days, no update",
                 "The tracking link never updated and delivery was {d} days late"],
    "product":  ["The {p} broke after a week",
                 "Love the {p}, great quality and well made",
                 "The {p} is much smaller than the photos suggest",
                 "Excellent {p}, works perfectly"],
    "billing":  ["I was charged twice for order {o}",
                 "Refund for order {o} still not received",
                 "The discount code did not apply at checkout",
                 "Invoice for order {o} shows the wrong amount"],
}
products = ["chopping board", "kettle", "desk lamp", "backpack", "water bottle"]
rows = []
for i in range(400):
    cat = random.choice(list(templates))
    msg = random.choice(templates[cat]).format(
        d=random.randint(2, 9), p=random.choice(products), o="GFY-%05d" % random.randint(10000, 99999))
    label = cat if random.random() > 0.08 else random.choice(list(templates))  # ~8% noisy labels
    rows.append({"text": msg, "category": label})
messages = pd.DataFrame(rows)

4.1 Turning text into structured data

Information extraction pulls specific facts out of free text — order numbers, dates, amounts, product names, people and organisations — so they can be counted, joined to other data and acted on. It's often the step that makes text useful to the rest of the business.

Practice mode on this page

Calling a real AI model needs a secret API key, and a key must never sit in a web page. So the cells that call a model on this page talk to a small pretend model built into the page. The code is what you'd write for the real thing, but the replies come from simple rules, not real AI. To use a real model, copy the code into a notebook such as Colab and add your own key (see Python for AI, Module 5).

Customer messageHi, the desk lamp from orderGFY-48213 arrived broken. I'dlike my money back.Structured recordorder_id:GFY-48213issue:productproduct:desk lampwants_refund:trueextractregex for fixed patterns · NER for names and places · LLM for flexible fields
Information extraction turns free text into fields other systems can use.

4.2 Regular expressions for well-defined patterns

When the pattern is precise, a regular expression is fast, free and fully predictable:

order_re = re.compile(r"\bGFY-\d{5}\b")
messages["order_id"] = messages["text"].str.extract(r"(GFY-\d{5})", expand=False)
print(messages["order_id"].notna().mean().round(2), "of messages mention an order")

text = "Order GFY-48213 was charged £24.99 twice on 03/10/2026. Email me at [email protected]"
print(order_re.findall(text))
print(re.findall(r"£\d+(?:\.\d{2})?", text))
print(re.findall(r"\b\d{2}/\d{2}/\d{4}\b", text))

Test patterns against real examples, including awkward ones. "03/10/2026" is 3 October in the UK and 10 March in the US — extraction is only half the job; interpretation is the other half.

4.3 Named entity recognition

Named entity recognition (NER) finds names of people, organisations, places, products, dates and amounts — things too varied for a regex. Libraries such as spaCy ship pre-trained NER models, and cloud services offer it as an API (for example Amazon Comprehend and Azure AI Language). Pre-trained models know general entities; for your own product names or contract terms you'll usually need custom training or an LLM.

The simplest form of entity recognition needs no model at all: a list of the names you care about, sometimes called a gazetteer. For a fixed product catalogue it is hard to beat.

Python · finding known products with a listcatalogue = ["chopping board", "kettle", "desk lamp", "backpack", "water bottle"]
product_re = re.compile("|".join(re.escape(p) for p in catalogue), re.IGNORECASE)

messages["product"] = messages["text"].str.extract(f"({product_re.pattern})", flags=re.IGNORECASE, expand=False)
print(messages["product"].value_counts())

print(product_re.findall("The Desk Lamp and the kettle both arrived, but my rucksack is missing"))

The list finds "Desk Lamp" despite the capitals, and misses "rucksack" completely: it is not in the catalogue, even though a person knows it is a backpack. That is the trade: a list is exact and free, and knows nothing beyond itself. Trained NER models and LLMs handle wording they have never seen, at the cost of occasional mistakes.

4.4 Extraction with an LLM

LLMs are excellent at flexible extraction: you describe the fields, and they return structured output — even from messy, multilingual text. The reliable way to ask is with a schema: you describe the fields as a small class, and the API guarantees the reply matches it (this is the structured-outputs feature from Python for AI, Module 5).

Python · LLM extraction with a schema (practice mode on this page)from typing import Literal, Optional
from pydantic import BaseModel
import anthropic

client = anthropic.Anthropic()   # the real SDK reads ANTHROPIC_API_KEY from the environment
MODEL = "YOUR-MODEL-NAME"        # copy a current model name from the provider's docs

class Ticket(BaseModel):
    order_id: Optional[str]                                    # None if no order is mentioned
    issue: Literal["delivery", "product", "billing", "other"]
    product: Optional[str]
    wants_refund: bool

def extract(message):
    reply = client.messages.parse(
        model=MODEL, max_tokens=200, output_format=Ticket,
        messages=[{"role": "user", "content":
                   f"Extract the fields from this customer message.\n\n<message>{message}</message>"}])
    return reply.parsed_output.model_dump()

print(extract("Hi, the desk lamp from order GFY-48213 arrived broken. I'd like my money back."))
print(extract("Where is my parcel? It has been 6 days."))

Two details in the prompt are worth copying. The message is wrapped in <message> tags, so the model can tell your instructions from the customer's words. And fields that may be absent are marked Optional, which gives the model a legitimate way to say "not mentioned" instead of inventing something.

If your provider or model doesn't support schemas, ask for JSON in the prompt and parse it with json.loads inside a try/except; the reply will usually be valid, but not always.

4.5 Validate everything

Whatever the method, check the output before it flows into other systems:

ALLOWED = {"delivery", "product", "billing", "other"}

def validate(record):
    problems = []
    if record.get("order_id") and not re.fullmatch(r"GFY-\d{5}", record["order_id"]):
        problems.append("bad order_id format")
    if record.get("issue") not in ALLOWED:
        problems.append("unknown issue type")
    if not isinstance(record.get("wants_refund"), bool):
        problems.append("wants_refund must be true/false")
    return problems

print(validate({"order_id": "GFY-48213", "issue": "product", "product": "desk lamp", "wants_refund": True}))
print(validate({"order_id": "48213", "issue": "complaint", "wants_refund": "yes"}))

A schema already guarantees the second kind of failure can't happen: the types and allowed values are enforced. It can't enforce your business rules (an order number must look like GFY-12345), and it can't stop a well-formed value from being wrong.

Measure extraction quality on a hand-labelled sample: for each field, how often is it correct, missing, or invented? LLMs occasionally hallucinate a plausible order number that isn't in the text — a check that the value actually appears in the source catches this.

4.6 Measure it field by field

"The extraction works" isn't a measurement. Write down the right answers for a sample of messages, run the extractor, and score each field separately:

Python · scoring an extractor against hand-checked answersgold = [
    ("The kettle from order GFY-20311 broke after two days, refund please",
     {"order_id": "GFY-20311", "issue": "product", "product": "kettle", "wants_refund": True}),
    ("Still waiting for my parcel, tracking has not moved",
     {"order_id": None, "issue": "delivery", "product": None, "wants_refund": False}),
    ("I was charged twice for order GFY-77102",
     {"order_id": "GFY-77102", "issue": "billing", "product": None, "wants_refund": False}),
    ("My rucksack strap snapped. Can I get my money back?",
     {"order_id": None, "issue": "product", "product": "backpack", "wants_refund": True}),
    ("Love the water bottle, thank you!",
     {"order_id": None, "issue": "product", "product": "water bottle", "wants_refund": False}),
]

results = pd.DataFrame([{field: extract(text)[field] == expected[field] for field in expected}
                        for text, expected in gold])
print(results)
print()
print("Share correct by field:")
print(results.mean().round(2))

Order numbers and refund requests come out right every time. The fourth message is where it goes wrong: the customer wrote "rucksack", and the extractor did not connect it to the backpack in the catalogue. A table like this tells you exactly what to fix (here, teach it the product synonyms) and gives you a number to compare against after the fix. Five messages is only enough to illustrate; a real check needs a hundred or more.

Exercise: catch invented values

Write grounded(record, message) that returns False if order_id or product is not null but does not appear (case-insensitively) in the original message.

Your turnmsg = "The desk lamp from order GFY-48213 arrived broken"

# Write your code here, then press Run
Show a solution
msg = "The desk lamp from order GFY-48213 arrived broken"

def grounded(record, message):
    low = message.lower()
    for field in ("order_id", "product"):
        value = record.get(field)
        if value and value.lower() not in low:
            return False
    return True

print(grounded({"order_id": "GFY-48213", "product": "desk lamp"}, msg))   # True
print(grounded({"order_id": "GFY-99999", "product": "desk lamp"}, msg))   # False
Exercise: amounts and dates into a table

Using regular expressions, turn the three messages in the starter code into a DataFrame with columns order_id, amount (as a number) and date (as text). Use None where a value is missing.

Your turnnotes = ["Order GFY-48213 was charged £24.99 twice on 03/10/2026",
         "Refund of £12 for GFY-50001 promised by 15/11/2026",
         "Customer called about a late parcel, no order number given"]

# Write your code here, then press Run
Show a solution
notes = ["Order GFY-48213 was charged £24.99 twice on 03/10/2026",
         "Refund of £12 for GFY-50001 promised by 15/11/2026",
         "Customer called about a late parcel, no order number given"]

def first(pattern, text):
    m = re.search(pattern, text)
    return m.group(1) if m else None

rows = []
for n in notes:
    amount = first(r"£(\d+(?:\.\d{2})?)", n)
    rows.append({"order_id": first(r"(GFY-\d{5})", n),
                 "amount": float(amount) if amount else None,
                 "date": first(r"(\d{2}/\d{2}/\d{4})", n)})
print(pd.DataFrame(rows))
ExtractedJSONValid format &allowed values?Values appearin source?Into thesystemHuman review / retryyesyesnono
Never trust extracted fields blindly: check format, allowed values and grounding before they reach other systems.

Key takeaways

  • Regex is fast and predictable for precise patterns.
  • NER finds names, places, organisations and dates.
  • LLMs handle messy, varied text — ask for JSON.
  • Validate formats and allowed values.
  • Check extracted values actually appear in the source.
  • A schema guarantees the shape of the answer, not that it is right.
  • Score each field against a hand-checked sample to see exactly what to fix.