Sub topic 11
Handling long documents
This chapter assumes you can extract text from a PDF, define a Pydantic schema, and call an LLM that returns JSON. Here you will split documents that are too large for one call, extract from each piece, and merge the results.
Why long documents need special handling
A single call can fail on a long document for three reasons:
- Context limit. The text plus the prompt and the answer must fit in the model's context window. A 300-page contract may not fit.
- Lost detail. Even when everything fits, models often miss details buried in the middle of a long input. Accuracy on a field can drop as the input grows.
- Cost and latency. You pay for every input token, and a retry repeats the whole cost.
Chunking addresses all three. It also introduces new failure modes, which this chapter covers: values split across a boundary, duplicates, and conflicting values.
First decide whether you need to chunk
Chunking adds code and new ways to be wrong, so skip it when you can. Estimate the size first. A rough rule is 4 characters per token for English text. Use your provider's tokenizer when you need an exact count.
Also ask what the fields are:
- Document-level fields appear once, such as vendor, invoice date and total. They are usually on a few pages, often the first or last.
- Repeating records appear many times, such as line items, transactions and clauses. They are spread across the whole document.
Document-level fields may not need every page. You can send only the first and last pages. Repeating records need every page, so they are the main reason to chunk.
Chunking by page
For PDFs, pages are the natural boundary. They are already available from reader.pages, and a page number is easy to cite later. Cutting at an arbitrary character offset can split a table row or a sentence in half.
The function below packs whole pages into chunks up to a character budget. It repeats the last overlap_pages pages at the start of the next chunk. Each page is labeled with its number so the model can report where a value came from.
def chunk_pages(pages, max_chars=12000, overlap_pages=1):
chunks = []
start = 0
while start < len(pages):
end = start
size = 0
# Always take at least one page, even if it exceeds the budget.
while end < len(pages) and (end == start or size + len(pages[end]) <= max_chars):
size += len(pages[end])
end += 1
text = "\n\n".join(f"[Page {i + 1}]\n{pages[i]}" for i in range(start, end))
chunks.append({"first_page": start + 1, "last_page": end, "text": text})
if end >= len(pages):
break
start = max(end - overlap_pages, start + 1) # always advance
return chunks
pages = ["page one " * 400, "page two " * 400, "page three " * 400, "page four " * 400]
for chunk in chunk_pages(pages, max_chars=8000):
print(chunk["first_page"], chunk["last_page"], len(chunk["text"]))The start + 1 guard prevents an infinite loop when overlap is as large as the chunk. A single page larger than the budget becomes its own oversized chunk. If that happens often, the page probably holds a big table, and you should split it by rows instead.
Why overlap helps
A table can continue from the bottom of one page to the top of the next. Without overlap, the second chunk starts mid-table with no column headers, and the model may misread the columns. With one page of overlap, the header row appears in both chunks. The cost is duplicate records, which you remove during merging.
Extract per chunk, then merge
The pattern is map and reduce. Run the same extraction on each chunk, then combine the partial results in code. Do not ask the model to merge. Merging in plain code is deterministic, free and testable.
Each chunk needs a schema suited to chunks. Every field must be optional, because any one chunk may contain only part of the document. Repeating records should carry a page number so you can deduplicate them.
from collections import Counter
from typing import Optional
from pydantic import BaseModel, Field
class LineItem(BaseModel):
page: int = Field(description="Page number shown in the [Page N] marker")
description: str
amount: Optional[float] = None
class ChunkResult(BaseModel):
vendor: Optional[str] = None
invoice_number: Optional[str] = None
total: Optional[float] = Field(default=None, description="Grand total, only if shown in this text")
line_items: list[LineItem] = []
def merge_results(results):
merged = {}
for field in ("vendor", "invoice_number", "total"):
values = [getattr(r, field) for r in results if getattr(r, field) is not None]
merged[field] = Counter(values).most_common(1)[0][0] if values else None
seen, items = set(), []
for r in results:
for item in r.line_items:
key = (item.page, item.description.strip().lower(), item.amount)
if key not in seen:
seen.add(key)
items.append(item)
merged["line_items"] = items
return mergedScalar fields use a majority vote over the non-null values. Line items are deduplicated on page, description and amount. Including the page in the key matters. Two identical rows on different pages, such as a recurring monthly fee, are both real. The same row seen twice because of overlap has the same page number both times.
Running the loop
This reuses PROMPT_TEMPLATE-style prompting from earlier chapters. call_llm(prompt) -> str is your own function.
def extract_long(pages, call_llm, chunk_prompt):
results = []
for chunk in chunk_pages(pages):
prompt = chunk_prompt.format(document_text=chunk["text"])
raw = call_llm(prompt)
results.append(ChunkResult.model_validate_json(raw))
return merge_results(results)Each chunk call can reuse your existing validate-and-retry loop. A failed chunk then retries on its own, and you do not repeat the whole document. Chunk calls are independent, so you can run them in parallel with a thread pool to cut latency.
Conflicts and gaps after merging
Majority voting is simple, but it hides problems. Check for these cases:
| Situation | Likely cause | What to do |
|---|---|---|
| Two different non-null values for one field | The field appears in different forms, such as a subtotal and a grand total | Make the field description more specific, or flag the document for review |
| Field is null in every chunk | Value is absent, or split across a chunk boundary | Increase overlap, or run a targeted second pass on the relevant pages |
| Duplicate line items | Overlap pages processed twice | Deduplicate by page and content, as above |
| Missing line items | Table split mid-row or header lost | Chunk on page boundaries, and repeat header text in each chunk |
If the model sees a subtotal in chunk 2 and the grand total in chunk 5, a majority vote on total can pick the wrong one. A field description such as "Grand total of the whole invoice, not a subtotal or page total" reduces this. A cross-check also helps: compare the sum of the line items against the total, and send mismatches to review.
Two-pass alternative for large documents
When the document is large but the fields are few, a cheaper design is a two-pass search:
- Locate. Use keyword search or a short LLM call over page summaries to find the pages that likely contain each field.
- Extract. Send only those pages to the extraction prompt.
This lowers cost and reduces the chance of a distracting value elsewhere in the document. The risk is a missed page, so keep a fallback that scans all pages when a required field comes back null.
Common mistakes
- Chunking by fixed character count and cutting through table rows.
- Making fields required in the chunk schema. A chunk without the vendor then fails validation, or the model invents a vendor to satisfy it.
- Forgetting page markers, which makes deduplication and source citation impossible.
- Asking an LLM to merge the partial results. This adds cost and can silently drop records.
- Setting chunk size by the context limit alone. Smaller chunks often extract more accurately than chunks that fill the window.
Exercise
Two chunks overlap by one page. Both report a line item with the description "Hosting fee" and amount 49.0. In one case both say page 3. In another, one says page 3 and the other page 7. How should your merge treat each case, and why?
Show answer
When both report page 3, treat it as one record. It was extracted twice because page 3 sits in the overlap, so the key (page, description, amount) matches and it is deduplicated. When the pages differ (3 and 7), keep both. They are separate rows that happen to look identical, such as a recurring fee, and removing one would lose data. This is why the page number must be part of the deduplication key.
Exercise
Why should every field in a per-chunk schema be optional, even if the final document must always have a vendor?
Show answer
Any single chunk may not contain the vendor. A required field forces the model to either fail validation or guess a value. With optional fields, the chunk returns null, and the merge step combines the chunks. Check that required fields are present after merging.