Designing a Two-Stage AI Q&A Workflow with Retrieval and Rewriting

    A two-stage architecture separates evidence retrieval from answer generation. This article explains how to design the workflow, including query rewriting, source ranking, content compression, style-controlled generation, citation validation, fallback strategies, caching, cost management, and implementation metrics.

    1. Why Split Q&A into Two Stages?

    When users ask an AI assistant a question, they usually want a clear and actionable answer: what something is and how to do it. In most scenarios, they do not need an extensive explanation of why it works. This requirement leads to two design priorities:

    1. Ensure that the answer is based on reliable source material.
    2. Present the answer clearly and in a style suitable for the target scenario.

    If a single model is responsible for both finding information and writing the answer, three common problems arise:

    1. Uncontrolled sources: The model may answer from its training data without being able to explain where the information came from.
    2. Limited freshness: Training data has a cutoff date, so the model may provide inaccurate information about newly released standards, version changes, or price updates.
    3. Coupled facts and style: Changing the writing style often requires regenerating the entire response, which may also change the underlying facts.

    A two-stage architecture separates these responsibilities. The retrieval layer answers “What is the evidence?”, while the generation layer answers “How should the answer be organized and expressed?” Each layer can be optimized, replaced, and evaluated independently. This separation is the core value of the architecture.

    2. Basic Architecture

    The overall workflow can be summarized as:

    User question → Query rewriting → Multi-path retrieval → Source filtering and ranking → Material compression → Style-controlled generation → Citation validation → Output

    2.1 Responsibilities of the Retrieval Layer

    The retrieval layer provides usable source material to the generation layer. Its responsibilities include:

    • Rewriting a conversational user question into multiple search queries that cover synonyms and broader or narrower concepts;
    • Retrieving candidate results from an index or search service;
    • Filtering and ranking results according to relevance, source credibility, and publication date;
    • Removing duplicate or highly similar content;
    • Compressing long documents into key passages related to the question.

    2.2 Responsibilities of the Generation Layer

    The generation layer receives the material selected by the retrieval layer and performs the following tasks:

    • Organizing the answer using only facts found in the supplied material;
    • Rewriting the content in the requested style, such as conversational, tutorial-oriented, or report-oriented;
    • Adding source identifiers to key conclusions so readers can verify them;
    • Clearly describing information gaps instead of filling them with speculation.

    2.3 Data Contract Between the Two Layers

    The two layers should use a consistent data structure so that the generation layer does not depend directly on the internal implementation of the retrieval layer. A minimal structure could include:

    1. {
    2. "id": 1,
    3. "title": "Source title",
    4. "url": "https://example.com/doc",
    5. "published_at": "2026-03-01",
    6. "score": 0.82,
    7. "content": "Relevant content excerpt"
    8. }

    A unified structure provides two benefits. First, the retrieval layer can change its underlying search method without requiring changes to the generation prompt. Second, evaluation can separately measure retrieval hit rate and generation quality.

    3. Key Practices for the Retrieval Layer

    3.1 Query Rewriting

    User questions often contain conversational language and omitted context. Searching with the original sentence alone usually produces a lower recall rate. A common approach is to generate three to five search queries covering the following perspectives:

    • A combination of keywords from the original question;
    • Synonyms or commonly used industry terms;
    • A version with specific constraints, such as a year, system platform, or applicable scope;
    • A solution-oriented formulation, such as “how to configure” or “common causes of this error.”

    A language model can perform the query rewriting, but its output format should be constrained and duplicate queries should be removed.

    3.2 Evaluating Source Credibility

    Not every search result is suitable as source material. Sources can be scored according to several dimensions:

    • Authority: Official documentation, standards organizations, academic papers, and vendor technical documentation are generally more reliable than reposts and personal blogs.
    • Freshness: For version-specific questions, recently published or updated content should be prioritized.
    • Consistency: Confidence is higher when multiple independent sources support the same conclusion.
    • Traceability: Content with an identifiable original source is preferable to an unattributed secondary summary.

    Scoring rules should be adapted to the business context. For example, medical and financial Q&A systems should assign greater weight to authority and apply stricter filtering thresholds.

    3.3 Deduplication and Compression

    Retrieved results often contain large amounts of repeated text. Passing the results directly to the generation layer consumes context-window capacity and increases the chance of repetitive output. A recommended processing sequence is:

    1. Remove duplicates based on text similarity, using sentence embeddings or simple character-level fingerprints.
    2. Keep passages relevant to the question and discard unrelated navigation elements, advertisements, and copyright notices.
    3. Summarize the retained passages and limit the total length to what the generation layer can handle.

    3.4 Example Implementation

    The following code illustrates the workflow. The functions and objects are placeholders and must be implemented according to the actual search service and model API.

    1. def answer_question(question: str, style: str) -> dict:
    2. queries = rewrite_queries(question) # Generate multiple search queries
    3. hits = []
    4. for q in queries:
    5. hits.extend(search_index.query(q, top_k=10))
    6. sources = filter_and_rank(hits) # Filter, deduplicate, and rank
    7. materials = compress(sources, max_tokens=3000)
    8. prompt = build_prompt(question, materials, style)
    9. draft = llm.generate(prompt)
    10. return {
    11. "answer": draft,
    12. "references": [s.url for s in sources[:5]],
    13. }
    14. def filter_and_rank(hits, min_score=0.6):
    15. kept = []
    16. for h in hits:
    17. if h.score < min_score:
    18. continue
    19. if is_duplicate(h, kept):
    20. continue
    21. h.credibility = score_source(h.url, h.published_at)
    22. kept.append(h)
    23. return sorted(kept, key=lambda h: (h.credibility, h.score), reverse=True)

    4. Key Practices for the Generation Layer

    4.1 Prompt Structure

    A stable prompt usually contains four parts: role definition, source material, constraints, and output format. The constraints are especially important because they determine whether the generated answer remains reliable.

    1. PROMPT_TEMPLATE = """
    2. You are a technical writing editor. Answer the user's question using only the
    3. material provided below.
    4. Constraints:
    5. 1. Use only facts that appear in the material. If the material is insufficient,
    6. clearly identify what is missing.
    7. 2. Add a source identifier after each key conclusion, such as [1].
    8. 3. Do not invent version numbers, parameter names, or numerical values.
    9. 4. Follow the requested writing style.
    10. Output structure: conclusion, implementation steps, and considerations.
    11. User question: {question}
    12. Target style: {style}
    13. Source material:
    14. {materials}
    15. """

    4.2 Style Transfer

    The key to style transfer is separating facts from expression. In practice, the model can first extract factual points from the source material into a structured list, and then rewrite that list in the target style. This reduces the risk of factual drift during rewriting.

    Common styles include:

    • Conversational: Short sentences with limited terminology, suitable for quickly obtaining a conclusion;
    • Tutorial-oriented: Organized as steps, with prerequisites and expected results for each step;
    • Report-oriented: Presents the conclusion first and then lists the supporting evidence, making it suitable for management audiences;
    • Comparison-oriented: Uses tables or parallel structures to show differences between multiple options.

    4.3 Output Validation

    Generated answers should pass format and content checks. Common validation items include:

    • Whether the answer contains a conclusion section;
    • Whether all citation identifiers exist in the source-material list;
    • Whether the length is within the target range;
    • Whether the answer contains numbers, version identifiers, or proper nouns not found in the source material.

    If validation fails, the system can retry once. If the second attempt also fails, it should fall back to returning the source-material list and asking the user to review the original sources.

    5. Answer Credibility and Traceability

    Credibility is a core metric for a two-stage architecture and can be protected at three levels.

    Level 1: Citation markers. Each conclusion is linked to a source identifier, allowing readers to trace it back to the original passage.

    Level 2: Fact verification. Key numbers, dates, and version identifiers can be checked using regular expressions or other rules to confirm that they appear in the original source material. This is inexpensive and can prevent many hallucinated details.

    Level 3: Uncertainty statements. When sources conflict or a conclusion is supported by only one source, the generation layer should explicitly state the uncertainty rather than selecting one answer without explanation. For example:

    The two sources provide inconsistent information. Refer to the official documentation for the authoritative answer.

    6. Engineering Considerations

    6.1 Latency and Fallbacks

    A Q&A request usually involves two external calls—retrieval and generation—so their latency can accumulate. Each step should have a timeout and a defined fallback strategy:

    • Retrieval timeout: Use locally cached historical material, while warning that the information may be outdated.
    • Generation timeout: Return a summary of the source material together with the citation list.
    • Validation failure: Return the source-material list instead of an unverified generated answer.

    6.2 Caching

    The same question may be asked repeatedly within a short period. A cache key can be based on the normalized question text and the requested style, with an appropriate expiration time. For highly time-sensitive questions, the expiration period should be shorter.

    6.3 Cost Control

    Generation costs mainly come from the length of the input and output. The following measures can reduce costs:

    • Set an upper limit for compressed source material;
    • Limit the output length;
    • Use a smaller model for simple questions.

    Cost metrics should be tracked by question type so that the most expensive categories can be identified.

    6.4 Logging and Privacy

    Logs should record the question category, rewritten queries, identifiers of matched sources, validation results, and latency. User questions may contain personal information, so they should be anonymized before storage and retained only for a defined period.

    The storage and distribution of source text must also comply with copyright requirements. A practical approach is to retain only the cited excerpts and source links.

    7. Common Trade-Offs

    Recall versus precision. A broader retrieval range provides more complete material but also introduces more noise. One approach is to start with broad retrieval and then apply stricter filtering rules.

    Speed versus quality. Multiple query-rewriting rounds and validation steps can improve reliability but increase latency. For real-time scenarios, only the most important validation checks may be retained.

    Consistent style versus diverse expression. A consistent style supports branding, but it may hide disagreements between sources. Uncertainty-expression rules should remain active regardless of the selected writing style so that source conflicts remain visible.

    8. Implementation Checklist

    1. Define a data contract and standardize the fields used for source material.
    2. Implement query rewriting and design at least three search queries for each question type.
    3. Establish source-scoring rules and calibrate the weights using manually labeled samples.
    4. Write generation prompts that define factual constraints, citation formats, and output structures.
    5. Add fact verification and format validation, with fallback behavior for failures.
    6. Track retrieval hit rate, validation pass rate, latency, and cost by question type.
    7. Review samples of generated answers every week and continuously refine the scoring rules and prompts.

    Following these steps can provide substantially greater controllability and traceability than allowing a single model to answer questions directly.