RAG · Lesson 49 of 120
Order Matters
Lost in the middle.
Researchers found that models pay most attention to the start and the end of a long prompt. Facts in the middle are more easily missed. This is called lost in the middle.

- Start and end get attention
- Middle gets missed
- Lost in the middle
Best chunks at the edges
Reorder takes hits in score order. It sends the first, third, and fifth to the front, and the second, fourth, and sixth to the back, reversed. Run it. The two best chunks now sit at the start and the end, and the weakest sit in the middle.
reorder.pypython
from rag_kit import load_docs, make_chunks, Index
index = Index(make_chunks(load_docs()))
def reorder(hits):
front, back = [], []
for i, hit in enumerate(hits):
(front if i % 2 == 0 else back).append(hit)
return front + back[::-1]
hits = index.search("How long does the battery last?", k=6)
print("by score: ", [s for s, c in hits])
print("reordered:", [s for s, c in reorder(hits)])Output
by score: [0.38, 0.37, 0.33, 0.28, 0.2, 0.19] reordered: [0.38, 0.33, 0.2, 0.19, 0.28, 0.37]
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]When to reorder
With three to five short chunks, order barely matters. With many chunks, put the best at the edges. LangChain has a long context reorder tool that does exactly this.
| key | value |
|---|---|
| Few chunks | order barely matters |
| Many chunks | best at the edges |
| LangChain | LongContextReorder |
| Better still | send fewer |
Summary
Models miss facts in the middle of long prompts. Put the best chunks at the start and the end. Next, practice with ten questions.
Key takeaways- Lost in the middle
- Best at the edges
- Send fewer
Next up: Practice: Ask the Help Centre — ten questions