After retrieval and reranking you have more relevant chunks than the context window can hold. Choose what goes in.
Each chunk is a dict with "id", "score" (relevance) and "tokens" (its length). Implement pack_context(chunks, budget, reserve=0):
budget - reserve (leave room for the question and the answer)."source" and overlapping "span" (both optional keys, where span is a (start, end) tuple). Keep the higher-scored one.chunks), plus the total tokens used: (ids, used).