Overview
LLMs often pay strong attention to the start and end of a prompt while missing facts placed in the middle, which creates a U-shaped accuracy curve called Lost in the Middle. This happens because positional encoding decay, causal attention bias, and training data patterns teach models to focus mostly on the beginning and the very end of text.
- Beginning and end get high attention: The first tokens act as attention sinks that stabilize the model, while the latest tokens sit closest to the question at the end.
- Middle tokens get diluted: Over thousands of tokens, rotary position embeddings (RoPE) decay relative signals and softmax spreads attention thin across distracting middle text.
Steps
- Place key facts at the start or end: Put your most important retrieved chunks at the very top or right before the user question instead of burying them in the middle.
- Rerank and trim noisy documents: Use a reranker to keep only the top 3 to 5 relevant chunks so distracting middle text does not dilute attention.
- Add clear chunk tags and citations: Wrap each document in numbered tags like
[Doc 1]and tell the model to cite the tag before answering. - Test retrieval position in your pipeline: Run evaluation checks with the true answer placed at the start, middle, and end to verify accuracy stays flat.
Example
export interface RankedChunk {
id: string;
text: string;
relevanceScore: number;
}
/**
* Reorders retrieved chunks so the highest-scoring facts sit at the
* start and end of the prompt instead of getting lost in the middle.
*/
export function mitigateLostInTheMiddle(
chunks: RankedChunk[],
userQuestion: string,
maxChunks = 6
): string {
// 1. Keep only the top relevant chunks to reduce middle noise
const topChunks = [...chunks]
.sort((a, b) => b.relevanceScore - a.relevanceScore)
.slice(0, maxChunks);
// 2. Place strongest facts at the edges (start and end) and weaker ones in the middle
const ordered: RankedChunk[] = new Array(topChunks.length);
let left = 0;
let right = topChunks.length - 1;
for (let i = 0; i < topChunks.length; i++) {
if (i % 2 === 0) {
ordered[left] = topChunks[i];
left++;
} else {
ordered[right] = topChunks[i];
right--;
}
}
// 3. Build a clean prompt with numbered document tags
const formattedContext = ordered
.map((chunk, idx) => `[Doc ${idx + 1} | id=${chunk.id}]\n${chunk.text.trim()}`)
.join("\n\n");
return [
"Answer the question using only the documents below.",
"Cite the [Doc X] tag for every fact you use.",
"",
"<documents>",
formattedContext,
"</documents>",
"",
`Question: ${userQuestion}`,
].join("\n");
}
// Sample usage
const prompt = mitigateLostInTheMiddle(
[
{ id: "c1", text: "Refunds take 5 business days.", relevanceScore: 0.96 },
{ id: "c2", text: "Store hours are 9 AM to 6 PM.", relevanceScore: 0.42 },
{ id: "c3", text: "Support email is help@example.com.", relevanceScore: 0.65 },
{ id: "c4", text: "Return window is 30 days.", relevanceScore: 0.91 },
],
"How many days do I have to return an item and get a refund?"
);
console.log(prompt);
Tips
- Put the question at the very bottom: Repeating or placing the user question after the long context keeps the newest tokens focused on what to look for.
- Send fewer, better chunks: Sending 5 clean chunks almost always beats sending 30 noisy chunks, even in a 128k context window.
- Check your model’s needle-in-a-haystack score: Newer long-context models handle middle facts better, so benchmark your exact model at your real prompt length.
You must log in or register to comment.