Long Inputs and Context Failure Modes
Choose between truncation, summarisation and retrieval for inputs that are too long to send, and know what each one loses. See why information in the middle of a long context is used least, how to order material around that, and how distraction, clash and poisoning make a context mislead the model.
Contentsand lesson path
On this page
- Why it matters
- Three strategies for input that does not fit
- Position effects: lost in the middle
- When the context misleads
- Check your understanding
- Apply it
- Review prompt
Lessons of Tokens & Context
- How an LLM Writes: One Sampled Token at a Time Concept · 20 min
- Tokenizers in Practice: Counting Tokens and Cost Worked example · 15 min
- Context Engineering: What Goes In and How Much Concept · 15 min
- Lab: Trim a Conversation to Fit a Budget Lab · 25 min
- Long Inputs and Context Failure Modes Concept · 15 min
- Check: Generation and Context Budget Scenarios Knowledge check · 8 questions
What you will learn
- Choose a strategy for long inputs (truncation, summarization or retrieval) and explain its quality trade-off, including position effects.
01. Why it matters
Real inputs are long: a 300-page contract, a year of support tickets, a log with a hundred thousand lines, a whole codebase. Sometimes the input is larger than any context window. More often it would fit in a modern window, but sending all of it on every request is slow and expensive, and the answers can get worse rather than better.
So for each feature that reads long material you make a choice: which part of the input the model sees, in what form and in what order. Every choice loses something. This lesson compares the three basic strategies, shows how the position of information inside the context changes whether the model uses it, and names the ways a context can mislead the model even when it fits.
02. Three strategies for input that does not fit
Truncation keeps part of the input by position: the start, the end, or both. It costs nothing extra, is predictable and is easy to test. Its weakness is that it is blind: it keeps text because of where it is, not because of what it says. The script below keeps the start and end of a checkout log and loses the one line that mattered.
import tiktoken
enc = tiktoken.get_encoding('o200k_base')
MARKER = '\n[... middle omitted ...]\n'
def keep_head_and_tail(text: str, limit: int) -> str:
ids = enc.encode(text)
if len(ids) <= limit:
return text
room = limit - len(enc.encode(MARKER))
head, tail = ids[: room // 2], ids[len(ids) - (room - room // 2) :]
return enc.decode(head) + MARKER + enc.decode(tail)
lines = [f'09:{m:02d} INFO checkout ok, order {48000 + m}' for m in range(60)]
lines[31] = '09:31 ERROR payment provider timed out, order 48031 not charged'
log = '\n'.join(lines)
short = keep_head_and_tail(log, limit=200)
print(len(enc.encode(log)), '->', len(enc.encode(short)), 'tokens')
print('ERROR kept?', 'ERROR' in short)723 -> 199 tokens
ERROR kept? FalseTruncation fits when position predicts value: the newest lines of a log while you watch it, the top of an email thread, the latest turns of a chat. Always mark the cut, as MARKER does, so the model knows text is missing instead of assuming it saw everything.
Summarisation compresses the input with a model. For a long document you summarise each chunk and then summarise the summaries (often called map-reduce); for a conversation you keep a running summary. It preserves the gist of the whole input, which suits questions about themes, progress or tone. It costs extra model calls and time, it drops specifics such as figures, names and exact wording, and it can introduce errors that every later step then trusts.
Retrieval splits the input into chunks, indexes them, and for each question sends only the chunks that look relevant. It scales to very large collections and keeps the original wording, so answers can quote and cite. It fails when the search misses (the question uses different words from the text), when a chunk loses the context it needs, or when the answer depends on the whole document rather than a few places in it. The embeddings, chunking and RAG skills of this track build it properly.
One more pattern matters when nothing may be missed: an exhaustive pass runs the same prompt over every chunk and then combines the results. It is the map step of map-reduce without the lossy summary, and it costs one call per chunk. A quick guide:
- a lookup of specific facts in a large collection: retrieval;
- an overview of themes or progress: summarisation;
- recent material that matters most: truncation that keeps the newest part;
- a review that must not miss any instance: an exhaustive pass.
03. Position effects: lost in the middle
Fitting into the window does not mean the model uses everything equally. In Lost in the Middle (Liu et al., 2023), models answered questions from a set of retrieved documents, and the researchers moved the one document with the answer to different positions. Accuracy was highest when that document came first or last and lowest when it sat in the middle, a U-shaped curve, and that held for models built for long contexts too.
Models have improved since then, and many now find a single planted sentence almost anywhere in a long input. Harder tasks, which combine several facts or ignore near-misses, still get less accurate as the context grows; Anthropic's documentation calls this context rot. The practical rules have not changed:
- Send fewer, better passages. Each weak passage pushes the strong ones apart.
- Put the strongest material at the edges and the weakest in the middle.
- Put long documents first and the instructions and question last. Anthropic reports that questions placed at the end improved response quality by up to 30% in its tests, especially with several documents.
- For long documents, ask the model to quote the relevant passages first and then answer from the quotes.
Rule 2 is a few lines of code. Given passages in ranked order, alternate them between the front and the back of the list:
def edges_first(ranked: list[str]) -> list[str]:
"""Put the strongest items at the start and end, the weakest in the middle.
`ranked` is ordered best first, as a retriever returns it.
"""
front: list[str] = []
back: list[str] = []
for i, item in enumerate(ranked):
(front if i % 2 == 0 else back).append(item)
return front + back[::-1]
ranked = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'] # p1 is the most relevant
print(edges_first(ranked))['p1', 'p3', 'p5', 'p6', 'p4', 'p2']The two best passages, p1 and p2, now sit at the two edges and the weakest, p5 and p6, in the middle. Treat this as a default to measure, not a law: test your own prompts with the key fact at the start, middle and end, and keep the layout that answers best.
04. When the context misleads
A context can fit the budget and still produce bad answers. In 2025 Drew Breunig gave names to the common patterns, and three of them account for most problems you will meet:
- Distraction. The context is so long or so noisy that the model leans on it instead of reasoning: it copies the pattern of earlier turns, or uses an irrelevant passage or tool just because it is there. Breunig separates the second case as confusion. Mitigation: curate harder, cap passages, and offer only the tools a task needs.
- Clash. Parts of the context disagree: two versions of the refund policy, a retrieved page that contradicts the system prompt, an early turn that a later one corrected. The model has to guess which to follow. Mitigation: label sources with dates and versions, remove superseded material, and state which source wins.
- Poisoning. A mistake gets into the context and is reused as fact on every later call: a hallucinated detail in a running summary, a wrong tool result, or instructions hidden inside a retrieved web page (prompt injection). Mitigation: keep track of where each piece came from, validate summaries and tool output, treat retrieved text as data rather than instructions, and be able to rebuild the context from the original sources.
All three get worse as contexts grow, which is the same lesson again: a smaller, deliberately chosen context usually beats a full one.
05. Check your understanding
06. Apply it
Give the practice project's request builder a long-input policy:
- Decide what happens when a single retrieved passage is larger than the whole passage cap: skip it, or keep its start and end with
keep_head_and_tail. Write the reason in a comment. - Order the selected passages with
edges_firstand keep the question last in the user message. - Build a small position test: 20 filler passages and one passage with a fact the question needs, placed at position 1, 10 and 20. Generate the three prompts and check their token counts against your budget.
- With API access, run each prompt five times, record how often the answer is right at each position, and keep the numbers in your project notes. Without access yet, keep the prompts and run them after the next skill.
07. Review prompt
Without looking back, compare truncation, summarisation and retrieval: what each keeps, what each loses, what each costs, and one task each suits. Add the exhaustive pass and say when it is worth its cost. Then explain the lost-in-the-middle result in two sentences, give three layout rules that follow from it, and describe distraction, clash and poisoning with one example and one mitigation each.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.