Building a RAG System for LLMs from Scratch

    This article walks through building a lightweight Retrieval-Augmented Generation (RAG) system for large language models, covering why parameter-only knowledge falls short, why vector retrieval is required, and how to structure the offline knowledge base pipeline and the online retrieval-and-generation flow. It also covers chunking strategies, embedding and storage with metadata, query rewriting, hybrid recall, reranking, prompt assembly, and the engineering practices needed to operate and evaluate the system in production.

    1. Why LLMs Need an External Knowledge Base

    A large language model’s capability boundary is defined by its training data. The training corpus has a fixed cutoff, so the model has no inherent awareness of events that happened afterward. At the same time, internal standards, business records, and private policies have never been part of the training set, so the model cannot possibly know them. These two kinds of knowledge gaps mean that relying on parametric memory alone cannot support real business question answering.

    One naive approach is to stuff entire documents into the prompt. But this path carries three costs:

    • Wasted cost: A full document consumes a large amount of context window, and token usage and inference latency rise together.
    • Noise interference: Irrelevant passages dilute key information, making the model more likely to produce plausible-sounding but unsupported content, i.e., hallucinations.
    • Position bias: Research consistently observes the “Lost in the Middle” effect, where models make heavy use of information at the beginning and end of the context while easily overlooking information in the middle.

    A more reasonable approach is therefore to give the model only a small number of fragments that are strongly relevant to the current question, or to let the model actively retrieve from a knowledge base when needed. This is Retrieval-Augmented Generation (RAG).

    2. Why Vector Retrieval Is Required

    Suppose a user asks “What is artificial intelligence?” With keyword matching, only documents containing the literal phrase “artificial intelligence” are recalled, while semantically equivalent content such as “machine learning,” “deep learning,” and “neural networks” is missed. Traditional inverted indexes depend on literal matches and cannot bridge differences in phrasing.

    Vector retrieval maps text to coordinates in a high-dimensional space, where semantically similar texts sit close to each other, turning retrieval into a nearest-neighbor search. In engineering practice, the flow is usually organized like this:

    1. Split documents into chunks according to rules;
    2. Compute a vector for each chunk and write it into a vector database;
    3. Compute a vector for the user’s question at query time;
    4. Recall the several closest chunks from the vector store;
    5. Pass the recalled chunks together with the question to the LLM to generate an answer.

    3. Offline Stage: Building the Knowledge Base

    The offline stage handles “load → chunk → embed → store” and is the foundation of retrieval quality.

    3.1 Chunking Strategies

    • Fixed-length chunking: Hard splits by character count. Simple to implement, but it may cut across semantic boundaries.
    • Recursive character chunking: Splits by paragraph first, then progressively subdivides oversized pieces by sentence and word, balancing semantics against length constraints.
    • Semantic chunking: Splits at points where the topic drifts. Best quality, but higher computational cost.

    In practice, “recursive splitting plus an overlap window” is recommended: keep chunks to a few hundred characters with roughly ten percent overlap, so an answer does not happen to straddle a split point. If the document is itself an itemized list (such as a coding standard), split along the natural item boundaries:

    1. from pathlib import Path
    2. from typing import List
    3. def load_chunks(doc_path: Path) -> List[str]:
    4. text = doc_path.read_text(encoding="utf-8")
    5. parts = text.split("【")
    6. return [p.strip() for p in parts if p.strip()]

    3.2 Embedding and Storage

    Call an embedding model to turn each chunk into a fixed-length vector, and write it into the vector store together with metadata (source file, section, item number). Metadata is critical for later filtering, provenance tracking, and deduplication.

    3.3 Quality Checks

    Sample-check the chunk length distribution, the proportion of empty chunks, and vector dimension consistency. Re-split oversized chunks and merge semantically incomplete ones to avoid “garbage in, garbage out.”

    4. Online Stage: Retrieval and Generation

    The online path has four steps:

    1. Rewrite the query: Use multi-turn history to resolve references, turning “what limits does it have” back into a complete question.
    2. Hybrid recall: Vector recall handles semantic similarity, while keyword recall handles exact matches on proper nouns and identifiers; the two result sets are merged and deduplicated.
    3. Rerank and truncate: Rerank candidate chunks with a cross-encoder and keep only the top three to five to control context length.
    4. Assemble the prompt: State the role, the reference material, the answering constraints, and the conditions for refusing to answer.
    1. prompt = f"""You are a rigorous technical assistant.
    2. Answer only based on the material below; if the material is insufficient, state clearly that you cannot answer.
    3. Material:
    4. {retrieved_context}
    5. Question: {question}
    6. """

    5. Engineering Practices and Evaluation

    • Observability: Log recalled chunks, similarity scores, and hit sources so you can tell whether a wrong answer came from retrieval or generation.
    • Permission isolation: Apply metadata filtering per user at the vector store level to prevent unauthorized reads.
    • Incremental updates: Rebuild only the affected chunks when a document changes, instead of rebuilding everything.
    • Evaluation loop: Prepare a test set of question-answer pairs, measure recall hit rate and answer accuracy separately, and keep tuning.
    • Deployment shape: The vector store, embedding service, and model service can be containerized, with object storage holding the original documents, and logging plus monitoring alerts tracking latency and failure rate.

    At this point, a runnable, extensible, and evaluable lightweight RAG system is complete. Its core value is not replacing the model, but using controlled retrieval to deliver the right knowledge precisely into the context and suppress hallucinations at the source.