Context engineering

Lost in the Middle in RAG

Separate candidate depth, prompt depth and temperature, then measure what changes answer quality.

The model received the evidence. Did it use it?

A service assistant prepares guidance for an AX-450 inverter running an older firmware release. Search finds a passage that states the relevant condition. Reranking brings the passage near the top. The final prompt then contains a long concatenation of manuals, error reports and other snippets. The exception is in the middle, surrounded by pages about different revisions. The assistant repeats the general procedure and omits the exception. A search improvement may not change this failure because the answer stage already received the right evidence.

Liu and colleagues studied how models used information at different positions within a long input. In their evaluated settings, performance often fell when the relevant information was placed in the middle compared with the beginning or end. That result is a reason to test packing and position on your chosen model and workload. It does not establish that every model has the same failure pattern or that a particular position always works. Long inputs can also fail because of truncation, contradictory sources, or instructions that do not describe what to do with an exception.

Reserve separate budgets for finding and presenting evidence

Top k can refer to different controls. In retrieval, it is the number of candidates returned by a search stage. Some systems also set how many candidates a reranker examines, how many of those it keeps, and how many passages get packed into the final prompt. A generation setting sometimes called top-k sampling has a different meaning. It restricts the token candidates considered at a decoding step. Changing it cannot add retrieved passages.

Give the settings names that reflect their jobs. For example, a service might ask BM25 and vector search for 30 results each, deduplicate and fuse them, rerank up to 25, and select up to 6 distinct evidence passages under a token budget. Those numbers are illustrative. The first depth should give the ranker enough breadth to find supporting evidence. The final depth should leave room for the discriminating facts without overwhelming the prompt. Log actual counts rather than only configured caps, since deduplication, permissions and document availability can reduce them.

If a required bulletin lands at rank 31, the 30-candidate search might miss it even if there is space for more final passages. If it enters the reranker and is retained but goes missing when packing context, raising the candidate depth is unlikely to address the cause. Diagnose at each boundary.

Example settings at three different stages
StageExample settingWhat it controls
First-stage retrieval30 per branchWhich candidates reach fusion.
RerankingUp to 25How many fused candidates receive a second score.
Prompt packingUp to 6 passagesWhich evidence the answer model can use.

Use an input budget that accounts for real tokens

Suppose the input budget allocated to evidence is 2,400 tokens after reserving space for system instructions, conversation turns and the expected answer where the model uses a combined context budget. Six passages averaging 300 tokens plus 40 tokens of reference metadata each consume about 2,040 tokens. One long passage can still force the prompt over budget. The maximum length the model accepts and the length it can use effectively are separate questions.

Build a packer that counts tokens with a compatible tokenizer and includes source headers, separators and tool schemas when they consume context. Track where the text was truncated. Prefer shortening a passage at a sensible boundary or selecting a more focused excerpt instead of cutting the last sentence of a safety or eligibility rule. Retain enough context to identify the source, product and revision. In a conversational system, a longer chat history can use budget previously available to evidence, so test both short and long conversations.

Review repeated evidence before you pack it. Three overlapping excerpts can take the space of one excerpt plus the missing prerequisite. Merge or de-duplicate overlapping regions from the same approved source and version. If the answer needs two different sources, preserve both even if one ranks lower individually. Context budgets are about coverage as well as length.

Move one passage while holding everything else steady

To diagnose a position effect, design a paired experiment. Take an authorised query, one short definitive passage, several plausible distractors, and a reference answer. Keep the passage set and lengths fixed. Put the definitive passage near the beginning of the evidence block in one run, in the middle in another, and near the end in a third. Make sure the full block reaches the model in all three runs. Use the same instructions, query, model version, and decoding settings.

For the inverter question, the definitive passage might say that the revision B procedure depends on harness H-17. Distractors might be a generic firmware update procedure and results for revision C. In each variant, check whether the response states the condition and cites the correct source. A result such as ten correct answers near the start and six in the middle on a small set is a prompt for further testing, not a reliable rule for deployment. Repeat on more workloads, vary distractor placement, and look for the same failure across document families and model versions.

Keep independent checks for unsupported claims and incorrect references. If a passage is cited but fails to support the answer, count that as an answer error. If the experiment accidentally truncates the middle position, fix the token accounting before making a claim about model attention.

Evidence-position experiment. Replay the same passages with the supporting passage near the start, middle and end. Keep the model and settings fixed, and score all variants against the same reference.

Choose the final top k by the evidence a question needs

Try a small set of final depths such as 3, 6 and 10 under both a fixed passage count and a fixed evidence token limit. A narrow product lookup may need one authoritative record plus the current bulletin. A procedure that combines a prerequisite, an exception and an approved escalation may require three distinct passages. Add cases with no eligible evidence to see whether more retrieved text tempts the model into inventing an answer.

In an illustrative run, retrieving more final passages raises evidence coverage from 75 to 88 out of 100 eligible queries. Answer support improves from 70 to 74. If nearly all new answer failures contain contradictory revisions or near-duplicate snippets, inspect what the context packer is doing. Use the current source by default when a supersession relation is known. Keep both versions when the user requests a comparison, and label them clearly. Promote the directly applicable evidence near the question or another tested position. Always test order on your model rather than relying on a universal recipe.

A multi-source question can break a policy that always selects the six highest individual scores. Two passages can together answer the question although one has only moderate relevance by itself. Evaluate whether evidence diversification, metadata constraints or intent-specific budgets help recover those combinations. Measure the added latency as well as accuracy.

Temperature changes the decoding distribution

P(token i) = exp(logitᵢ / T) / Σⱼ exp(logitⱼ / T), for T > 0

For ordinary token sampling with positive temperature, a decoder scales its logits before softmax. Lower temperature sharpens the distribution and typically makes high-scoring tokens more likely. Higher temperature gives more probability to alternatives. A temperature of zero is usually a provider's shorthand for a greedy or near-greedy mode where supported. Check the model's documented controls. A model can produce the same confident wrong answer repeatedly when the necessary evidence is absent or ambiguous.

For grounded service answers, a low-temperature configuration is a reasonable baseline where available. Compare it with a second supported setting while keeping evidence constant. In one example, both settings produce wording that sounds distinct, yet both miss the revision B exception because the hardware condition was never in the prompt. In another, all evidence is present and a higher setting produces extra speculative advice that the evidence does not support. Those outcomes reflect different problems. The first calls for context repair, while the second calls for stricter answer evaluation and perhaps adjustments to decoding or instructions.

Avoid relying on a low-temperature setting as a reproducibility guarantee. Serving infrastructure, batching, model updates and tie handling can affect results. Use repeated trials and record the settings and model version. Research on decoding such as Holtzman and colleagues' work on nucleus sampling shows the importance of sampling choices for generated text. It does not establish a factuality guarantee for a particular temperature in RAG.

This example applies temperature alone at one decoding step. Other controls, such as nucleus sampling, can further change which tokens are eligible. The percentages are rounded independently. They describe the next token. Assess support for the answer and its sources separately.

Illustrative next-token probabilities for logits [2, 1, 0]
TemperatureToken AToken BToken C
0.586.7%11.7%1.6%
1.066.5%24.5%9.0%
2.050.6%30.7%18.6%

Make answers useful when the evidence is incomplete

Suppose the model input contains an approved update procedure but has neither the installed revision nor an applicable bulletin. A useful answer might be, “I found the update procedure. I need the hardware revision to confirm whether it applies to this unit.” When two authorised documents disagree, show the source labels and dates if relevant, explain the uncertainty, and follow the procedure for resolving the conflict. A grounded assistant should be evaluated on these outcomes as well as on direct answers.

Make it possible to inspect the actual evidence passed into the model. Save the selected IDs and ordering, token count, truncation decisions and the source cited. Keep the trace within the application's access and retention policy. That lets a reviewer distinguish a missing candidate, a context-budget omission, and a failure to use evidence that was present. Use this trail to reproduce the example rather than tuning every setting at once.

When time permits, score answer statements against the specific passage. A citation to a broad manual can make a response look more reliable than it is. The relevant test asks whether the cited text establishes the recommendation for the correct revision and firmware version.

Repeat the experiment at two levels of distraction

Start with an easy controlled set where irrelevant passages share few words with the question. Then add distractors that look useful, such as a bulletin for a different revision, an earlier policy with a different threshold, or a neighbouring runbook that uses the same field names. At the same position and depth, compare results between these sets. A larger gap on plausible distractors tells you something different from a uniform penalty at the middle position.

Keep one deliberately contradictory case. If the approved current bulletin and an old guide give different instructions, state which source the assistant should prefer or when it should escalate. Ask reviewers to score the response after masking the model and configuration names. That helps avoid attributing a preferred answer style to better handling of context. Report the result with the document set and exact variant so a future model change can be evaluated under the same conditions.

Debug in the order information moves through the system

Start by checking whether the source contains the required evidence and whether the user can access it. Inspect retrieval and the rerank pool, then confirm the prompt contains the full applicable passage. Measure how ordering and packing affect supported answers. Adjust generation settings after those stages are understood. When tuning, change one family of settings at a time so a gain can be attributed to a particular intervention.

For a rollout, declare the operating point in terms of supported answers, meaningful clarifications, response time and evidence token cost. Include degraded cases when a search or ranking service times out. Store a small position-sensitivity regression set for changes to prompt formatting or model selection. Recheck it alongside your usual retrieval evaluations. With those controls in place, the original long-prompt failure becomes measurable and reproducible, and the team can choose a context budget that serves the technician rather than maximising how many passages it can send.

More in the retrieval engineering series

Contact Cortex IR