跳到主要內容
Open on GitHub

檢索增強生成(RAG)

先決條件

概觀

檢索增強生成(RAG)是一種強大的技術,透過將語言模型與外部知識庫結合,來增強語言模型的功能。RAG 解決了模型的一個主要限制:模型依賴固定的訓練資料集,這可能導致資訊過時或不完整。當收到查詢時,RAG 系統首先在知識庫中搜尋相關資訊。然後,系統將檢索到的資訊納入模型的提示中。模型使用提供的上下文來產生對查詢的回應。透過彌合龐大的語言模型和動態、目標明確的資訊檢索之間的差距,RAG 是一種強大的技術,可用於建構更強大且更可靠的 AI 系統。

主要概念

Conceptual Overview

(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)])
延伸閱讀

RAG 是一個深入的領域,具有許多可能的最佳化和設計選擇


此頁面是否對您有幫助?