Sub topic 11
Handling long documents
This chapter assumes you can extract text from a PDF, define a Pydantic schema, and call an LLM API with a prompt. A long document can exceed the model's context window. Even when it fits, accuracy often drops as the input grows. The usual fix is to split the text into chunks, extract from each chunk, and merge the results.
When to chunk
Chunk only when you need to. A document that fits comfortably in the context window is simpler and more accurate to process in one call. Chunk when the text is near the context limit, when cost or latency matters, or when you see fields missed from the middle of long inputs.
Split on page boundaries
You already have text per page from pypdf. Group whole pages into chunks up to a size limit, and overlap chunks by one page so a table or sentence that crosses a page break appears intact in at least one chunk.
def chunk_pages(pages, max_chars=12000, overlap_pages=1):
chunks, start = [], 0
while start < len(pages):
end, size = start, 0
while end < len(pages) and (size + len(pages[end]) <= max_chars or end == start):
size += len(pages[end])
end += 1
chunks.append("\n\n".join(pages[start:end]))
if end >= len(pages):
break
start = max(end - overlap_pages, start + 1)
return chunksThe end == start condition guarantees progress when one page is larger than the limit. The max(..., start + 1) guard prevents an infinite loop.
Merge the results
Each chunk produces a partial record, with null for fields it did not see. Merging depends on the field type.
- Single-value fields (vendor, invoice number, total): take the first non-null value. If chunks disagree, keep both and flag the field for review.
- List fields (line items): concatenate, then remove duplicates caused by the overlap.
def merge_records(records):
merged, conflicts = {}, []
for record in records:
for key, value in record.items():
if value is None:
continue
if key not in merged:
merged[key] = value
elif merged[key] != value:
conflicts.append((key, merged[key], value))
return merged, conflictsRun the validation step from the earlier chapter on each chunk result and again on the merged record. A merge can produce a combination that no single chunk contained.
Common errors
- Totals taken from the wrong chunk. A subtotal on page 2 may be extracted as the grand total. Tell the prompt which value you want, for example "the final amount due", and check conflicts.
- Duplicate line items from overlap. Deduplicate on a stable key such as the item description plus amount.
- Header fields missing in later chunks. The vendor name usually appears only on page 1. This is fine for single-value fields, but a list item that depends on header context needs that context passed in.
- Cost multiplication. Every chunk repeats the prompt instructions. Keep the instructions short, and skip chunks that cannot contain the field, such as terms-and-conditions pages.
Exercise
Two chunks return different values for total: 1,200.00 and 1,450.00. What should the merge step do, and why?
Show answer
It should not silently pick one. Record the disagreement as a conflict and route the document to review, or re-run extraction with a prompt that asks for the final amount due. Choosing the first value could keep a subtotal and produce a wrong but valid-looking record.
Exercise
Why does chunk_pages overlap chunks by one page?
Show answer
A table, sentence or total may continue across a page break. With overlap, at least one chunk contains the whole item. The cost is duplicate results, so list fields need deduplication after the merge.