Building a Lightweight RAG System with Large Language Models: A Practical Guide
This guide explains why large language models need retrieval-augmented generation (RAG) to answer questions about recent events and private knowledge. It walks through a minimal Python implementation covering document chunking, vector indexing, semantic retrieval, and prompt construction, and it lists practical steps for improving retrieval quality and maintaining the knowledge base.
Why RAG Is Needed
A large language model gains its capabilities from pretraining on a large corpus collected up to a certain point in time. This training approach leaves the model with two inherent blind spots:
- Time blind spot: The model knows nothing about events, published standards, or updated APIs that appeared after its training data cutoff.
- Private knowledge blind spot: Internal company documents, team guidelines, and project codebases never enter the training set, so the model cannot access them either.
A straightforward workaround is to paste the relevant documents directly into the prompt and let the model answer “open-book.” This approach quickly runs into three problems. First, documents often run to tens of thousands of words, so feeding in the full text consumes many tokens and raises costs sharply. Second, redundant information dilutes the model’s attention and can lead to more hallucinations. Third, multiple studies show that models handle very long contexts poorly because of the “Lost in the Middle” effect: they recall content at the beginning and end well, but content in the middle is easily overlooked.
A better approach is to provide the model with only a small amount of content that is truly relevant to the current question. This is the core idea of RAG (Retrieval-Augmented Generation). Before generating an answer, RAG runs a semantic search and uses the retrieved passages to highlight the key information for the model.
Core Principle of RAG: From Keyword Matching to Semantic Search
Suppose a user asks “What is AI?” An ideal retrieval system should return not only documents that contain the word “AI,” but also content that is semantically related, such as “artificial intelligence,” “deep learning,” and “machine learning.” Traditional databases rely on exact matching or inverted indexes, which cannot handle this kind of semantic similarity. This is why vector databases are used.
A vector can be thought of as a coordinate. An embedding model maps a piece of text to a point in a high-dimensional space. The closer two texts are in meaning, the closer their points sit. Distance is typically measured with cosine similarity or Euclidean distance. Based on this, the RAG workflow has two stages:
- Offline stage (building the index): Load documents, split them into chunks by rule, compute a vector for each chunk, and store the vectors in a vector database.
- Online stage (answering questions): Convert the user’s question into a vector, retrieve the top-K most similar chunks from the vector store, combine the chunks and the question into a prompt, and send the prompt to the large language model to generate the final answer.
The following example uses a development guideline document organized as numbered entries and walks through the full process in Python.
Offline Stage: Building a Local Knowledge Base
1. Document Chunking
Chunking quality directly determines retrieval accuracy. There are three common strategies:
- Fixed-size chunking: Split text at a fixed number of characters. It is the simplest to implement, but it can cut meaningful units in half.
- Recursive character chunking: Set a maximum chunk length. Split by paragraph first. If a paragraph is still too long, split by sentence. If a sentence is still too long, split by word. This keeps semantic units intact as much as possible.
- Semantic chunking: Split where the topic of the text changes. It produces the best results but is also the most costly to implement.
For a document structured as a list of numbered entries, the most natural approach is to use each entry as a chunk boundary, so that one rule becomes one chunk:
from pathlib import Pathfrom typing import Listimport redef load_chunks(doc_path: Path) -> List[str]:"""Read the document and split it into independent chunks at entry markers."""text = doc_path.read_text(encoding="utf-8")# Use entry numbers such as "【1】" or "1." as split pointsparts = re.split(r"(?=【\d+】|^\d+\.)", text, flags=re.M)return [p.strip() for p in parts if p.strip()]
Two parameters matter in practice. Chunk size should not be too large, or retrieval becomes coarse and noisy. Overlap keeps a small amount of repeated content between adjacent chunks, which reduces the risk of cutting a meaning in half at a boundary.
2. Vectorization and Storage
After chunking, generate a vector for each chunk and save the vectors:
def build_index(chunks: List[str]):embeddings = [embed(chunk) for chunk in chunks] # Call the embedding modelindex = VectorStore(dimension=len(embeddings[0]))index.add(embeddings, metadata=chunks) # Store vectors together with the original textindex.save("kb.index")return index
The embed function can be a locally deployed open-source embedding model or a cloud-based general text embedding service, such as those offered by platforms like Baidu AI Cloud. During prototyping, a lightweight local index works well. When the data grows, migrate to a production-grade vector database or a storage service that supports vector search.
Online Stage: Retrieval and Generation
1. Semantic Retrieval
When a user question arrives, pass it through the same embedding process to get a question vector, then run a nearest-neighbor search:
def retrieve(question: str, index, top_k: int = 3) -> List[str]:q_vec = embed(question)hits = index.search(q_vec, top_k=top_k)return [hit.text for hit in hits]
top_k is the key parameter. If it is too small, you may miss important evidence. If it is too large, noise returns. Start with 3 to 5 and adjust based on evaluation results.
2. Building the Prompt and Generating the Answer
Insert the retrieved passages into a prompt template as context:
PROMPT = """Answer the question based only on the reference material below. If the material contains no relevant information, clearly state "I don't know".Reference material:{context}Question: {question}"""def rag_answer(question: str, index) -> str:context = "\n\n".join(retrieve(question, index))return llm_chat(PROMPT.format(context=context, question=question))
llm_chat can connect to any large language model inference service that offers a compatible chat interface, whether it is a locally deployed open-source model or a cloud model inference platform. The constraint in the prompt, which tells the model to answer only from the reference material and to say “I don’t know” when the material has no relevant content, matters a great deal. It significantly reduces the model’s tendency to make up answers.
Engineering Recommendations
Getting a prototype to run is only the starting point. To make the system truly usable, keep iterating in these areas:
- Retrieval quality evaluation: Prepare a set of question and source test pairs, measure the retrieval hit rate, and use the results to tune the chunking strategy and
top_k. - Hybrid retrieval: Pure vector search is not sensitive to exact information such as proper nouns and numbers. Add keyword search (such as BM25) and merge the results.
- Reranking: Expand the initial retrieval to the Top 20, then use a reranking model to select the Top 3. This noticeably improves precision.
- Traceable answers: Return the document name and entry number of each source chunk with the answer, so users can verify it and the team can find gaps in the knowledge base.
- Knowledge base maintenance: When documents change, rebuild the vectors for the affected chunks incrementally. Record a version and timestamp for each chunk to keep old and new knowledge from mixing.
- Production deployment: Host documents, indexes, and conversation logs separately on object storage, container platforms, and logging services. Combine them with monitoring and alerting to keep the service stable.
Summary
RAG compensates for the two limits of a large language model, its knowledge and its context window, by using retrieval. In the offline stage, private documents are split into chunks, converted into vectors, and stored. In the online stage, each question is turned into a vector for semantic nearest-neighbor search, and the matched passages are passed to the model as evidence for its answer. Mastering four key steps (chunking strategy, embedding-based retrieval, prompt constraints, and continuous evaluation) lets you build a usable, extensible, and evolvable lightweight knowledge base Q&A system in just a few dozen lines of Python.
