# 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.

AI and LLM interview question Q095, Prompt and context engineering. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-handle-very-long-documents

## Say it in 30 seconds

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.

## Say it in 2 minutes

The first question is whether the whole document fits. A context window is the amount of text a model can hold at one time. Anthropic's engineers say context must be treated as a finite resource with diminishing marginal returns. So a bigger window still needs care.

If the document fits, send it whole. Anthropic's September 2024 guidance says a knowledge base under about 200,000 tokens, roughly 500 pages, can go straight into the prompt. Above that size, split it by its own sections, keep each heading with its piece, and fetch only the pieces that match. If it fits and many questions hit the same text, reuse a cached copy instead.

For a huge job, such as reading a 400-page policy wording or many contracts at once, split the work. Helper agents each read one part and return short findings, and a lead agent merges them. In a long chat, compaction summarises the older messages. Each step keeps page references, because a summary can be wrong too.

Finally, put the long document first and the question last. Models miss detail in the middle of long inputs, so I test with a fact planted in the middle and check that it is found. Then I check each answer against the page itself.

## 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.

- **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.

*Diagram, Three routes for a long document: 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. The long document goes to one of three routes, picked by its size and the job.
2. Whichever route runs, the answer comes back with the page it came from.

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. **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. **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:

```text
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.

*Diagram, Reading a long document in parts: 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. The policy is cut into three parts by page.
2. Each helper sends back its short findings, not its whole reading.
3. The lead agent writes one answer, and every finding keeps its pages.

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. **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. **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. **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." Better: A 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." Better: Fixed 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." Better: Models 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?

A. 1. Claims window. Claims must be filed within 90 days of the loss.
B. unless the flood rider was bought before the loss. The 90-day limit does not apply.
C. 3. Excess. The first 500 of any claim is paid by the customer.
D. 2. Flood cover. Flood damage is covered only with the flood rider.

**Answer:** B. It starts mid-sentence with no heading, so the assistant cannot tell which rule the exception belongs to. Split by heading, and keep the heading with every piece.

**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?

A. A longer system prompt
B. Put the question last, and split by section with page numbers
C. A lower temperature
D. A bigger model

**Answer:** B. The question at the end and labelled pieces with their pages keep the clause findable. A longer system prompt adds more text, a lower temperature (a setting for how random the wording is) changes only the wording, not what the model can see, and a bigger model can still miss detail in the middle of a long input.

## Can you answer these from memory?

**Flash cards**

- **What is a context window?** The most text a model can hold at one time: instructions, document and answer.
- **Is more context always better?** No. Anthropic calls context a finite resource with diminishing returns.
- **Why do models miss detail?** Detail in the middle of a long input is often missed, per a 2023 study.
- **What does retrieval do?** Finds the few chunks that match the question, and sends only those.
- **Where should the question go?** At the end, after the long document. Anthropic reports better answers this way.
- **What is compaction?** Summarising old chat messages, so the context window stays small.

## Likely follow-up questions

- Q083 What is "context rot"? https://designervenkat.online/interview/ai/what-is-context-rot
- Q096 What is compaction (summarising history)? https://designervenkat.online/interview/ai/what-is-compaction-summarising-history
- Q106 Just-in-time retrieval vs preloading context? (full answer coming)
- Q113 What is chunking, and why does size matter? https://designervenkat.online/interview/ai/what-is-chunking-in-rag
- Q138 RAG vs long context: which to use? https://designervenkat.online/interview/ai/rag-vs-long-context

## Learn it in depth

- [Long-Context Processing](https://designervenkat.online/learn/ai-engineering/long-context-processing)
- [Chunking](https://designervenkat.online/learn/ai-engineering/chunking)
- [Context Compaction](https://designervenkat.online/learn/ai-engineering/context-compaction)
