RAG Retrieval-Augmented Generation
RAG Retrieval-Augmented Generation
Have you ever encountered a scenario like this:
-
You have a product manual hundreds of pages long, and a user asks a very specific question, but you search for ages and can't find the answer.
-
Your company has accumulated several years of internal documents, meeting minutes, and technical specifications, and a new employee wants to understand a certain business rule but doesn't know where to start looking.
-
You have a pile of e-books, research reports, and papers, and you want the AI to answer questions based on this content, but pasting the entire book to the AI won't fit in the context window.
This is the problem that RAG aims to solve.
RAG (Retrieval-Augmented Generation) is a technology that enables large language models to answer questions based on a specific knowledge base.
The core idea of RAG is simple: first, find the most relevant content from your knowledge base, then send this content along with the user's question to the LLM, allowing the LLM to answer based on this context.
Without RAG, the LLM only knows the content in its training data; with RAG, the LLM can use your private and up-to-date data.
Why is RAG needed?
RAG is not the only solution to these problems, but it is one of the most practical and lowest-cost solutions currently.
The LLM knowledge cutoff date problem
-
All LLMs have a knowledge cutoff date—their training data only goes up to a certain point, and they do not know about events that happened afterward.
-
For example, if GPT-4's knowledge cutoff is October 2023, if you ask it about news from 2024, it can only say it doesn't know.
-
More importantly, your private data (internal documents, product manuals, company specifications) has never appeared in the LLM's training data; how could it possibly know?
Private data cannot be directly input into LLM
You might ask: Can't I just paste the document to the LLM?
The answer is: short documents can, but long documents cannot.
-
Firstly, LLMs have a limited context window. For example, GPT-3.5 only has 16K tokens, which is about 10,000 characters. A several-hundred-page manual simply cannot be pasted in.
-
Secondly, even if the context window is large enough, stuffing the entire document in will not yield good results. LLMs tend to get lost in long texts and fail to find truly relevant information.
-
Finally, there is the cost issue. The price for GPT-4 128K context is $10 per million input tokens; stuffing an entire book in every time will make your wallet cry.
RAG vs Fine-tuning: How to choose
Another way to enable LLMs to use new data is fine-tuning—continuing to train the model with new data.
But fine-tuning and RAG have fundamental differences and completely different applicable scenarios:
| Comparison items | RAG | Fine-tuning |
|---|---|---|
| Data freshness | Can be updated at any time and is immediately available | Requires retraining, which takes a long cycle |
| Applicable data volume | Very large (millions of documents) | Medium (thousands to tens of thousands of samples) |
| Citation source | Can show which document the answer comes from | Source cannot be traced |
| Hallucination problem | Reduce hallucinations by providing context | May still generate hallucinations |
| Modify knowledge | You can directly delete or update the document | Requires retraining, difficult to "forget" |
| Technical threshold | Low, can use existing frameworks | High, requires GPU and training experience |
| Cost | Mainly vector database and Embedding | High training cost, and high inference cost |
A simple decision principle: if you want the LLM to "know" certain factual knowledge (such as product specifications or company policies), use RAG; if you want the LLM to "learn" a certain style or capability (such as writing style or coding standards), use fine-tuning.
Overview of the RAG architecture
RAG is divided into two stages: the offline indexing stage and the online retrieval stage.
First, look at a complete architecture diagram:
Offline indexing stage (Data preparation)
This stage runs in the background and is not directly visible to the user.
Its task is to process your documents into a format that can be quickly retrieved.
The steps are as follows:
-
1.Document Loading: Reads documents in various formats such as PDF, TXT, DOCX, and web pages.
-
2.Document Splitting: Divides long documents into small text chunks, usually several hundred to a thousand words.
-
3.Vectorization: Convert each text chunk into a vector (a string of numbers) using an Embedding model.
-
4.Storage: Store the vectors and the original text together in a vector database.
This stage only needs to be run once, or rerun when the document is updated.
Online Retrieval Stage (User Query)
This stage happens in real-time when the user asks a question.
The steps are as follows:
-
1.Question vectorization: Convert the user's question into a vector using the same Embedding model.
-
2.Similarity search: Find the text chunks closest to the question vector in the vector database.
-
3.Construct PromptAssemble the Prompt by using the retrieved text chunks as context along with the user's question.
-
4.LLM GenerationSend the Prompt to the LLM to answer based on the context.
-
5.Return AnswerReturn the LLM's answer to the user, usually accompanied by the cited document sources.
Introduction to Vector Databases
Vector databases are one of the core components of RAG. To understand it, you must first understand what a vector is.
What is a Vector (Embedding)
A vector (Embedding) is a sequence of numbers that converts text.
For example, the word "cat" might be converted into a hundreds-dimensional vector like [0.23, -0.45, 0.12, 0.89, ...].
The key point is: texts with similar semantics will have vectors that are close in space.
For example:
- The vectors for "cat" and "kitty" are very close.
- The vector distance between "cat" and "dog" is closer to "car"
- The vector distance between "I like cats" and "I love cats" is very close
This is the basis of what we can do with "semantic search"—matching by meaning, not by keyword.
The principle of calculating semantic similarity
The similarity between two vectors is usually calculated using "Cosine Similarity".
The range of Cosine Similarity is -1 to 1:
- 1 indicates complete similarity
- 0 indicates no relevance
- -1 indicates completely opposite
In practical applications, we usually only care about positive similarity, where closer to 1 means more relevant.
When you ask a question, the vector database quickly calculates the similarity between the question vector and all document vectors, returning the top few most relevant ones.
Mainstream vector databases
There are many vector databases on the market, each with its own characteristics:
| Database | Type | Characteristics | Applicable Scenarios |
|---|---|---|---|
| Chroma | Local/Open Source | Lightweight, easy to use, Python friendly | Prototyping, small-scale applications |
| Pinecone | Cloud Service/SaaS | Managed service, no operations required, elastic scaling | Production environment, large-scale applications |
| Weaviate | Open source/Managed | Rich features, supports GraphQL | Scenarios requiring advanced features |
| Qdrant | Open source/Managed | High performance, written in Rust | Scenarios with high performance requirements |
| Milvus | Open source/Managed | Comprehensive features, enterprise-grade | Large-scale enterprise applications |
| FAISS | Local database | Facebook product, extremely fast | Scenarios without persistence |
For beginners, we recommend starting with Chroma—it is easy to install and requires no extra configuration, making it very suitable for learning and prototyping.
Document processing workflow
Document processing is an easily overlooked but actually very important part of RAG.
How good your retrieval results are largely depends on how well the documents are processed.
Supported document formats
LangChain supports many document formats:
- Plain text: .txt, .md
- PDF: .pdf
- Office: .docx, .pptx, .xlsx
- Webpage: HTML, URL
- Code: .py, .js, .java, etc.
- JSON: .json, .jsonl
- CSV: .csv
There is a corresponding loader for each format, which is very convenient to use.
Document splitting strategy
Document chunking is the process of splitting long documents into smaller pieces.
This seems simple, but there are many nuances:
- Too small chunks: may lose context, and a complete meaning might be cut off
- Too large chunks: may contain irrelevant information, wasting the context window
Common chunking strategies:
| Strategy | Principle | Applicable scenarios |
|---|---|---|
| By character count | Simple splitting by word count, for example, in chunks of 500 characters | Simple scenarios, not requiring high context |
| By paragraph | Splitting by newline character, trying to keep paragraphs intact | Formatted documents |
| Recursive splitting | Prioritize by paragraph, then by sentence if too long, finally by word | Preferred for most scenarios |
| Semantic splitting | Splits based on semantic similarity, ensuring semantic integrity | Scenarios with high semantic requirements |
In most cases, LangChain's RecursiveCharacterTextSplitter is sufficient.
Tips for choosing chunk size
Chunk Size is a parameter that needs to be adjusted according to the scenario.
Some guiding principles:
- Q&A scenario: 500-1000 characters, just enough to contain a complete question-answer pair
- Summary scenario: 1000-2000 characters, requires more context
- Code scenario: can be split by function or class, keeping the code block intact
There is also an important parameter: Overlap—the number of characters overlapping between two adjacent text chunks.
Overlap can prevent important information from being split across two chunks, usually set to 10%-20% of the chunk size.
Do not blindly pursue the "optimal" chunking parameters. Start with 500 characters and 50 overlap, test the actual effect, and then adjust.
Embedding Model
An embedding model is a model that converts text into vectors.
Its quality directly affects the retrieval effect—a good Embedding model can accurately understand semantics and rank relevant documents at the top.
What is an Embedding model?
An Embedding model is a pre-trained neural network where the input is text and the output is a vector.
Its training objective is: to make the vectors of semantically similar texts also close to each other.
For example:
- "How to learn Python" and "Python learning methods" -> vectors are close
- "The cat is very cute" and "The puppy is very cute" -> vectors have some distance but are relatively close
- "How to learn Python" and "The cat is very cute" -> vectors are very far apart
OpenAI text-embedding-3 series
OpenAI provides the most popular Embedding model:
| Model | Dimension | Price (per million tokens) | Features |
|---|---|---|---|
| text-embedding-3-small | 1536 | $0.02 | High cost-performance, sufficient for most scenarios |
| text-embedding-3-large | 3072 | $0.13 | Better performance, suitable for high-precision requirements |
text-embedding-3-small is the current preferred choice—it performs better and is cheaper than the previous generation text-embedding-ada-002.
Open-source Embedding model
If you do not want to use OpenAI, or have data privacy requirements, there are also many open-source options:
| Model | Dimension | Feature |
|---|---|---|
| sentence-transformers/all-MiniLM-L6-v2 | 384 | Lightweight, fast, and good performance |
| sentence-transformers/all-mpnet-base-v2 | 768 | Better performance, but also slower and larger |
| BAAI/bge-large-zh-v1.5 | 1024 | Specifically optimized for Chinese |
| Alibaba-NLP/gte-large-zh | 1024 | Produced by Alibaba, good Chinese performance |
For Chinese scenarios, it is recommended to use the BAAI/bge series or the Alibaba-NLP/gte series—they are specifically optimized for Chinese and perform better than general-purpose models.
Retrieval Strategies
Retrieval is not as simple as "finding the most relevant documents"—different strategies suit different scenarios.
Vector Similarity Search
This is the most commonly used retrieval method: calculating the similarity between the query vector and all document vectors, and returning the top K most relevant ones.
Advantage: It can understand semantics, matching synonyms and near-synonyms.
Disadvantage: It may be less accurate for precise terminology or proper nouns compared to keyword search.
For example, if the user asks "runoob's Python tutorial," vector search can understand that "tutorial" and "course" are similar, but if the user asks for "runoob Python3.10 documentation," keyword search might be more accurate.
Keyword Search (BM25)
This is a method used by traditional search engines: matching keywords and scoring based on term frequency, inverse document frequency, etc.
-
Advantage: Good results for precisely matching terms, product names, models, etc.
-
Disadvantage: Cannot understand synonyms or semantic relationships.
For example, if a user asks how to learn programming, keyword search can only find documents containing the word "programming" and cannot find documents that say "write code" but mean the same thing.
Hybrid Search
Since both methods have their strengths and weaknesses, why not use them together?
Hybrid Search performs vector search and keyword search simultaneously, then merges and re-ranks the results.
This way, both semantic understanding and precise matching can be utilized.
Many vector databases support hybrid search, such as Weaviate, Pinecone, and Qdrant.
If you are unsure which one to use, choose hybrid search—it works best in most cases.
Generation Stage Optimization
Retrieving relevant documents is only the first step; there are also many techniques on how to make the LLM generate a good answer based on these documents.
Prompt Template Design
The prompt template is a key factor affecting the output quality in RAG.
A good RAG prompt usually includes:
- Role setting: Tell the LLM what role it is
- Context: The retrieved document content
- Task description: What the LLM should do
- Constraints: For example, "Answer only based on the context," or "Say you don't know if you don't know"
- Output format: How you want the LLM to answer
A classic template:
Example
A typical RAG Prompt template
RAG_PROMPT_TEMPLATE
=
"""You are a professional {role}.
Please answer the user's question based on the following context. If there is no relevant information in the context, please say "Sorry, I could not find relevant information".
Context:
{context}
User question: {question}
Please answer in concise and accurate language:"""
How to reduce hallucinations
Hallucination is the phenomenon of LLMs fabricating facts—they sound plausible, but are entirely false.
RAG can reduce hallucinations, but cannot eliminate them completely.
Some techniques to reduce hallucinations:
- Emphasize "answer only based on the context" in the Prompt
- Have the LLM cite original text snippets in its answer
- If the retrieved results are irrelevant, have the LLM say "I don't know"
- Use multiple LLMs to cross-validate answers
- Have the LLM first find relevant content from the context before answering
Cite sources
Let the user know where the answer came from; this is important—it not only increases credibility but also makes it easy for users to verify.
Common practices:
- Mark the source in the answer, such as "According to Document A, page 2"
- List the titles and links of the reference documents at the end of the answer
- Allow users to click to jump to the original text location
Some advanced frameworks in LangChain (like LlamaIndex) can do this automatically for you.
Practical: Building a Document Q&A System based on LangChain
After all this, let's build a complete RAG system.
We will use LangChain + Chroma + OpenAI to build a document Q&A system.
Environment Preparation
First, install the required libraries:
pip install langchain langchain-openai langchain-chroma python-dotenv
Then, create a .env file in the project directory and fill in your OpenAI API Key:
Original prompt (Chinese, left untranslated)
OPENAI_API_KEY=你的-api-key-在这里
Complete Code Implementation
This is a complete RAG system, including indexing creation and query functionality:
Instance
============================================
Complete implementation of RAG document Q&A system
============================================
import
os
from
dotenv
import
load_dotenv
from
langchain.
text_splitter
import
RecursiveCharacterTextSplitter
from
langchain_openai
import
OpenAIEmbeddings
from
langchain_chroma
import
Chroma
from
langchain_openai
import
ChatOpenAI
from
langchain.
chains
import
RetrievalQA
from
langchain.
prompts
import
PromptTemplate
from
langchain.
schema
import
Document
def
load_documents_from_directory
(
directory:
str
)
list
[
Document
]
:
Load documents from the directory
Here, we manually create some documents for demonstration
In actual projects, DirectoryLoader can be used to load real files
"""
documents
=
[
Document
(
page_content
=
"""RUNOOB tutorial website was founded in 2013 by the Cainiao Tutorial team.
The website aims to provide simple and easy-to-understand programming tutorials for programming beginners.
We offer tutorials for various programming languages such as HTML, CSS, JavaScript, Python, Java, and C++."""
,
metadata
=
{
"source"
:
"runoob_intro.txt"
,
"page"
:
1
}
)
,
Document
(
page_content
=
"""RUNOOB's Python tutorial covers all important knowledge points of Python.
Includes: Python basic syntax, data types, control statements, functions, modules, file operations, etc.
The tutorial provides a large number of code examples, each of which has been carefully designed and tested.
We also provide an online Python editor where you can run code directly in the browser.
,
metadata
=
{
"source"
:
"python_tutorial.txt"
,
"page"
:
1
}
)
,
Document
(
page_content
=
The features of the RUNOOB tutorial are concise content, rich examples, and focus on practice.
We believe "the best way to learn programming is to write code."
Therefore, each knowledge point is equipped with runnable code examples, allowing you to practice as you learn.
Our tutorials are completely free, and anyone can access them to learn.
,
metadata
=
{
"source"
:
"features.txt"
,
"page"
:
1
}
)
,
Document
(
page_content
=
In addition to text tutorials, RUNOOB also provides video tutorials.
Video tutorials are more intuitive and suitable for visually learning users.
Our video tutorials cover popular topics such as Python, Web development, and data analysis.
You can find our videos on Bilibili and YouTube.
,
metadata
=
{
"source"
:
"video_course.txt"
,
"page"
:
1
}
)
,
]
(
f
"Loaded {len(documents)} documents"
)
return
documents
def
split_documents
(
documents:
list
[
Document
]
,
chunk_size:
int
=
500
,
chunk_overlap:
int
=
50
)
list
[
Document
]
:
"""Split document"""
text_splitter
=
RecursiveCharacterTextSplitter
(
chunk_size
=
chunk_size
,
chunk_overlap
=
chunk_overlap
,
length_function
=
len
,
separators
=
[
""
,
"\n"
,
.
,
!
,
"?"
,
","
,
" "
,
""
]
,
)
splits
=
text_splitter.
split_documents
(
documents
)
(
f
"Successfully split {len(documents)} documents into {len(splits)} text chunks"
)
return
splits
def
create_vector_store
(
splits:
list
[
Document
]
,
persist_directory:
str
=
"./chroma_db"
)
Chroma:
"""Create vector database"""
embeddings
=
OpenAIEmbeddings
(
model
=
"text-embedding-3-small"
)
vector_store
=
Chroma.
from_documents
(
documents
=
splits
,
embedding
=
embeddings
,
persist_directory
=
persist_directory
,
)
(
f
"Vector database created, total {vector_store._collection.count()} records"
)
return
vector_store
def
load_vector_store
(
persist_directory:
str
=
"./chroma_db"
)
Chroma:
"""Load existing vector database"""
embeddings
=
OpenAIEmbeddings
(
model
=
"text-embedding-3-small"
)
vector_store
=
Chroma
(
persist_directory
=
persist_directory
,
embedding_function
=
embeddings
,
)
(
f
"Vector database loaded, total {vector_store._collection.count()} records"
)
return
vector_store
def
create_rag_chain
(
vector_store: Chroma
)
:
"""Create RAG Q&A chain"""
Custom Prompt Template
template
=
"""You are a professional RUNOOB customer service assistant.
Please answer the user's question based on the following context. If there is no relevant information in the context, please say "Sorry, I could not find relevant information."
The answer should be concise and clear, using Chinese.
Context:
{context}
User question: {question}
Answer:"""
prompt
=
PromptTemplate
(
template
=
template
,
input_variables
=
[
"context"
,
"question"
]
,
)
llm
=
ChatOpenAI
(
model
=
"gpt-3.5-turbo"
,
temperature
=
0
)
Create retrieval chain
rag_chain
=
RetrievalQA.
from_chain_type
(
llm
=
llm
,
chain_type
=
"stuff"
,
retriever
=
vector_store.
as_retriever
(
search_kwargs
=
{
"k"
:
3
}
)
,
chain_type_kwargs
=
{
"prompt"
: prompt
}
,
return_source_documents
=
True
,
)
return
rag_chain
def
main
(
)
:
"""Main function"""
Load environment variables
load_dotenv
(
)
Check if the database exists
db_exists
=
os
.
path
.
exists
(
"./chroma_db"
)
and
os
.
path
.
isdir
(
"./chroma_db"
)
if
db_exists:
(
"Database already exists, loading..."
)
vector_store
=
load_vector_store
(
)
else
:
(
"Creating a new database..."
)
1. Load document
docs
=
load_documents_from_directory
(
"./data"
)
2. Split documents
splits
=
split_documents
(
docs
)
3. Create vector database
vector_store
=
create_vector_store
(
splits
)
4. Create RAG chain
rag_chain
=
create_rag_chain
(
vector_store
)
5. Test query
test_questions
=
[
When was RUNOOB founded?
,
What are the features of RUNOOB's Python tutorials?
,
"Does RUNOOB have video tutorials?"
,
"How to learn C++ on RUNOOB?"
,
Is the RUNOOB tutorial paid?
,
]
for
question
in
test_questions:
(
f
"\n{'='*60}"
)
(
f
"Question: {question}"
)
(
f
"{'='*60}"
)
result
=
rag_chain.
invoke
(
{
"query"
: question
}
)
answer
=
result
[
"result"
]
sources
=
result
[
"source_documents"
]
(
f
"Answer: {answer}"
)
(
"Reference sources:"
)
for
i
,
doc
in
enumerate
(
sources
,
1
)
:
(
f
" [{i}] {doc.metadata['source']} (Page {doc.metadata['page']})"
)
(
f
" Snippet: {doc.page_content[:50]}..."
)
if
name
==
"main"
:
main
(
)
When you run this program, you will see output similar to this:
Original prompt (Chinese, left untranslated)
创建新的数据库...
已加载 4 个文档
已将 4 个文档切分为 4 个文本块
向量数据库已创建,共 4 条记录
============================================================
问题:RUNOOB 是什么时候创立的?
============================================================
回答:RUNOOB 教程网站创立于 2013 年。
Reference source:
[1] runoob_intro.txt (第 1 页)
片段:RUNOOB 教程网站创立于 2013 年,由菜鸟教程团队创建。...
[2] features.txt (第 1 页)
片段:除了文字教程,RUNOOB 还提供了视频教程。...
============================================================
问题:RUNOOB 的 Python 教程有什么特点?
============================================================
回答:RUNOOB 的 Python 教程涵盖了 Python 的所有重要知识点,包括基础语法、数据类型、控制语句、函数、模块、文件操作等,并且提供了大量经过精心设计和测试的代码示例,还提供了在线 Python 编辑器,可以直接在浏览器中运行代码。
Reference source:
[1] python_tutorial.txt (第 1 页)
片段:RUNOOB 的 Python 教程涵盖了 Python 的所有重要知识点。...
[2] features.txt (第 1 页)
片段:RUNOOB 教程的特点是内容简洁、示例丰富、注重实践。...
Congratulations! You have successfully built a complete RAG document question-answering system.
Advanced Optimization: Re-ranking, HyDE
Basic RAG is usable, but if you want better results, you can try these advanced optimization methods.
Re-ranking
The results returned by vector retrieval are sorted by similarity, but high similarity does not necessarily mean the best fit for answering the question.
Re-ranking is: first use vector retrieval to return the top K results (e.g., 20), then use a more precise model to re-rank these results, and send the best few to the LLM.
Commonly used Re-ranking models:
- cross-encoder/ms-marco-MiniLM-L-6-v2
- BAAI/bge-reranker-large
Although it adds an extra step, the improvement in effect is very obvious, and it is worth trying.
HyDE (Hypothetical Document Embedding)
HyDE is a clever idea: first, use an LLM to generate a "hypothetical answer" for the user's question, and then use this hypothetical answer for retrieval.
Why is this effective? Because questions are usually short with low information density; while the hypothetical answer is longer and more like the style of a document, resulting in higher similarity to real documents.
For example:
- User question: "When was RUNOOB founded?"
- Hypothetical answer: "The RUNOOB tutorial website was founded in 2013 by the Cainiao Tutorial team, aiming to provide high-quality tutorials for programming beginners."
Searching with hypothetical answers often yields more relevant documentation.