Building a Lightweight RAG System with Large Language Models: A Practical Guide

    Retrieval-Augmented Generation (RAG) addresses key limitations of large language models, including outdated knowledge, lack of access to private data, and degraded performance on long contexts. This practical guide explains the two-phase RAG architecture—offline knowledge base construction and online retrieval generation—with a focus on document chunking strategies, vector-based semantic search, and prompt engineering. It includes a Python example for rule-based text splitting and outlines the complete workflow from embedding generation to final answer synthesis, enabling developers to build reliable and cost-efficient Q&A systems on top of mainstream LLMs.

    Introduction: Inherent Limitations of Large Language Models

    Mainstream large language models (LLMs) demonstrate impressive natural language understanding and generation capabilities. However, in real-world enterprise deployments, several critical pain points remain.

    The first is knowledge recency and private knowledge blind spots. An LLM is trained on public datasets collected up to a specific cutoff date. Consequently, it cannot access information published after that date, nor can it directly reach into an organization’s internal documents, business manuals, or proprietary databases.

    The second issue is the “Lost in the Middle” phenomenon in long-context processing. While modern models support increasingly large context windows—allowing developers to stuff entire document collections into prompts—research shows that when input contexts become excessively long, models tend to accurately recall only the beginning and end portions while losing information in the middle. This degrades answer quality, increases hallucinations due to redundant noise, and incurs substantial token costs.

    To address these challenges, we need a mechanism that supplies the LLM with precisely the most relevant information for the current conversation, undistracted by unrelated content. This is the core idea behind Retrieval-Augmented Generation (RAG).

    1. From Keyword Matching to Vector Semantic Retrieval

    Consider a user asking “What is AI?” A traditional full-text search would only mechanically match documents containing the literal term “AI.” In practice, however, documents about “deep learning” or “artificial intelligence” are equally valuable references. Traditional relational databases or inverted-index search engines struggle to capture this semantic similarity.

    This is where vector databases and embedding models come into play. Vectorization maps text to coordinates in a high-dimensional space. Using pre-trained language models, the semantic meaning of text is converted into high-dimensional floating-point vectors. The closer two texts are semantically, the closer their coordinates in this space. A vector database enables efficient similarity computation, making true semantic-level retrieval possible.

    2. The Two-Phase Architecture of RAG

    A complete RAG system consists of two phases:

    • Offline phase (data preparation): Document loading → Document chunking → Embedding generation → Storage in a vector database.
    • Online phase (retrieval and generation): User query embedding → Vector database similarity search → Prompt assembly → LLM answer generation.

    Offline Phase: Knowledge Base Construction and Processing

    The offline phase determines the overall quality of a RAG system, and document chunking is its most critical step.

    Document Chunking Strategies

    Vectorizing an entire long document dilutes semantic meaning, so it must be split into reasonably sized text chunks. Common strategies include:

    1. Recursive Character Splitting

    This is the most basic and practical approach. The developer sets a target chunk size (e.g., 500 characters) and an overlap size. The algorithm first splits by paragraph (e.g., double newlines). If a paragraph exceeds the size limit, it is further split by sentence (periods, question marks). If a sentence is still too long, it is finally split by word or character. This method preserves the relative integrity of paragraphs and sentences.

    2. Semantic Chunking

    More intelligent than mechanical character counting, semantic chunking uses NLP models to analyze the text and identify natural breakpoints where the topic shifts. This approach maximizes semantic coherence within each chunk but comes with higher computational costs.

    3. Rule-Based Custom Chunking

    For documents with well-defined structures, the document’s own formatting can guide the splitting logic. For example, if a technical specification is organized as a series of enumerated points (marked by specific delimiters or numbering), each point can be treated as an independent text chunk.

    Python Example: Rule-Based Custom Chunking

    The following Python code demonstrates how to read a document and split it using a custom delimiter:

    1. from pathlib import Path
    2. from typing import List
    3. def load_and_chunk_document(doc_path: Path, delimiter: str = "【") -> List[str]:
    4. """
    5. Load a document and split it into chunks by a specific delimiter.
    6. :param doc_path: Path to the document
    7. :param delimiter: Delimiter used for splitting
    8. :return: List of text chunks
    9. """
    10. # Read the document content, assuming UTF-8 encoding
    11. text = doc_path.read_text(encoding="utf-8")
    12. # Split by the full-width left bracket and filter out empty strings
    13. chunks = [chunk.strip() for chunk in text.split(delimiter) if chunk.strip()]
    14. return chunks
    15. # Example usage
    16. # file_path = Path("tech_guidelines.txt")
    17. # rag_chunks = load_and_chunk_document(file_path)
    18. # print(f"Successfully generated {len(rag_chunks)} chunks")

    In this example, the document is split at each occurrence of “【”, with each segment becoming an independent knowledge chunk. In a production pipeline, additional cleaning—such as removing unnecessary newlines or meaningless whitespace—is also recommended.

    Embedding and Storage

    After chunking, an embedding model is used to convert each text chunk into a high-dimensional vector. The original text, its vector, and any relevant metadata (such as source filename or page number) are then written to a vector database. A variety of general-purpose vector retrieval services or object storage solutions are available for this role.

    Online Phase: Retrieval and Generation Pipeline

    Once the knowledge base is ready, the system can respond to user queries.

    When a user submits a question (e.g., “How should exception handling be done according to the coding standards?”), the system first converts the query into a vector using the same embedding model employed in the offline phase. It then calculates the distance between this vector and all vectors stored in the database (using metrics such as cosine similarity or Euclidean distance) and retrieves the Top-K closest chunks—those most semantically relevant to the query.

    2. Context Assembly and Prompt Engineering

    Once relevant chunks are retrieved, they are combined with the user’s original question into a prompt the LLM can understand. A typical RAG prompt template looks like this:

    1. You are a professional technical assistant. Answer the user's question based on the reference materials provided below. If the materials do not contain the relevant information, respond with "I don't know." Do not make up an answer.
    2. Reference materials:
    3. {retrieved_chunks}
    4. User question:
    5. {user_query}

    This approach provides the model with precise context while using explicit instructions to constrain hallucination.

    3. Generation and Response

    The assembled prompt is then sent to the LLM. The model reasons and generates an answer based on this specific, focused context. Because the input is both highly relevant and appropriately sized, the model produces accurate responses more quickly and efficiently.

    Conclusion

    RAG technology combines the strengths of information retrieval and large language models, effectively addressing limitations in knowledge recency, private data coverage, and long-context handling. Through careful document chunking, efficient vector retrieval, and rigorous prompt engineering, developers can build professional, reliable intelligent Q&A systems over mainstream LLMs at low cost. Mastering these fundamental components and workflows is an essential step toward building sophisticated enterprise-grade AI applications.