Working with long documents and files
Learn how to get accurate answers from long PDFs, reports and notes: how context windows work, how to ask questions that stay grounded in the text, and how to split a document that is too big.
Students paste lecture notes, job seekers paste job descriptions, analysts paste reports. Long inputs fail in predictable ways: the model skims, mixes up sections, or answers from general knowledge instead of your document. This tutorial shows how to prevent each failure.
You will practise on any long document you have: a PDF chapter, a company policy, a research paper, or a long chat export. You will also write a small Python script that splits a text file into chunks, for the times when a document is too big for one prompt.
Prerequisites: you know the parts of a prompt from *Anatomy of a good prompt*. Python 3.8+ is only needed for the last section.
How the context window works
A model can only read a limited amount of text at once. That limit is the context window, measured in tokens (small pieces of words; roughly, 100 tokens is about 75 English words, though it varies by language). Your prompt, any uploaded files, the earlier conversation and the model's reply all share this one window.
Two things follow. First, a very long chat slowly pushes early messages out of the window or makes the model pay less attention to them. Second, even when a document fits, the model does not read it like a person with a highlighter. It tends to work best when the question is specific and the relevant part is easy to find.
Window sizes differ by model and change often, so check the tool's help page rather than trusting a number from a blog post. Upload limits (pages, file size) are separate from the window and also differ by app and plan.
Common problems with long inputs
| Problem | What you see | Fix |
|---|---|---|
| Skimming | Summary covers the start and end but misses the middle | Ask for a summary section by section |
| Outside knowledge | Answer sounds right but isn't in your document | Tell it to use only the document and to quote the evidence |
| Wrong section | Mixes up two similar clauses or chapters | Label sections and ask it to cite the label |
| Too big | Upload is rejected or the answer ignores later pages | Split the document and work in chunks |
| Long chat drift | Model forgets your earlier rules | Restate the rules or start a fresh chat with a short summary |
Rule 1: instructions first, material clearly marked
Put your instructions before the document, mark where the document starts and ends, and repeat the key question after it if the document is very long. Tags such as <document> work well because they cannot be confused with the text inside.
You will answer questions about the document between the <document> tags.
Rules:
- Use only the document. Do not use outside knowledge.
- After each answer, quote the exact sentence(s) that support it, in quotation marks.
- If the document does not contain the answer, reply: "The document does not say."
<document>
[paste the text here]
</document>
Question: [your question]What to expect: Check that every quote really appears in your document (use Ctrl+F). If a quote is missing or reworded, the answer is not grounded and you should not trust it.
Uploading a file instead of pasting
Most chat tools let you attach PDFs or documents. The same rules apply: put the rules in your message, name the file ("the attached policy PDF"), and ask for quotes with page or section numbers. Scanned PDFs are images, and some tools read them poorly, so if the answer looks wrong, try copying real text from the file.
Rule 2: ask narrow questions
"Summarise this report" gives an average summary. Narrow tasks get better results because the model knows what to look for. Compare these on a 40-page company policy:
Broad versus narrow
| Broad | Narrow |
|---|---|
| "Summarise this policy." | "List every rule about leave that applies in the first 6 months. Quote each rule and give the section number." |
| "What are the risks?" | "List clauses that let the company end the contract early. For each, say who can end it and how much notice is needed." |
| "Explain this paper." | "Explain the method in section 3 in simple English for a second-year student. Then list the datasets used." |
Rule 3: summarise in layers
For a long document, do not ask for one big summary. Ask for a structure first, then go deeper only where you need to. This is a small prompt chain (see *Prompt chaining: breaking big tasks into steps*).
A layered reading workflow
- 1Ask for an outline: the document's sections and what each is about, in one line each.
- 2Pick the sections that matter to you and ask for a detailed summary of just those.
- 3Ask targeted questions with quotes on the parts you will act on.
- 4Finally ask for a one-page summary built from the verified section summaries.
Read the document below and give me an outline: each section or chapter heading (or, if there are none, each major topic), followed by one line on what it covers. Do not summarise the details yet.
<document>
[paste or attach the document]
</document>What to expect: A good outline lists every section in order. Use it to see whether the model has understood the whole document before you spend time on details.
Using only the document, summarise sections [list of sections] for a reader who [who you are, e.g. is preparing for an exam / must decide whether to sign this].
For each section give:
- 3 to 5 bullet points of the main ideas
- Any numbers, dates or conditions, exactly as written
- Anything that looks unclear or contradictory
If a section is not in the document, say so.What to expect: The last line stops the model from inventing a section that doesn't exist. Numbers and dates should match the document word for word.
Comparing and extracting across documents
You can give the model two or three documents and ask it to compare them. Label each clearly so it can refer to them. A table is usually the best output for comparisons because gaps become visible.
Compare the two documents below on these points: [point 1], [point 2], [point 3].
Reply as a table with columns: Point | Document A | Document B | Difference. Use short quotes where possible. If a document says nothing about a point, write "not stated".
<document name="A">
[text of first document]
</document>
<document name="B">
[text of second document]
</document>What to expect: Spot-check two or three rows against the originals. Comparisons are where models most often mix up which document said what.
Do not paste private or confidential data
Do not paste other people's personal data, company secrets, exam papers under embargo or confidential contracts into a public AI tool. Check your college or employer's policy first. Many tools have settings that control whether your chats are used to improve the model; read them. In India, personal data about others is also covered by the Digital Personal Data Protection (DPDP) Act, so remove names, phone numbers and ID numbers when you don't need them.
When the document is too big: chunking
If a file is too large for one prompt, split it into chunks, process each chunk with the same instructions, then combine the results. This is often called map-reduce: *map* each chunk to a short result, then *reduce* all the short results into one answer.
Two details matter. Split at natural boundaries (paragraphs, not the middle of a sentence), and let chunks overlap slightly so an idea cut at the edge appears whole in one of them. The script below splits a plain-text file by paragraphs and writes numbered chunk files you can paste one by one.
import sys
from pathlib import Path
def split_into_chunks(text, max_chars=8000, overlap_paragraphs=1):
"""Split text on blank lines into chunks of at most max_chars characters.
The last `overlap_paragraphs` paragraphs of each chunk are repeated at the
start of the next chunk, so ideas cut at a boundary are not lost.
"""
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks = []
current = []
size = 0
for para in paragraphs:
if current and size + len(para) > max_chars:
chunks.append("\n\n".join(current))
current = current[-overlap_paragraphs:] if overlap_paragraphs else []
size = sum(len(p) for p in current)
current.append(para)
size += len(para)
if current:
chunks.append("\n\n".join(current))
return chunks
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("Usage: python split_text.py yourfile.txt")
source = Path(sys.argv[1])
chunks = split_into_chunks(source.read_text(encoding="utf-8"))
for number, chunk in enumerate(chunks, start=1):
out = source.with_name(f"{source.stem}_part{number:02d}.txt")
out.write_text(chunk, encoding="utf-8")
print(f"{out.name}: {len(chunk)} characters")
print(f"Done: {len(chunks)} chunks.")Run it with python split_text.py notes.txt. A single paragraph longer than max_chars stays whole in its own chunk. Lower max_chars if your tool rejects the chunks.
notes_part01.txt: 7941 characters
notes_part02.txt: 7620 characters
notes_part03.txt: 3105 characters
Done: 3 chunks.This is part [n] of [total] of a longer document about [topic]. Do not try to summarise the whole document; work only on this part.
Extract:
- The main points (max 5 bullets)
- Any definitions, formulas, dates or numbers, exactly as written
- Open questions the next part might answer
<part>
[paste chunk n]
</part>What to expect: Save each reply. Keep the output format identical for every chunk so the results are easy to combine.
Below are notes extracted from [total] consecutive parts of one document about [topic]. Combine them into a single study summary.
Rules:
- Merge duplicate points; keep the order of the original document.
- Keep numbers, definitions and formulas unchanged.
- If two parts seem to contradict each other, list the contradiction at the end instead of choosing one.
<notes>
[paste all the chunk replies]
</notes>What to expect: Because the reduce step sees only your extracted notes, anything the map step dropped is gone. That is why the map step asks for exact numbers and definitions.
Retrieval tools do this for you
Some tools (NotebookLM, project knowledge in chat apps, and RAG systems that developers build) search your documents and give the model only the relevant passages. This works well for questions about specific facts, but it can miss answers that need the whole document. For "what is the overall argument?" a layered summary is more reliable. RAG is covered in the AI tracks.
Try it: Audit a long document
Take a document of at least 10 pages (a syllabus, a company policy, a research paper or a rental agreement). 1) Get an outline. 2) Ask five narrow questions using the grounded prompt and check every quote with Ctrl+F. 3) Ask one question whose answer is NOT in the document. Record how many answers were fully supported and whether the model correctly said it did not know.
Long-document checklist
- Instructions come first, and the document is inside clear markers.
- I told the model to use only the document and to say when it isn't there.
- I asked for quotes or section numbers and spot-checked them.
- I asked narrow questions instead of "summarise everything".
- For very large files, I split at paragraph boundaries and kept the same instructions for every chunk.
- I removed private data that the model doesn't need.
Key takeaways
- Your prompt, files, chat history and the reply all share one context window, and it is limited.
- Mark the document clearly, put instructions first, and tell the model to use only the document.
- Ask for quotes with section numbers, then verify a sample yourself.
- Summarise in layers: outline, chosen sections, then a final summary.
- For files that are too big, split into overlapping chunks, map each one with identical instructions, then reduce the results.
- Keep confidential and personal data out of public tools.
Check yourself
Finishing the quiz marks the lesson as done.
1. You paste a 30-page policy and the model gives a confident answer that sounds right, but you can't find it in the document. What most likely happened?
2. Which request is most likely to give a reliable result on a long report?
3. Why should chunks overlap slightly when you split a document?
4. In the map-reduce approach, what does the reduce step do?
5. A model's summary of your 50-page document covers only the first and last pages well. What is the best next step?
Saved on this device. Create a free account to keep it on every device.
Practise this with Sam
A real mock interview, out loud, with an honest scorecard. Free to start.