老胡茶室
老胡茶室

无废话 RAG:理论篇

胡键

看过星爷《鹿鼎记》的同学应该都记得影片开头韦小宝青楼说书的那段:“平生不识陈近南,便称英雄也枉然”。在如今的 AI 界,“陈近南”便是 RAG(Retrieval-Augmented Generation)。论江湖地位,RAG 相当于 AI 时代的 CRUD。

虽然人人都说 CRUD 简单,谈话间还略带轻视或戏虐。但现实是,这些人们口中简单的 CRUD 应用却在生产环境中问题频发,成为不少开发者噩梦的开始。在如今的 AI 时代,这类现象依旧存在,只是这次的主角换成了 RAG。

于是,我打算在这次的无废话文章中,聊聊 RAG,同时分享一下我们在实际项目中使用 RAG 的经验。

这同样是一篇付费文章,并且我同样会列出相关的大纲供动手能力强的同学自行探索和学习:

  • 以下内容,可自行问 AI 或搜索
    • RAG 的 what 和 why
    • RAG 的架构和组件
    • RAG 的两个阶段:indexing 和 querying
  • 主流框架的文档几乎都有 RAG 的示例代码
  • 自行专研典型 RAG 的场景,包括但不限于:Agentic、Hybrid Search、CAG、权限和 Filter 等。
  • 最后,再去了解另一个热门的扩展概念:Knowledge Graph。

按此大纲学习,你基本上不会遗漏 RAG 的要点。至于细节上了解到什么程度,就看你自己了。

个人建议在学习过程中结合 Deep Research,按它的报告按图索骥,同时辅以框架代码实战找找感觉。如此往复,迟早神功可成!

初识 RAG

What 和 Why

RAG 是 Retrieval-Augmented Generation 的缩写,意为“检索增强生成”,其核心目的是通过检索外部知识来增强生成模型的能力,减少模型的 hallucination(幻觉)。

How

最简单的 RAG 的工作流程如下:

  1. 根据用户的输入查询外部知识库或文档。
  2. 将结果与系统 prompt 模版合并,生成最终的系统 prompt。以我之前写的 TSW 插件为例,其生成函数如下。其中的 context 为 1 的结果。
const pageRagPrompt = (context: string) => {
  return `
  You are a helpful assistant and can do the following tasks:
  1. answering users's question based on the given context.
  2. finding relevant information based on the input.

  Workflow:
  1. try to answer the question based on the context.
  2. if the context is not sufficient, ask the user if he/she wants to search on web.
  3. if the user agrees, search the web and provide the answer. Don't try to answer the question without searching.

  Try to keep the answer concise and relevant to the context without providing unnecessary information and explanations.
  If you don't know how answer, just respond "I could not find the answer based on the context you provided."

  Page Context:
  ${context}
  `;
};
  1. 将最终系统 prompt 和用户输入一并传给 LLM 模型,生成最终的响应。

但是,以上流程只挑明了 RAG 的一半,即 querying 阶段。对于另一半,即知识库的如何建立却只字未提。

RAG 应用的一般性架构和关键组件

下图较好地展示了 RAG 的架构和关键组件,并且清晰地划分了 indexing (左侧)和 querying (右侧)两个阶段。

RAG 架构 【来源:Best Practices in Retrieval Augmented Generation

...
付费内容

本文是付费文章

以上是此文章的预览内容

数字产品一经出售,概不退款