Building a Lightweight RAG System with Open-Source Reasoning LLMs
This article explores the practice of building a lightweight Retrieval-Augmented Generation (RAG) system using open-source reasoning Large Language Models (LLMs). It addresses the inherent knowledge limitations of LLMs and outlines a two-stage RAG architecture. Key technical details include offline knowledge base construction strategies (chunking, embedding, and indexing), online query processing, and advanced optimization techniques to ensure reliable and traceable enterprise knowledge QA.
1. Why RAG? Two Inherent Limitations of LLMs
Any Large Language Model (including current open-source reasoning models) is trained on data collected before a specific point in time. This fact dictates two unavoidable capability boundaries:
1. Temporal Knowledge Boundary. The model is unaware of events occurring after its training cutoff—recent policy documents, newly released API changes, or yesterday’s production incident reviews are outside its cognitive scope.
2. Spatial Knowledge Boundary. The model has only seen public training datasets. Enterprise internal regulations, private API documentation, and historical project codebases are entirely unfamiliar to it.
The most intuitive remedy for these shortcomings is to “stuff documents into the prompt.” However, this approach quickly hits three walls:
- The Cost Wall: Large documents mean massive token consumption. Repeatedly sending them with every dialogue causes costs to scale linearly with API calls.
- The Hallucination Wall: The more irrelevant information present, the higher the probability of the model being disrupted by noise, leading to content generation that deviates from facts.
- The Context Wall: Research shows that when processing ultra-long contexts, models exhibit a phenomenon where they “only remember the beginning and the end, losing the middle part”—the well-known “Lost in the Middle” problem. Documents stuffed into the prompt are not equivalent to documents the model has “read and memorized.”
From this, a core design principle can be derived: Only provide the model with the minimal set of information highly relevant to the current question, rejecting all irrelevant redundancy. Reversing this principle naturally leads to the RAG solution—allowing the system to actively retrieve information when needed, rather than blindly stuffing it.
2. Core Concepts and Overall Architecture of RAG
The essence of RAG (Retrieval-Augmented Generation) is transforming a “closed-book exam” into an “open-book exam”: the model is responsible for understanding and expression, while the external knowledge base provides factual evidence.
2.1 Why Not Use a Traditional Database?
Suppose a user asks, “What are the core methods of artificial intelligence?” and the relevant document in the knowledge base states, “Deep learning fits data distributions through multi-layer neural networks.” Keyword matching would completely fail here—the two texts share almost no literal overlap, yet they are highly semantically related.
The solution is Vectorization (Embedding): using a semantic encoding model to map any text to a coordinate point in a high-dimensional space. Texts with similar semantics will have coordinates that are close in this space. Thus, the fuzzy natural language problem of “retrieving relevant documents” is transformed into a clear mathematical problem—finding the K vectors with the closest distance to the query vector in high-dimensional space. This is exactly where vector databases (or vector indices) come into play.
2.2 Two-Stage Architecture
A standard RAG system is naturally divided into two stages: offline construction and online serving:
Offline Stage (Knowledge Base Construction)Raw documents -> Loading & parsing -> Text chunking -> Per-chunk vectorization -> Write to vector indexOnline Stage (Retrieval-Augmented Generation)User question -> Query vectorization -> Similarity retrieval of Top-K chunks-> Context assembly & prompt construction -> LLM generates answer
The offline stage is the “foundation” of retrieval quality, while the online stage is the “final kick” that delivers results. Both are indispensable, and any rough edge in any step will be amplified downstream.
3. Offline Stage: Three Key Decisions for Knowledge Base Construction
3.1 Chunking Strategy: No Silver Bullet, Only Adaptation
Chunking is the most easily underestimated step in RAG. If chunks are too large, retrieval granularity is coarse, and recalled content is mixed with massive noise. If chunks are too small, semantics are fragmented, and the context the model receives is incomplete. Common industry strategies fall into three categories:
- Fixed-length chunking: Hard cuts based on a fixed character count (e.g., 512 characters per chunk). Easiest to implement, but highly likely to sever semantics mid-sentence. Usually requires an overlap window to mitigate this.
- Recursive chunking: Set a target chunk size; first split by paragraphs, downgrade to sentences for overly long paragraphs, and then to finer granularity if still too long. Balances semantic integrity and length controllability, making it a safe default for general scenarios.
- Semantic chunking: Uses a model to determine text topic boundaries and cuts where topics shift. Highest quality but also highest cost, suitable for premium knowledge bases with high value and low update frequency.
A technique repeatedly proven effective in practice is to respect the document’s inherent structure. Take an engineering development specification that lists items sequentially by number: its natural structure, where “each specification item is a complete semantic unit,” serves as the ideal chunk boundary. Splitting directly by item is often superior to any general-purpose algorithm. An illustrative code snippet is as follows:
def load_chunks(doc_path: str) -> list[str]:"""Read specification documents and split into retrieval chunks by item boundaries."""raw_text = read_file(doc_path)chunks = split_by_item_marker(raw_text) # Split by item prefix symbolsreturn [c.strip() for c in chunks if len(c.strip()) > 0]
Key tip: After splitting, it is recommended to perform a manual spot check to ensure no bad samples exist, such as “half a sentence forming a chunk” or “titles separated from the body text.” Additionally, each chunk should be accompanied by metadata (source document, section location, item number) to lay the foundation for subsequent tracing and filtering.
3.2 Vectorization: Model Selection Determines the Retrieval Ceiling
The core decision in the vectorization step is choosing the Embedding model. Dimensions to consider include: Chinese semantic understanding capability (if the knowledge base is primarily in Chinese, this is almost a veto factor), vector dimensionality (higher dimensions mean finer representation but increased storage and computation costs), and inference overhead (offline indexing is a one-time cost, while online querying is a high-frequency cost). When selecting a model, it is advisable to conduct a small-scale recall evaluation using real business queries rather than relying solely on public leaderboards—your data distribution is the only authoritative test set.
3.3 Storage and Indexing
After chunking and vectorization, the results are written into vector storage, with the original text and metadata bound to each vector. For small to medium-scale scenarios, a single-node vector index is more than sufficient. When the number of chunks reaches the millions, consider introducing Approximate Nearest Neighbor (ANN) indices to balance precision and latency. Over-engineering should be avoided here—for a specification document library of tens of thousands of chunks, brute-force cosine similarity retrieval typically takes only milliseconds.
4. Online Stage: From User Question to Trustworthy Answer
The online pipeline can be broken down into four steps, each with details worth refining:
Step 1: Query Processing. Encode the user’s question into a query vector. Advanced approaches include rewriting/expanding colloquial questions first (the HyDE approach: letting the model generate a hypothetical answer, then using that hypothesis to retrieve) to improve matching with document expressions.
Step 2: Similarity Retrieval. Using cosine similarity or inner product as the metric, recall the Top-K chunks (K is typically 3 to 8). Note the importance of setting a similarity threshold as a fallback: when even the highest similarity falls below the threshold, explicitly tell the model “there is no relevant content in the knowledge base” instead of force-feeding weakly related text—this is a critical switch for suppressing hallucinations.
Step 3: Context Assembly. Concatenate the recalled chunks sorted by relevance, and wrap them in a structured prompt template:
Please answer the question based ONLY on the following reference materials. If the materials are insufficient to answer, please state so clearly.[Reference Materials]{chunk_1}{chunk_2}...[Question]{user_query}
Step 4: Generation and Constraints. Call the open-source reasoning LLM to generate the answer. Two engineering recommendations: first, set a low temperature (e.g., 0.1 to 0.3); knowledge QA scenarios do not require creativity. Second, require the model in the prompt to cite the source item numbers for its answers. Combined with the metadata saved during the offline stage, this enables answer traceability, which is of immense value for compliance and trust-building in enterprise scenarios.
5. Advanced Optimization Directions
Once the baseline pipeline is operational, iterate based on the following priorities:
- Hybrid Retrieval: Vector retrieval excels at semantics, while sparse retrieval (e.g., inverted indices) excels at precise terms and numbers. Fusing the two (via weighting or reranking) can significantly improve performance in scenarios with proper nouns.
- Reranking: Use a cross-encoder model to fine-rank initial recall results, trading a small amount of latency for a noticeable improvement in precision.
- Evaluation Loop: Accumulate a batch of “question-standard answer” pairs to continuously quantify recall hit rates and answer accuracy, ensuring every strategy adjustment is data-driven.
- Incremental Updates: When knowledge base documents change, invalidate and rebuild corresponding chunks at the document level to avoid full rebuilds.
6. Conclusion
The barrier to RAG is not the framework, but a reverence for the iron law that “retrieval quality determines generation quality.” Chunking that fits document structure, retrieval that holds the similarity bottom line, prompts that frame answer boundaries, and metadata that supports answer tracing—mastering these four pillars ensures that even a lightweight, self-built solution paired with an open-source reasoning model can deliver reliable answers in enterprise knowledge QA scenarios. In terms of cloud-native deployment, raw documents can be hosted on object storage, while vector indices and inference services run on container platforms. By leveraging logging services and monitoring alerts to observe retrieval hit rates and latency metrics, a sustainable knowledge service system can be established.
