Contextual Compression for RAG: Implementation and Optimization
Picture this: your RAG system piles up 10 chunks of 800 tokens each, but only 100 tokens are actually useful. The LLM pays for noise, and the answers are a mess. A typical scenario – support for technical documentation: 10 chunks retrieved, only 2–3 relevant. Each chunk weighs about 800 tokens, but the useful information is just 100 tokens. The LLM wastes its context window on irrelevant text, leading to hallucinations and incomplete answers. Context window is consumed, cost grows. Contextual Compression is a technique that extracts only the query-relevant fragment from each chunk. We reduce noise, cut tokens, and improve faithfulness. Over our time in AI/ML, we have deployed this in 15+ projects — here we share our experience. Get a consultation on optimizing your RAG system.
Problems Without Contextual Compression
Standard RAG feeds the LLM full chunks (512–1024 tokens). A typical picture: a chunk contains 600 tokens, of which only 80 actually answer the question, the rest is irrelevant context. This leads to:
- Increased cost (more input tokens)
- Reduced accuracy (the LLM "gets lost" in irrelevant text)
- Shrunk effective context window (less room for truly important chunks)
How LLM-based Contextual Compression Works
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor
from langchain_openai import ChatOpenAI
# LLM-based compressor
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor,
base_retriever=vectorstore.as_retriever(search_kwargs={"k": 8}),
)
compressed_docs = compression_retriever.invoke(
"What is the contract approval procedure?"
)
# Each document contains only the relevant fragment
for doc in compressed_docs:
print(len(doc.page_content), "chars (vs original ~2000)")
According to LangChain documentation, LLMChainExtractor uses the same LLM to extract relevant content. This gives high accuracy but increases latency.
When to Use Embedding-based Compressor
A faster and cheaper option is filtering by cosine similarity. We often use it as the first stage of the pipeline:
from langchain.retrievers.document_compressors import EmbeddingsFilter
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
embeddings_filter = EmbeddingsFilter(
embeddings=embeddings,
similarity_threshold=0.76,
)
filtering_retriever = ContextualCompressionRetriever(
base_compressor=embeddings_filter,
base_retriever=vectorstore.as_retriever(search_kwargs={"k": 8}),
)
The threshold 0.76 is an empirical value that gives a good balance between recall and precision. It must be calibrated for your dataset.
Why Combine Compression and Reranking?
EmbeddingsFilter removes clearly irrelevant chunks but does not rank the remaining ones. A cross-encoder reranker (e.g., BAAI/bge-reranker-large) provides more accurate relevance sorting but is more expensive. The combination gives a sweet spot: the filter removes 40–60% of chunks, the reranker refines the order of the top-N. A pipeline with Filter and Reranker achieves 15% higher faithfulness than no compression, while being 2.5 times cheaper than the LLM Extractor.
Let's compare methods:
| Method |
Cost per query |
Latency p99 |
Faithfulness gain |
| No compression |
1× |
1.8 s |
— |
| EmbeddingsFilter |
0.2× |
0.3 s |
+8% |
| LLM Extractor |
0.5× |
2.4 s |
+19% |
| Pipeline (Filter + Reranker) |
0.4× |
0.9 s |
+15% |
How to Build a Pipeline with Compression and Reranking
from langchain.retrievers.document_compressors import DocumentCompressorPipeline
from langchain_community.document_transformers import EmbeddingsRedundantFilter
from langchain.retrievers.document_compressors import CrossEncoderReranker
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
cross_encoder = HuggingFaceCrossEncoder(model_name="BAAI/bge-reranker-large")
reranker = CrossEncoderReranker(model=cross_encoder, top_n=3)
compressor_pipeline = DocumentCompressorPipeline(
transformers=[
EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.75),
EmbeddingsRedundantFilter(embeddings=embeddings),
reranker,
]
)
pipeline_retriever = ContextualCompressionRetriever(
base_compressor=compressor_pipeline,
base_retriever=vectorstore.as_retriever(search_kwargs={"k": 10}),
)
Which Compressor to Choose for Your Scenario?
In production we prefer a hybrid approach: an EmbeddingsFilter for noise removal, then an LLM compressor for key queries where high accuracy is critical. If latency is a concern, we use only the EmbeddingsFilter with a low threshold (0.7–0.75).
Steps to Implement Contextual Compression
- Audit your current RAG system: metrics, bottlenecks, scenarios.
- Select and calibrate the compressor (LLM / Embedding / Pipeline).
- Integrate via LangChain or custom code.
- Test: faithfulness, relevancy, latency, cost.
- Document and train the team.
- Monitor and tweak thresholds as new data arrives.
Practical Case: From Our Client's Experience
Task: an assistant for technical manuals (chunks ~800 tokens). After compression, the average context dropped from 4800 to 1200 tokens per query.
| Metric |
Without Compression |
With Compression (LLM) |
| Input tokens/query |
5200 |
1450 |
| Faithfulness (RAGAS) |
0.79 |
0.94 |
| Answer Relevancy |
0.81 |
0.89 |
| Cost (GPT-4o-mini) |
1× |
0.3× |
| Latency |
1.8 s |
2.4 s (+compression LLM) |
Compression reduced cost by 3.3× while increasing faithfulness by 19%. Our engineers selected the threshold and compressor model in 2 days, with another 2 days for integration.
What's Included in the Implementation
- Audit of your current RAG system: metrics, bottlenecks, scenarios
- Selection and calibration of the compressor (LLM / Embedding / Pipeline)
- Integration via LangChain or custom code
- Testing: faithfulness, relevancy, latency, cost
- Documentation and team training
- Guarantee on optimization results according to KPIs
We support the project post-deployment — fix thresholds for new data, add monitoring. Order optimization of your RAG system and get token reduction up to 4×. Contact us to discuss your case.
Timelines and Cost
- Basic integration: from 2 days
- Calibration and testing: 2–3 days
- Full cycle (including pipeline and reranker): 1 week
Cost is calculated individually based on data volume and requirements. Average token savings are 60–70%. Order your RAG system optimization – our engineers will help select the right compressor.
LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment
Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.
A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.
Why Do RAG Systems Break and How to Fix It?
RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.
Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.
Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.
No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.
Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.
Typical production architecture for a corporate knowledge base
- Documents → preprocessing (PyMuPDF, Unstructured)
- Chunking → embedding (BGE-M3)
- Qdrant (hybrid dense+sparse)
- Cross-encoder re-ranking
- Context → LLM (vLLM or OpenAI API)
- Answer with sources (RAGAS for quality evaluation)
When to Fine-Tune Instead of Prompt Engineering?
Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.
LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.
DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.
Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.
How to Choose a Base Model: 8B or 70B?
| Model |
Parameters |
Strengths |
Context |
| Llama-3.1 8B |
8B |
Quality/speed balance |
128k |
| Llama-3.1 70B |
70B |
Complex reasoning |
128k |
| Mistral 7B / Mixtral 8x7B |
7B / 47B |
Efficiency for size |
32k |
| Qwen2.5 72B |
72B |
Code, multilingual |
128k |
| Gemma 2 27B |
27B |
Open license |
8k |
For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.
What Does PagedAttention Bring to Production?
vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.
Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.
Multi-Agent Systems
Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:
- ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
- Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.
In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.
How We Work: Stages, Timeline, Deliverables
| Stage |
Duration |
What You Get |
| Audit and data collection |
1–2 weeks |
Eval dataset of 100+ examples, task formalization |
| Baseline (prompt + RAG) |
1–2 weeks |
Working prototype, quality metrics |
| Fine-tuning (if needed) |
2–4 weeks |
Trained model, LoRA weights, model card |
| Deployment and monitoring |
1–2 weeks |
vLLM server, Grafana + Prometheus |
| Documentation and training |
1 week |
API documentation, team training |
What Is Included
We deliver:
- Technical documentation (model card, configs, deployment instructions)
- Access to infrastructure (code repository, trained weights)
- 1 month of post-deployment support (consultations, bug fixes)
- Customer team training (2–3 sessions on system operation)
Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.
We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.
Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.