AI Coding Agents
LLMLingua Prompt Compression: A Practical Guide for Pipelines
LLMLingua is Microsoft’s family of local prompt compressors for pipelines you control. Microsoft reports up to 20× compression for the original LLMLingua method. It installs with pip and has LangChain and LlamaIndex integrations, so it fits retrieval pipelines where your own code builds the prompt. In an LLMLingua-2 trial, compress retrieved prose and keep instructions, paths, code, and exact values outside the compressor.
LLMLingua is Microsoft’s family of local prompt compressors for pipelines you control. Microsoft reports up to 20× compression for the original LLMLingua method. In an LLMLingua-2 trial, compress retrieved prose and keep instructions, paths, code, and exact values outside the compressor.
At a glance
| Question | Answer |
|---|---|
| What is it? | Microsoft’s family of local prompt compressors under the PromptCompressor API. |
| What cost does it target? | Input from retrieved passages, long documents, and accumulated context in a pipeline you control. |
| Where does it act? | The application calls the library on selected prompt content before sending it to the model. |
| How do you try it? | Install the llmlingua Python package with pip. |
| Can you recover originals? | There is no decoder for dropped tokens. Keep the original text for a fallback. |
| What license is stated? | MIT. |
| What is its maturity signal? | 6,894 stars and 125 open issues as of November 30, 2026. |
| When is it a good fit? | A pipeline that can compress retrieved prose while keeping paths, code, and exact values outside the compressor. |
What LLMLingua is and which cost layer it targets
The project lives at microsoft/LLMLingua, MIT licensed, with three peer-reviewed methods under one PromptCompressor API. LLMLingua (EMNLP 2023) uses a compact language model such as GPT2-small or LLaMA-7B to score and drop low-value tokens, claiming up to 20x compression with minimal performance loss. LongLLMLingua (ACL 2024) targets long contexts and the “lost in the middle” failure, claiming up to 21.4% better RAG performance using a quarter of the tokens. LLMLingua-2 (ACL 2024 Findings) distills token-level decisions from GPT-4 into a BERT-level encoder for task-agnostic compression the authors report as 3x-6x faster than the original. A fourth variant, SecurityLingua (CoLM 2025), applies the same machinery to jailbreak detection.
The cost layer is input tokens on calls you construct: retrieved passages in a RAG pipeline, long documents in batch jobs, accumulated context in an agent harness you wrote yourself. As of November 30, 2026, the repo has 6,894 stars, 461 forks, and 125 open issues. The last numbered release is v0.2.2 from April 2024, though the repository still received commits as of late November 2026, which means you are effectively running a maintained research codebase rather than a productized tool.
How it works
PromptCompressor loads a small model and scores each token (LLMLingua) or classifies keep/drop per token (LLMLingua-2), then emits a shorter prompt plus statistics. The README’s own demo shows the character of the output: a 2,365-token GSM8K-style problem compresses to 211 tokens (11.2x) with text like “He reanged five of boxes into packages of sixlters each”. The large model can often still answer because compression preserves key tokens, but the compressed text is not something a human or a downstream string-match should read.
The API surface in the README:
from llmlingua import PromptCompressor
llm_lingua = PromptCompressor()
compressed_prompt = llm_lingua.compress_prompt(
prompt, instruction="", question="", target_token=200
)
# LLMLingua-2 (xlm-roberta-large or bert-base-multilingual variants)
llm_lingua = PromptCompressor(
model_name="microsoft/llmlingua-2-xlm-roberta-large-meetingbank",
use_llmlingua2=True,
)
compressed_prompt = llm_lingua.compress_prompt(prompt, rate=0.33, force_tokens=['\n', '?'])
# LongLLMLingua
compressed_prompt = llm_lingua.compress_prompt(
prompt_list,
question=question,
rate=0.55,
condition_in_question="after_condition",
reorder_context="sort",
dynamic_context_compression_ratio=0.3,
condition_compare=True,
context_budget="+100",
rank_method="longllmlingua",
)
Use rate or target_token to set the compression budget, depending on the variant. The LLMLingua-2 example uses force_tokens as a token-level control for newlines and question marks. Keep whole identifiers outside compression when exact spelling is required. For LongLLMLingua, condition_compare and question= allow conditioning on the query. The README demonstrates structured tags separately, and issue #114 reports a problem using them with LLMLingua-2. Pass system instructions, code, and identifiers around the LLMLingua-2 compressor.
Install and first run
pip install llmlingua
That is the full install line from the README; the compressor model downloads on first use, and GPU is strongly implied by the issue tracker (multiple OOM and CUDA reports) though CPU operation is possible for the smaller LLMLingua-2 encoders. There is nothing to remove beyond the pip package and the cached model weights. Integrations exist for LangChain and LlamaIndex as retriever post-processors and for Microsoft Prompt flow; both integrations are referenced in the README.
What it saves: claims versus evidence
The papers report up to 20x compression with minimal performance loss (LLMLingua), up to 21.4% RAG improvement at quarter-token budgets (LongLLMLingua), and 3x-6x speed over LLMLingua with better out-of-domain handling (LLMLingua-2). These are peer-reviewed results on academic benchmarks, which makes them better sourced than most tool READMEs, but they are still the authors’ numbers on those benchmarks, not a guarantee on your workload.
The open issues (125 as of November 30, 2026) show where practice diverges from paper: #114 reports structured_compress_prompt not working correctly with LLMLingua-2, #4 reports garbled output on a Chinese LLaMA, and a long tail of issues (#94, #86, #156) are people unable to reproduce published benchmark scores, alongside OOM (issue #6, #8) and CUDA environment failures (#55). Closed issue #71 asked why LangChain integration took so long; it exists now.
Tamp reports guard activation on 92% of text blocks in its own fixtures. The guard bypasses its LLMLingua-2 stage for blocks containing patterns such as paths, URLs, and version strings. The percentage measures bypass frequency. Downstream accuracy requires a separate answer check.
Prompt-cache and extra-turn risk
LongLLMLingua can change its output when the question changes. LLMLingua-2 is task-agnostic. Measure cache reuse for the variant you deploy, especially when compressed text occupies a shared prefix. In the 8,000-token example below, a 2,000-token compressed attempt followed by an 8,000-token retry uses 10,000 context tokens, 25% more than one uncompressed attempt.
A cost example
Assume a RAG service sends 8,000 tokens of retrieved context per query, 5,000 queries a day, on deepseek-v4-pro at $1.32 per million input tokens (rates).
- Uncompressed: 40,000,000 input tokens/day, $52.80/day (estimate).
- At an assumed 4× reduction in retrieved context: 10 million tokens × $1.32 per million = $13.20 per day, saving an estimated $39.60.
- At a hypothetical 20× reduction, the ceiling Microsoft reports for the original method: 2 million tokens × $1.32 per million = $2.64 per day, saving an estimated $50.16.
The compressor adds local CPU or GPU work. In this example, if 1% of requests need an uncompressed retry, 50 × 8,000 adds 400,000 context tokens per day before the rest of each retried request. Track local latency and price both attempts before deciding whether compression pays.
Who should use it, who should skip it
Use it if:
- You control the pipeline: RAG retrieval, batch summarization, document QA, or a custom agent where you decide what reaches the model.
- Your long-context payloads are mostly prose (documents, transcripts, meeting notes) rather than code, paths, or structured identifiers.
- You can run local inference and want published papers behind the method.
Skip it if:
- You want a drop-in for Claude Code or Cursor; LLMLingua is a library, and agent-facing proxies like Tamp wrap it only behind heavy guards.
- Your prompts depend on exact file paths, SHAs, JSON, or code, and your pipeline cannot keep those fields outside the compressor.
- You need reversible output. There is no decode; dropped tokens are gone.
How to trial it safely
- Start with LLMLingua-2’s encoder (fast, small) at
rate=0.5on a fixed set of 20-50 real queries; check answers against an uncompressed baseline. - Send system instructions, code, and identifiers around the LLMLingua-2 compressor. Compress the prose slice in isolation.
- Measure provider-billed input tokens and answer quality together, per the checklist in how to measure coding agent token savings.
- Add a retry rule up front (answer check fails → re-run uncompressed) and count retries in the cost ledger.
- Lower
rategradually and repeat the answer checks at each step.
Worked example with retrieved prose. Suppose a support assistant reads an incident note and must name the configuration change that restored a service. Store the approved configuration key, rollout identifier, and any exact command in separate fields as soon as you ingest the incident record. Keep the original note so you can resend it if the answer fails. If the only copy of the cause or remedy appears in narrative text, retain a separate passage as protected evidence when your application can identify it reliably. Record which fields are protected before testing so the same policy applies to both arms.
Reuse the LLMLingua-2 PromptCompressor initialized above. The README’s example calls compress_prompt and reads the compressed_prompt result. Here the application’s request builder can send the system instruction and question in their existing fields and use either control_context or trial_context as the retrieved context. The sample strings are synthetic. Use full passages to measure compression.
question = "Which configuration change restored the service?"
protected = "Approved key: workers.max_parallel\nRollout: release-042"
prose = "The service recovered after the team restored the concurrency limit."
control_context = f"{protected}\n\n{prose}"
result = llm_lingua.compress_prompt(prose, rate=0.5)
trial_context = f"{protected}\n\n{result['compressed_prompt']}"
Use the same retrieved passage, model, system instruction, and question for both arms. Keep the protected fields in the same order and location, and vary only the narrative field. Include cases where the decisive sentence occurs late in a passage, where an earlier incident offers a plausible competing explanation, and where the note lacks enough evidence to answer. Those cases exercise whether the model keeps the relevant relationship, distinguishes similar incidents, and abstains when the evidence is insufficient.
Write an acceptance check for each case before running the requests. In the example, require the answer to identify restoring the concurrency limit as the remedy and reproduce the exact configuration key if the output format asks for it. An answer that names the correct key but says the team raised the limit fails. A grader can compare identifiers and structured fields directly. For the causal statement, use an expected-answer rubric and inspect ambiguous results against the original note. Record first-pass acceptance for each arm as well as final acceptance after fallback.
Put a failed compressed attempt and its uncompressed retry on the same ledger row. Record the provider’s fresh input, cache reads, cache writes where applicable, and output for both calls. Record compressor latency separately and include any retries when comparing end-to-end latency. If the uncompressed control also fails, keep that failure visible and use the same acceptance criteria. Cost per accepted answer is the total cost of an arm divided by the number of answers accepted in that arm. That keeps failures and retries in the calculation even when their answers never reach the user.
At a given rate, check how much of the billed request actually changes. The rate applies to the prose you pass to the compressor. The protected fields, tool definitions if present, and the application’s request framing still contribute to provider usage. Start by comparing provider totals for the paired requests, then compare them with the compressor’s counts for the prose field. The difference helps explain a trial that shows a large local reduction and a small change on the bill. For each request, keep the compression setting and the provider usage on the same record so you can trace changes to the rate you actually tested.
Record whether the fallback was triggered by a deterministic check, such as a missing rollout identifier, or only found later during manual review. In the first case, include the retry in trial cost. In the second, count the wrong first answer as a quality failure even if an offline retry recovers it. If your live application cannot flag a certain failure reliably, either protect the evidence involved or stop compressing that class of query. Recheck the same cases at the next rate so you can tell which setting first broke the acceptance criterion.
Use the earlier 8,000-token scenario as a check on the ledger. If each compressed attempt uses 2,000 context tokens and 1% of 5,000 daily attempts retry with the original 8,000, the daily context volume is 5,000 × 2,000 + 50 × 8,000 = 10.4 million tokens. At $1.32 per million fresh input tokens, that is an estimated $13.73 per day for context alone. Add the repeated system instruction, question, protected fields, and output using actual request usage. Keep the rate that meets your acceptance target and offers a lower measured cost after retries.
Alternatives and next reads
For agent-side integration examples, see the Tamp proxy review and the sqz review. For another neural, query-aware approach with open weights, see SuperCompress. Background on the resource these tools protect: what is an LLM context window and how to calculate LLM API cost.
Sources
- microsoft/LLMLingua repository (GitHub, accessed 2026-11-30)
- LLMLingua paper (EMNLP 2023) (ACL Anthology, accessed 2026-11-30)
- LongLLMLingua paper (ACL 2024) (ACL Anthology, accessed 2026-11-30)
- LLMLingua-2 paper (ACL 2024 Findings) (ACL Anthology, accessed 2026-11-30)
- LLMLingua issue #114: structured_compress_prompt not working with LLMLingua2 (GitHub, accessed 2026-11-30)
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
LLMLingua Prompt Compression: A Practical Guide for Pipelines. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/llmlingua-prompt-compression-guide/