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

(1) 检索系统:从知识库中检索相关信息。
(2) 添加外部知识:将检索到的信息传递给模型。
检索系统
模型具有内部知识,这些知识通常是固定的,或者由于训练成本高,至少不经常更新。 这限制了他们回答有关时事的问题或提供特定领域知识的能力。 为了解决这个问题,有各种知识注入技术,例如微调或持续的预训练。 两者都很昂贵,而且通常不适合事实检索。 使用检索系统具有以下几个优点:
- 最新信息:RAG 可以访问和利用最新数据,使回复保持最新状态。
- 特定领域的专业知识:借助特定领域的知识库,RAG 可以提供特定领域的答案。
- 减少幻觉:将反应建立在检索到的事实中有助于最大限度地减少虚假或虚构的信息。
- 经济高效的知识集成:RAG 为昂贵的模型微调提供了一种更有效的替代方案。
延伸阅读
请参阅我们的 检索概念指南.
添加外部知识
有了检索系统,我们需要将知识从这个系统传递给模型。 RAG 管道通常按照以下步骤实现此目的:
- 接收输入查询。
- 使用检索系统根据查询搜索相关信息。
- 将检索到的信息合并到发送给 LLM 的提示中。
- 生成利用检索到的上下文的响应。
例如,这是一个简单的 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)])