Building a RAG Application from Scratch: Retrieval-Augmented Generation Principles and Engineering Practices

    Learn how retrieval-augmented generation (RAG) connects large language models to external knowledge sources. This article covers the indexing and question-answering pipelines, document chunking, hybrid retrieval, reranking, prompt design, troubleshooting, and evaluation practices for building a reliable enterprise knowledge assistant.

    1. Why RAG Is Needed

    Large language models (LLMs) offer strong general-purpose language understanding and generation capabilities, but three limitations stand out in real-world applications.

    Outdated knowledge. A model’s parametric knowledge comes from the static data used during training. It does not automatically incorporate information published after its training cutoff. Internal knowledge bases, product documentation, and industry regulations change frequently, making model parameters alone insufficient.

    Hallucinations. When faced with unfamiliar or ambiguous questions, a model may produce answers that sound plausible but are factually incorrect. This unpredictability poses serious risks in fields such as finance, healthcare, and law.

    Missing domain knowledge. General-purpose models do not inherently know an organization’s private data, such as support tickets, internal policies, or technical manuals. Asking about this information directly often produces irrelevant answers.

    Retrieval-augmented generation (RAG) addresses these limitations by retrieving relevant information from external knowledge sources at inference time, adding it to the prompt as context, and asking the model to answer based on that evidence—without changing the model’s parameters.

    This approach supports traceable, verifiable answers and allows knowledge updates through document maintenance rather than model retraining.

    2. RAG System Architecture

    A complete RAG system typically consists of two pipelines.

    Offline Indexing Pipeline

    1. Document ingestion: Parse and clean documents from formats and sources such as PDF, Word, Markdown, web pages, and database records.
    2. Document chunking: Split long documents into semantically coherent chunks.
    3. Embedding generation: Use an embedding model to map each text chunk to a high-dimensional vector.
    4. Storage: Store vectors together with the original text and metadata in a vector database or a storage service that supports vector search.

    Online Question-Answering Pipeline

    1. Query preprocessing: Rewrite or expand the user’s question and incorporate relevant context from previous conversation turns.
    2. Retrieval: Compare the query vector with knowledge-base vectors to retrieve the top-K candidate chunks. Keyword search can also be included for hybrid retrieval.
    3. Reranking: Use a reranking model to reorder candidates by relevance and select a smaller set of the most relevant chunks.
    4. Generation: Submit the retrieved chunks and the user’s question to the LLM, then generate an answer with source citations.

    3. Key Engineering Practices

    Document Chunking: The First Step Toward Better Retrieval

    Chunking strategy directly affects retrieval quality. Fixed-length chunking is straightforward, but it can split related information across boundaries. More suitable approaches include:

    • Structure-based chunking: Split documents along natural boundaries, such as heading levels, paragraphs, and lists.
    • Overlapping sliding windows: Keep some overlap between adjacent chunks—for example, 10–20%—to reduce the risk of losing important context at a boundary.
    • Semantic-aware chunking: Use sharp changes in sentence embedding similarity to identify boundaries, keeping each chunk focused on a coherent topic.

    Chunk size involves a trade-off. Long chunks can dilute key information and increase token costs, while short chunks may lack sufficient context. A few hundred tokens per chunk is a reasonable starting point, followed by A/B testing for different document types.

    Vector-only retrieval can struggle with exact-match queries, such as model numbers or specialized terms. Common improvements include:

    • Hybrid retrieval: Run vector search and keyword search, such as BM25, in parallel, then merge and rank their results.
    • Query rewriting: Use a model to turn conversational or ambiguous questions into retrieval-friendly queries, or break a complex question into multiple subqueries.
    • Multiple retrieval paths: Retrieve from different knowledge bases or indexes with different levels of granularity to broaden candidate coverage.

    Illustrative pseudocode:

    1. def retrieve(query, top_k=10):
    2. dense_results = vector_db.search(embed(query), top_k=top_k)
    3. sparse_results = keyword_index.search(query, top_k=top_k)
    4. merged = reciprocal_rank_fusion(dense_results, sparse_results)
    5. return rerank(query, merged, top_k=5)

    Reranking and Context Assembly

    Initial top-K retrieval results inevitably contain some noise. A lightweight reranker, such as a cross-encoder, scores each query–chunk pair and can substantially improve the relevance of the material included in the final prompt.

    When assembling context:

    • Place the most relevant chunks near the beginning of the prompt.
    • Preserve metadata, including document titles and section paths, to help the model interpret the material and cite its sources.
    • Apply truncation safeguards to prevent the assembled context from exceeding the model’s context window.

    Prompt Design

    The generation prompt should explicitly constrain the model’s behavior. For example:

    1. You are an enterprise knowledge assistant. Answer the question using only
    2. the reference material provided below.
    3. If the material is insufficient to answer, state that clearly.
    4. Do not invent information.
    5. List the reference source numbers you cited at the end of your answer.
    6. Reference material:
    7. [1] ...
    8. [2] ...
    9. User question: {query}

    4. Common Problems and Troubleshooting

    • Poor retrieval accuracy: Start by checking the chunking strategy and whether the embedding model is suitable for the domain’s content. Consider fine-tuning the embedding model for a specialized domain.
    • Incorrect answers despite retrieving the right content: Weak prompt constraints or excessive context may be obscuring important information. Reduce the number of chunks and strengthen the instructions.
    • Failures in multi-turn conversations: Incorporate conversation history into query rewriting. Resolve references in questions such as “How do I configure it?” so that retrieval receives a complete, explicit query.
    • Poor retrieval of tables and images: Convert tables into structured text during parsing. Use OCR or multimodal descriptions to make image content searchable before indexing it.

    5. Evaluation and Continuous Improvement

    A RAG system requires ongoing evaluation rather than a one-time delivery. Evaluation typically operates at two levels.

    Retrieval evaluation measures how well the system finds relevant information. Common metrics include recall, precision, and mean reciprocal rank (MRR).

    Generation evaluation measures answer quality through faithfulness to the retrieved content, relevance to the question, and factual consistency.

    Build an evaluation dataset covering representative questions. Run regression evaluations whenever chunking parameters, embedding models, or prompts change, and use the results to guide further improvements.

    For deployment and operations, common cloud components—including object storage, vector search services, container platforms, and monitoring and alerting systems—can support a complete operational workflow. This infrastructure enables incremental knowledge-base updates, retrieval-pipeline observability, and staged rollouts.

    6. Conclusion

    RAG supplies an LLM with current, trustworthy knowledge through retrieval. Its main engineering challenges lie in document processing, retrieval quality, and control over generation.

    Combining effective chunking, embeddings, hybrid retrieval, reranking, and prompt design with continuous evaluation provides a practical foundation for enterprise question-answering systems with reliable answers and traceable sources.