Sending raw retrieved chunks straight into the prompt can use a large share of the context window, which raises API cost and can hurt quality: models often pay less attention to information in the middle of a long prompt, the lost-in-the-middle effect. The fix is to send less, not to buy a bigger window: retrieve only the chunks that matter, then compress them before they are inserted into the prompt.
What you need
- A long document, chunked and embedded
- A retrieval step that returns only relevant chunks
- A token counter for the prompt
Step 1: Retrieve only the chunks that matter
Run the question against the chunked document and keep the top few chunks. Sending the whole document is what fills the window; retrieval is what keeps it small.
Step 2: Compress the retrieved chunks
Use a lightweight summarizer or sentence extractor, such as LLMLingua, to shrink the retrieved chunks before they are inserted into the system prompt. The aim is to drop conversational filler and keep facts, dates and names.
Step 3: Re-count and check the answer still holds
Count the tokens of the compressed prompt and confirm it fits with room for the answer. Then check the answer against the uncompressed chunks: if a fact the answer needs was compressed away, restore that chunk.
Worked example: synthetic long-document fit
The table below is a synthetic example. It shows the expected result of fitting a document; no prompt was sent.
| Stage | Tokens | Fits? |
|---|---|---|
| Whole document | 48,000 | No – over a 32,000 window |
| Retrieved chunks only | 10,000 | Yes |
| After compression | 4,000 | Yes, with room |
| Facts kept | Dates and names kept | Pass |
Expected result (UNTESTED). the whole document does not fit, the retrieved chunks do, and compression leaves 4,000 tokens with all facts kept. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- How much you can safely remove depends on the corpus; measure answer quality and cost together rather than aiming at a fixed percentage.
- Compression can drop a fact the answer needs; check the answer against the uncompressed chunks.
- Models pay less attention to information in the middle of a long prompt, so a shorter prompt is also a more accurate one.
- If compression keeps failing, the document may need re-chunking rather than a bigger window.
