LLMLingua compresses prompts for accelerated inference of large language models, using a compact, well-trained language model to identify and remove non-essential tokens. The method achieves up to 20x compression with minimal performance loss, and LongLLMLingua extends it to long-context scenarios, improving RAG performance by up to 21.4 percent using only a quarter of the tokens. Use compression when the prompt is too long for the context window or too expensive to send whole, but never compress the instruction or the question itself.
What you need
- Python with llmlingua installed
- The long prompt and the target token count
- A test question whose answer is in the prompt
Step 1: Separate what must stay from what can shrink
Keep the instruction and the question untouched, and mark only the background context as compressible. A compressed instruction can change the task, and a compressed question can lose the thing being asked.
Step 2: Compress to the target token count
Create a PromptCompressor and call compress_prompt with the prompt, the instruction, the question and the target token count. The result reports the origin tokens, the compressed tokens and the compression ratio, so you can see what was removed.
Step 3: Check the answer survives compression
Send the compressed prompt to the model with the test question and compare the answer with the answer from the full prompt. If the answer changes, lower the compression ratio or force the key tokens to stay.
Worked example: synthetic prompt compression check
The table below is a synthetic example. It shows the expected result of compressing a prompt; no prompt was compressed.
| Version | Tokens | Answer correct? |
|---|---|---|
| Full prompt | 2,365 | Yes |
| Compressed to 211 | 211 | Yes – 11.2x compression |
| Compressed to 50 | 50 | No – key facts lost |
| Decision | 211 chosen | Same answer, tenth the tokens |
Expected result (UNTESTED). compressing to 211 tokens keeps the correct answer at 11.2x compression, while compressing to 50 tokens loses key facts. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- LLMLingua-2 is 3x to 6x faster than LLMLingua and handles out-of-domain data better; prefer it for new work.
- Compression can remove a fact the question needs, so always test with a question whose answer is in the prompt.
- The compressed prompt is not readable prose; do not show it to a user as if it were the original.
- Compression saves tokens and cost, but it adds a compression step of its own, so it only pays off on long prompts.
