什么是RAG?Retrieval-Augmented Generation — 让AI学会查阅文档
Trí tuệ nhân tạo

什么是RAG?Retrieval-Augmented Generation — 让AI学会查阅文档

RAG(检索增强生成)是一种让LLM在回答前先检索真实文档的技术,可有效减少幻觉,并实时更新企业知识库。

系列文章: Trí tuệ nhân tạo
  1. 1 向量数据库是什么?语义 AI 搜索的基础
  2. 2 推荐系统是什么?TikTok 与 Shopee 如何推荐产品
  3. 3 什么是AI Agent?智能体如何自动化完成复杂任务?
  4. 4 Deepfake 是什么?如何检测和保护自己
  5. 5 什么是Prompt Engineering?高效指令AI的艺术
  6. 6 Fine-tuning 是什么?为企业定制 AI 模型
  7. 7 什么是RAG?Retrieval-Augmented Generation — 让AI学会查阅文档
  8. 8 什么是越南AI法律?人工智能监管框架(2026年更新)
✦ 快速摘要
RAG(检索增强生成)是一种让LLM在回答前先检索真实文档的技术,可有效减少幻觉,并实时更新企业知识库。
这篇文章怎么样?

RAG——Retrieval-Augmented Generation(检索增强生成)的缩写——是一种将LLM的语言生成能力与回答前实时查阅文档相结合的技术,让AI不再需要单纯依赖固定参数中存储的"记忆"来"猜测"答案。本文将逐步拆解RAG的完整架构、构建方式,以及与微调的对比和在企业中的应用。

什么是RAG?

**RAG(Retrieval-Augmented Generation,检索增强生成)**是一种通过自动检索相关文档、并在模型生成回答前将这些内容注入提示词(prompt)的方式来增强大语言模型知识的方法。与仅依赖训练过程中"烘焙"进参数的知识不同,RAG模型额外拥有一个外部信息源——灵活、可更新且可溯源。

最直观的类比:想象一次开卷考试。闭卷考试的学生必须全凭记忆作答——容易出错,甚至可能编造答案。开卷考试的学生则可以在回答前查阅教材——答案更准确,来源更清晰。RAG正是让LLM从"闭卷"变为"开卷"。

RAG解决了哪些问题

在理解RAG的工作原理之前,先看看它针对的三个核心痛点。

幻觉(Hallucination)——AI编造信息

LLM通过基于概率预测下一个token来生成文本。当参数中缺乏足够信息时,模型仍可能自信地给出完全错误的回答——这种现象被称为"幻觉"(hallucination)。在企业环境中,这会带来严重风险:错误报告、不准确的法律建议、导致故障的技术支持。

知识截止日期——知识被"冻结"

所有LLM都有训练截止日期(cutoff)。此后发生的事件、新出台的法规或新产品,模型一概不知。对于企业而言,内部文档(合同、政策、产品目录)持续更新——每次更新都重新训练模型,无论从成本还是时间上都不现实。

企业私有知识不在模型中

企业内部数据(内部技术文档、客服历史记录、业务报告)从未出现在公开训练集中。LLM无法了解它从未"读过"的内容。

RAG架构逐步解析

典型的RAG系统分为两个阶段:索引(Indexing)(文档加载与建立索引)离线运行,**检索+生成(Retrieval + Generation)**在用户提问时在线运行。

阶段一——索引(离线)

步骤1:文档加载(Document Loading) 来自多种来源(PDF、Word、网页、数据库、Confluence、Notion等)的文档被读取并标准化为纯文本格式。

步骤2:分块(Chunking)——将文档切分为小段 长文档被切分为更小的片段,称为chunk(块)。这是RAG中最关键的步骤——块太长会引入噪音,块太短则丢失上下文。通常每块使用256至512个token,并保留10%至20%的重叠,以确保语义连贯。

步骤3:嵌入(Embedding)——生成向量 每个chunk通过嵌入模型(如OpenAI的text-embedding-3-large、Google的embedding-001)转换为多维实数向量。语义相近的片段在向量空间中距离更近。

步骤4:存入向量数据库 (chunk文本,向量)对存入向量数据库,如Pinecone、Weaviate、Qdrant或pgvector,随时备查。

阶段二——检索+生成(在线)

步骤5:用户问题嵌入 用户提问后,该问题同样通过相同的嵌入模型转换为查询向量。

步骤6:检索top-k个块 向量数据库找出与查询向量最相近的k个chunk(通常k=3至10),使用余弦相似度或点积计算。

步骤7:注入提示词(Context Augmentation) 检索到的chunk被拼入用户问题前的提示词,形成包含完整上下文的提示词。

步骤8:LLM生成回答 LLM接收到已补充文档的提示词,生成有据可查、来源清晰的回答。

text
 1[提示词示例]
 2
 3你是一名技术支持助理。请根据以下文档回答问题:
 4
 5--- 文档内容 ---
 6{chunk_1}
 7{chunk_2}
 8{chunk_3}
 9--- 文档结束 ---
10
11问题:{user_question}
12请简洁、准确地作答。如果文档信息不足,请明确说明。

嵌入与向量数据库——简明解释

什么是嵌入?

想象一张语义地图:"狗"和"猫"因为都是宠物而彼此相近;"银行"(金融机构)和"河岸"虽然写法相同,含义却相距甚远。嵌入技术将文本表示为该语义地图上的坐标——以数千维的向量形式呈现。

嵌入模型在数十亿对相似句子上训练,学习如何放置向量:即使"产品出现电源故障"和"机器无法开机"没有任何相同词汇,它们的向量也会彼此相近。

什么是向量数据库?

向量数据库是专为向量数据而构建的搜索工具。与SQL依靠等于/大于/小于条件检索不同,向量数据库计算查询向量与库中所有向量之间的相似度,并返回最近的k个结果。HNSW等近似最近邻(ANN)算法即使面对数百万个向量也能实现极速检索。

已有PostgreSQL的话,直接用pgvector

如果你的基础设施已经运行PostgreSQL,pgvector扩展可以让你直接在Postgres中存储和检索向量——无需额外部署独立数据库。适合原型项目或向量数量在数百万以内的系统。

如何构建高效的RAG系统

分块策略

分块策略是决定RAG质量最关键的环节。常见策略包括:

  • 固定大小分块(Fixed-size chunking):按固定token数切分,简单但可能在句中截断。
  • 句子/段落分块(Sentence / Paragraph chunking):按句子或段落边界切分——上下文更自然。
  • 递归分块(Recursive chunking):先尝试按较大段落切分,过长时再进一步细分——保留文档结构。
  • 语义分块(Semantic chunking):利用嵌入自动检测话题转换点并在此切分——质量最高,但成本也更高。

重排序(Re-ranking)——提升top-k质量

初步向量检索优先考虑速度(ANN),有时返回的chunk相关但精度不足。重排序器(如Cohere Rerank或交叉编码器)逐对读取(查询,chunk)并进行更精细的打分,在注入提示词前重新排列列表。重排序可显著提升准确性,但会增加约100至300毫秒的延迟。

调整top-k数量

k越大,LLM获得的上下文越多——但提示词也越长、消耗token越多,有时还会导致"迷失在中间"(LLM忽略长提示词中间的信息)。实践中通常从k=5开始,再根据实际回答质量进行调整。

RAG vs 微调——实际对比

RAG vs 微调:全面对比
Tested on 2026-06-12 RAG Pipeline vs Fine-tuned LLM
针对中型企业内部文档问答机器人的使用场景(500+页文档,每周更新)进行评估:
评估维度 RAG 微调
初始成本 低至中等 高(GPU训练)
知识更新 即时(向数据库添加文件) 需要重新训练
领域准确性 高(基于具体文档) 高(训练充分后)
来源可控性 可引用具体chunk 来源不透明
幻觉风险 较低 较低(但类型不同)
适用场景 频繁变动的文档 固定风格/语调

在灵活性和来源可验证性方面,RAG明显胜出。当需要模型学习特定回答风格或深入理解领域专有术语时,微调更为适合。

RAG的实际应用

内部文档问答机器人

这是最常见的使用场景:员工可以直接询问公司政策、运营流程、技术规范——无需在数百个文件中手动翻找。系统检索出准确的文档片段,生成简洁、附有引用的回答。

自动化客户支持

客服机器人加载了完整的FAQ、产品目录和保修政策。当客户询问具体故障时,系统找到对应的处理指引并准确作答——无需手动编写所有对话场景。

法律与医疗查询

在法律或医疗等对准确性要求极高的领域,RAG使AI能够引用具体的法规条文或治疗方案——更重要的是,可以显示来源供用户核实。

结合RAG的企业数据分析

RAG不仅限于静态文本。结合Apache Spark等大数据管道批量处理和更新语料库,或通过API集成让RAG系统自动从多个来源拉取最新数据,是企业实际部署中的常见方向。

希望快速从内部业务报告中挖掘洞察的企业,可以将RAG与AlgoData等分析平台结合使用——该平台的市场与运营数据已经过组织整理,可直接接入检索管道。

RAG的局限性

RAG并非万能解药。以下几点局限性值得关注:

输出质量完全取决于输入文档的质量。"垃圾进,垃圾出"——如果源文档过时、存在矛盾或写作质量低下,RAG的回答质量也会随之下降。

**难以处理综合性问题。**需要整合分散在多份文档中的信息,或涉及多步推理的问题,简单的top-k检索难以胜任。Advanced RAG(多跳检索、HyDE、查询分解)正是为解决这一局限而发展起来的。

**增加额外延迟。**每个请求都需要先进行查询嵌入、向量检索,以及可选的重排序,然后才调用LLM。对于低延迟系统,这可能额外增加200至500毫秒。

**token成本增加。**由于上下文被注入提示词,每次请求的提示词更长,消耗的token也更多,规模化部署时会直接影响成本。

切勿将敏感数据加载到共用向量数据库

如果不同访问权限的用户群体共用同一套RAG系统,需要在检索层实施访问控制——在返回结果前按元数据(部门、保密级别)过滤chunk。缺少这一步骤,可能导致敏感信息泄露给无权访问的群体。

结论: RAG是将LLM引入企业环境最务实的一步——它将一个强大却缺乏上下文的语言模型,转变为真正能够查阅组织文档、给出准确且可溯源回答的智能助理。

参考资料

常见问题

常见问题Q&A
RAG与微调(Fine-tuning)有何区别?
RAG在推理时从外部检索文档——无需修改模型参数,只需向向量数据库中添加新文件即可更新知识。微调则通过重新训练将知识注入模型权重,成本更高,在数据频繁变动时也更为僵化。两者可结合使用:通过微调让模型理解领域背景,再借助RAG提供具体文档。
什么是向量数据库?
向量数据库是一种专门用于存储和检索向量(多维实数数组)的数据库管理系统。与关键字匹配不同,它通过语义相似度(余弦相似度、点积)进行搜索——即使用户使用的词汇与文档不完全相同,也能找到相关内容。Pinecone、Weaviate、Qdrant和pgvector都是常见选择。
什么是嵌入(Embedding)?
嵌入是将文本(句子、段落、文档)转换为多维实数向量(通常为768至3072维)的过程,使语义相近的文本在空间中距离更近。OpenAI的text-embedding-3-large和Google的embedding-001等嵌入模型负责完成这一转换;输出的向量存储在向量数据库中,以便快速检索。
RAG能完全消除幻觉吗?
不能完全消除。RAG通过将回答锚定在真实文档上,可显著降低幻觉,但无法彻底根除。LLM仍可能误解检索到的文档、遗漏长文档中的信息,或将背景知识与文档内容混淆。合理的分块策略、重排序以及严格的提示工程可进一步降低幻觉风险。
构建RAG系统需要哪些组件?
需要四个核心组件:(1)文档加载与分块管道,(2)用于生成向量的嵌入模型,(3)用于存储和检索的向量数据库,(4)根据检索到的上下文生成回答的LLM。实践中还会加入重排序器(Re-ranker)以提升top-k质量,以及编排框架(LangChain、LlamaIndex)来连接各个环节。

RAG — short for Retrieval-Augmented Generation — is a technique that combines the language generation capabilities of an LLM with a real document retrieval step performed before each answer, freeing AI from having to "guess" purely from a fixed set of learned parameters. This article walks through the complete RAG architecture step by step, covering how to build one, how it compares to fine-tuning, and how it applies in enterprise settings.

What is RAG?

RAG (Retrieval-Augmented Generation) is a method for augmenting large language models with knowledge by automatically retrieving relevant documents and inserting their content into the prompt before the model generates a response. Rather than relying solely on knowledge "baked" into its parameters during training, a RAG-powered model gains access to an external information source — one that is flexible, updatable, and verifiable.

The easiest analogy is an open-book exam. A student taking a closed-book exam must rely entirely on memory — easy to confuse things, easy to make things up. A student allowed to consult their notes can look up the answer before responding — more accurate, with a clear source. RAG transforms an LLM from a closed-book student into an open-book one.

The problems RAG solves

Before understanding how RAG works, it helps to understand the three pain points it targets.

Hallucination — AI fabricating information

LLMs generate text by predicting the next token based on probabilities. When the model's parameters don't contain enough relevant information, it can still produce a confident-sounding answer that is completely wrong — a phenomenon known as hallucination. In enterprise environments this creates serious risks: incorrect reports, inaccurate legal guidance, or support responses that cause technical failures.

Knowledge cutoff — frozen knowledge

Every LLM has a training cutoff date. After that point, the model knows nothing about new events, regulations, or products. For businesses, internal documents (contracts, policies, product catalogs) change constantly — retraining the model with every update is neither cost-effective nor practical.

Proprietary enterprise knowledge absent from the model

Internal data — technical documentation, customer-service history, business reports — never appears in public training sets. An LLM simply cannot know what it has never read.

RAG architecture, step by step

A typical RAG system splits into two phases: indexing (ingesting and indexing documents), which runs offline, and retrieval + generation, which runs online when a user asks a question.

Phase 1 — Indexing (offline)

Step 1: Document loading Documents from multiple sources (PDF, Word, web pages, databases, Confluence, Notion, etc.) are read in and normalized to plain text.

Step 2: Chunking — splitting documents into passages Long documents are divided into smaller segments called chunks. This is the single most important step in RAG — chunks that are too long introduce noise, while chunks that are too short lose context. A common starting point is 256–512 tokens per chunk with a 10–20% overlap to preserve continuity across boundaries.

Step 3: Embedding — generating vectors Each chunk is passed through an embedding model (e.g., OpenAI's text-embedding-3-large, Google's embedding-001) to produce a high-dimensional vector of real numbers. Passages with similar meaning will have vectors close together in the vector space.

Step 4: Storing in the vector database Each (chunk text, vector) pair is stored in a vector database such as Pinecone, Weaviate, Qdrant, or pgvector — ready to be searched.

Phase 2 — Retrieval + Generation (online)

Step 5: The user's question is embedded When a user asks a question, that question is run through the same embedding model to produce a query vector.

Step 6: Retrieving the top-k chunks The vector database finds the k chunks whose vectors are closest to the query vector (typically k = 3–10) using cosine similarity or dot product.

Step 7: Context augmentation — injecting chunks into the prompt The retrieved chunks are prepended to the user's question, forming a context-rich prompt.

Step 8: The LLM generates an answer The LLM receives the document-augmented prompt and produces a response — grounded in real sources and verifiable.

text
 1[Sample prompt]
 2
 3You are a technical support assistant. Answer the question based on the documents below:
 4
 5--- DOCUMENTS ---
 6{chunk_1}
 7{chunk_2}
 8{chunk_3}
 9--- END DOCUMENTS ---
10
11Question: {user_question}
12Answer concisely and accurately. If the documents do not contain enough information, say so clearly.

Embeddings and vector databases — a plain-language explanation

What is an embedding?

Imagine a semantic map: "dog" and "cat" sit close together because both are pets; "bank" (financial institution) and "bank" (riverbank) sit far apart despite being spelled the same. Embedding is the technique of representing text as coordinates on that semantic map — expressed as a vector with thousands of dimensions.

Embedding models are trained on billions of similar sentence pairs to learn how to position vectors: the sentence "The product has a power fault" and "The device won't turn on" will end up near each other even though they share no common words.

What is a vector database?

A vector database is a search engine built specifically for vector data. Unlike SQL, which filters by equality or range conditions, a vector database computes the similarity between a query vector and every vector in the store, then returns the k closest results. Approximate Nearest Neighbor (ANN) algorithms such as HNSW make this search extremely fast even across millions of vectors.

Use pgvector if you already run PostgreSQL

If your infrastructure already runs PostgreSQL, the pgvector extension lets you store and search vectors directly inside Postgres — no separate database to deploy. It is a good fit for prototypes or systems with fewer than a few million vectors.

How to build an effective RAG system

Chunking strategy

Chunking has the greatest single impact on RAG quality. Common strategies include:

  • Fixed-size chunking: splits by a fixed token count — simple but can cut sentences mid-thought.
  • Sentence / paragraph chunking: splits on sentence or paragraph boundaries — more natural context.
  • Recursive chunking: attempts to split on larger boundaries first, falling back to smaller ones only when needed — preserves document structure.
  • Semantic chunking: uses embeddings to detect topic shifts automatically and splits at those points — highest quality but more expensive.

Re-ranking — improving top-k quality

The initial vector retrieval step prioritizes speed (ANN) and sometimes returns chunks that are related but not quite precise enough. A re-ranker (such as Cohere Rerank or a cross-encoder) re-reads each (query, chunk) pair and scores them more carefully, reordering the list before it enters the prompt. Re-ranking meaningfully improves precision at the cost of roughly 100–300 ms of additional latency.

Tuning the top-k value

A larger k gives the LLM more context — but also makes the prompt longer, consumes more tokens, and can trigger "lost in the middle" behavior (where the LLM ignores information in the middle of a long prompt). A practical starting point is k = 5, adjusted based on observed answer quality.

RAG vs Fine-tuning — a practical comparison

RAG vs Fine-tuning: Comprehensive Comparison
Tested on 2026-06-12 RAG Pipeline vs Fine-tuned LLM
Evaluated on a mid-size enterprise internal-documentation chatbot use case (500+ pages of docs, updated weekly):
Criterion RAG Fine-tuning
Setup cost Low–medium High (GPU training)
Knowledge updates Instant (add file to DB) Requires retraining
Domain accuracy High (specific documents) High (after sufficient training)
Source traceability Can cite specific chunks Source is opaque
Hallucination risk Lower Lower (but different failure mode)
Best suited for Frequently changing documents Fixed style / tone

RAG wins decisively on flexibility and source verifiability. Fine-tuning is the better choice when you want the model to learn a distinctive response style or develop deep familiarity with domain-specific terminology.

Real-world applications of RAG

Internal document Q&A chatbot

This is the most common use case: employees can ask directly about company policies, operational procedures, or technical documentation — instead of manually searching through hundreds of files. The system retrieves the right passage and generates a concise, cited answer.

Automated customer support

A customer support chatbot can be loaded with the full FAQ, product catalog, and warranty policies. When a customer reports a specific error, the system finds the correct troubleshooting steps and responds accurately — no need to manually script every possible scenario.

In fields requiring high accuracy, such as law and medicine, RAG lets AI cite specific regulatory texts or clinical treatment protocols — and, crucially, display the source so users can verify the answer themselves.

Enterprise data analysis with RAG

RAG is not limited to static text. Combining it with large-scale data pipelines like Apache Spark to process and refresh corpora in batches, or integrating via API to let the RAG system automatically pull fresh data from multiple sources, are practical deployment patterns in enterprise environments.

Businesses that want to quickly extract insights from internal business reports can use RAG together with an analytics platform like AlgoData — where market and operational data is already organized and ready to feed into a retrieval pipeline.

Limitations of RAG

RAG is not a silver bullet. Several limitations deserve attention:

Output quality depends entirely on the quality of the ingested documents. Garbage in, garbage out — if the source documents are outdated, contradictory, or poorly written, RAG answers will be too.

Synthesis questions are hard. Questions that require aggregating information scattered across many documents, or multi-step reasoning, are difficult to handle with simple top-k retrieval. Advanced RAG variants (multi-hop retrieval, HyDE, query decomposition) have been developed specifically to address this limitation.

Added latency. Every request now requires an extra embedding step for the query, a vector search, and optionally a re-ranking pass before the LLM call. This can add 200–500 ms to the total response time for latency-sensitive systems.

Higher token costs. Longer prompts — filled with retrieved context — mean more tokens consumed per turn, which directly affects cost at scale.

Never ingest sensitive data into a shared vector database

If multiple user groups with different access levels share a RAG system, access control must be enforced at the retrieval layer — filtering chunks by metadata (department, security classification) before returning results. Without this step, sensitive information can leak to users who should not see it.

Conclusion: RAG is the most pragmatic step forward for deploying LLMs in enterprise settings — transforming a powerful but context-blind language model into a genuine assistant that knows how to look things up in the organization's own documents, answer accurately, and point to verifiable sources.

Sources

Frequently Asked Questions

Frequently Asked QuestionsQ&A
How does RAG differ from fine-tuning?
RAG retrieves external documents at inference time — it never modifies model parameters, and updating knowledge is as simple as adding a new file to the vector database. Fine-tuning bakes knowledge into model weights through additional training, which is more expensive and less flexible when data changes frequently. The two techniques can be combined: fine-tune to give the model a deeper understanding of your domain's context, then use RAG to supply specific documents at query time.
What is a vector database?
A vector database is a database management system optimized for storing and searching vectors (multi-dimensional arrays of real numbers). Instead of keyword matching, it retrieves results by semantic similarity (cosine similarity, dot product) — finding the right document passage even when the user's wording differs entirely from the source text. Pinecone, Weaviate, Qdrant, and pgvector are popular choices.
What is an embedding?
Embedding is the process of converting text (a sentence, passage, or document) into a high-dimensional vector of real numbers (typically 768–3,072 dimensions) such that semantically similar texts end up close together in the vector space. Embedding models such as OpenAI's text-embedding-3-large or Google's embedding-001 perform this conversion; the resulting vectors are stored in a vector database for fast retrieval.
Does RAG completely eliminate hallucination?
Not completely. RAG significantly reduces hallucination by grounding answers in real documents, but it does not eliminate it entirely. An LLM can still misinterpret the retrieved text, miss information buried in long documents, or blend background training knowledge with the retrieved content. Good chunking, re-ranking, and tight prompt engineering help reduce it further.
What does it take to build a RAG system?
You need four core components: (1) a document ingestion and chunking pipeline, (2) an embedding model to generate vectors, (3) a vector database to store and search those vectors, and (4) an LLM to generate answers from the retrieved context. In practice you'll also want a re-ranker to improve top-k quality and an orchestration framework (LangChain, LlamaIndex) to wire everything together.