Sub topic 6
Classifying text and extracting fields
Classification and extraction are the most dependable things an LLM does in production. Both turn free text into a small, predictable value that code can act on. This chapter covers prompt design, validation, and the errors that show up once real data arrives.
Prerequisites
This chapter assumes you can write basic Python and read JSON. You should also know how to write a prompt with clear instructions, from the earlier chapter on prompting. The code uses a complete(prompt) -> str function. It wraps whichever model API you use, takes a prompt string, and returns the reply text.
The two tasks
- Classification assigns a piece of text to one of a fixed set of labels. Examples are routing a support ticket, tagging sentiment, or flagging spam.
- Extraction pulls specific fields out of text. Examples are the vendor and total from an invoice, or the date and city from an email.
Both tasks have a closed answer space. That makes them easier to test than open-ended writing, because you can compare each output to a known correct answer.
Classification
A reliable classifier prompt does four things:
- It names the task in one sentence.
- It lists the allowed labels.
- It says how to format the reply, for example "Reply with the label only."
- It puts the input text last, clearly separated from the instructions.
The code below follows that pattern. It also checks the reply against the label list and falls back to other when the model returns anything else.
LABELS = ["billing", "bug", "feature_request", "other"]
def classify(ticket: str, complete) -> str:
prompt = (
"Classify the support ticket into exactly one label from: "
+ ", ".join(LABELS)
+ ".\nReply with the label only.\n\nTicket: " + ticket
)
answer = complete(prompt).strip().lower()
return answer if answer in LABELS else "other"The last line matters. Models sometimes reply "Label: billing" or add an explanation. Without the check, that string would travel into your routing code. With it, every call returns a value from LABELS.
Define the labels
Most classification errors come from unclear labels, not from the model. Write a one-line definition for each label, and say how to handle overlap. For example: "Use bug when something that should work is broken. Use feature_request when the user wants new behavior."
If two labels are hard for a human to tell apart, the model will confuse them too. Merge them, or add a rule for the boundary.
Add examples
Adding a few worked examples to the prompt is called few-shot prompting. Pick examples that cover the hard boundaries, not only the easy cases. Two or three examples per confusing pair is usually enough. Keep the example format identical to the real input format.
Allow an escape label
Always include a label such as other or unclear. Without one, the model must pick a wrong label for text that fits none of them. Count how often the escape label fires. A rising count tells you the label set no longer matches your data.
Extraction
Extraction prompts name each field, give its type, and say what to do when the value is missing. Models tend to fill gaps with plausible guesses, so tell them to use null instead.
EXTRACT_PROMPT = """Extract these fields from the invoice text.
Return JSON only, with exactly these keys:
- vendor: string
- total: number, no currency symbol
If a value is not in the text, use null. Do not guess.
Invoice text:
"""
def extract_invoice(text: str, complete) -> str:
return complete(EXTRACT_PROMPT + text)The function returns the raw reply. The next step is to parse and check it, as covered in the following section.
Validate before you use the result
Never pass model output straight to other code. Parse it, then check types and required values. A bad extraction should raise an error, not slip through.
import json
def parse_invoice(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data.get("vendor"), str):
raise ValueError("vendor must be a string")
if not isinstance(data.get("total"), (int, float)):
raise ValueError("total must be a number")
return data
print(parse_invoice('{"vendor": "Acme", "total": 129.5}'))This check rejects null values for required fields. That is intentional here. If a field is optional, accept None explicitly. Decide per field, and write the rule down.
The next chapter covers structured output in more depth, including ways to constrain the format at the API level.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Reply includes extra words | Format instruction is vague | Say "Reply with the label only" and normalize with `strip().lower()` |
| Label not in the list | Model invented or reworded a label | Check membership and use a fallback |
| JSON wrapped in prose or code fences | Model adds explanation | Say "JSON only" and strip fences before parsing |
| Invented field values | Missing data and no instruction for it | Allow `null` and say "do not guess" |
| Different answers on repeat runs | Sampling randomness | Set temperature low, and test with repeated runs |
| Wrong label on long inputs | Instructions buried or text truncated | Put instructions first, check context limits |
A note on confidence
A model's reply does not come with a trustworthy probability. If you ask for a "confidence" number, treat it as a rough hint, not a measurement. A safer pattern is to route uncertain items to a person. You can detect them with the escape label, with validation failures, or by running the prompt twice and flagging disagreements.
Measuring quality
Build a small labeled test set before you tune the prompt. Fifty to one hundred real examples is a good start. Include the awkward ones: typos, mixed topics, empty fields, and very short messages.
For classification, track accuracy overall and per label. A single accuracy number hides a label that is always wrong. For extraction, score each field separately, because a model can get vendors right and totals wrong.
def accuracy(cases, complete):
correct = sum(
1 for text, expected in cases
if classify(text, complete) == expected
)
return correct / len(cases)Rerun this after every prompt change. A small edit that fixes one case often breaks another, and only a test set shows that.
Choosing between approaches
| Situation | Better choice |
|---|---|
| Few labels, clear rules, high volume | Rules or a small trained classifier, possibly with an LLM only for the leftovers |
| Labels change often, little training data | LLM prompt with examples |
| Fields follow a fixed template | Regular expressions or a parser |
| Fields appear in varied wording | LLM extraction with validation |
An LLM is flexible, but each call costs money and time. If a regular expression solves the task, use it.
Exercise
Your classifier prompt lists labels billing, bug, feature_request, other. The model sometimes replies "Billing issue". Name two changes that prevent this from reaching your routing code.
Show answer
First, make the format instruction explicit ("Reply with the label only") so the model is less likely to add words. Second, normalize the reply with strip().lower() and check it against the LABELS list, returning the fallback label "other" when it does not match. The membership check is the one that guarantees the result, because it works even when the model ignores the prompt.
Exercise
An invoice extraction returns {"vendor": "Acme", "total": null} for an invoice that has no total. With the parse_invoice function above, what happens, and when would you change it?
Show answer
parse_invoice raises ValueError("total must be a number"), because None is not an int or float. That is correct when every invoice must have a total, since it stops the bad record early. Change the check to accept None if a missing total is a normal case that later code handles.