Sub topic 6
Classifying text and extracting fields
This chapter assumes you can write basic Python, read JSON, and have a function that sends a prompt to a model and returns text. You should also know how to write a prompt with clear instructions, as covered in the prompting chapter.
Two tasks, one pattern
Classification assigns a piece of text to one label from a fixed set. Extraction pulls named fields, such as a vendor or a date, out of free text. Both turn messy language into values your program can branch on. Both follow the same pattern: constrain the output, then check it in code.
Classifying a ticket
The prompt names the allowed labels and asks for the label only. The code then verifies the reply, because a model can add words, change capitalization, or invent a label.
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"Here complete is any function that takes a prompt string and returns the model's text. The fallback to "other" means a bad reply never escapes as an unknown label.
Extracting fields
For extraction, ask for JSON with named keys. Then parse and validate the result before any other code uses it.
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}'))Malformed JSON raises an error from json.loads. A missing or wrongly typed field raises ValueError. Either way the failure is loud and happens at the boundary, not three functions later.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Reply contains extra words | The instruction did not say "label only" | State the output format and show an example |
| Label outside the set | The model paraphrased a label | Normalize, check membership, use a fallback |
| Invalid JSON | The model added prose or a code fence | Ask for JSON only, strip wrappers, retry once |
| Invented field values | The text lacked the information | Allow `null` and say "use null if absent" |
| Wrong label on edge cases | Labels overlap or are vague | Define each label in one line and add examples |
Practical habits
- Keep labels few, distinct, and defined in the prompt.
- Put one or two examples in the prompt for ambiguous cases.
- Allow
nullfor fields that may be missing. - Log every fallback so you can see how often the model misses.
Exercise
A model replies "Billing." (with a capital B and a period) to your classifier. What does classify return, and how would you make it return "billing"?
Show answer
It returns "other", because "billing." is not in LABELS after strip().lower(). Strip trailing punctuation too, for example with .strip().lower().strip("."), or ask the model more strictly for the bare label.
Exercise
Why does parse_invoice raise an error instead of returning a default total of 0?
Show answer
A default would hide a failed extraction, and wrong totals would flow into later code unnoticed. Raising makes the failure visible so you can retry, flag the document for review, or log it.