Sub topic 7
How prompted extraction fails
This chapter assumes you know basic Python, can read JSON, and understand precision, recall and F1 at an introductory level. You have seen how to write a zero-shot or few-shot extraction prompt and how to validate its output. Here you will learn the ways a prompted extractor goes wrong, how to detect each failure, and which fixes work.
A prompted extractor can fail in two places. The model can produce output that is not usable (a format failure). Or it can produce well-formed output with wrong content (a content failure). Format failures are easy to catch with code. Content failures are harder, because the output looks correct.
Format failures
Format failures are the cheapest to find. The parser from the previous chapter rejects them, so you can count them.
Common causes:
- Conversational wrapping. The model writes "Sure! Here is the JSON:" before the object, or wraps it in a Markdown fence.
- Truncation. The output hits the token limit in the middle of a string, so the JSON never closes.
- Key drift. The model renames
totaltoamount, adds anoteskey, or drops a key it considers empty. - Type drift.
"total": "120.50 EUR"instead of120.5, or"null"as a string instead of JSONnull.
The right response is to reject the output and handle it explicitly. Do not silently repair it, because a repair rule written for one failure often corrupts another. A bounded retry with a stricter instruction is reasonable. If your provider supports constrained decoding or a JSON schema mode, use it, since it removes most format failures at the source. It does not remove content failures.
A useful habit is to log the parse failure rate separately from accuracy. A system with a 4% parse failure rate and 90% F1 on parsed outputs does not have 90% F1 overall.
import json
EXPECTED = {"vendor", "total", "currency"}
def classify_output(raw):
"""Return (status, data). Status names the first failure found."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return "not_json", None
if not isinstance(data, dict):
return "not_object", None
if set(data) != EXPECTED:
return "wrong_keys", None
total = data["total"]
if total is not None and (isinstance(total, bool) or not isinstance(total, (int, float))):
return "wrong_type", None
return "ok", data
outputs = [
'{"vendor": "Acme", "total": 120.5, "currency": "EUR"}',
'Sure! {"vendor": "Acme"}',
'{"vendor": "Acme", "amount": 120.5, "currency": "EUR"}',
'{"vendor": "Acme", "total": "120.5 EUR", "currency": "EUR"}',
'{"vendor": "Acme", "total": 120.5, "curr',
]
counts = {}
for raw in outputs:
status, _ = classify_output(raw)
counts[status] = counts.get(status, 0) + 1
print(counts)The isinstance(total, bool) check matters because in Python True is an instance of int, so a boolean would otherwise pass as a number.
Content failures
When the output parses and matches the schema, the values can still be wrong. These are the failures that dominate in practice.
Hallucination
The model reports a value that is not in the text. It happens most when the schema asks for a field the document does not contain. If the invoice has no currency, a model may output "USD" because most invoices it has seen use dollars. The instruction "Use null when a field is not stated. Do not guess" reduces this but does not eliminate it.
A cheap detector is a grounding check: for extractive fields, the returned string should appear in the source text.
import re
def normalize(s):
return re.sub(r"\s+", " ", s).strip().lower()
def is_grounded(value, text):
"""True if an extracted string value occurs in the source text."""
if value is None:
return True
return normalize(value) in normalize(text)
text = "Invoice from Acme Corp. Total due: 120.50 EUR"
print(is_grounded("Acme Corp", text))
print(is_grounded("Acme Corporation", text))
print(is_grounded("USD", text))The second call returns False: the model expanded "Corp" to "Corporation". This is a typical case where the value is plausible but not what the text says. Grounding checks do not apply to normalized fields such as dates converted to ISO format, so apply them only to fields defined as verbatim.
Omission
The model returns null or an empty list for something that is present. Omission is common in long documents, in lists with many entities, and when the target appears in an unusual form ("twelve hundred euros"). The model often extracts the first few entities and stops. It shows up as low recall with high precision.
Boundary errors
The model finds the right entity but returns the wrong span. Examples are "Dr. Angela Merkel" versus "Angela Merkel", or "Acme" versus "Acme Corp." Under exact-match span scoring, a boundary error counts as one false positive and one false negative. Your labeling guidelines decide which boundary is correct, so a prompt that does not repeat those rules will make the model choose its own.
Wrong label or wrong field
The model assigns the wrong type, such as tagging a company named after a person as a person. In key-value extraction, the model may fill vendor with the customer's name because both appear near the top of the invoice. Few-shot examples that include confusable cases help here more than extra easy examples.
Offsets and positions
If you ask the model for character offsets, expect errors. Language models do not count characters reliably, and tokenization hides character positions from them. Ask for the exact text and compute offsets yourself by searching the source. When a string occurs more than once, you need a rule, such as returning every occurrence or asking for a short left context.
def find_spans(text, value):
"""Return (start, end) for every occurrence of value in text."""
spans = []
start = text.find(value)
while start != -1:
spans.append((start, start + len(value)))
start = text.find(value, start + 1)
return spans
print(find_spans("Paris to Paris via Lyon", "Paris"))Failures that depend on the setup
Some failures come from the system around the model, not from the text.
| Failure | Typical trigger | How to detect | Common fix |
|---|---|---|---|
| Prompt sensitivity | Rewording instructions, reordering examples | Run the same gold set on two paraphrased prompts and compare F1 | Fix the prompt, pin its version, test every change |
| Example bias | Few-shot examples that all contain the entity, or that share a label order | Check whether outputs copy example values | Include negative examples and vary the order |
| Nondeterminism | Sampling temperature above 0 | Run the same input several times | Set temperature to 0, and still expect small differences |
| Long-context loss | Entities in the middle of a long document | Plot recall against position in the document | Split the document into chunks, then merge and deduplicate |
| Model version drift | The provider updates the model behind a name | Run a fixed regression set on a schedule | Pin a dated model version, keep a regression set |
| Injection | The document contains text such as "ignore the instructions" | Add adversarial documents to the test set | Delimit the input, treat output as untrusted, validate it |
Prompt sensitivity deserves emphasis. A change that looks harmless, such as adding a sentence about being careful, can move F1 by several points in either direction. Measure it on your gold data, not on one or two examples you looked at.
Chunking creates its own errors. An entity cut across a chunk boundary is missed or split in two. Overlapping chunks fix that but create duplicates, so you need a merge step that removes identical spans.
Measuring failures
To see which failure matters most, tag every error in a gold-set run with a category. Do this before you change the prompt. A table of counts shows where to spend effort.
from collections import Counter
def categorize(gold_spans, pred_spans):
"""Label each error as boundary, wrong_label, missed or spurious.
Spans are (start, end, label) tuples."""
gold, pred = set(gold_spans), set(pred_spans)
errors = []
for g in gold - pred:
overlapping = [p for p in pred - gold if p[0] < g[1] and g[0] < p[1]]
if any(p[2] == g[2] for p in overlapping):
errors.append("boundary")
elif overlapping:
errors.append("wrong_label")
else:
errors.append("missed")
for p in pred - gold:
if not any(p[0] < g[1] and g[0] < p[1] for g in gold):
errors.append("spurious")
return Counter(errors)
gold = [(0, 15, "PER"), (24, 29, "LOC"), (40, 44, "ORG")]
pred = [(4, 15, "PER"), (24, 29, "ORG"), (60, 66, "LOC")]
print(categorize(gold, pred))On this example the output is one boundary error, one wrong label, one missed span and one spurious span. Hallucination appears as spurious, and omission appears as missed. Once errors are counted, the next chapters' error analysis becomes mechanical.
The decision of what to change follows from the dominant category:
- Mostly format failures: constrain decoding, shorten the output, raise the token limit.
- Mostly spurious spans: tighten the null rule, add negative examples, add grounding checks.
- Mostly missed spans: split long inputs, ask for exhaustive extraction, add examples of unusual forms.
- Mostly boundary errors: add the boundary rules to the prompt with examples, or normalize spans in post-processing.
- Mostly wrong labels: add examples of the confusable cases and clarify the definitions.
If the same categories persist after several prompt revisions, the task may need labeled training data instead. That is the subject of the fine-tuning chapters.
Common mistakes when diagnosing
- Judging the prompt on a handful of examples. Small samples hide rare failures and exaggerate common ones.
- Tuning the prompt on the same documents you report results on. Hold out a test set.
- Counting only parsed outputs. Report the parse failure rate next to F1.
- Treating a retry as free. Each retry adds cost and latency, and retries can mask a prompt that is fragile.
- Fixing symptoms in post-processing without recording them. A growing pile of regex repairs becomes an unmaintained rule system.
Exercise
A prompted invoice extractor returns valid JSON for 97% of documents. On those, it scores precision 0.92 and recall 0.70 on the vendor field. Which failure category is most likely dominant, and name two changes you would try first.
Show answer
Precision is high and recall is low, so the dominant error is omission (missed values), not hallucination. Likely causes are long documents, unusual formats, or an over-strict null rule that makes the model return null when unsure. First changes: split long documents into overlapping chunks and merge results, and add few-shot examples that show vendors in unusual positions or forms. Also check the null instruction wording, and report the 3% parse failures separately, because they count as missed values in the overall recall.
Exercise
Why is it safer to ask the model for the extracted text and compute character offsets in code than to ask the model for offsets?
Show answer
Language models see tokens, not characters, and they do not count characters reliably, so returned offsets are often shifted. Searching the source for the returned string gives exact offsets. It also lets you detect hallucination, because a string that is not found in the text is not grounded. The remaining problem is strings that occur more than once, which needs an explicit rule.