Prompt Compression

Shrink prompts and agent context before they hit the LLM: lower cost, faster inference, and longer effective context using LLMLingua and Headroom.

What Is Prompt Compression?

Prompt compression reduces the number of tokens sent to a large language model while preserving the information needed for a correct answer. Unlike summarization by the same LLM you are about to call, compression usually runs through a smaller model, classifier, or structure-aware algorithm before the expensive inference step.

Targets include:

Compression is distinct from context window extension (e.g. sliding windows, memory stores). It makes existing context denser. It is complementary to KV-cache optimization, quantization, and smaller models.

Why It Matters

Rule of thumb: Measure task accuracy on a golden set at multiple compression rates. Token savings are meaningless if faithfulness or tool-call accuracy drops below your SLA.

How Compression Works (General)

Methods fall into several families:

FamilyIdeaExamples
Perplexity / information filteringRemove tokens a small LM finds predictable (low surprise)LLMLingua v1, SelectiveContext
Token classificationClassifier predicts keep/drop per tokenLLMLingua-2
Query-aware selectionReorder or filter context based on the user questionLongLLMLingua
Structure-aware crushingPreserve schema, signatures, errors; compress boilerplateHeadroom SmartCrusher, CodeAwareCompressor
Extractive summarizationLLM or SLM produces shorter paraphraseVarious; higher latency, risk of hallucinated drops

Most production stacks compress before the target LLM call and treat the compressor as a separate service with its own CPU/GPU budget.

When to Use Compression

Good fits

Poor fits

When to combine tools

Use LLMLingua for natural-language prompt bodies (instructions + demonstrations + question). Use Headroom for agent pipelines heavy on tool outputs, logs, JSON, and code. Many agent stacks run Headroom on tool results and LLMLingua on the final assembled prompt.

LLMLingua (Microsoft Research)

LLMLingua is a research-backed prompt compression framework. It works with black-box LLMs because compression uses an external small language model; only the shortened text is sent to GPT-4, Claude, etc.

LLMLingua (v1)

Coarse-to-fine pipeline on prompts structured as {Instruction, Demonstrations, Question}:

  1. Budget controller - allocates compression budget across prompt parts (few-shot examples compressed more aggressively than core instructions).
  2. Demonstration-level filtering - small LM perplexity scores sentences; low-surprise (predictable) content is dropped first.
  3. Iterative token-level compression - remaining segments compressed token-by-token using conditional perplexity, preserving interdependent phrases better than one-shot filtering.
  4. Distribution alignment - optional tuning so compressed prompts align with target LLM behavior.

Reported results: up to 20x compression with small accuracy loss on benchmarks like GSM8K, BBH, ShareGPT. Best when prompts contain redundant natural language and long ICL examples.

LongLLMLingua

Extends LLMLingua for long-context RAG. Query-aware compression reorders and prioritizes chunks so question-relevant evidence sits where the target LLM attends reliably, mitigating lost-in-the-middle. Use when retrieved context spans thousands of tokens and the user question is known at compression time.

LLMLingua-2

Task-agnostic compression formulated as token classification. A bidirectional encoder (e.g. XLM-RoBERTa-sized) trained via distillation from GPT-4 labels which tokens to keep. Typically 3-6x faster than v1 and stronger on out-of-domain text. Recommended default for new projects unless you specifically need LongLLMLingua query routing.

Key features

How to use LLMLingua

pip install llmlingua

from llmlingua import PromptCompressor

# LLMLingua-2 (recommended starting point)
compressor = PromptCompressor(
    model_name="microsoft/llmlingua-2-xlm-roberta-large-meetingbank",
    use_llmlingua2=True,
)

long_prompt = """
Instruction: Answer using the examples below.
...
[thousands of tokens of few-shot examples and context]
...
Question: What is the refund policy for enterprise tier?
"""

result = compressor.compress_prompt(
    long_prompt,
    rate=0.5,                    # keep ~50% of tokens
    force_tokens=["\n", ".", "?"],
    drop_consecutive=True,
)

compressed = result["compressed_prompt"]
print(result["origin_tokens"], "->", result["compressed_tokens"])

LongLLMLingua example (RAG)

compressor = PromptCompressor(
    model_name="NousResearch/Llama-2-7b-hf",
    use_llmlingua2=False,
)

compressed = compressor.compress_prompt(
    context=retrieved_documents,   # long multi-doc string
    question=user_query,
    rate=0.55,
    condition_in_question="after_condition",
    reorder_context="sort",
    dynamic_context_compression_ratio=0.3,
)

LLMLingua pros and cons

ProsCons
Strong on NL prompts and few-shot bloat; well-studied academically Extra SLM load (memory, latency) before main LLM call
Black-box compatible with any API model Compressor tokenizer may differ from target model
LLMLingua-2 is fast and task-agnostic Can drop rare but critical tokens (IDs, uncommon entity names)
LongLLMLingua helps long RAG contexts Less specialized for raw JSON/logs than Headroom

Headroom

Headroom is an open-source context compression layer for AI agents. It targets tool outputs, logs, RAG chunks, files, and conversation history before they reach the LLM. Typical savings: 60-95% on JSON/search results, 15-70% on code-heavy agent traces, with a focus on preserving errors, stack traces, and structurally important fields.

What makes Headroom different

Compression pipeline

  1. CacheAligner - separates dynamic tokens (dates, session vars) from static system prompt prefix.
  2. ContentRouter - routes each message block to a compressor:
Content typeCompressorTypical reductionPreserves
JSON arrays / API payloadsSmartCrusher70-90%Keys, structure, high-variance values
Source codeCodeAwareCompressor40-70%Signatures, imports, AST-critical spans
grep / search resultsSearchCompressor80-95%Matching lines, file paths
Build / CI logsLogCompressor85-95%Errors, stack traces, FATAL lines
Plain textText utilities / LLMLingua60-80%High-entropy tokens

IntelligentContext (optional) scores messages by recency, relevance, and error signals to drop lowest-value history when still over budget.

Integration modes

1. Python library

pip install headroom-ai

from headroom import compress

messages = [
    {"role": "system", "content": "You are a debugging assistant."},
    {"role": "user", "content": "Why did deploy fail?"},
    {"role": "tool", "content": huge_ci_log_string},
]

optimized, stats = compress(messages)
print(stats.tokens_before, stats.tokens_after, stats.compression_ratio)

2. Transparent proxy

pip install "headroom-ai[proxy]"
headroom proxy --port 8787 --mode token

# Point your OpenAI/Anthropic client base URL to localhost:8787
# Requests are compressed automatically before forwarding

--mode token maximizes compression. --mode cache freezes prior turns to preserve provider prefix-cache bytes on long conversations.

3. Compression-only HTTP API

# POST http://localhost:8787/v1/compress
# Body: {"messages": [...]}
# Returns tokens_before, tokens_after, compressed messages

4. MCP server

Tools: headroom_compress, headroom_retrieve, headroom_stats for any MCP-compatible agent client.

5. Agent wrap

headroom wrap claude   # one-command wrapper for supported agents
headroom unwrap claude

Headroom + RAG example

from headroom import compress

rag_chunks = load_retrieved_chunks()  # 40k tokens of HTML + metadata
tool_message = format_chunks_as_tool_output(rag_chunks)

messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": user_question},
    {"role": "tool", "content": tool_message},
]

compressed_messages, stats = compress(
    messages,
    enable_ccr=True,   # store originals for headroom_retrieve
)

response = llm.invoke(compressed_messages)
# Model can call headroom_retrieve if it needs a full passage

Headroom pros and cons

ProsCons
Excellent on agent tool output, logs, JSON, search hits Another moving part in the agent stack (proxy/service to operate)
CCR gives reversible compression; model can pull originals CCR store needs sizing, retention, and security policies
CacheAligner pairs well with provider prompt caching Savings vary; short prompts see little benefit
Drop-in proxy, MCP, and agent wrappers Code-aware mode needs optional headroom-ai[code] extra
Apache 2.0, local-first, auditable Less research literature than LLMLingua for pure NL few-shot

LLMLingua vs Headroom

DimensionLLMLinguaHeadroom
Primary focusNatural-language prompt compressionAgent context and tool outputs
Best inputInstructions, few-shot, long NL contextJSON, logs, code, RAG chunks, search results
ReversibilityLossy by defaultCCR store + retrieve tool
Query-aware RAGLongLLMLinguaContent routing + optional context scoring
DeploymentPython library in your appLibrary, proxy, MCP, agent wrap
Prompt cache optimizationNot a core featureCacheAligner built in
Typical stack rolePre-LLM prompt shrinkerMiddleware on agent message list

They are complementary, not mutually exclusive.

Production Patterns

RAG Q&A API

  1. Retrieve top-k chunks (hybrid search + rerank).
  2. Run LongLLMLingua or LLMLingua-2 on assembled context with the user question.
  3. Optionally run Headroom if chunks include HTML tables, JSON metadata, or logs.
  4. Call target LLM with compressed context; log compression ratio and faithfulness scores.

Coding agent

  1. Wrap agent with Headroom proxy or compress() on each tool result.
  2. Enable CCR so the model can retrieve full files when diffs reference missing lines.
  3. Use --mode cache on long sessions to protect prefix-cache discounts.

High-volume extraction

  1. Fixed instruction prefix (cached at provider).
  2. Compress variable few-shot block with LLMLingua-2 at rate tuned on eval set.
  3. Batch requests; track $/successful extraction.

Evaluation Checklist

Summary: What, Why, How, When

LLMLinguaHeadroom
WhatSLM/classifier-based NL prompt compressorAgent context compression layer with typed compressors + CCR
WhyCut tokens on instructions, ICL, long NL contextCut tokens on tool output, logs, JSON, code, RAG blobs
HowPromptCompressor.compress_prompt()compress(), proxy, MCP, or agent wrap
WhenRAG NL passages, few-shot bloat, batch templatesAgents, devtools, log-heavy workflows, structured API dumps