Building a RAG System for LLMs: A Practical Guide

    This guide walks through building a Retrieval-Augmented Generation (RAG) system for large language models, covering why LLMs need external knowledge, the role of vector retrieval, and a two-stage architecture split into offline knowledge base construction and online question answering. It details document loading and cleaning, three mainstream chunking strategies, embedding and storage, and an observable retrieval funnel with query rewriting, hybrid recall, reranking, prompt assembly, and citation tracing. It also covers evaluation and tuning, common pitfalls, and engineering extensions, concluding that retrieval sets the upper bound of RAG quality while prompt constraints set the lower bound.

    1. The Starting Problem: Why LLMs Need “External Memory”

    A large language model’s capabilities are bounded by its training data. Every model has a knowledge cutoff and cannot perceive content outside its training corpus, such as internal company policies, private business documents, or freshly updated regulations. Faced with these questions, the model either answers “I don’t know” or fabricates a plausible-sounding answer based on language priors. This is one of the main sources of hallucination.

    A naive approach is to stuff entire documents into the prompt. But this quickly runs into three walls:

    • The cost wall: long text consumes a large number of tokens, making both input and output more expensive and responses slower.
    • The effectiveness wall: irrelevant information dilutes attention, making the model more easily led astray by noise.
    • The structure wall: the industry has widely observed that “middle content tends to be ignored,” meaning information at the beginning and end of an extra-long context is used better, while mid-section information is underutilized.

    A more reasonable approach is to give the model only the minimal necessary fragments truly relevant to the current question, or to let the model proactively retrieve from a knowledge base when needed. This is the core idea of Retrieval-Augmented Generation (RAG): use retrieval to supply knowledge and generation to produce expression.

    2. Why Vector Retrieval Is Necessary

    When a user asks “What is artificial intelligence,” the ideal result should include semantically similar passages like “machine learning” and “deep learning,” not just text that literally contains the four words “artificial intelligence.” Keyword matching relies on literal overlap and cannot bridge synonyms, near-synonyms, and colloquial expressions.

    Vectors offer a solution: map text to a coordinate in a high-dimensional space, where semantically similar text has nearby coordinates. This turns “finding relevant content” into “finding neighboring points in space.” This capability is provided by a vector retrieval engine (a vector database or a storage service with vector retrieval capabilities), which typically supports similarity metrics, index construction, and filter conditions at the same time.

    It is worth emphasizing that vector retrieval is not a panacea. For strong literal signals such as proper nouns, IDs, error codes, and function names, keyword retrieval is often more accurate. In engineering, hybrid retrieval is commonly used: vector recall handles semantic generalization, keyword recall handles exact matches, and a reranking model then produces unified scores.

    3. Overall Architecture: Two Pipelines, Offline and Online

    A RAG system naturally splits into two stages.

    Offline stage (knowledge base construction): document loading → cleaning and structuring → chunking → vectorization → writing to the vector store, while retaining metadata.

    Online stage (Q&A service): receive question → question rewriting and vectorization → retrieval recall → reranking and filtering → prompt assembly → call the model to generate → citation tracing and post-processing.

    The two pipelines are connected through “chunks” as a shared contract: however you chunk offline is how you query online, and however metadata is stored is how you filter online.

    4. Offline Stage Implementation Essentials

    1. Document Loading and Cleaning

    First unify the format (plain text, Markdown, exported document text, etc.), remove headers, footers, table-of-contents noise, and repeated blank lines, and preserve heading hierarchy. Heading hierarchy is highly valuable metadata that can later be used for filtering and citation location.

    2. Three Mainstream Chunking Approaches

    • Fixed-length chunking: hard-split by character count. Simplest to implement, but prone to cutting across semantics.
    • Recursive chunking: first split by paragraph, then by sentence if a paragraph is too long, then by word if a sentence is still too long, balancing semantics and a length limit.
    • Semantic chunking: split where the topic shifts. Usually the best results, but requires extra model overhead.

    In practice, “recursive chunking + overlap window” is recommended, with overlap generally set to 10%–20% of the chunk length, to avoid an answer being split right at a cut point.

    Sample code (splitting by structural markers, suitable for itemized specification documents):

    1. from pathlib import Path
    2. from typing import List
    3. def load_chunks(doc_path: Path, marker: str = "【") -> List[str]:
    4. """Read a document and split it into retrieval units by structural markers"""
    5. text = doc_path.read_text(encoding="utf-8")
    6. parts = [p.strip() for p in text.split(marker) if p.strip()]
    7. chunks = []
    8. for idx, p in enumerate(parts):
    9. chunks.append({
    10. "text": p,
    11. "meta": {"doc": doc_path.name, "chunk_id": idx}
    12. })
    13. return chunks

    3. Vectorization and Storage

    Choose a general-purpose text embedding model, noting its maximum input length and vector dimension. Within the same system, offline indexing and online querying must use the same model and the same version; otherwise the vector spaces are not comparable. When writing, it is recommended to store metadata such as the original text, source, heading path, and chunk index, to facilitate filtering and citation.

    5. Online Stage Implementation Essentials

    The retrieval flow is best built as an observable funnel:

    1. Question rewriting: combine multi-turn history to complete references and omissions, splitting into multiple sub-questions when necessary.
    2. Hybrid recall: take top-k from each path (e.g., 20–50), with source filter conditions attached.
    3. Reranking: use a cross-encoder to fine-rank candidates, keeping the top 3–6.
    4. Prompt assembly: clearly define the role, the data boundary, the output format, and the constraint to “clearly state when data is insufficient.”
    5. Generation and tracing: require answers to annotate the cited chunk index, making manual verification easy.
    1. def build_prompt(question: str, hits: list) -> str:
    2. ctx = "\n\n".join(f"[{h['meta']['chunk_id']}] {h['text']}" for h in hits)
    3. return f"""You are a rigorous technical assistant.
    4. Answer based only on the following material. When the material does not cover it, clearly state "insufficient data" and do not speculate.
    5. At the end of the answer, annotate the cited source with [index].
    6. Material:
    7. {ctx}
    8. Question: {question}
    9. """

    6. Evaluation and Tuning

    Without evaluation there is no tuning. It is recommended to build an evaluation set of 50–200 real questions, annotate the chunk where the answer resides, and separately measure recall hit rate (whether the correct chunk enters the candidates), answer correctness, and citation accuracy. Common tuning actions, ranked by cost-effectiveness: optimize chunking and overlap, add metadata filtering, introduce reranking, enable hybrid retrieval, and only then consider swapping the embedding model.

    7. Common Pitfalls Checklist

    • Using different embedding models or different versions for indexing and querying.
    • Chunks too large, producing too much noise; chunks too small, producing incomplete semantics.
    • Missing source filtering, causing cross-department and cross-version documents to contaminate each other.
    • The prompt does not constrain the “insufficient data” scenario, so the model forcibly fabricates.
    • No logging across the entire pipeline, making it impossible to locate whether the error is in retrieval or generation.

    8. Engineering Extensions

    After going live, you still need to fill in: incremental document updates and version management, index rebuilding and backup for the vector store, logging and monitoring alerts for the retrieval and generation pipelines, and permission filtering and masking of sensitive information. If data volume or concurrency rises, each stage can be split into independent services, carried by common cloud capabilities such as container platforms, object storage, message queues, and log monitoring, to achieve elastic scaling and fault isolation.

    In one sentence: the upper bound of RAG effectiveness is determined by retrieval, and the lower bound is determined by prompt constraints. First make chunking and evaluation solid, then talk about swapping models and frameworks.