Reorder retrieved chunks so the best sit at the edges of the prompt

Why it matters RAG frameworks offer this reordering because long-context models often miss facts buried in the middle of the prompt.

Language models tend to use information at the start and end of a long context better than information in the middle. A simple fix places the most relevant chunks at the two edges.

Write edge_order(ranked). ranked is a list of chunk ids, best first. Place rank 1 first, rank 2 last, rank 3 second, rank 4 second to last, and so on, alternating front and back, so the least relevant chunks end up in the middle. Return the new list.

Signaturedef edge_order(ranked)

Example

edge_order([1, 2, 3, 4, 5]) gives [1, 3, 5, 4, 2].

Understand the idea

Studies of long-context language models found a U-shaped pattern: facts near the beginning or end of the prompt are used well, facts in the middle are often missed. If retrieval gives us chunks ranked by relevance, we can arrange them so the strongest ones sit where the model looks hardest.

Example with five chunks ranked 1 to 5: place 1 at the front, 2 at the back, 3 next to the front, 4 next to the back, and 5 in the middle. The result reads 1, 3, 5, 4, 2. The two best chunks are the first and last things the model sees.

Rule: front = ranks 1, 3, 5, ...; back = ranks 2, 4, 6, ... reversed; order = front + back.

It costs nothing to compute and is often tried along with reranking and context compression when answers miss facts present in the retrieved text.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleedge_order([1, 2, 3, 4, 5])
  • Sample 2: even lengthedge_order(['a', 'b', 'c', 'd', 'e', 'f'])
  • Test 3: shortedge_order([7])
  • Test 4: emptyedge_order([])