[KongchangAI]
· 3 min read· 1,651 words

RAG from Beginner to Interview-Ready: A Complete Guide to Retrieval-Augmented Generation Principles and Practical Workflow

RAG from Beginner to Interview-Ready: A Complete Guide to Retrieval-Augmented Generation Principles and Practical Workflow

RAG solves the problems of frozen large model knowledge and private data Q&A by retrieving external knowledge bases in real time and injecting results into prompts.

This article systematically introduces the principles and complete workflow of retrieval-augmented generation (RAG). Large model knowledge is frozen after training and cannot answer new information after the training cutoff or enterprise private documents; fine-tuning is costly and hard to update, while RAG retrieves external knowledge bases in real time and injects results into prompts for context-based answering. A complete RAG system has two phases: offline indexing (document loading, chunking at 500-1000 tokens with overlap, vectorization, and storage) and online retrieval (query rewriting, vector coarse ranking, reranking, and generation). The article emphasizes that multi-path recall plus reranking compensates for pure vector retrieval's lack of semantic understanding, and prompt constraints suppress hallucination. RAG's core value is low-cost hot knowledge updates and traceable answers—it's a core foundational topic in large model job interviews.

Why Do We Need RAG?

A large model's knowledge is "frozen" once training is complete. You can ask any large model about its knowledge cutoff date, and the answer is usually some date in the past. This means the model knows nothing about anything that happened after the training data cutoff. While some models can access the latest information through web-connected tools, they still cannot directly answer questions about a company's internal private documents.

Some might ask: can't we update knowledge through fine-tuning? Theoretically yes, but it's costly, time-consuming, and once knowledge is written into model parameters, updating it requires retraining from scratch—like having to go through college all over again just to remember a single news item.

RAG takes a completely different approach: it doesn't stuff knowledge into model parameters. Instead, when a user asks a question, it retrieves relevant content from an external knowledge base in real time and places the found content into the prompt for the large model to read. Large models inherently have strong reading comprehension—as long as relevant content is placed in the context window, they can answer based on that content. This is the essence of RAG.

What Is RAG: Retrieval-Augmented Generation

RAG stands for Retrieval-Augmented Generation. The core problem it solves is: a large model's knowledge is fixed after training, so it cannot answer questions about private data or the latest information.

The approach is straightforward: before generating an answer, first retrieve relevant content from an external knowledge base, then submit the retrieval results along with the user's question to the large model, letting it answer based on this context.

The Complete RAG Workflow: Offline Indexing and Online Retrieval

A complete RAG system consists of three parts: building the knowledge base, using the knowledge base, and large model generation. Building the knowledge base belongs to the offline phase, while using the knowledge base belongs to the online phase—the two have clear division of labor.

Offline Phase: Building the Knowledge Base

The goal of the offline phase is to create the knowledge base before users ask questions. It involves four steps.

Document Loading: Read in raw data in various formats—PDF, Word, Markdown, web pages, or database records—and load it into memory through document readers.

Document Chunking: Split documents into small segments called chunks. Why not store entire documents directly? First, embedding models have input length limits, so whole documents can't fit. Second, even without length limits, compressing an entire document into a single vector would "average out" many details, leading to inaccurate retrieval results. There are various chunking methods—the simplest is fixed-character splitting, but this can easily truncate semantic meaning. Chunks that are too large contain too much mixed information, making it easy to recall a bunch of irrelevant content during retrieval; chunks that are too small lead to incomplete semantics. Generally, 500 to 1000 tokens is a reasonable chunk size, with some overlap to avoid cutting complete semantics in the middle. This is also a common interview topic.

500 tokens

Vectorization: This is the most critical step in the offline pipeline. The embedding model converts a piece of text into a high-dimensional numerical vector—for example, a list of 1536-dimensional floating-point numbers. You can think of it as semantic coordinates—texts with similar meanings are positioned closer together in the coordinate space, while unrelated ones are farther apart. Cosine similarity is commonly used for calculation, where a smaller value means more relevant (depending on the specific metric).

Why can vectors represent semantic relevance? The reason lies in training. The embedding model learns from massive amounts of text to identify which sentences express the same meaning, then uses contrastive learning to continuously adjust weights so that texts with similar meanings are close in the output space and unrelated ones are pushed apart. Once this spatial structure is formed, similar content can be found through computation during queries. It's important to emphasize that vector matching compares semantic similarity, not whether keywords overlap.

Document chunking

Storage: Persistently store vectors along with the original text in a vector database such as Chroma or Milvus. Vector databases are specifically optimized for storing high-dimensional vectors and similarity search, supporting fast retrieval of the most similar records from tens of millions of vectors.

Vectors and original text stored together

Online Phase: Using the Knowledge Base

The online phase provides real-time retrieval for user queries and has response speed requirements. It involves four core steps.

User Input Rewriting: User questions are often colloquial or vague, and direct retrieval may not work well. Typically, the question is rewritten into a form more suitable for retrieval so that both the embedding model and the large model can better understand user intent.

Vector Retrieval (Coarse Ranking): Convert the user's question into a vector as well, perform similarity matching in the vector database, and find the top-k chunks with the closest distance. This step is fast—even million-scale vector databases typically return results quickly. However, vector retrieval essentially compares the distance between two vectors and doesn't deeply understand the semantic relationship between the query and documents. The recall results inevitably include content that seems close but is actually irrelevant, so this step is also called coarse ranking.

Reranking (Fine Ranking): To compensate for the shortcomings of coarse ranking, the reranking model concatenates the user's question with each candidate chunk, deeply understands their relevance, reorders them, and filters out irrelevant content. In production, multi-path recall is commonly used—for example, vector retrieval plus keyword matching—and reranking unifies all recalled data from different paths for fine ranking to ensure the most relevant content is returned to the user.

Multi-path recall and reranking

Generation: Concatenate the user's question and the fine-ranked content into the prompt and submit it to the large model to generate the final answer. The prompt typically explicitly requires the model to answer only based on the provided materials, and to say it doesn't know if the information isn't in the materials—this effectively suppresses hallucination. Many people find that when using large models, the output logic seems fine but the facts are wrong—the root cause is that the model is making things up. Giving the model clear constraints and guidelines is the responsible approach.

The Core Value of RAG

RAG's core value lies in two points. First, knowledge can be hot-updated at any time by updating documents in the knowledge base—no need to retrain the model, keeping costs low. Second, answers are traceable—every response can be traced back to which chunk it came from, making it more reliable than pure large model generation; even if an answer is wrong, you can clearly identify which piece of knowledge caused the problem.

RAG vs. Fine-tuning vs. Long Context: To understand RAG's positioning, it's necessary to distinguish it from two other technical approaches. Fine-tuning writes knowledge into model parameters—suitable for learning styles, formats, and specific task patterns, but not for frequently updated factual knowledge, and it carries the risk of catastrophic forgetting. Long Context allows the model to read more text at once, but is limited by context window size, inference cost grows quadratically with length, and "needle-in-a-haystack" experiments show that model utilization of information in the middle of long texts decreases. RAG's advantages are externalized knowledge, on-demand retrieval, controllable cost, and traceability; its disadvantage is dependence on retrieval quality—if retrieval fails, answers will be poor. In practice, all three are often combined: fine-tuning teaches the model "how to answer," RAG provides "what to answer," and long context carries multiple retrieval results.

Extensions and Interview Tips

Beyond the basic form, there is also RAG Graph, which uses graph databases to maintain relationships between knowledge. After the system is built, it also needs evaluation and optimization—focusing on metrics like recall accuracy, recall rate, and faithfulness, which can be evaluated and analyzed using tools like RAGAS. No system is built once and done forever—it requires continuous adjustment and optimization during business development.

RAG is a core foundational topic in large model job interviews, requiring a clear knowledge system. When writing about project experience, it's best to include an RAG project. Describing the entire design workflow and operational steps completely and clearly is the key to scoring well on this question.

Background Supplement

Embedding Models and Contrastive Learning: An embedding model is a type of neural network specifically designed to map text into dense vectors. Typical examples include OpenAI's text-embedding series, open-source BGE, Sentence-BERT, and others. Its training objective is not to predict the next word, but to make sentences with the same meaning close to each other in vector space. The mainstream method for achieving this is contrastive learning: constructing positive sample pairs (e.g., original sentence and paraphrased sentence) and negative sample pairs (e.g., unrelated sentences), and using a loss function to pull positive samples closer and push negative samples apart. After training on large-scale corpora, the model's output vectors carry semantic structure information. Also note that the embedding model's dimensionality (e.g., 1536) and training data domain directly affect retrieval performance—for Chinese scenarios, models trained or fine-tuned on Chinese corpora should be prioritized.

Multi-path Recall and Reranking Models: Multi-path recall refers to using multiple retrieval strategies simultaneously to obtain candidate sets. Common combinations include vector retrieval (semantic matching) and BM25 keyword retrieval (exact matching)—the two are complementary: vector retrieval can recall synonymous expressions but may miss proper nouns, while keyword retrieval can hit exact terms but doesn't understand semantics. Reranking models (Reranker) are typically cross-encoders that concatenate the query with each candidate document and feed them together into the model, allowing the attention mechanism to fully interact and produce more refined relevance scores. The cost is high computation—unlike vector retrieval, it cannot pre-compute and can only fine-rank a small number of candidates. Commonly used reranking models in the industry include BGE-Reranker, Cohere Rerank, etc., typically placed after coarse-ranking recall of top-50 to top-100, then fine-ranking to select top-3 to top-5 for submission to the large model.

#RAG#Retrieval-Augmented Generation#vector database#embedding#reranking#fine-tuning#large language model
Share:

Related articles