Sub topic 3
Handling Long Documents
Assume you know Python, JSON, PDFs, and how to call an LLM. The main challenge with long documents is keeping enough context for accurate extraction without exceeding the model's context limit.
Chunking and merging
Split a document into chunks that preserve useful boundaries, such as pages, sections, or table groups. Avoid cutting a table or an item description in half. Add a small overlap when a value may depend on nearby text.
Extract each chunk into the same schema. Then merge the results with explicit rules:
- Keep one document-level value, such as an invoice number, when repeated values agree.
- Combine repeated line-item arrays.
- Mark conflicting values for review instead of choosing silently.
- Preserve the page or chunk where each value was found.
Grounding values in the source
Grounding means checking whether an extracted value is supported by the document. Exact substring checks work for names and invoice numbers after normalizing case and whitespace. Dates and amounts may need canonical formatting before comparison.
def is_grounded(value, source_text):
if value is None:
return True
source = " ".join(source_text.split()).lower()
candidate = " ".join(str(value).split()).lower()
return candidate in source
suspect = [
field for field in ("vendor", "invoice_number")
if not is_grounded(invoice.get(field), document_text)
]A failed check does not always prove the value is wrong. OCR may change characters, and the model may normalize a date. Treat it as a review signal.
Measuring extraction accuracy
Create a labeled test set containing representative documents and trusted answers. Measure accuracy per field, not only per document. A system might extract vendors well but fail on totals or table rows.
| Metric | Meaning |
|---|---|
| Field exact match | Predicted value equals the labeled value |
| Document accuracy | All required fields are correct |
| Review rate | Share of results sent to a person |
Track errors by document type and extraction path. This reveals whether scans, tables, or particular vendors cause failures.
Managing cost and latency
Use native text extraction before OCR or vision when possible. Process only relevant pages, use smaller models for simple fields, and cache extracted text. Parallel chunk requests reduce elapsed time but can increase rate-limit pressure and total concurrent cost.
Privacy and prompt injection
Remove unnecessary personal data before sending documents to an external model. Use approved retention settings and keep secrets out of prompts and logs. Treat document text as untrusted data. A sentence inside a PDF that says “ignore previous instructions” is content to extract, not an instruction to follow.
Routing uncertain results to human review
Send a result to review when validation fails, grounding fails, required fields are missing, chunks conflict, or confidence falls below a tested threshold. Store the source page, extracted value, and reason for review so a person can correct it efficiently.
Assembling the pipeline
Exercise
Why should conflicting values from two chunks be routed to review instead of silently selecting one?
Show answer
The conflict may indicate a real document difference, a chunking problem, or a model error. Silent selection hides that uncertainty.