Skip to main content
Open on GitHub

检索增强生成 (RAG)

前置条件

概览

检索增强生成(RAG)是一种强大的技术,它通过将语言模型与外部知识库相结合来增强它们的功能。 RAG 解决了模型的一个关键局限性:模型依赖于固定的训练数据集,这可能导致信息过时或不完整。 当收到查询时,RAG 系统首先会在知识库中搜索相关信息。 随后,系统将检索到的信息整合到模型的提示词中。 模型利用提供的上下文来生成对查询的响应。 通过弥合庞大的语言模型与动态、针对性信息检索之间的差距,RAG 是构建更强大、更可靠的 AI 系统的有力技术。

关键概念

Conceptual Overview

(1) 检索系统: 从知识库中检索相关信息。

(2) 添加外部知识:将检索到的信息传递给模型。

检索系统

模型拥有内部知识,这些知识通常是固定的,或者由于训练成本高昂而不常更新。 这限制了它们回答时事问题或提供特定领域知识的能力。 为了解决这个问题,有多种知识注入技术,如微调或继续预训练。 这两者都成本高昂,且通常不适合事实检索。 使用检索系统具有多个优势:

  • 最新信息: RAG 可以访问并利用最新数据,保持回复的时效性。
  • 领域专业知识: 通过领域专用知识库,RAG 可以提供特定领域的回答。
  • 减少幻觉: 将回复基于检索到的事实有助于最小化错误或虚构的信息。
  • 具有成本效益的知识整合:RAG 提供了比昂贵的模型微调更高效的替代方案。
进一步阅读

查看我们的关于检索的概念指南。

添加外部知识

在部署检索系统后,我们需要将该系统的知识传递给模型。 RAG(检索增强生成)流水线通常通过以下步骤实现这一目标:

  • 接收一个输入查询。
  • 使用检索系统根据查询搜索相关信息。
  • 将检索到的信息整合到发送给大语言模型的提示中。
  • 生成一个利用检索到的上下文的响应。

作为一个示例,这里有一个简单的 RAG 工作流,它将信息从 检索器 传递给 聊天模型

from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage

# Define a system prompt that tells the model how to use the retrieved context
system_prompt = """You are an assistant for question-answering tasks.
Use the following pieces of retrieved context to answer the question.
If you don't know the answer, just say that you don't know.
Use three sentences maximum and keep the answer concise.
Context: {context}:"""

# Define a question
question = """What are the main components of an LLM-powered autonomous agent system?"""

# Retrieve relevant documents
docs = retriever.invoke(question)

# Combine the documents into a single string
docs_text = "".join(d.page_content for d in docs)

# Populate the system prompt with the retrieved context
system_prompt_fmt = system_prompt.format(context=docs_text)

# Create a model
model = ChatOpenAI(model="gpt-4o", temperature=0)

# Generate a response
questions = model.invoke([SystemMessage(content=system_prompt_fmt),
HumanMessage(content=question)])
进一步阅读

RAG 是一个拥有众多优化和设计选择的深度领域: