0tokens

Chat · context compression for llms

Context Compression for LLMs: A Practical Guide

  1. aigi

    Large language models are powerful, but their context windows are not free. Every token sent to an LLM increases inference cost, latency, memory usage, and—at scale—operational complexity. Long prompts can also reduce answer quality: irrelevant instructions, repeated history, and noisy retrieved documents make it harder for a model to identify the information that matters.

    Context compression for LLMs is the practice of reducing the size of a model’s input context while preserving the information required to complete a task accurately. It is increasingly important for retrieval-augmented generation (RAG), AI agents, enterprise search, coding assistants, customer support, and multimodal systems.

    This guide explains how context compression works, which techniques are suitable for different workloads, how to measure quality loss, and how Indian AI teams can build cost-efficient production systems.

    What Is Context Compression for LLMs?

    Context compression transforms a large context into a smaller representation before it is sent to the target language model. The compressed context may be:

    • A shorter extractive passage containing only relevant sentences
    • An abstractive summary of conversation history or documents
    • A set of structured facts, entities, and relationships
    • A lower-dimensional vector or latent representation
    • A filtered collection of retrieved chunks ranked by task relevance
    • A compact prompt containing normalized instructions and state

    The objective is not simply to delete tokens. A good compressor preserves task-relevant information, including constraints, evidence, definitions, user preferences, dates, exceptions, and source provenance.

    For example, an LLM-based support agent may receive 30 pages of conversation history. Compression could preserve the customer’s product, error code, troubleshooting steps already attempted, account constraints, and unresolved question—while removing greetings and repeated explanations.

    Why Context Compression Matters

    Lower inference cost

    LLM pricing is commonly tied to input and output tokens. Compressing a prompt from 20,000 tokens to 5,000 can substantially reduce the input bill. The savings become significant when an application handles millions of requests or repeatedly calls a model during agent execution.

    For Indian startups operating under tight runway constraints, prompt compression can make the difference between a prototype and a commercially viable deployment. It also helps teams use higher-quality models selectively rather than choosing smaller models solely to control costs.

    Reduced latency

    Longer contexts require more token processing and can increase time to first token. Shorter inputs are particularly valuable in interactive applications such as voice assistants, coding tools, and customer-service chat.

    Better retrieval quality

    RAG pipelines often retrieve too many chunks. Passing every candidate to the generator can introduce duplicated or contradictory evidence. Compression helps the generator focus on the passages that actually answer the query.

    More reliable agent behavior

    Agents accumulate observations, tool outputs, plans, and prior messages. Without compression, the context becomes noisy and may exceed the model’s effective reasoning capacity. A compact state representation can improve tool selection and reduce repeated actions.

    Longer practical memory

    A model may support a large nominal context window, but quality can degrade as the window fills. Compressing old messages allows an application to maintain useful long-term memory without continuously replaying the complete transcript.

    The Main Types of Context Compression

    1. Extractive compression

    Extractive compression selects existing text rather than generating new wording. Typical methods include sentence ranking, passage filtering, keyword matching, and query-focused extraction.

    A practical extractive pipeline may:

    1. Split documents into sentences or smaller semantic units.
    2. Score each unit against the user query.
    3. Remove duplicates and low-value material.
    4. Preserve surrounding context for selected claims.
    5. Assemble the highest-value units within a token budget.

    Extractive methods are fast, auditable, and less likely to invent facts. They are suitable for legal, financial, healthcare, and compliance workflows where exact wording matters. Their limitation is that they may retain awkward fragments and fail to combine information spread across multiple passages.

    2. Abstractive summarization

    Abstractive compression asks a model to rewrite a long context in fewer words. It can produce coherent summaries and combine related evidence, making it useful for conversation history, meeting transcripts, and long reports.

    However, summarization can introduce omissions or hallucinations. The compressor may remove a small but important condition, change a number, or merge two separate events. Production systems should therefore use structured prompts, explicit preservation rules, and automated factual checks.

    A strong summarization instruction specifies:

    • The task the final model must perform
    • Facts that must be retained exactly
    • Required names, dates, identifiers, and numerical values
    • Uncertainty and conflicting sources
    • The maximum output token count
    • A requirement not to infer unsupported facts

    3. Query-focused contextual compression

    Query-focused compression uses the current question to decide what information to retain. This is often more effective than summarizing a document in isolation because relevance depends on the downstream task.

    For instance, a policy document may need one compressed representation for a question about eligibility and another for a question about deadlines. Query-aware compression is a natural fit for RAG systems and enterprise search.

    A common architecture is:

    User query
       ↓
    Retriever: broad candidate selection
       ↓
    Reranker: relevance scoring
       ↓
    Compressor: extract or summarize relevant content
       ↓
    Generator LLM
       ↓
    Answer with citations

    The retriever should favor recall, while the compressor and reranker improve precision before generation.

    4. Structured state compression

    Instead of preserving natural-language history, applications can convert it into a schema. An agent’s compressed state might contain:

    {
      "user_goal": "Compare GST registration options",
      "known_facts": ["Business is incorporated in India"],
      "constraints": ["Needs compliance guidance, not legal advice"],
      "decisions": [],
      "open_questions": ["Expected annual turnover"],
      "sources": ["official government guidance"],
      "last_updated": "2026-10-30"
    }

    Structured compression is highly efficient and easier to validate. It works well for workflow agents, CRM systems, planning tasks, and applications that must maintain durable state. The schema must be versioned carefully, and important free-form evidence should remain available for audit.

    5. Token-level and latent compression

    Some systems compress context into special tokens, embeddings, or learned latent representations. A compressor model may encode a long sequence into a shorter sequence that another model consumes.

    These methods can achieve strong compression ratios, but they introduce complexity:

    • The compressor and generator may need compatible training.
    • Latent representations are difficult to inspect.
    • Errors may be hard to attribute.
    • Embeddings are not a direct replacement for exact evidence.

    Latent compression is promising for high-volume, stable workloads, but extractive and structured methods are usually easier for early production deployments.

    Context Compression Techniques for RAG

    RAG is one of the most common use cases. A robust compression strategy typically combines several stages.

    Deduplicate retrieved chunks

    The same information may appear in multiple chunks, especially when documents overlap. Use similarity thresholds, document identifiers, and maximal marginal relevance to reduce repetition.

    Rerank before compression

    A cross-encoder or LLM reranker can assess query-passage relevance more accurately than vector similarity alone. Reranking prevents the compressor from spending tokens on semantically related but non-answering content.

    Compress at sentence level

    Passage-level filtering can retain unnecessary paragraphs. Sentence-level selection offers finer control, particularly for policy, technical, and research documents.

    Preserve citation boundaries

    Do not merge text from different sources without retaining source IDs. The final response should be able to map each claim back to the original document, page, section, or URL.

    Keep negative evidence

    A passage stating that a condition does not apply may be as important as a positive match. Compression prompts and ranking models should account for negation, exceptions, and scope.

    Use adaptive budgets

    Not every query needs the same context size. Allocate more tokens for multi-hop questions and less for simple factual lookups. A budget can depend on query complexity, number of evidence sources, model cost, and confidence.

    Conversation and Agent Memory Compression

    Long conversations should not be summarized into one permanent blob. A better design separates memory into layers:

    • Recent window: Keep the latest messages verbatim for local coherence.
    • Episodic summary: Store important past events, decisions, and outcomes.
    • Semantic memory: Store stable user preferences or domain facts.
    • External records: Keep original messages, tool logs, and citations outside the prompt.
    • Task state: Maintain current goals, constraints, and unresolved questions in structured form.

    When new messages arrive, update the relevant layer rather than rewriting everything. Summaries should include timestamps and confidence indicators because old information can become stale.

    For agents, tool outputs deserve special handling. Large API responses should be normalized into the fields needed for the next decision. Raw responses can be stored in an object store or database and referenced by an ID. This avoids inserting thousands of tokens of irrelevant JSON into every subsequent agent turn.

    Designing a Context Compression Pipeline

    Step 1: Define the task and failure modes

    Compression quality depends on the final task. Identify what the model must answer, which facts are indispensable, and what mistakes are unacceptable. A summarizer optimized for conversational tone is not necessarily safe for compliance analysis.

    Step 2: Establish a token budget

    Set budgets separately for system instructions, user input, retrieved evidence, memory, and expected output. Leave headroom for the model’s response and tool calls. Tokenization differs across models, so measure with the tokenizer used in production.

    Step 3: Select the least lossy method

    Start with filtering and extraction when exact wording matters. Add summarization when information must be combined or the input is highly repetitive. Use learned latent compression only when the workload justifies specialized infrastructure.

    Step 4: Preserve metadata

    Every compressed fact should retain provenance where possible. Useful metadata includes source ID, page number, timestamp, author, confidence, and whether the content is directly quoted or summarized.

    Step 5: Validate the compressed output

    Validation can include:

    • Required-field checks for structured summaries
    • Number and date consistency checks
    • Entailment comparison with source passages
    • Citation coverage tests
    • PII and secret detection
    • Contradiction checks across sources
    • A second-model review for high-risk workflows

    Step 6: Route difficult cases to a larger budget

    If the compressor detects ambiguity, conflicting evidence, or low confidence, retain more source text or escalate to a stronger model. Compression should be adaptive rather than blindly aggressive.

    How to Evaluate Context Compression

    A lower token count is not enough. Measure both efficiency and task quality.

    Compression ratio

    Compression ratio = original input tokens / compressed input tokens

    Also track the percentage reduction and the absolute tokens saved per request.

    Retrieval and evidence recall

    Measure whether the compressed context still contains the evidence required to answer benchmark questions. Evidence recall is often more informative than summary similarity.

    Answer quality

    Use exact match, F1, groundedness, citation correctness, rubric-based human evaluation, or domain-specific metrics. Compare the compressed pipeline with a full-context baseline.

    Faithfulness

    Check whether the compressed version introduces claims unsupported by the original. This is critical for medical, legal, financial, and public-sector applications in India.

    Latency and cost

    Record compressor latency, generator latency, total model calls, input and output tokens, cache hit rate, and cost per successful task. A compressor that saves tokens but adds an expensive extra call may not improve economics.

    Robustness

    Test long inputs, duplicated documents, conflicting sources, adversarial instructions, multilingual text, tables, code, and formatting-heavy documents. Indian deployments may require evaluation across English and major Indian languages, along with code-mixed queries.

    Common Failure Modes

    Over-compression

    Removing context too aggressively can eliminate qualifiers, exceptions, or evidence. Use minimum retention rules for dates, numbers, definitions, and negative statements.

    Summary drift

    Repeatedly summarizing a summary causes information to gradually change. Periodically regenerate from the original source or maintain a compressed state plus immutable evidence references.

    Prompt injection survival

    Retrieved documents may contain instructions intended to manipulate the model. Compression can accidentally make malicious instructions more prominent. Treat retrieved content as untrusted data, label it clearly, and apply injection detection before and after compression.

    Lost chronology

    Conversation summaries often collapse events that occurred in a specific order. Preserve timestamps, sequence, and causal relationships when they affect the decision.

    Unsupported merging

    Combining statements from different sources can create a conclusion no source actually made. Keep source boundaries and require citations for synthesized claims.

    Language and script loss

    Translating or compressing multilingual material can remove culturally or legally important wording. Evaluate Hindi, Tamil, Bengali, Telugu, Marathi, and code-mixed inputs when they are part of the product’s target market.

    Production Best Practices

    • Cache compressed documents and summaries using content hashes.
    • Version compression prompts, models, schemas, and token budgets.
    • Store the original context outside the prompt for auditability.
    • Use deterministic settings for compliance-sensitive compression.
    • Redact secrets and unnecessary personal data before sending content to an external API.
    • Monitor compression quality by tenant, language, document type, and query class.
    • Keep a fallback path that sends more evidence when confidence is low.
    • Use batch processing for stable document collections.
    • Separate system instructions from untrusted retrieved text.
    • Test provider-specific tokenization and context-window behavior.

    For Indian companies, data residency, DPDP Act obligations, sectoral regulations, and vendor terms should be reviewed before transmitting customer or citizen data to third-party model APIs. Compression reduces exposure but does not automatically make sensitive processing compliant.

    A Practical Reference Architecture

    A scalable implementation can use the following components:

    1. Ingestion service: Parses PDFs, HTML, office files, tables, and transcripts.
    2. Document store: Retains immutable originals and metadata.
    3. Indexing layer: Creates lexical and vector indexes.
    4. Retriever and reranker: Produces high-recall, high-precision candidates.
    5. Compression service: Applies extraction, deduplication, summarization, or schema conversion.
    6. Validation layer: Checks citations, required facts, sensitive data, and confidence.
    7. Generation service: Sends the compact context to the target LLM.
    8. Observability stack: Tracks tokens, latency, quality, and cost.

    The compression service should be independently deployable so teams can update its model or policy without changing the application’s core orchestration.

    FAQ: Context Compression for LLMs

    Does context compression reduce answer quality?

    It can, especially when important exceptions or evidence are removed. Quality depends on the compression method, task, token budget, and validation. Always compare against a full-context baseline.

    Is summarization the same as context compression?

    No. Summarization is one form of compression. Context compression also includes extraction, deduplication, reranking, structured state, token pruning, and latent representations.

    Should I compress before or after retrieval?

    For RAG, retrieve broadly, rerank candidates, and then compress the most relevant evidence. Compressing the entire corpus before retrieval can remove details needed for future queries.

    Can embeddings replace compressed text?

    Usually not for final generation. Embeddings support similarity search but do not reliably preserve exact numbers, negation, legal wording, or citations. Use them alongside textual evidence.

    What is a good starting strategy for a startup?

    Begin with deduplication, reranking, sentence extraction, a recent-message window, and structured task state. Add LLM summarization only where it demonstrably improves quality or reduces total cost.

    Conclusion

    Context compression for LLMs is a systems discipline, not merely a prompt-writing trick. The best implementations preserve the facts, constraints, provenance, and uncertainty that matter to the task while removing repetition and irrelevant detail. Start with measurable token budgets, use the least lossy technique that meets your needs, and evaluate compression against real business and safety outcomes.

    For RAG and agent products, compression can reduce inference cost, improve latency, extend practical memory, and make model behavior more reliable. With careful validation and an auditable fallback path, it becomes a core capability for production-grade AI.

    Apply for AI Grants India

    Are you building an Indian AI product that uses context compression, efficient inference, RAG, or agent memory? Apply to AI Grants India for support, visibility, and opportunities to accelerate your AI venture.

    Last updated 30 October 2026

Apply for AI Grants India

Financial support for innovators building the future of AI in India.

Apply now

AIGI may be inaccurate. Replies seeded from the guide above.