Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 15 min · revision 2

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

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.

Python · truncate.py
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)
Expected output (python truncate.py, tiktoken 0.14)
723 -> 199 tokens
ERROR kept? False

Truncation 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:

  1. Send fewer, better passages. Each weak passage pushes the strong ones apart.
  2. Put the strongest material at the edges and the weakest in the middle.
  3. 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.
  4. 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:

Python · order.py
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))
Expected output (python order.py)
['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

Practice check · 3 questions

Long inputs and position

Three design decisions for long contexts.

Q1. Your retriever returns six passages ranked by relevance, and all six fit the budget. Given position effects, how should you lay out the prompt?
Q2. In turn 3 a chat assistant's running summary recorded the wrong order number. Every later answer repeats it, even after the user corrects it once. Which failure mode is this, and what fixes it?
Q3. A compliance team must find every clause in a 300-page contract that limits liability. Which approach fits best?
Practice only: not graded, not saved, not evidence.

06. Apply it

Give the practice project's request builder a long-input policy:

  1. 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.
  2. Order the selected passages with edges_first and keep the question last in the user message.
  3. 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.
  4. 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check