How to Build a RAG System for LLMs: A Complete Workflow
This article walks through the full process of building a Retrieval-Augmented Generation (RAG) system for large language models. It explains why LLMs need external knowledge, how vector retrieval works, and what happens during the offline indexing and online query stages. You will learn the main chunking strategies, prompt design basics, and key engineering practices such as evaluation, hybrid retrieval, incremental updates, and access control.
1. The Starting Problem: Why LLMs Need External Memory
A large model’s knowledge comes from its training corpus, which creates two natural boundaries. The first is a time boundary: the model has no way of knowing about events that happened after the training cutoff. The second is a scope boundary: internal company documents, private specifications, and business records are usually not part of the training set.
A simple approach is to stuff entire documents into the prompt. This quickly hits a wall. Documents are large, so token costs rise. Irrelevant content dilutes the model’s attention and can amplify hallucinations. More importantly, research has widely observed that models make less use of information in the middle of a long context, a phenomenon known as “lost in the middle”: the beginning and the end are remembered clearly, while the middle is easily ignored.
So the right goal is not “provide more” but “provide just enough”: pass only the fragments strongly related to the current question to the model, and leave the rest to the retrieval system.
2. What RAG Is: Definition and Intuition
RAG (Retrieval-Augmented Generation) separates “looking up material” from “writing the answer”: a retriever first finds relevant fragments from a knowledge base, and then the generation model answers based on those fragments.
Why do we need a vector database? When a user asks “What is artificial intelligence?”, literal matching only hits paragraphs containing the exact words “artificial intelligence”, and misses semantically related content such as “deep learning” or “machine learning”. Vector retrieval solves exactly this problem.
You can think of a vector as a coordinate: an embedding model maps a piece of text to a point in a multi-dimensional space, and the closer the meaning, the closer the points. Retrieval then becomes “find the nearest few neighbors”.
The standard pipeline can be summarized as:
- Offline: document loading → cleaning → chunking → vectorization → writing to the vector database
- Online: question vectorization → nearest-neighbor retrieval → fragment reranking and trimming → prompt assembly → model generation
3. The Offline Stage: How the Knowledge Base Is Built
1. Document Loading and Cleaning
First unify the formats (plain text, Word, PDF, web exports, and so on), then remove headers and footers, table-of-contents noise, repeated whitespace, and meaningless symbols. Cleaning quality directly determines later retrieval quality, because dirty data causes vector semantics to drift.
2. Three Main Chunking Strategies
- Fixed-length chunking: hard cuts by character count. It is the simplest to implement, but it easily cuts a sentence in half and has poor semantic integrity.
- Recursive character chunking: set a target chunk size, split by paragraph first, then by sentence if a paragraph is too long, then by word if a sentence is still too long. It balances length constraints and semantic boundaries, and is the most common engineering compromise.
- Semantic chunking: split where the topic shifts, so each chunk is the most semantically focused, but it relies on extra computation and costs more.
In practice, metadata is often attached to each chunk (source file, section title, item number) to make tracing and filtering easier after retrieval. Example code:
from pathlib import Pathfrom typing import Listdef load_chunks(doc_path: Path) -> List[str]:"""Split a document by item markers; each item is one retrieval unit"""text = doc_path.read_text(encoding="utf-8")parts = text.split("[Item]")chunks = [p.strip() for p in parts if p.strip()]# Metadata can be added here: source, index, sectionreturn chunks
3. Vectorization and Storage
Use an embedding model to convert each chunk into a fixed-length vector and write it to the vector database. Three things need attention: the vector dimension must match the embedding model; the similarity metric (cosine similarity or inner product) must be consistent; and metadata filter conditions should be built to support “filter first, then retrieve”.
4. The Online Stage: What Happens During a Single Query
- Question rewriting: clarify and complete questions with unclear references or colloquial phrasing, and generate a standalone question using multi-turn history when necessary.
- Vector retrieval: take the top-k nearest chunks. A small k misses information, while a large k introduces noise; tuning usually starts from 3 to 5.
- Reranking and deduplication: rerank candidates with a finer relevance score, merge duplicate fragments, cut low-score content, and control the total length.
- Prompt assembly: define the role, answer boundaries, and citation requirements, and require the model to explicitly say it does not know when the material is insufficient.
- Generation and citation: output the answer with the source fragments marked, making manual verification easy.
A minimal usable prompt skeleton:
You are an enterprise knowledge assistant. Answer only based on the material below; if the material does not cover it, explicitly state that you cannot confirm.Material:[1] ...[2] ...Question: {question}Requirement: answer in bullet points and mark the cited material number at the end of each sentence.
5. Engineering Practices and Common Pitfalls
- Evaluate first: prepare a Q&A test set and look at retrieval hit rate and answer accuracy separately, instead of “tuning by feeling”.
- Hybrid retrieval: keyword retrieval and vector retrieval complement each other; queries with proper nouns and ID-like terms rely especially on the former.
- Incremental updates: after a document changes, recompute only the affected chunks instead of rebuilding everything; deletions must also clean up old vectors.
- Access isolation: the retrieval layer must inherit the access control of the original documents to prevent unauthorized recall.
- Cost control: cache high-frequency questions, control context length, and keep irrelevant chunks out of the prompt.
- Common pitfalls: chunks that are too large and mix semantics; ingesting data without cleaning; tuning only the generation model and not the retriever; lacking a fallback phrase for “I don’t know”.
6. Conclusion
The essence of RAG is to trade limited context for highly relevant context through retrieval. Make these five steps solid: chunking, vectorization, retrieval, reranking, and prompt constraints. Combined with an evaluation loop and access governance, you can build a stable, usable knowledge Q&A system on any large model. If you want to reduce the burden of self-built operations, you can also run offline indexing and online services on cloud capabilities such as general-purpose object storage, container platforms, and monitoring and alerting.
