旧经新练:RAG 篇

旧经新练:RAG 篇

Ginkgo True love prevails.

RAG(Retrieval-Augmented Generation)是把检索和生成结合起来:在 LLM 回答之前,先从外部知识库中检索相关文档作为上下文,再让模型结合这些信息生成答案。这一篇按”完整流程”的顺序,把每个环节的常见做法、选型考量、面试加分点都串起来。


一、概念速览

RAG 解决了什么问题

  • 减少幻觉:模型不再是”空想”,而是拿着资料回答问题
  • 引入私有知识:公司的技术文档、产品手册、客服知识库等
  • 知识可更新:换文档就行,不用重新训练模型

完整流程

1
2
3
4
5
文档 → 分割(Chunk) → 向量化(Embedding) → 存入向量库
↓
用户问题 → 查询改写 → Embedding → 向量检索 → 重排序(Rerank)
↓
上下文 + 问题 → LLM 生成回答

二、文档加载与分割(Chunking)

文档加载

用 DirectoryLoader 从本地目录加载文档:

1
2
3
4
5
6
7
8
9
from langchain_community.document_loaders import DirectoryLoader

path = "./data/RAG/rtdocs_new/"
loader = DirectoryLoader(path=path, glob="*.html")
docs = loader.load()

print(f"loaded {len(docs)} documents")
text = " ".join(docs[0].page_content.split())
print(text[:100] + "...")

为什么要对文档分块

LLM 有上下文窗口限制,同时 embedding 对长文本的语义表征效果会下降(虽然后续长上下文模型兴起后有人讨论”RAG 是否已死”,但 RAG 在效率、成本和可控性上仍然有不可替代的优势)。

分块策略:

策略 做法 适用场景
固定长度 + overlap 512 tokens,10% 重叠 通用,实现简单
语义分割 按句子/段落边界分 语义完整性好
递归字符分割 RecursiveCharacterTextSplitter 兼顾结构和语义
1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np
from langchain_text_splitters import RecursiveCharacterTextSplitter

CHUNK_SIZE = 512
chunk_overlap = np.round(CHUNK_SIZE * 0.10, 0)

child_splitter = RecursiveCharacterTextSplitter(
chunk_size=CHUNK_SIZE,
chunk_overlap=chunk_overlap)

chunks = child_splitter.split_documents(docs)
print(f"{len(docs)} docs split into {len(chunks)} child documents.")

面试加分:chunk 大小是一个经典 tradeoff——太小则语义不完整,太大则检索不精准。overlap 的作用是防止信息在切分边界处断裂。


三、向量化(Embedding)

选型

将文本转为稠密向量,常用的 embedding 模型:

  • 英文:BAAI/bge-large-en-v1.5(BGE 系列,性能稳定)
  • 中文:shibing624/text2vec-base-chinese 等
  • 中英混杂:bge-m3等多语言嵌入模型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import torch
from sentence_transformers import SentenceTransformer

device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

model_name = "BAAI/bge-large-en-v1.5"
encoder = SentenceTransformer(model_name, device=device)

EMBEDDING_DIM = encoder.get_sentence_embedding_dimension()
MAX_SEQ_LENGTH_IN_TOKENS = encoder.get_max_seq_length()

print(f"model_name: {model_name}")
print(f"EMBEDDING_DIM: {EMBEDDING_DIM}")
print(f"MAX_SEQ_LENGTH_IN_TOKENS: {MAX_SEQ_LENGTH_IN_TOKENS}")

向量归一化

检索时通常用余弦相似度,embedding 归一化后点积等价于余弦相似度:

点积定义:
余弦相似度:
向量归一化:

1
2
3
4
5
6
7
8
9
10
11
12
import numpy as np

embeddings = torch.tensor(encoder.encode(list_of_strings))
embeddings = np.array(embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)) # Norm

dict_list = []
for chunk, vector in zip(chunks, embeddings):
dict_list.append({
'chunk': chunk.page_content,
'source': chunk.metadata.get('source', ""),
'vector': vector.astype(np.float32),
})

四、向量数据库

以 Milvus 为例(向量数据库通过近似最近邻算法(如 HNSW)降低检索复杂度,从 O(N) 降到对数级。)

新建集合并写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import time
from pymilvus import MilvusClient

mc = MilvusClient("milvus_demo.db")

COLLECTION_NAME = "MilvusDocs"
mc.create_collection(
COLLECTION_NAME,
EMBEDDING_DIM,
consistency_level="Eventually",
auto_id=True,
overwrite=True)

print("Start inserting entities")
start_time = time.time()
mc.insert(COLLECTION_NAME, data=dict_list, progress_bar=True)
print(f"Milvus insert time for {len(dict_list)} vectors: "
f"{round(time.time() - start_time, 2)} seconds")

向量库选型对比

方案 优势 劣势
Milvus 分布式、高性能、功能全 部署重
Chroma 轻量、本地开发友好 生产级能力弱
pgvector 依托 PostgreSQL 有 PG 环境时方便
FAISS 纯本地、速度极快 不支持增量更新

五、查询优化:让检索更准

查询改写

直接拿用户原始 query 去检索,效果往往不好。查询改写的方法:

  1. LLM 重写:让模型把 query 改写成更清晰/完整的表达
  2. Multi-Query:生成多个不同问法,分别检索后聚合
  3. Step-Back Prompting:从具体问题”后退”到抽象问题:如”HNSW 参数含义” → “向量索引的工作原理”

稠密检索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import torch.nn.functional as F

SAMPLE_QUESTION = "What do the parameters for HNSW mean?"

query_emb = torch.tensor(encoder.encode([SAMPLE_QUESTION]))
query_emb = F.normalize(query_emb, p=2, dim=1)
query_emb = query_emb.cpu().numpy().astype(np.float32).tolist()

OUTPUT_FIELDS = [k for k in dict_list[0].keys() if k != 'vector']
TOP_K = 2

results = mc.search(
COLLECTION_NAME,
data=query_emb,
output_fields=OUTPUT_FIELDS,
limit=TOP_K,
consistency_level="Eventually")

六、混合检索(Hybrid Retrieval)

为什么需要混合检索

  • 稀疏检索(BM25):基于词频、倒排索引,擅长精确关键词匹配
  • 稠密检索(Embedding):基于语义向量,擅长近义词和语义理解

两者互补,结合使用效果更好。

融合方式

  1. Score Fusion:加权求和 final_score = α × BM25_score + β × embedding_score,归一化后再加权
  2. RRF(Reciprocal Rank Fusion):对每个文档在两个检索结果中的排名取倒数融合

'_' allowed only in math mode \text{RRF_score}(d) = \sum_{r \in \text{rankings}} \frac{1}{k + \text{rank}_r(d)}

其中 k 是一个平滑常数(通常取 60)。RRF 的好处是不需要分数归一化,只依赖排名。


七、重排序(Rerank)

为什么需要 Rerank

向量检索返回 Top-K,但召回率高的代价是精度低。Rerank 用更强的模型(通常是用 Cross-Encoder)对 (query, document) 直接打分,精排出最相关的文档。

流程:

1
2
3
4
5
检索 → 拿到 Top-50(粗排)
↓
Cross-Encoder 打分
↓
取 Top-3 给 LLM(精排)

Rerank 本质上是 recall vs precision 的 tradeoff。检索阶段(召回)要广,Rerank 阶段(精排)要准。Cross-Encoder 虽然效果好,但要对每个 (query, doc) pair 做一次前向传播,成本高,所以只用在最后几步。


八、构建 Prompt 生成答案

组装上下文

1
2
3
4
5
6
7
8
9
10
contexts = []
sources = []

for hit_group in results:
for hit in hit_group:
contexts.append(hit.entity.get("chunk"))
sources.append(hit.entity.get("source"))

contexts_combined = ' '.join(contexts)
source_combined = ' '.join(reversed(list(dict.fromkeys(sources))))

System Prompt 设计

1
2
3
4
5
6
7
SYSTEM_PROMPT = f"""First, check if the provided Context is relevant to
the user's question. Second, only if the provided Context is strongly relevant, answer the question using the Context. Otherwise, if the Context is not strongly relevant, answer the question without using the Context.
Be clear, concise, relevant. Answer clearly, in fewer than 2 sentences.
Grounding sources: {source_combined}
Context: {contexts_combined}
User's question: {SAMPLE_QUESTION}
"""

注意:Prompt 中加了”强相关才用上下文”的逻辑,这是一个很好的兜底策略——检索到的文档可能不相关,强行使用反而会误导模型。

LLM 生成

1
2
3
4
5
6
7
8
9
10
# 以 vLLM 为例
from vllm import SamplingParams

sampling_params = SamplingParams(temperature=0.2, top_p=0.95)
outputs = llm.generate([SYSTEM_PROMPT], sampling_params)

for output in outputs:
generated_text = output.outputs[0].text
print(f"Question: {SAMPLE_QUESTION!r}")
print(f"Generated text: {generated_text!r}")

九、RAG 的关键作用

  1. 减少幻觉——模型不再”编造”知识
  2. 引入私有知识——公司内部文档、最新资料都能用
  3. 知识可更新——换知识库就行,无需重新训练
  4. 成本可控——相比微调,RAG 的维护和部署成本更低
  5. 可解释性——可以溯源到具体文档,答案是”有据可查”的

小结:RAG 各环节速查

环节 主要做法 常见坑点
文档分块 固定长度 + overlap / 语义分割 chunk 太大小/大,overlap 不够
Embedding BGE / text2vec 模型选型不适合语言/领域
向量存储 Milvus / Chroma / pgvector / FAISS 部署和增量更新策略
查询改写 LLM rewrite / Multi-Query / Step-Back 改写过度引入噪声
检索 稠密 / 稀疏(BM25) / 混合(RRF) 单种检索召回不全
Rerank Cross-Encoder 精排 计算成本高,不能对所有候选重排
Prompt 组装 强相关才用上下文 不相关文档会误导模型

RAG 的每一个环节都有 tradeoff 可以做文章——面试中能清晰地指出”为什么这么做”和”不这么做会怎样”,比背模板更有说服力。
RAG 更适合知识密集型任务,微调更适合行为/风格对齐。

  • Title: 旧经新练:RAG 篇
  • Author: Ginkgo
  • Created at : 2026-04-24 20:00:00
  • Updated at : 2026-04-26 21:32:43
  • Link: https://g1nkgo7.github.io/2026/04/24/旧经新练-RAG篇/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments