Skip to content

2.6 RAG in Action. Techniques for QA

Three Stages of Handling a Question

When a user's question enters a RAG system, it passes through three clearly defined stages. Each stage has its own bottleneck and its own optimization opportunities (see Fig. 18).

Stage 1: Retrieval. The question is converted into an embedding and used to search for relevant fragments in the index. The quality of retrieval determines whether the model gets the context it needs.

Stage 2: Augmentation. The found fragments are formatted and packed into a prompt together with the question and the instructions. How the context is presented affects how the model uses it.

Stage 3: Generation. The model processes the prompt and forms the answer. The instructions in the prompt and the model parameters play the decisive role here.

Figure 18. The three stages of handling a question in RAG.

Figure 18. The three stages of handling a question in RAG.

Here is a minimal implementation of the three-stage pipeline:

class RAGPipeline:
    def __init__(self, retriever, llm, prompt_template):
        self.retriever = retriever
        self.llm = llm
        self.prompt_template = prompt_template

    def answer(self, question):
        docs = self.retriever.get_relevant_documents(question)

        context = self.format_context(docs)
        prompt = self.prompt_template.format(
            context=context,
            question=question
        )

        response = self.llm.generate(prompt)

        return {
            "answer": response,
            "sources": [doc.metadata.get("source") for doc in docs]
        }

    def format_context(self, docs):
        formatted = []
        for i, doc in enumerate(docs):
            source = doc.metadata.get("source", "Unknown")
            formatted.append(f"[Source {i+1}: {source}]\n{doc.page_content}")
        return "\n\n".join(formatted)

Designing a Prompt for QA

A prompt is an instruction to the model, and for QA it must be very explicit. A good prompt for question answering:

  • clearly states that the answer must be based on the provided context, not on external knowledge
  • describes the expected answer format
  • gives instructions for cases where the information is insufficient
  • asks for references to the sources
QA_PROMPT = """You are an assistant that answers questions based on the provided context.

Context:
{context}

Question: {question}

Instructions:
1. Answer only on the basis of the information in the context
2. If the context contains no information for an answer, say so
3. Cite sources by their number in square brackets, [1], [2]
4. Be specific and avoid generic phrases

Answer:"""

Formatting the context matters too. Explicit separators between fragments help the model see the boundaries. Numbering the sources lets the model refer to them in the answer. Instead of simply concatenating text, it is better to label each fragment explicitly.

Fighting Hallucinations

Hallucinations in RAG systems are when the model generates information that is not in the context. This is especially critical in systems where high accuracy is required.

The model can hallucinate in several ways. It may extrapolate from general knowledge, guess numbers and dates when similar data is in the context, or simply answer confidently even when information is lacking.

The solution is multi-layered. First, the prompt must be reinforced with explicit instructions emphasizing that the model must rely only on the context. Second, you can add post-processing: check that all statements in the answer are backed by quotes. And third, ask the model for a confidence assessment: can it state that the answer is fully based on the context?

Here is an example of a reinforced prompt for a highly demanding application:

STRICT_QA_PROMPT = """You are an assistant that answers questions about documentation.

CRITICALLY IMPORTANT: Answer ONLY on the basis of the provided context.
Do not use any external knowledge.
Do not make assumptions and do not extrapolate.

Context:
{context}

Question: {question}

Answer format:
1. ANSWER: [your answer with citations of the sources]
2. SOURCES: [list of the sources used, with numbers]
3. COMPLETENESS: [FULL / PARTIAL / INSUFFICIENT DATA]

If the context contains no information for answering the question, write:
ANSWER: The information on this question was not found in the provided documentation.
COMPLETENESS: INSUFFICIENT DATA

Answer:"""

Working with Long Context

The model's context window is limited, so it is not always possible to pass all the found documents in full. There are several strategies (see Fig. 19).

The Stuff strategy is the simplest. All the found documents are placed into one prompt. It is easy to implement and preserves context well, but it works only if the total size of the context plus the question and the instructions fits into the model's window.

from langchain.chains import RetrievalQA

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=retriever,
    return_source_documents=True
)

The MapReduce strategy processes each document separately. First a partial answer is generated for each document (map), then all the partial answers are combined into the final one (reduce). This makes it possible to handle large volumes of context, but it increases the number of model calls and can lose connections between documents.

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="map_reduce",
    retriever=retriever
)

The Refine strategy improves the answer iteratively. An initial answer is generated from the first document, then it is refined step by step with the content of the second, third, and so on. This preserves coherence and context better, but it is sensitive to the order of the documents and also increases the number of calls.

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="refine",
    retriever=retriever
)

Figure 19. Strategies for working with long context.

Figure 19. Strategies for working with long context.

Handling Unanswerable Questions

A RAG system must handle correctly the questions for which the knowledge base simply has no answer. Silence is better than a confident wrong answer.

You can combine several signals. Low similarity scores during retrieval indicate that there may be no relevant documents. If you instruct the model to state explicitly when its information is insufficient, that is an additional signal. Then you can check whether the answer actually refers to its sources.

def answer_with_confidence(question, rag_pipeline, score_threshold=0.6):
    docs_with_scores = rag_pipeline.retriever.similarity_search_with_score(
        question, k=5
    )

    if not docs_with_scores or docs_with_scores[0][1] < score_threshold:
        return {
            "answer": "Unfortunately, the knowledge base contains no information on your question.",
            "confidence": "LOW",
            "sources": []
        }

    docs = [doc for doc, score in docs_with_scores]
    answer = rag_pipeline.generate_answer(question, docs)

    if "not found" in answer.lower() or "insufficient data" in answer.lower():
        return {
            "answer": answer,
            "confidence": "LOW",
            "sources": []
        }

    return {
        "answer": answer,
        "confidence": "HIGH",
        "sources": [doc.metadata.get("source") for doc in docs]
    }

Integrating Dialogue Memory

In dialogue scenarios, questions often depend on the previous context. For example, the question "What about the second item?" cannot be understood without the history.

The solution is to rephrase the question into a self-contained form that takes the previous dialogue into account (see Fig. 20). This makes it possible to use the standard RAG pipeline without losing meaning:

Figure 20. Integrating dialogue memory into RAG.

Figure 20. Integrating dialogue memory into RAG.

CONDENSE_PROMPT = """Given the dialogue history and the user's latest question,
rephrase the question so that it can be understood without the dialogue context.

Dialogue history:
{chat_history}

Latest question: {question}

Standalone question:"""

def condense_question(question, chat_history, llm):
    if not chat_history:
        return question

    history_text = "\n".join([
        f"User: {q}\nAssistant: {a}"
        for q, a in chat_history
    ])

    prompt = CONDENSE_PROMPT.format(
        chat_history=history_text,
        question=question
    )

    return llm.generate(prompt)

LangChain provides the built-in ConversationalRetrievalChain, which does this automatically:

from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)

qa_chain = ConversationalRetrievalChain.from_llm(
    llm=llm,
    retriever=retriever,
    memory=memory,
    condense_question_prompt=condense_prompt
)

result = qa_chain({"question": "What are the password requirements?"})
result = qa_chain({"question": "And for the login?"})

Controlling the Answer Style

The answers of a RAG system must meet user expectations. Technical documentation needs a precise, structured style with code examples. Customer support needs a friendly and clear one. For management, the answer should be brief and focused on conclusions.

The style is set in the system prompt and can be parameterized:

STYLE_TEMPLATES = {
    "technical": """Answer in a technical style:
- Use precise terminology
- Include code examples where appropriate
- Structure the answer logically""",

    "support": """Answer in the friendly style of a support team:
- Address the user directly and politely
- Explain in plain language
- Offer further help""",

    "executive": """Answer briefly and to the point:
- Start with the main conclusion
- Minimum technical details
- Focus on business implications"""
}

def build_qa_prompt(style="technical"):
    style_instructions = STYLE_TEMPLATES.get(style, STYLE_TEMPLATES["technical"])

    return f"""You are an assistant that answers questions.

{style_instructions}

Context:
{{context}}

Question: {{question}}

Answer:"""

Questions for Reflection and Practice

Theoretical questions

  1. Describe the three stages of handling a question in a RAG system (retrieval, augmentation, generation) and the optimizations possible at each stage.

  2. How do the limits of the context window affect the architecture of a RAG system, and which strategies exist for working with long context?

  3. What role does prompt design play in the quality of a RAG system's answers, and how do you protect against hallucinations?

  4. Compare the MapReduce and Refine strategies for processing long context: in which situations is each one preferable?

  5. Which signals indicate that the system cannot answer a question, and how can they be used?

  6. How do you integrate dialogue history into a RAG pipeline, and which techniques help handle dependent questions?

  7. Which types of memory exist in LangChain, and how do you choose one for a dialogue scenario?

  8. How do you parameterize the style and format of answers for different use cases (technical documentation, support, analytics)?

Practical exercises

  1. Implement a basic RAG pipeline with retrieval, context augmentation, and answer generation.

  2. Create several QA prompt variants (strict, friendly, technical) and compare the quality of the answers.

  3. Implement post-processing of an answer that checks for the presence of citations and determines confidence in the answer.

  4. Configure RetrievalQA with a custom prompt that includes instructions for citing sources and for handling cases of insufficient information.

  5. Create a dialogue system with ConversationalRetrievalChain that correctly handles questions that depend on the conversation context.

  6. Implement a comparison of the Stuff, MapReduce, and Refine strategies on a set of 15–20 documents, measuring answer quality and the number of model calls.

  7. Build a system for detecting unanswerable questions based on similarity scores and analysis of the model's answer.