Sub topic 2
Defining the schema and labeling rules
This chapter assumes you can read basic Python and JSON, know roughly what a language model does, and have met precision, recall and F1. The previous chapter listed the task types: named entities, relations and key-value fields. Here you turn one of them into a precise written contract.
Why the schema comes first
A schema says what you want extracted. Labeling rules say how to decide each borderline case. Together they serve four purposes:
- Annotators read them to label gold data.
- Prompt writers copy their wording into instructions.
- Fine-tuning pipelines use them to define the label set.
- Evaluation code uses them to decide whether a prediction counts as correct.
The two approaches in this tutorial, prompting and fine-tuning, both depend on the schema. A vague schema hurts both. An LLM guesses at the vague parts differently on each run. A fine-tuned model learns whatever inconsistency the annotators left in the data. The schema is also the main reason a score is hard to interpret. If two annotators disagree on 20% of cases, no model can reliably score above what those annotators would agree on.
What a schema contains
A usable schema answers the following questions for every item you want extracted.
- Name and definition. What is this item, in one or two sentences? "Vendor: the company that issued the invoice, not the company billed."
- Type. Is it a text span, a number, a date, a category from a closed list, or a boolean?
- Cardinality. Can it appear zero times, exactly once, or many times in a document?
- Null rule. What should the system output when the item is not stated? Decide between
null, an empty list and omitting the key. State it explicitly. - Source rule. Must the value appear verbatim in the text, or may it be inferred or normalized? Is "twelve hundred euros" extracted as the string
"twelve hundred euros"or as1200? - Scope. Does the item apply to the whole document, a section, or one sentence?
Two schema shapes
Most projects use one of two shapes. They differ in what counts as an answer, so they differ in how you evaluate them.
| Aspect | Span schema | Field schema |
|---|---|---|
| Output | A list of (start, end, label) spans | A JSON object with named fields |
| Example | `PER` at characters 0 to 13 | `{"vendor": "Acme", "total": 120.5}` |
| Position matters | Yes, the offsets are part of the answer | No, only the value matters |
| Normalization | Rare, the text is kept as written | Common, such as numbers, dates and currency codes |
| Typical model | Token classifier with BIO tags | Prompted LLM or fine-tuned generative model |
| Typical metric | Exact-match span F1 | Per-field accuracy or per-field F1 |
The shapes can be mixed. For example, you can extract spans and then normalize each one into a field. Decide which shape is the source of truth before you annotate. Changing it later usually means relabeling.
Labeling rules for spans
Spans cause the most disagreement, because the model must get both the label and the exact boundaries right under exact-match scoring. Write down a rule for each of the following.
- Boundaries. Include or exclude titles ("Dr. Smith" or "Smith")? Include or exclude trailing punctuation and possessives ("Paris's")? A common default is to include only the words that name the entity, and to exclude punctuation and leading whitespace.
- Nesting. Is "Bank of America" an
ORGthat contains aLOC? Flat schemas allow one label per token and are simpler. BIO tagging, covered later, assumes a flat schema. If you need nesting, say so now, because it changes the model design. - Overlap. If a phrase fits two labels, which wins? Give an ordering or a tie-breaker.
- Discontinuous mentions. In "the Paris and Berlin offices" you may need two separate
LOCspans. Say whether you annotate them separately. - Repeated mentions. Do you label every occurrence or only the first? Evaluation by span counts every occurrence you label, so this choice changes recall.
- Generic and pronoun mentions. Do "he", "the company" and "our CEO" count? Most NER schemas exclude pronouns and generic nouns. Relation or coreference tasks may not.
- Metonymy and context. In "Paris rejected the proposal", is Paris a
LOCor anORG? Choose by how the word is used here, or by its usual type, and apply the rule consistently.
Labeling rules for fields
Field schemas need a different set of decisions.
- Which value wins when there are several? An invoice may show a subtotal, a tax amount and a grand total. The rule "total is the final amount due" is checkable. "The total" alone is not.
- Format of the normalized value. Dates as ISO 8601 (
2026-11-29), amounts as numbers without thousands separators, currency as a three-letter code. - Closed lists. If
currencymust be one ofEUR,USDorGBP, say what happens forJPY. Options are to add it, map it tonull, or map it to"OTHER". - Absent versus unknown.
nullshould mean "the text does not say". Do not usenullfor "the model was not sure". - Inference limits. If the invoice shows a
$sign but no currency name, may the system outputUSD? Write down yes or no. LLMs tend to infer unless told not to, and annotators tend to differ on this.
Writing the guidelines document
Keep the guidelines short enough that annotators actually read them. For each label or field, a good entry has:
- A one-sentence definition.
- Two or three clear positive examples.
- Two or three clear negative examples that look similar but must not be labeled.
- A list of edge-case decisions, each with a one-line reason.
Version the document. Every time you change a rule, record the date and the reason, and note which gold items need relabeling. The same text, which becomes your prompt later, is also the text that explains why a gold label is what it is.
The schema as code
Put the schema in a file that annotation checks, prompts and evaluation all read. Then the rules stay in one place. The following program validates field records and span annotations against a schema. Run it on every batch of gold data before you use it.
LABELS = {"PER", "LOC"}
FIELDS = {
"vendor": {"type": (str,), "allowed": None},
"total": {"type": (int, float), "allowed": None},
"currency": {"type": (str,), "allowed": {"EUR", "USD", "GBP"}},
}
def check_record(record):
problems = []
if set(record) != set(FIELDS):
problems.append("keys must be exactly " + ", ".join(sorted(FIELDS)))
return problems
for name, rule in FIELDS.items():
value = record[name]
if value is None:
continue
if isinstance(value, bool) or not isinstance(value, rule["type"]):
problems.append(f"{name}: wrong type")
elif rule["allowed"] is not None and value not in rule["allowed"]:
problems.append(f"{name}: {value!r} not in allowed values")
return problems
def check_spans(text, spans, labels):
problems = []
last_end = 0
for start, end, label in sorted(spans):
if label not in labels:
problems.append(f"{(start, end)}: unknown label {label}")
if not 0 <= start < end <= len(text):
problems.append(f"{(start, end)}: out of range")
continue
piece = text[start:end]
if piece != piece.strip():
problems.append(f"{(start, end)}: boundary includes whitespace")
if start < last_end:
problems.append(f"{(start, end)}: overlaps an earlier span")
last_end = max(last_end, end)
return problems
print(check_record({"vendor": "Acme", "total": 120.5, "currency": "EUR"}))
print(check_record({"vendor": "Acme", "total": "120.5", "currency": "JPY"}))
text = "Angela Merkel visited Paris."
print(check_spans(text, [(0, 13, "PER"), (22, 27, "LOC")], LABELS))
print(check_spans(text, [(0, 14, "PER"), (7, 13, "PER"), (22, 27, "ORG")], LABELS))The first record and the first span list pass and print []. The second record fails on the type of total and on the value of currency. The second span list reports a boundary that includes whitespace, an overlap, and an unknown label.
The same FIELDS table can feed the prompt. You can generate the key names and the null rule from it, so the prompt and the validator cannot drift apart.
Iterating on the schema
You will not get the schema right on the first draft. The standard loop is to draft, label a small sample, measure agreement, and fix the rules where annotators disagree.
A pilot of 30 to 50 documents is usually enough to expose the main ambiguities. For span tasks, you can measure agreement by treating one annotator as gold and the other as the prediction, then computing the span-level F1 from the next chapters. For field tasks, count the share of fields where both annotators gave the same normalized value. If agreement stays low after two rounds, the task itself may be underspecified. In that case, narrow the schema before you collect more data.
Common errors
- Definitions by label name only. A label called
ORGwith no definition gets applied inconsistently to governments, brands and product names. - No null rule. Annotators leave fields blank, models fill them with guesses, and you cannot tell the two apart in evaluation.
- Mixing "what the text says" with "what is true". The schema must say whether the system extracts what is stated or what is correct. Extracting a wrong figure that the document states is still a correct extraction.
- Too many labels too early. Each label needs enough examples to train or to illustrate in a prompt. Start with the few labels your application needs. Split a label later if error analysis shows you must.
- Changing rules without relabeling. After a rule change, old gold items that contradict it silently turn correct predictions into errors in your metrics.
- Treating the schema as a prompt detail. If the schema lives only inside a prompt string, the fine-tuning and evaluation work cannot reuse it.
What carries forward
The next chapters use this schema in three ways. Annotators label gold data with it. The evaluation code compares predictions with the gold labels under the boundary and null rules you wrote here. Both the prompt and the fine-tuning label set are derived from it. A schema that is precise on paper and checked in code is the cheapest way to avoid wasted annotation and misleading scores.
Exercise
You are extracting total from invoices. Annotator A labels the subtotal before tax, and annotator B labels the final amount due, on the same invoices. Name the schema problem, and give a rewritten rule for total that settles it. Also say what value the field should hold when an invoice shows no amount at all.
Show answer
The definition of total is ambiguous, because the invoice contains several amounts and the schema does not say which one counts. A better rule is "total: the final amount due on the invoice, including tax, as a number without thousands separators or currency symbols". If the invoice states no amount, the field is null, meaning "the text does not say". Do not use 0 or a guessed value. After the fix, relabel the pilot items that used the old rule and measure agreement again.
Exercise
A span schema labels PER and LOC. Which of these annotations would check_spans flag for the text "Dr. Smith met Ana in Rome."? (a) (0, 9, "PER"), (b) (0, 10, "PER"), (c) (14, 17, "PER"), (d) (21, 25, "LOC")
Show answer
Positions: "Dr. Smith" is 0 to 9, a space is at 9, "met" is 10 to 13, a space at 13, "Ana" is 14 to 17, "in" is 18 to 20, "Rome" is 21 to 25. (a) is valid under a rule that includes titles. (b) is flagged because the span ends in a trailing space. (c) is valid. (d) is valid. If your guidelines exclude titles, then (a) is not a checker error but a guideline violation, which the checker cannot see. That is why the rules need to be written down and reviewed, as well as encoded.