Contextual Retrieval: The Preprocessing Step That Makes RAG Actually Work
From the publisher’s feed, collected in the ZeroLabs newsroom.
We all know the frustration. You build your RAG pipeline, fire your first query, and get back answers that are technically correct but completely useless. Why? Because a raw chunk reading “500mg dosage, twice daily” means absolutely nothing in isolation. Is that Ibuprofen? Metformin? Warfarin? Your retrieval system has no idea. Now imagine an AI that wraps that chunk with “this is the dosage for Metformin, from a Type 2 Diabetes management guideline” — before it ever hits your index.That’s Contextual Retrieval Preprocessing. And today we’re not just talking about it — we’re building it, end to end, with real code. Your RAG pipeline is about to get a whole lot smarter.created by author M K Pavan KumarThe Architecture:The architecture starts with a very common problem in traditional RAG systems. Most retrieval pipelines simply split a document into chunks, generate embeddings, store them in a vector database, and retrieve the nearest chunks during inference. While this works for simple use cases, it starts breaking down when documents become large, technical, or highly interconnected. A chunk by itself often loses the surrounding meaning that originally existed in the document. The embedding captures only what is locally present inside that isolated piece of text, not the broader context around it.This architecture tries to solve exactly that problem by introducing a context enrichment layer before indexing. Instead of directly embedding raw chunks, every chunk first passes through a preprocessing stage powered by a language model. The purpose of this stage is not summarization in the traditional sense. It is more about reconstructing the missing context around a chunk so that the chunk becomes semantically complete before it is embedded and indexed.Imagine reading a random paragraph from the middle of a research paper. Even if the paragraph is technically correct, it may reference concepts introduced several pages earlier. A normal chunking pipeline would embed that paragraph as-is, which means the embedding may fail to capture the actual intent or meaning of the section. In this architecture, the language model analyzes the chunk and enriches it with surrounding semantic understanding. The enriched representation carries more contextual depth, making retrieval significantly more accurate later during querying.One important detail here is that the original chunk is not discarded. The pipeline combines both the generated context and the raw chunk together before indexing. This becomes extremely powerful because the system preserves the exact source information while also augmenting it with additional semantic signals generated during preprocessing. In many ways, this acts like creating a “self-explained chunk” before it enters the retrieval system.After enrichment, the data moves into the indexing layer where hybrid search is used. Instead of relying only on dense embeddings, the architecture combines dense vector retrieval with sparse retrieval techniques. Dense retrieval is excellent for semantic similarity, but it can sometimes miss highly specific keywords, identifiers, abbreviations, or domain terminology. Sparse retrieval, on the other hand, is very strong at lexical matching and exact term relevance. By combining both approaches, the retrieval layer becomes much more balanced and robust.This is where Qdrant plays a critical role in the architecture. The enriched chunks are indexed with both dense and sparse representations, allowing the system to retrieve results using semantic understanding and keyword precision at the same time. In practical production systems, this hybrid approach consistently performs better than purely dense retrieval because real-world queries are often messy, ambiguous, and partially keyword driven.At query time, the user prompt enters the retrieval pipeline and gets transformed into retrieval representations. The system then performs hybrid search against the indexed enriched chunks. Since the chunks already contain contextual augmentation, retrieval quality improves substantially. Instead of returning fragmented information, the system retrieves chunks that are semantically richer and more self-contained.Another interesting aspect of this architecture is how it indirectly reduces hallucinations. Hallucinations in RAG systems often happen because the retriever surfaces incomplete or weakly related chunks. The generation model then tries to “fill the gaps” on its own. By improving retrieval quality through context enrichment, the generation layer receives far more grounded information. The model does not need to invent missing connections because those connections already exist inside the retrieved context.The evaluation side of this architecture is equally important. A lot of RAG systems are evaluated only on response quality, but retrieval itself needs independent measurement. In this workflow, retrieval quality can be measured before and after enrichment using metrics such as context relevance, hit rate, recall, semantic similarity, and answer grounding. This creates a measurable way to validate whether contextual augmentation is actually improving the retrieval layer rather than just making the chunks longer.What makes this architecture practical is that it does not require replacing the existing RAG ecosystem. It acts as an enhancement layer on top of traditional chunking and retrieval workflows. The indexing system remains familiar, the retrieval flow remains familiar, and the generation layer remains familiar. The major difference is the intelligence introduced before indexing. That small architectural shift changes how the entire retrieval pipeline behaves.In many ways, this architecture moves RAG systems closer to how humans process documents. Humans rarely understand a paragraph in complete isolation. We naturally connect sections, infer missing references, and carry contextual memory across pages. Context enrichment attempts to inject a similar capability into retrieval systems before knowledge is stored inside the vector database.The ImplementationThe project structure is as below.├── chunk_and_ingest.py├── context_preprocessor.py├── data│ ├── cardiology.pdf│ ├── cardiology.txt│ └── golden.jsonl├── evaluation_results.json├── pyproject.toml├── qdrant_store.py├── retrieve_and_evaluate.py└── uv.lockChunk_and_ingest.py:This file is the orchestration layer of the entire pipeline. It controls how the document moves through chunking, optional context enrichment, and finally into hybrid indexing inside Qdrant. In many ways, this is the backbone of the ingestion workflow because it coordinates every major component of the architecture.The pipeline starts by configuring the retrieval experiment. Variables such as COLLECTION_NAME, QDRANT_URL, and QDRANT_TOKEN define where the processed knowledge will be stored. One particularly important configuration is is_context_enriched. This flag changes the behavior of the entire retrieval system. When disabled, the architecture behaves like a traditional semantic RAG pipeline where raw chunks are embedded directly. When enabled, every chunk first passes through an LLM-powered contextual augmentation process before indexing. This makes the codebase extremely useful for retrieval benchmarking because both approaches can be compared under the same conditions.The initialization of HybridStore abstracts away all direct interaction with Qdrant. Instead of handling collection creation, vector schemas, and indexing logic manually inside the ingestion script, those responsibilities are delegated into a dedicated storage layer. This separation keeps the ingestion workflow clean and easier to maintain.from datetime import datetimefrom chonkie import SemanticChunkerfrom chonkie.embeddings import AutoEmbeddingsfrom context_preprocessor import enrich_contextfrom qdrant_store import HybridStore# configsis_context_enriched = FalseCOLLECTION_NAME = "cardiology_without_context" # cardiology_without_contextQDRANT_URL = "http://localhost:6333"QDRANT_TOKEN = "th3s3cr3tk3y"# create the Hybrid store and collection in qdrantstore = HybridStore(collection_name=COLLECTION_NAME, qdrant_url=QDRANT_URL, qdrant_api_key=QDRANT_TOKEN)store.create_collection()# read the filewith open('data/cardiology.txt', 'r', encoding='latin-1') as f: text = f.read()# Experiment with different thresholdsthresholds = [0.8]# Use AutoEmbeddings for automatic model selectionembeddings = AutoEmbeddings.get_embeddings( model="sentence-transformers/all-MiniLM-L6-v2")# Basic initialization with default parametersfor threshold in thresholds: chunker = SemanticChunker( embedding_model=embeddings, # Default model threshold=threshold, # Similarity threshold (0-1) chunk_size=2048, # Maximum tokens per chunk similarity_window=3, # Window for similarity calculation skip_window=0 # Skip-and-merge window (0=disabled) ) chunks = chunker.chunk(text) print(f"\nThreshold {threshold}: {len(chunks)} chunks created") # Lower threshold = larger, more diverse chunks # Higher threshold = smaller, more focused chunks avg_size = sum(c.token_count for c in chunks) / len(chunks) print(f"Average chunk size: {avg_size:.1f} tokens") _metadata = [ {"source": "clinical-cardiology", "timestamp": datetime.timestamp(datetime.now())} for _ in chunks ] if not is_context_enriched: _texts = [chunk.text for chunk in chunks] else: # enable the context enrichment _texts = [chunk.text+enrich_context(chunk.text, text, index) for index, chunk in enumerate(chunks)] store.ingest( texts=_texts, metadata=_metadata, )# print(TextEmbedding.list_supported_models())The document loading section reads the cardiology dataset using latin-1 encoding. This detail may look minor, but it is actually practical for real-world ingestion systems. Medical and legacy datasets often contain inconsistent encodings, and explicitly handling them prevents ingestion failures caused by character parsing errors.The chunking logic is one of the most important sections in the entire architecture. Instead of fixed-size chunking, the implementation uses semantic chunking through Chonkie. This means chunks are created based on semantic continuity rather than arbitrary token boundaries. The threshold parameter directly influences chunk granularity. Lower thresholds create larger chunks with broader semantic coverage, while higher thresholds generate smaller and more focused chunks. This tradeoff becomes extremely important because chunk size strongly affects retrieval precision and contextual retention.The similarity_window=3 parameter improves chunk stability by considering nearby semantic relationships when determining boundaries. Without this contextual window, chunking decisions become too local and unstable. Meanwhile, skip_window=0 disables skip-and-merge behavior, ensuring chunk formation remains sequential and predictable.Once chunks are generated, metadata is attached to every chunk. The metadata currently includes the document source and a timestamp. Although simple, this layer becomes very important in production systems because metadata enables filtering, auditing, debugging, and traceability during retrieval.The context enrichment branch is the heart of the architecture. If enrichment is disabled, the pipeline directly indexes raw chunk text. If enabled, every chunk is sent to the enrich_context() function, where additional surrounding context is generated using an LLM. The enriched context is appended to the original chunk rather than replacing it. This is a very important architectural decision because it preserves exact source wording while also injecting additional semantic understanding into the embedding representation.Finally, the processed chunks are ingested into Qdrant using the hybrid store abstraction. At this stage, the system converts semantically enriched knowledge into searchable hybrid retrieval representations.One critical issue in this file is scalability during enrichment. Since every chunk may trigger a separate LLM call, ingestion latency and token usage can grow rapidly for large documents. This becomes one of the biggest bottlenecks in production-scale pipelines.context_preprocessor.pyThis file is responsible for contextual augmentation. Conceptually, it behaves like a semantic reconstruction layer that attempts to restore surrounding meaning around isolated chunks before indexing.The most important part of this file is the system prompt. The prompt strictly constrains the language model to operate only within the boundaries of the provided document. It explicitly prevents external knowledge injection, hallucination, paraphrasing, or inference. This is extremely important because unrestricted generation during indexing can poison retrieval quality. If hallucinated information becomes embedded into the vector database, retrieval results become unreliable.The architecture intentionally frames the LLM as a “document-bound context enricher” rather than a generative assistant. This distinction matters because the purpose here is not creativity or summarization. The goal is semantic grounding.The retry mechanism implemented with tenacity is another critical production detail. LLM APIs frequently encounter rate limits or transient failures during large ingestion jobs. Without retries, the pipeline would become unreliable when processing large corpora. The retry wrapper improves stability by automatically retrying failed enrichment calls.The _call_llm() function encapsulates the actual inference request sent to the Venice AI endpoint using the Gemma model. Separating inference logic into its own function keeps the architecture modular and makes model swapping easier in future experiments.The enrich_context() function performs the actual enrichment workflow. It injects the full document into the system prompt and sends the current chunk as user context. The returned response is then appended back into the chunk during ingestion.from textwrap import dedentfrom tenacity import retry, stop_after_attempt, wait_fixed, retry_if_exception_typeimport openaisystem_prompt = dedent(f"""You are a document-bound context enricher. Your ONLY job is to expand the given chunk using content strictly from the provided document.STRICT RULES:- Use ONLY the text present in the provided document below. Nothing else.- Do NOT use any prior knowledge, training data, or external information.- Do NOT infer, assume, or generate content that is not explicitly stated in the document.- Do NOT paraphrase or rewrite — only pull relevant surrounding context from the document as-is.- If the document does not contain relevant enrichment for the chunk, return the chunk as-is.- while returning the enriched text consider the chunk given to you and the text around it.PROVIDED DOCUMENT:""")@retry( retry=retry_if_exception_type(openai.RateLimitError), wait=wait_fixed(5), stop=stop_after_attempt(5), reraise=True)def _call_llm(client, prompt, context): return client.chat.completions.create( model="google-gemma-4-31b-it", messages=[ {"role": "system", "content": prompt}, {"role": "user", "content": context} ] )def enrich_context(context: str, full_document: str, index: int) -> str: enriched_prompt = system_prompt.replace("", full_document) # fix: local variable client = openai.OpenAI( api_key="DVfuZhMXrIp736tQewMKQQmh760PkkHWLpTtoSpq2p", base_url="https://api.venice.ai/api/v1" ) response = _call_llm(client, enriched_prompt, context) print(f"context {index}: {context}") print(f"response: {response.choices[0].message.content}") print("=" * 100) return response.choices[0].message.contentThis section introduces one of the biggest architectural risks in the entire system. The implementation injects the complete document into the prompt for every single chunk:enriched_prompt = system_prompt.replace("", full_document)This means the entire document is repeatedly transmitted to the model once per chunk. For small documents this works well, but for large documents it becomes computationally expensive, slow, and extremely token intensive. In production environments, this design can quickly become impractical.A more scalable approach would retrieve only nearby sections surrounding the chunk instead of passing the entire document every time. That would significantly reduce token consumption while preserving contextual relevance.Another important observation is that the enriched context is appended directly to the original chunk without filtering or compression. While this improves semantic richness, it can also increase embedding noise and token size if enrichment becomes excessively verbose.Qdrant_store.pyThis file abstracts all hybrid retrieval operations behind a clean storage interface. Instead of exposing raw Qdrant operations throughout the application, the architecture centralizes vector storage and retrieval logic into a dedicated class called HybridStore.The constructor initializes both dense and sparse retrieval models. Dense embeddings are generated using sentence-transformers/all-MiniLM-L6-v2, while sparse retrieval is powered by Splade_PP_en_v1. Together, these models create hybrid retrieval capabilities where semantic similarity and exact keyword matching coexist.from typing import Optionalfrom qdrant_client import QdrantClientfrom qdrant_client.models import QueryResponseclass HybridStore: DENSE_VECTOR_FIELD = None SPARSE_VECTOR_FIELD = None def __init__( self, collection_name: str, dense_model: str = "sentence-transformers/all-MiniLM-L6-v2", sparse_model: str = "prithivida/Splade_PP_en_v1", qdrant_url: Optional[str] = None, qdrant_api_key: Optional[str] = None, ): self.collection_name = collection_name if qdrant_url: self.client = QdrantClient(url=qdrant_url, api_key=qdrant_api_key) else: self.client = QdrantClient(":memory:") self.client.set_model(dense_model) self.client.set_sparse_model(sparse_model) def create_collection(self): if not self.client.collection_exists(self.collection_name): self.client.create_collection( collection_name=self.collection_name, vectors_config=self.client.get_fastembed_vector_params(), sparse_vectors_config=self.client.get_fastembed_sparse_vector_params(), ) def ingest(self, texts: list[str], metadata: Optional[list[dict]] = None): meta = metadata if metadata else [{} for _ in texts] ids = list(range(1, len(texts) + 1)) self.client.add( collection_name=self.collection_name, documents=texts, metadata=meta, ids=ids, ) def retrieve(self, query: str, top_k: int = 5) -> list[QueryResponse]: return self.client.query( collection_name=self.collection_name, query_text=query, limit=top_k, )This hybrid design is extremely important for real-world retrieval systems. Dense retrieval is excellent for semantic understanding but can miss exact terminology, abbreviations, or identifiers. Sparse retrieval complements this weakness by preserving lexical matching behavior. Combining both approaches significantly improves retrieval robustness.The create_collection() method automatically configures the vector schema using FastEmbed integration. Instead of manually defining dense and sparse vector structures, the implementation delegates schema generation to Qdrant helper methods. This reduces configuration complexity and ensures compatibility between embeddings and storage formats.The ingest() method handles document insertion into the collection. The implementation automatically generates metadata placeholders when metadata is not provided. The method also generates sequential numeric IDs for stored documents.This section contains a subtle but important risk:ids = list(range(1, len(texts) + 1))Since IDs restart from 1 during every ingestion run, document collisions may occur if the collection already contains data. In production systems, document identifiers should ideally be UUIDs or globally unique values.The retrieval logic itself is intentionally simple. The retrieve() method hides all hybrid query complexity behind a single function call. Internally, Qdrant performs dense and sparse retrieval fusion, allowing downstream applications to remain clean and minimal.One of the strongest aspects of this architecture is that retrieval complexity remains isolated inside this storage layer. This makes experimentation easier because embedding models, sparse retrievers, indexing strategies, and retrieval configurations can all evolve independently without affecting the rest of the pipeline.The Evaluation:This file is the evaluation engine of the entire RAG architecture. While the ingestion pipeline focuses on storing knowledge, this file measures whether the retrieval system is actually improving answer quality. Its main purpose is to compare two collections: one indexed with raw chunks and another indexed with context-enriched chunks.The pipeline begins by loading a golden dataset containing questions, expected contexts, and expected answers. This dataset acts as the ground truth for evaluation. Without a golden dataset, retrieval quality becomes subjective and difficult to benchmark consistently.One of the most important sections in this file is the COLLECTIONS configuration. The architecture intentionally evaluates two separate Qdrant collections side by side:cardiology_without_contextcardiology_with_contextThis is critical because it transforms the project from a simple RAG implementation into an experimental retrieval framework. The evaluation is not based on assumptions anymore. It quantitatively measures whether context enrichment actually improves retrieval performance.The RAG_SYSTEM_PROMPT is another important component. Just like the enrichment pipeline, the prompt strictly forces the model to answer only from retrieved chunks. This prevents the evaluation from being contaminated by the model’s prior knowledge. Without this restriction, the LLM could answer correctly even when retrieval quality is poor, making the metrics meaningless.The file uses two different models for two different responsibilities. Venice AI handles answer generation, while a local Ollama model acts as the evaluation judge. This separation is very important architecturally because it prevents the same model from generating and judging answers, which could introduce evaluation bias.The query_llm() function is the runtime RAG flow. It retrieves chunks from Qdrant, formats them into structured context blocks, injects them into the system prompt, and generates an answer using the LLM. The retrieved chunks are also returned separately because they are required for metric evaluation.The evaluation metrics are the core of this file. Three contextual metrics are measured:Contextual PrecisionContextual RecallContextual RelevancyContextual Precision measures whether the retrieved chunks are actually useful and relevant to the answer. High precision means the retriever is not bringing excessive noise.Contextual Recall measures whether the retrieval system captured enough information required to answer the question completely. High recall means important evidence was not missed.Contextual Relevancy measures how semantically aligned the retrieved chunks are with the query itself.Together, these metrics provide a much deeper understanding of retrieval quality than simply checking whether the final answer “looks correct.”The evaluate_collection() function is the main evaluation loop. For every question in the golden dataset, the pipeline retrieves chunks, generates an answer, computes all evaluation metrics, and stores the results. This creates both per-question analysis and aggregate collection-level summaries.One particularly important design detail is that metric failures are isolated with try/except blocks. Evaluation pipelines frequently fail because judge models, APIs, or retrieval outputs can be inconsistent. Instead of crashing the entire benchmark run, the pipeline logs failures and continues evaluation. This is extremely important for long-running experiments.The compute_summary() function aggregates scores across all questions and produces average precision, recall, and relevancy metrics. This final summary becomes the most important output because it provides measurable evidence of whether context enrichment improves retrieval performance.One critical observation in this architecture is that the evaluation itself is also LLM-driven. Metrics like contextual precision and relevancy are judged by another language model. While this creates more intelligent evaluation than simple string matching, it also introduces dependency on the judge model’s consistency and reasoning quality.Another critical section is latency and cost. Every evaluation question triggers:Retrieval from QdrantLLM answer generationThree separate metric evaluationsThis means evaluation becomes computationally expensive very quickly for large datasets. The architecture is powerful for experimentation, but scaling this evaluation framework to thousands of questions would require batching, caching, or asynchronous execution.The Conclusion:Traditional RAG pipelines often fail not because the language model is weak, but because the retriever surfaces fragmented and context-poor chunks. This architecture addresses that problem at the indexing layer itself by enriching every chunk with surrounding semantic context before retrieval even begins.The evaluation results clearly show the impact. While precision and recall improved consistently, the biggest improvement came in contextual relevancy, where the enriched pipeline significantly outperformed the baseline retrieval system. That improvement is important because relevancy directly affects grounding, answer quality, and hallucination reduction in production RAG systems.The key takeaway from this architecture is simple: retrieval quality is not only about better embeddings or better vector search. Sometimes the biggest improvement comes from improving the knowledge representation before indexing.Instead of storing isolated chunks, the system stores semantically aware knowledge units. That small architectural shift fundamentally changes how retrieval behaves.Contextual Retrieval: The Preprocessing Step That Makes RAG Actually Work was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.