In RAG, the retrieved chunks and the user query are combined into a prompt, and the larger the context sent to the model, the higher the cost, while stuffing the context window is also more expensive than retrieval itself. More chunks give the model more evidence, but they also add noise, push the key evidence into the middle where models read it worst, and can overflow the window. The fix is a token budget for retrieved context: rank the chunks, add them in order, and stop when the budget is spent.
What you need
- The model context window size
- A token budget for retrieved context, for example half the window
- The ranked chunks the retriever returned
Step 1: Set the chunk budget in tokens
Decide how many tokens of retrieved context the prompt may carry, leaving room for the system message, the question and the output. Half the window is a reasonable starting point, not a rule.
Step 2: Add chunks in rank order until the budget is spent
Take the ranked chunks from the retriever and add them one by one, counting tokens as you go. Stop when the next chunk would exceed the budget, even if more chunks exist.
Step 3: Check the answer still has its evidence
Ask a question whose answer is in a chunk near the budget edge. If the model misses it, the budget cut the evidence, and you need a smaller chunk size or a better ranking, not a bigger budget.
Worked example: synthetic chunk budget for one question
The table below is a synthetic example. It shows the expected result of budgeting retrieved chunks; no search was run.
| Chunk rank | Tokens | Included? |
|---|---|---|
| 1 | 500 | Yes |
| 2 | 500 | Yes |
| 3 | 500 | Yes |
| 4 | 500 | No – budget spent |
| Budget | 1,500 of 4,096 | 3 chunks included |
Expected result (UNTESTED). 3 chunks fit the 1,500-token budget and the fourth is left out, so the prompt stays inside the window. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- LongLLMLingua mitigates the lost-in-the-middle issue in long contexts, which is one reason to compress rather than stuff the window.
- A bigger budget is not always better: more chunks can add noise that buries the right evidence.
- The budget must leave room for the output, or the model will stop mid-answer at the window edge.
- If the answer needs a chunk that never ranks in the top-k, the fix is retrieval quality, not a larger budget.
