esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

How Do You Handle Very Long Documents?

Three routes for a long contract, manual or log, when each works and what it costs, for your AI interview.

In short

Check whether the whole document fits, then pick a route: send it whole, split it and retrieve only the matching pieces, or read it in parts and merge the notes. Models often miss detail in the middle of long text, so every route must return the page it came from.

12 min readIntermediateCommon · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

A long document is a problem because a model can only hold so much text at once, and detail in the middle gets missed. First I check whether it fits. If it does, I send it whole, and reuse a cached copy for repeat questions. If it doesn't, I split it by section, keep each heading, and retrieve only the matching pieces, with page numbers. For a huge job, like searching many contracts, helper agents read parts and send back short findings. Every answer must point to its source, because a model can still be wrong.

What is a very long document problem, in plain words?

A language model reads text as tokens, which are small pieces of words. Its context window is the most it can hold at one time: your instructions, the document and the answer it writes. A 400-page insurance policy may not fit in one go, and when it does fit, the model can still read the middle of it poorly.

Think of a new claims handler on their first morning. The handbook is huge, so they don't read it cover to cover before every call. They use the index, open the right section and note the page. A good AI setup works the same way: it searches, reads the right part and points to the page.

The same problem shows up in AI products. A claims team asks an assistant about one 400-page policy, or a legal team searches 40,000 contracts for one clause. The right fix depends on how big the job is.

Key words

Context window
The most text a model can hold at one time, counted in tokens.
Chunk
A piece of a document, cut so it can be searched and sent on its own.
Retrieval
Finding the few pieces most likely to answer a question, and sending only those.
Compaction
Replacing old chat messages with a short summary, so the window stays small.
Agent
An AI program that runs steps on its own, such as reading a file or calling a tool.

Why does length hurt, even when it fits?

Length costs in two ways. The window is a limited resource, and every token uses a share of the model's attention (how much focus it gives each part of the text). Position matters too: a clause buried in the middle is easier to miss than one at the start or end.

A 2023 study called Lost in the Middle, submitted in July 2023, found that performance was often highest when the key text sat at the start or end of a long input, and dropped when it sat in the middle. Read its results as a warning about models of that time.

  • “Context, therefore, must be treated as a finite resource with diminishing marginal returns.”

    Anthropic engineering team

  • “performance is often highest when relevant information occurs at the beginning or end of the input context, and significantly degrades when models must access relevant information in the middle of long contexts”

    Lost in the Middle paper, 2023

  • “as the number of tokens in the context window increases, the model's ability to accurately recall information from that context decreases”

    Anthropic engineering team

Tip

Put the long document first and the question last. Anthropic's docs report that a question placed at the end can improve the response, by up to 30 percent in tests.

Length also grows during a chat. Anthropic notes that response quality degrades as a conversation grows, so old messages need summarising before the window fills.

What are the three routes, and when does each win?

Pick the route by two questions: does the whole thing fit, and does the job need one answer or many reads? Each route trades something away.

Three routes for a long document

Long document

more text than one clear read

Pick by size and job

Fits: send it whole

small enough to load in one prompt

Too big: split and search

send only the matching pieces

Many reads: helper agents

each helper reads one part

Answer with page numbers

every claim points to its page

  1. 1The long document goes to one of three routes, picked by its size and the job.
  2. 2Whichever route runs, the answer comes back with the page it came from.
A long document takes one of three routes, picked by its size and the job. Each route ends in an answer that cites its pages. The steps below say what each route costs.
  1. 1

    Fits: send it whole

    Anthropic's September 2024 guidance says a knowledge base under about 200,000 tokens, roughly 500 pages, can go in the prompt whole, with no search step. Anthropic says prompt caching, which reuses a saved copy of the prompt, makes this approach significantly faster and more cost-effective.

  2. 2

    Too big: split and search

    Cut the document by its own sections, keep each heading with its piece, and search for the pieces that match. Anthropic's contextual retrieval method, which adds context to each chunk before search, reported 49 percent fewer failed retrievals, and 67 percent with reranking, a second pass that sorts the hits.

  3. 3

    Many reads: helper agents

    Helper agents each read one part and send back short findings. A lead agent merges them. Each helper starts with a clean context window, so the lead's window stays small.

Anthropic also names the trade-off of searching at run time: runtime exploration is slower than retrieving pre-computed data. So for a fixed set of documents, build the index once and reuse it.

Worked example: a claims team has a 400-page policy wording and a question about flood cover. The wording is too big for one comfortable read, so the assistant splits it by its headings, finds the flood section on page 118, and answers with that page number. A claims handler checks the page before any money moves.

How do you split a document so it still makes sense?

Cut at the document's own structure, such as its numbered headings. Anthropic notes that in traditional RAG (retrieval-augmented generation, where the model answers from pieces of documents it searches), documents are split into smaller chunks, and that these systems often destroy context. A piece that starts mid-clause can make a rule look like it applies to the wrong case.

The code below splits a made-up policy wording by its numbered headings. Each piece keeps its heading, so the search hit still says which rule it is.

Python
# A made-up policy wording, split by its numbered headings so each piece keeps its heading.
import re

WORDING = """1. Claims window
Claims must be filed within 90 days of the loss.
2. Flood cover
Flood damage is covered only with the flood rider.
3. Excess
The first 500 of any claim is paid by the customer."""

def split_by_heading(text):
    # Start a new piece at each line that begins with a number and a dot.
    return re.split(r"\n(?=\d+\. )", text)

def find(pieces, word):
    # A keyword match, standing in for the search step of a real system.
    return [p for p in pieces if word.lower() in p.lower()]

pieces = split_by_heading(WORDING)
print(len(pieces), "pieces")
for hit in find(pieces, "flood"):
    print("hit:", hit.splitlines()[0])
print("first piece:", repr(pieces[0]))

Output

3 pieces
hit: 2. Flood cover
first piece: '1. Claims window\nClaims must be filed within 90 days of the loss.'

Tip

A piece with no heading can match a search and still answer the wrong question. Keep the heading with every piece, and store the page number too.

How would you answer questions across 40,000 contracts?

A legal team needs every contract that lets a supplier raise prices with no notice. The answer is spread across thousands of files, and no single read finds them all. Here is a plan that fits a budget.

Reading a long document in parts

400-page policy wording

too long to read in one go

Helpers, one part each

Pages 1 to 130

reads only its own pages

Pages 131 to 260

sends back short findings

Pages 261 to 400

runs at the same time as the others

Lead agent merges

keeps the notes, drops the raw text

Answer with page numbers

each finding cites its pages

  1. 1The policy is cut into three parts by page.
  2. 2Each helper sends back its short findings, not its whole reading.
  3. 3The lead agent writes one answer, and every finding keeps its pages.
A long document is split across helpers, each with a clean context window. The lead agent keeps only their findings and writes one answer. Every finding keeps its page numbers, so a person can check it.
  1. 1

    Index once

    Split each contract by section, and store the file name and page with every piece. Rebuild only the files that change.

  2. 2

    Search for the clause

    Find the pieces about price changes and notice periods. Keep the top hits from each file, not just the single best one.

  3. 3

    Read the hits in parts

    Helper agents each read the hits from a few files and return yes or no, with the clause text and its page.

  4. 4

    Check a sample by hand

    A lawyer reads a random sample of yes and no answers. If the sample is wrong, fix the search before the full run.

Budget first. Every helper reads tokens, so the cost grows with the number of hits. Estimate it on a small set of files before the full run.

What does the interviewer want to hear?

A strong answer covers

  • Check whether the whole document fits, before choosing a method.
  • Name the three routes: send whole, split and search, or read in parts.
  • Say why length hurts: a limited window, and misses in the middle.
  • Keep the structure and a page number with every piece.
  • Say the answer must cite its source, because a summary can be wrong.
  • Name a test: plant a fact in the middle, then ask about it.

Common traps

  • Trap"Use a bigger context window and send it all."

    BetterA bigger window still gets worse with length, and each call costs more. Check that the detail is found, not just that it fits.

  • Trap"Chop it every 500 words and embed the pieces."

    BetterFixed cuts can split a rule from its exception. Split by structure, keep the heading, and keep the page.

  • Trap"The model reads the whole document equally well."

    BetterModels miss detail in the middle of long inputs. Put the question last and test with a fact planted mid-document.

Can you spot the bad piece?

Spot the bad piece

A splitter cuts a policy every 800 characters. Which piece will mislead the assistant most?

Quick check

An assistant misses a clause on page 212 of a 400-page document. Which change makes that clause easiest to find and check?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q083What is "context rot"?10 min
  2. Q096What is compaction (summarising history)?11 min
  3. Q106Just-in-time retrieval vs preloading context?Coming soon
  4. Q113What is chunking, and why does size matter?13 min
  5. Q138RAG vs long context: which to use?12 min

Learn it in depth

Last updated on 26 November 2026

Building a product on long contracts, manuals or logs?

I design and build AI systems for long documents, with search, page citations and human checks. Book a short call and tell me what your documents look like.