When debugging a case where the answer was wrong, I couldn’t find fault with the retrieval results: several passages were present, and the standard answer was hidden in one of them. I re-fed these fragments in a different order, unchanged, and the model answered correctly.
The only difference was the ordering. In production, they were concatenated by similarity from high to low, and the most relevant passage happened to land in the middle, sandwiched between two weaker pieces of evidence.
After that, I stopped treating context construction as glue code that “joins strings together.” It is actually arranging a temporary set of materials for the model: which go first, which go later, what label each carries, and how much budget they take in total—each of these changes the answer. This layer of work is less visible than swapping models or tuning embeddings, but it is cheap to change and can be validated independently, so the cost-effectiveness is often higher.
Post 10/15 in this series · Previous: Reranking: The Benefits and Costs of a Two-Stage Architecture · Next: RAG Evaluation: No Test Set, No Optimization
Putting the most relevant passage in the middle is the same as not including it
Long-context models generally use information at the beginning and end better than in the middle; this phenomenon is often called lost in the middle. It is not a formula you can apply precisely, but it is enough to overturn a default practice: sort the most relevant fragments by score in descending order and let the model handle the rest. Descending order pushes everything after ranks 2 and 3 into the middle, while most answers need several pieces of evidence to support each other.
My current arrangement rules are simple:
- Put the strongest evidence at the beginning and the end, and put relatively secondary, background-only material in the middle;
- Order by argument sequence rather than score sequence; when materials have causal or temporal relationships, preserve them;
- Try to avoid adjacent fragments coming from the same
doc_id, so that several consecutive passages repeating the same text do not eat up attention; - Keep the final number of fragments at 5–8; beyond that, the gain from additional fragments usually cannot offset attention dilution.
I usually write the wrapping format like this: each passage starts with a number, followed by a line of source (path plus anchor, publication time and update time), and the body is wrapped in a uniform tag; after all materials, write the answering requirements—answer only based on the above materials, mark the source number after each conclusion, and if the materials are insufficient, directly say it cannot be confirmed; the user question comes last.
Three notes. The numbers are anchors for citation validation; after generation, check whether the numbers appearing in the answer really exist in the materials sent in. Sources and dates are the basis for judging timeliness. Answering requirements placed after the materials and immediately before the question are easier to follow than stuffing them deep in the system prompt. With the same model, moving constraints from system to just before the question produces a change in compliance rate that is visible in manual spot checks. I suggest you verify this yourself with twenty cases; don’t take my word for it.
Deduplication and budget determine whether you waste slots
After fusion and reranking, candidates often include multiple chunks (slices) of the same article, different pagination, and old and new versions. Without deduplication, three of five context passages are the same text, which means two slots are wasted.
1 | def build_context(candidates, budget_tokens, tokenizer): |
This section contains three constraints: rate-limit by doc_id, keeping at most two per document; perform approximate deduplication based on the first 120 characters of the body; and skip fragments that have been superseded by newer versions.
is_superseded handles the problem in post 4 where old and new conclusions conflict: when a fragment with a higher revision of the same doc_id is present, the old fragment does not enter the context. But some old articles are the only source and cannot be discarded indiscriminately by date. So my approach is downweighting plus explicit labeling rather than deletion: write in the wrapper “published in 2021, may be outdated,” return the judgment to the model, and prompt it to be cautious.
The budget should be split by role, not just given as one total for context: total window = system instructions + tool definitions + conversation history + retrieved materials + user question + output reserve.
The output reserve is the easiest to forget. If you stuff the context until only a few hundred tokens remain, the model is forced to give a very short or even truncated answer. I explicitly reserve space for output, more for generative tasks, and log the actual token proportion of each part. This proportion table is also the first place to check when investigating “why have recent answers gotten shorter”—much faster than digging through prompts.
Tokens saved by compression are paid for with faithfulness
There are three types of context compression, with increasing risk.
Extractive compression keeps only sentences relevant to the query, scored by rules or a lightweight model. It is controllable, cheap, and introduces no new facts, but it easily deletes transitions and qualifiers along with the rest: “usually works, except for monthly-settlement accounts” gets cut to “usually works,” and the conclusion flips. My rule is to keep qualifier sentences, negative sentences, and conditional sentences whole, with no intra-sentence truncation.
Abstractive compression uses a small model to compress long fragments into a few sentences. It saves more but loses details and may introduce summaries not present in the original. It is suitable for background material, not for evidence passages carrying precise numbers or clauses.
Token-level compression (approaches like LLMLingua) uses a small model to estimate the information value of each token for the current query and deletes low-value ones. It has the highest compression ratio, but the output is often no longer fluent natural language, readability is poor, and mistakenly deleting numbers and proper nouns is costly.
In actual production, I only do two things: when tracing back to parent documents, trim by section rather than stuffing in the whole article (post 5), and apply extractive compression to obviously overlong background material. Evidence passages are never compressed. The criterion is straightforward: if deleting it could change the answer, don’t delete it. Compression saves latency and cost, and pays with faithfulness; these two should not be bundled into the same trade by default.
A similarity threshold cannot decide whether to answer
I have tried using a similarity threshold to decide “whether to answer,” and it is basically ineffective: there is always something in the corpus with a decent similarity score that is completely irrelevant, and once the model gets it, it can cobble together a plausible-looking answer. A more reliable approach is two-stage judgment: first let the model look only at the titles and abstract list of candidate materials and judge whether any material can answer this question; if not, refuse directly; if yes, proceed to fragment construction and generation. On my own small evaluation set, this change brought a much larger improvement than swapping the embedding model.
Timeliness conflicts need to be made explicit through metadata. The wrapper carries published_at, updated_at, and revision, and the instructions state: “when materials conflict, prefer the one with the later update time and explain that there is disagreement.” Don’t expect the model to infer from the body which one is newer; it has no reason to know whether 2021 or 2026 comes first.
After generation, there is still work pure code can do
Between generation completion and returning to the user, there is a small, inexpensive piece of work that can be done:
1 | def post_check(answer, picked): |
Citation number validation is cheap, yet it blocks the most glaring type of hallucination: an answer that cites “material 7” which was never sent in. A stricter approach is to check sentence by sentence whether the numbers, dates, and proper nouns in the answer can be supported by the materials; the cost is another model call, so I only enable it in scenarios with high compliance requirements.
Another thing that often gets skipped is recording the actual prompt sent to the model. Without that snapshot, the failure-attribution table in Post 4 can’t be filled in at all: you don’t know what the model actually saw, so you can only guess. I write context_snapshot into the trace along with each chunk’s chunk_id, score, and position, so when something goes wrong I can reproduce it in one click instead of re-narrating symptoms and hoping the signals match.
When this layer isn’t worth building
Treating context construction as its own layer has a clear benefit: the boundaries are clean. Position arrangement, deduplication, budgeting, citation, refusal, and validation each have a home, and any change can be evaluated in isolation; the trace also makes production issues reproducible. The cost is an extra layer of code and a wrapping format, and that format is tightly coupled to the model—when you switch models, instruction placement, numbering style, and tag format usually all need re-validation. This part of the model-migration cost is often underestimated because it isn’t on any version of the design doc’s evaluation checklist.
The cases where it doesn’t apply are equally clear. For single-chunk, short Q&A where the answer barely depends on multiple pieces of evidence, careful arrangement yields little; a template join is enough. Conversely, for multi-hop reasoning, cross-document comparison, and cases where the materials themselves conflict, this layer is nearly decisive: with the same batch of retrieval results, good versus poor arrangement is, in the cases I’ve seen, the difference between getting the answer right and not getting it at all.
The chain from corpus to answer ends here. But “I think it got better” doesn’t count: all five layers—splitting, embedding, fusion, reranking, and arrangement—can be tuned, and without evaluation you don’t know which layer to touch. The next post covers how to turn this chain into a measurable system.
Here’s a self-check question: can you right now print the complete context_snapshot for a given answer, including each chunk’s position, token count, and final order? If you can’t, then all of the above discussion is basically guesswork.
Comments