Pack retrieved chunks into a token budget for the prompt

Why it matters Every RAG prompt builder must fit the most relevant chunks into a fixed context budget without repeats.

After retrieval, the prompt builder must choose which chunks to include under a token budget, skip exact duplicates, and present them in reading order.

Write pack_context(chunks, budget). Each chunk is a dict with "id", "doc", "pos", "tokens", "score" and "text". Go through chunks by score descending (ties by smaller id). Skip a chunk whose text, after strip(), equals an already selected chunk's text. If its tokens fit in the remaining budget, select it; if not, skip it and keep trying lower-scored chunks. Return the selected ids sorted by (doc, pos).

Signaturedef pack_context(chunks, budget)

Example

pack_context([{"id": 1, "doc": "a", "pos": 2, "tokens": 50, "score": 0.9, "text": "x"}, {"id": 2, "doc": "a", "pos": 0, "tokens": 60, "score": 0.8, "text": "y"}, {"id": 3, "doc": "b", "pos": 0, "tokens": 30, "score": 0.5, "text": "z"}], 90) gives [1, 3].

Understand the idea

Retrieval returns more text than fits in the prompt, so the prompt builder solves a small packing problem: include the most useful chunks without going over the token budget. A simple greedy rule works well: go from most to least relevant, take each chunk that still fits, skip ones that do not, and drop exact duplicates that often come from copied pages.

Example: budget 90. The best chunk (50 tokens) fits, leaving 40. The next (60 tokens) does not fit, so we skip it, but the third (30 tokens) still fits, leaving 10. The final list follows reading order: chunk 1 (doc a) comes before chunk 3 (doc b), giving [1, 3].

Rule: for chunks by score: skip duplicates; take if tokens <= remaining; finally sort by (doc, position).

Reading order helps the model follow arguments that span neighbouring chunks.

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

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

  • Sample 1: examplepack_context([{'id': 1, 'doc': 'a', 'pos': 2, 'tokens': 50, 'score': 0.9, 'text': 'x'}, {'id': 2, 'doc': 'a...
  • Sample 2: duplicatespack_context([{'id': 5, 'doc': 'd', 'pos': 1, 'tokens': 10, 'score': 0.7, 'text': 'same '}, {'id': 4, 'doc'...
  • Test 3: nothing fitspack_context([{'id': 1, 'doc': 'a', 'pos': 0, 'tokens': 500, 'score': 1.0, 'text': 'big'}], 100)
  • Test 4: reading orderpack_context([{'id': 9, 'doc': 'b', 'pos': 5, 'tokens': 20, 'score': 0.9, 'text': 'p'}, {'id': 8, 'doc': 'b...