Module 4 · Query engines
Query engines, retrievers and post-processors
5 min read
A query engine turns a question into a sourced answer. Behind the index.as_query_engine() call there are three distinct components, worth tuning separately: the retriever finds passages, post-processors filter and reorder them, the synthesizer writes the answer. This lesson takes this mechanism apart and builds Lumen's main engine, which cites its sources and refuses to answer outside its base.
The pipeline of a query
question ─► retriever ─► post-processors ─► synthesizer ─► answer + source nodes
(top k) (threshold, filter, (prompt, synthesis
reranking) mode)
def knowledge_engine(index: VectorStoreIndex, sku: str | None = None):
filters = None
if sku:
condition = MetadataFilter(key="skus", value=sku, operator=FilterOperator.EQ)
filters = MetadataFilters(filters=[condition])
retriever = index.as_retriever(similarity_top_k=config.TOP_K, filters=filters)
synthesizer = get_response_synthesizer(llm=models.main_llm(), response_mode=ResponseMode.COMPACT)
synthesizer.update_prompts({"text_qa_template": PromptTemplate(QA_PROMPT)})
return RetrieverQueryEngine(
retriever=retriever,
response_synthesizer=synthesizer,
node_postprocessors=[SimilarityPostprocessor(similarity_cutoff=config.SIMILARITY_CUTOFF)],
)
The response contains the text and the nodes used (response.source_nodes, with their score), which makes it possible to show the sources and to evaluate retrieval.
The retriever
| Parameter | Effect |
|---|---|
similarity_top_k | Number of passages retrieved. Too few: you miss the information; too many: you drown the model and pay for tokens |
filters | Metadata filters applied before similarity search |
vector_store_query_mode | Dense (default), sparse or hybrid (lesson 3.1) |
Filters are one of the most effective and most underused levers. If the support agent is looking at the mug's sheet, searching only in passages about MUG-01 removes at once all the noise from other products. Filters combine (AND / OR) and support comparisons, lists and text, depending on the vector database (lesson 3.1).
Post-processors
A post-processor receives the retrieved passages and returns a selection, possibly reordered or modified:
| Post-processor | Role |
|---|---|
SimilarityPostprocessor | Drops passages below a similarity threshold |
KeywordNodePostprocessor | Requires or excludes keywords |
LLMRerank / StructuredLLMRerank | The LLM reorders passages by relevance |
SentenceTransformerRerank | A reranking model (cross-encoder) reorders, more precise than similarity alone |
MetadataReplacementPostProcessor | Replaces the passage with a metadata field (the sentence window, lesson 2.2) |
FixedRecencyPostprocessor | Favors the most recent passages |
LongContextReorder | Places the best passages at the start and end of the context |
PIINodePostprocessor | Masks personal data before sending to the model |
The most cost-effective pattern in production is reranking: retrieve wide (similarity_top_k=20), then reorder with a finer model and keep only the top 4. Vector similarity is fast but coarse; a reranker reads the question and the passage together, and judges their fit much better.
The similarity threshold is Lumen's safeguard: if no passage is close enough, the synthesizer receives nothing and the engine answers that it doesn't know, instead of improvising from off-topic passages. The threshold depends on the embedding model: calibrate it on your data, by looking at the scores of relevant and irrelevant questions.
The synthesizer
The synthesizer assembles the passages into a prompt and calls the LLM. Its mode determines how it handles several passages:
| Mode | How it works | Use |
|---|---|---|
compact (default) | Packs as many passages as possible per call, then refines if needed | The general case: few calls |
refine | One call per passage, the answer being refined at each step | Many passages, detailed answer; slow |
tree_summarize | Summarizes in groups, then summarizes the summaries | Synthesis questions (lesson 3.2) |
simple_summarize | Truncates to fit everything in one call | Fast, risk of loss |
accumulate | One answer per passage, concatenated | Compare what each source says |
no_text | No answer, only the passages | Debug retrieval |
The prompt: cite and know how to say "I don't know"
The default prompt is generic. Lumen's sets three requirements:
QA_PROMPT = """Tu es l'assistant interne du support de la boutique Nimbus.
Réponds UNIQUEMENT à partir des extraits ci-dessous. Si la réponse n'y figure pas, dis-le :
ne la devine pas, car le conseiller transmettra ta réponse au client.
Cite la source entre crochets, par exemple [policies/returns.md].
Extraits :
{context_str}
Question : {query_str}
Réponse :"""
- Answer only from the excerpts: the base is the source of truth, not the model's general knowledge.
- Say when information is missing, explaining why it matters (the support agent will pass it on to the customer): recent models follow an instruction better when they understand its reason.
- Cite the source, so the support agent can check.
The {context_str} and {query_str} variables are imposed by the synthesizer. The prompt is replaced with update_prompts, and get_prompts() displays all prompts of an engine — a good reflex to know what is actually sent to the model.
For passage-level citations, LlamaIndex also offers a CitationQueryEngine, which numbers the excerpts and asks the model to cite [1], [2]…
Streaming
An engine can stream its answer as it's generated with streaming=True; the response then exposes a token generator. For a chat interface, it's almost essential: retrieval and synthesis can take several seconds.
Key takeaways
- An engine = retriever (find) + post-processors (filter, reorder) + synthesizer (write).
- Metadata filters before retrieval; a similarity threshold after, to be able to say "I don't know".
- Retrieve wide, then rerank: the most cost-effective quality gain.
- Choose the synthesis mode according to the question;
compactby default,tree_summarizefor syntheses.- A prompt that requires sources, citations and admitting ignorance — with the reason for each instruction.
Practice
- Ask a question with
response_mode="no_text"and display the passages and their scores: is the 0.2 threshold suitable? - Add an
LLMRerank(fast model) after a retrieval withsimilarity_top_k=10, and compare the passages kept. - Display the engine's prompts with
get_prompts(): find Lumen's prompt and the refine prompt, left at its default.