Context in a mature RAG LLM architecture doesn't appear from a single query to a vector database – it goes through a full processing cycle.
Query Analysis. The system analyzes the user's query: intent, type of question, need for structured or unstructured data. This determines which retrieval strategy to apply.
Query Expansion. The initial query is expanded with synonyms, related terms, or rephrased variants to cover a broader semantic space and not lose relevant document chunks formulated in other words.
Retrieval. The actual search is performed – a combination of vector search based on embeddings and lexical search within hybrid search. This is the point where knowledge retrieval – and, more broadly, information retrieval as a discipline – turns from an abstract task into a concrete list of candidates obtained from the knowledge base.
Ranking. The retrieved fragments are ordered by relevance to the query. A reranking model is often applied here, separate from the one used for the initial vector search – it evaluates semantic correspondence more precisely.
Filtering. Duplicates, outdated or contradictory fragments are filtered out, as well as data that doesn't match the metadata filters (access rights, date, source, document type).
Context Compression. Long document chunks are compressed down to their essence while preserving key facts – this is critical for the efficient use of the context window, especially when the available volume is limited or expensive in tokens.
Context Assembly. The selected and compressed fragments are assembled into a single structure: the order, priority, and presentation format are determined – tables, lists, and quotes with a reference to the source.
Grounding. Each fragment of context is tied to a specific source, which allows the model (and the user) to verify the origin of the fact and significantly reduces the risk of hallucinations.
Input to LLM. The assembled context, together with the prompt, is passed to the language model to generate the final response.
In agentic systems, this cycle is rarely linear: the agent itself evaluates whether the gathered context is sufficient for a confident answer and, if necessary, returns to the Retrieval or Query Expansion stage, repeating the cycle iteratively rather than going through it once. The relevance of a response is the result of the sequential work of at least seven or eight stages, not a single successful query to the database.
It is precisely the coordinated work of all these stages that ensures stable response quality. If even one of them is missing, Production RAG may show good results on test examples but unpredictably lose accuracy under real load.
