Building a Simple RAG System with LLMs: A Complete Practical Guide

    Retrieval-Augmented Generation (RAG) lets large language models answer questions over private knowledge without stuffing entire documents into the prompt. This guide explains why long-context prompting falls short, how semantic vector search works, and walks through the full RAG pipeline—chunking, embedding, vector storage, retrieval, and prompt construction—with runnable example code. It closes with practical optimization tips such as hybrid retrieval, metadata filtering, and evaluation strategies for taking a demo to production.

    Building a Simple RAG System with LLMs: A Complete Practical Guide

    Why RAG Matters: Long Context Is Not a Silver Bullet

    When using a large language model (LLM) for question answering over private knowledge, the most intuitive approach is to paste all your documents directly into the prompt. This works acceptably for small documents, but as the knowledge base grows, three problems quickly emerge:

    1. Token costs skyrocket. Sending every document with each request means paying for large amounts of irrelevant content. For inference services billed by token, this is a significant and avoidable waste.

    2. Hallucination risk increases. When the context is filled with redundant, off-topic information, the model can be “distracted” by it and produce answers that sound plausible but are wrong. The noisier the context, the harder it is for the model to focus on what matters.

    3. The “Lost in the Middle” phenomenon. Multiple studies have shown that LLMs exhibit positional bias when processing very long contexts: they retain information near the beginning and end of the context well, while content in the middle is often overlooked. In other words, even if a document fits entirely within the context window, the model may never effectively “read” its key passages.

    This leads to a core conclusion: you should provide the LLM only with information highly relevant to the current question, rather than dumping your entire knowledge base into the prompt. This is exactly the motivation behind RAG (Retrieval-Augmented Generation)—when the model needs to answer, it first retrieves relevant content from the knowledge base, then generates an answer grounded in that content.

    The Limits of Traditional Retrieval

    Suppose a user asks, “What is AI?” If you rely purely on literal keyword matching, only documents containing the string “AI” will be found. Semantically related content—passages discussing “deep learning,” “artificial intelligence,” or “neural networks”—would be completely missed. Traditional relational databases and inverted indexes excel at exact matching but cannot understand semantic similarity.

    Vectors: Semantic Coordinates for Text

    The solution is to map text into vectors—think of them as points in a multi-dimensional space. Using an embedding model, semantically similar texts land close together in this space, while unrelated texts end up far apart. Finding “the documents most relevant to a question” thus becomes a geometric problem: locate the document vectors nearest to the question vector in the vector space.

    Common similarity metrics include cosine similarity and Euclidean distance. The industry generally favors cosine similarity because it is insensitive to vector magnitude and focuses on directional (i.e., semantic) alignment.

    The Overall RAG Workflow

    Once vector search is understood, the full RAG pipeline breaks cleanly into two phases:

    Offline phase (knowledge base construction):

    1. Load the raw documents;
    2. Split documents into chunks according to some rule;
    3. Call an embedding model to compute a vector for each chunk;
    4. Store the vectors together with the original text in a vector store.

    Online phase (retrieval and generation):

    1. Encode the user’s question into a vector;
    2. Retrieve the Top-K chunks in the vector store closest to the question vector;
    3. Assemble those chunks into the prompt as context;
    4. Pass the prompt to the LLM to generate the final answer.

    Offline Phase: Building the Knowledge Base

    Chunking Strategies

    Chunking quality directly determines retrieval quality. Three common strategies exist:

    • Fixed-size chunking: Split at a fixed character count. Simple to implement, but it can easily cut a complete semantic unit (a paragraph, a rule) in half.
    • Recursive character chunking: Set a target chunk size, splitting by paragraph first; if a paragraph is too long, fall back to sentence-level splitting; if a sentence is still too long, split by word. This is the most common approach for balancing generality and semantic integrity, and it is the default choice in most engineering practice.
    • Semantic chunking: Use a model to detect topic shifts and split there. Best results, but the highest cost.

    Additionally, if documents have natural structure (e.g., specification documents organized by numbered items or chapters), the best first move is to split along the document’s own structural boundaries, so each chunk corresponds to exactly one complete knowledge unit.

    Here is an example implementation that splits a document along structural markers:

    1. from pathlib import Path
    2. from typing import List
    3. def load_rag_chunks(doc_path: Path) -> List[str]:
    4. """Read a document and split it into RAG chunks by structural markers"""
    5. text = doc_path.read_text(encoding="utf-8")
    6. raw_parts = text.split("【") # split at the item markers in the document
    7. chunks = []
    8. for part in raw_parts:
    9. part = part.strip()
    10. if not part:
    11. continue
    12. # Restore the stripped marker so each chunk stays semantically complete
    13. chunks.append("【" + part)
    14. return chunks

    Two engineering details are worth noting when chunking. First, chunks should not be too large—oversized chunks dilute semantics, reduce retrieval precision, and eat into the context budget. Second, keep a small overlap between adjacent chunks so that critical information doesn’t fall exactly on a split boundary and get lost.

    Embedding and Storage

    Once chunked, call the embedding model on each chunk and write the vectors, together with the original text, into a vector store:

    1. def build_index(chunks: List[str], embed_model, vector_store):
    2. """Offline indexing: chunk → embed → store"""
    3. for i, chunk in enumerate(chunks):
    4. vector = embed_model.encode(chunk) # text → vector
    5. vector_store.upsert(
    6. id=f"chunk-{i}",
    7. vector=vector,
    8. metadata={"text": chunk} # keep the original text alongside the vector for retrieval
    9. )

    Note that the choice of embedding model affects retrieval quality: for Chinese-language scenarios, pick a model with strong Chinese semantic understanding. More importantly, the offline indexing and online querying must use the same embedding model—otherwise the two sets of vectors live in different semantic spaces and retrieval will fail completely.

    Vector storage can be scaled in tiers: for experiments, a simple in-memory array with similarity computation is enough; for small-to-medium workloads, a lightweight local vector library works well; for large-scale production, consider a standalone vector database service or managed vector search on a cloud platform.

    Online Phase: Retrieval and Generation

    When a user asks a question, first encode it into a vector, then run a Top-K nearest-neighbor search:

    1. def retrieve(question: str, embed_model, vector_store, top_k: int = 3) -> List[str]:
    2. q_vec = embed_model.encode(question)
    3. results = vector_store.search(q_vec, top_k=top_k)
    4. return [r.metadata["text"] for r in results]

    top_k is a key hyperparameter: too small and you may miss critical information; too large and you introduce noise and waste context. In practice, start with 3–5 and tune from there, optionally applying a similarity threshold to filter out clearly irrelevant results.

    Constructing the Prompt and Generating the Answer

    Organize the retrieved chunks into a context and add explicit instructions constraining the model to “answer only based on the given material”—this significantly reduces hallucination:

    1. def rag_answer(question: str, embed_model, vector_store, llm) -> str:
    2. contexts = retrieve(question, embed_model, vector_store)
    3. context_text = "\n\n".join(contexts)
    4. prompt = (
    5. "Answer the question using only the reference material below. "
    6. "If the material does not contain relevant information, state clearly "
    7. "that you don't know—do not fabricate an answer.\n\n"
    8. f"Reference material:\n{context_text}\n\nQuestion: {question}"
    9. )
    10. return llm.generate(prompt)

    The key technique here is explicitly constraining the model’s knowledge boundary in the instruction—allowing the model to say “I don’t know” is one of the simplest and most effective ways to suppress hallucination.

    Engineering Optimizations and Practical Advice

    A working RAG demo is still some distance from a production-grade system. The following directions are worth continued investment:

    1. Hybrid retrieval: Combine vector-based semantic search with keyword search to balance semantic generalization and exact term matching, then use a reranking model to reorder the candidates—this noticeably improves retrieval quality.
    2. Metadata filtering: Attach metadata such as source, section, and timestamp to each chunk, and filter by metadata before retrieval to improve both speed and precision.
    3. Query rewriting: Rewrite or expand user questions (e.g., synonym expansion, coreference resolution in multi-turn conversations) so the question vector aligns better with how the knowledge base is expressed.
    4. Evaluation: Build a standard Q&A test set and continuously measure recall hit rate, answer accuracy, and citation correctness—avoid tuning by gut feeling.
    5. Data update mechanisms: The knowledge base should support incremental updates and invalidation handling so answers always reflect the latest material.

    Conclusion

    The essence of RAG is “retrieval-augmented generation”: using vector search to precisely curate the LLM’s context, delivering high-quality answers grounded in private knowledge at lower token cost and with fewer hallucinations. This article started from the limits of long-context prompting and walked through the complete pipeline—chunking, embedding, storage, retrieval, and prompt construction—with runnable example code. Once you’ve mastered this core flow, combining hybrid retrieval, reranking, and systematic evaluation will let you gradually evolve a simple demo into a reliable, enterprise-grade knowledge Q&A system.