主题
检索
大型语言模型(LLM)功能强大,但有两个关键局限:
- 有限的上下文:它们无法一次摄取整个语料库。
- 静态知识:它们的训练数据冻结在某个时间点。
检索通过在查询时获取相关的外部知识来解决这些问题。这是**检索增强生成(Retrieval-Augmented Generation,RAG)**的基础,用特定于上下文的信息来增强 LLM 的回答。
构建知识库
知识库是检索期间使用的文档或结构化数据的存储库。
如果你需要自定义知识库,可以使用 LangChain 的文档加载器和向量存储,从你自己的数据构建一个。
NOTE
如果你已经拥有知识库(例如 SQL 数据库、文档数据库、CRM 或内部文档系统),你不需要重建它。你可以:
- 在 Agentic RAG 中将其作为智能体的工具连接。
- 查询它,并将检索到的内容作为上下文提供给 LLM (2 步 RAG)。
有关更多信息,请参阅以下教程,构建可搜索的知识库和最小化的 RAG 工作流:
Tutorial: Semantic search
了解如何使用 LangChain 的文档加载器、嵌入和向量存储,从你自己的数据创建可搜索的知识库。 在本教程中,你将针对一个 PDF 构建搜索引擎,从而能够检索与查询相关的段落。你还将在此引擎之上实现一个最小化的 RAG 工作流,以了解如何将外部知识集成到 LLM 推理中。
Learn more →
从检索到 RAG
检索让 LLM 能够在运行时访问相关上下文。但大多数实际应用又向前迈进了一步:它们将检索与生成集成,以产生有依据且具有上下文感知能力的答案。
这就是**检索增强生成(RAG)**背后的核心思想。检索流水线成为将搜索与生成相结合的更广泛系统的基础。
检索流水线
典型的检索工作流如下所示:
%%{init: {'flowchart': {'nodeSpacing': 12, 'rankSpacing': 18, 'padding': 4}, 'themeVariables': {'fontSize': '12px'}}}%%
flowchart TB
subgraph ingest[" "]
direction LR
S(["Sources<br>(Google Drive, Slack, Notion, etc.)"]) --> L[Document Loaders]
L --> A([Documents])
end
A --> B[Split into chunks]
B --> C[Turn into embeddings]
C --> D[(Vector Store)]
Q([User Query]) --> E[Query embedding]
E --> D
D --> F[Retriever]
F --> G[LLM uses retrieved info]
G --> H([Answer])
classDef trigger fill:#F6FFDB,stroke:#6E8900,stroke-width:2px,color:#2E3900
classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:2px,color:#030710
classDef output fill:#EBD0F0,stroke:#885270,stroke-width:2px,color:#441E33
classDef neutral fill:#F2FAFF,stroke:#40668D,stroke-width:2px,color:#2F4B68
class S,Q trigger
class L,B,C,E,F,G process
class D output
class A,H neutral
每个组件都是模块化的:你可以在不重写应用逻辑的情况下替换加载器、拆分器、嵌入或向量存储。
构建模块
Document loaders
从外部来源(Google Drive、Slack、Notion 等)摄取数据,返回标准化的 Document 对象。
Learn more →
Text splitters
将大型文档拆分为更小的文本块,使其可被单独检索并放入模型的上下文窗口。
Learn more →
Embedding models
嵌入模型将文本转换为数字向量,使含义相似的文本在该向量空间中彼此靠近。
Learn more →
Vector stores
用于存储和搜索嵌入的专用数据库。
Learn more →
Retrievers
检索器是一个接口,它根据非结构化查询返回文档。
Learn more →
RAG 架构
RAG 可以通过多种方式实现,具体取决于你的系统需求。我们将在以下各节中概述每种类型。
| 架构 | 描述 | 控制力 | 灵活性 | 延迟 | 示例用例 |
|---|---|---|---|---|---|
| 2 步 RAG | 检索总是在生成之前进行。简单且可预测 | ✅ 高 | ❌ 低 | ⚡ 快 | FAQ、文档机器人 |
| Agentic RAG | 由 LLM 驱动的智能体在推理过程中决定何时以及如何检索 | ❌ 低 | ✅ 高 | ⏳ 可变 | 可访问多个工具的研究助手 |
| 混合式 | 结合两种方法的特征并加入验证步骤 | ⚖️ 中等 | ⚖️ 中等 | ⏳ 可变 | 带质量验证的领域特定 Q&A |
INFO
延迟:在 2 步 RAG 中,延迟通常更可预测,因为 LLM 调用的最大次数是已知且有上限的。这种可预测性假设 LLM 推理时间是主导因素。然而,现实世界中的延迟还可能受到检索步骤性能的影响,例如 API 响应时间、网络延迟或数据库查询,这些会因所使用的工具和基础设施而异。
2 步 RAG
在 2 步 RAG 中,检索步骤总是在生成步骤之前执行。这种架构简单直接且可预测,适合许多将检索相关文档作为生成答案的明确前提的应用。
%%{init: {'flowchart': {'nodeSpacing': 12, 'rankSpacing': 18, 'padding': 4}, 'themeVariables': {'fontSize': '12px'}}}%%
graph TB
A[User Question] --> B["Retrieve Relevant Documents"]
B --> C["Generate Answer"]
C --> D[Return Answer to User]
%% Styling
classDef startend fill:#F6FFDB,stroke:#6E8900,stroke-width:2px,color:#2E3900
classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:1.5px,color:#030710
class A,D startend
class B,C process
Tutorial: Semantic search
使用文档加载器、嵌入和向量存储构建可搜索的知识库,然后在其之上运行一个最小化的先检索后生成的 RAG 工作流。
Learn more →
Tutorial: Evaluate a RAG application
构建一个简单的先检索后生成的 RAG 应用,并使用 LangSmith 衡量答案的正确性、相关性、依据性和检索质量。
Learn more →
Agentic RAG
智能体式检索增强生成(Agentic Retrieval-Augmented Generation,RAG)将检索增强生成的优势与基于智能体的推理相结合。智能体(由 LLM 驱动)不是在回答之前先检索文档,而是在交互过程中逐步推理,并决定何时以及如何检索信息。
TIP
智能体要启用 RAG 行为,唯一需要的是能够访问一个或多个可以获取外部知识的工具,例如文档加载器、Web API 或数据库查询。
%%{init: {'flowchart': {'nodeSpacing': 12, 'rankSpacing': 18, 'padding': 4}, 'themeVariables': {'fontSize': '12px'}}}%%
graph TB
A[User Input / Question] --> B["Agent (LLM)"]
B --> C{Need external info?}
C -- Yes --> D["Search using tool(s)"]
D --> H{Enough to answer?}
H -- No --> B
H -- Yes --> I[Generate final answer]
C -- No --> I
I --> J[Return to user]
%% Dark-mode friendly styling
classDef startend fill:#F6FFDB,stroke:#6E8900,stroke-width:2px,color:#2E3900
classDef decision fill:#FDF3FF,stroke:#7E65AE,stroke-width:2px,color:#504B5F
classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:1.5px,color:#030710
class A,J startend
class B,D,I process
class C,H decision
python
import requests
from langchain.tools import tool
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
@tool
def fetch_url(url: str) -> str:
"""Fetch text content from a URL"""
response = requests.get(url, timeout=10.0)
response.raise_for_status()
return response.text
system_prompt = """\
Use fetch_url when you need to fetch information from a web-page; quote relevant snippets.
"""
agent = create_agent(
model="claude-sonnet-4-6",
tools=[fetch_url], # A tool for retrieval
system_prompt=system_prompt,
)扩展示例:用于 LangGraph llms.txt 的 Agentic RAG
本示例实现了一个 Agentic RAG 系统,用于帮助用户查询 LangGraph 文档。智能体首先加载 llms.txt,其中列出了可用的文档 URL,然后可以根据用户的问题动态使用 fetch_documentation 工具来检索并处理相关内容。
python
import requests
from langchain.agents import create_agent
from langchain.messages import HumanMessage
from langchain.tools import tool
from markdownify import markdownify
ALLOWED_DOMAINS = ["https://langchain-ai.github.io/"]
LLMS_TXT = 'https://langchain-ai.github.io/langgraph/llms.txt'
@tool
def fetch_documentation(url: str) -> str:
"""Fetch and convert documentation from a URL"""
if not any(url.startswith(domain) for domain in ALLOWED_DOMAINS):
return (
"Error: URL not allowed. "
f"Must start with one of: {', '.join(ALLOWED_DOMAINS)}"
)
response = requests.get(url, timeout=10.0)
response.raise_for_status()
return markdownify(response.text)
# We will fetch the content of llms.txt, so this can
# be done ahead of time without requiring an LLM request.
llms_txt_content = requests.get(LLMS_TXT).text
# System prompt for the agent
system_prompt = f"""
You are an expert Python developer and technical assistant.
Your primary role is to help users with questions about LangGraph and related tools.
Instructions:
1. If a user asks a question you're unsure about—or one that likely involves API usage,
behavior, or configuration—you MUST use the `fetch_documentation` tool to consult the relevant docs.
2. When citing documentation, summarize clearly and include relevant context from the content.
3. Do not use any URLs outside of the allowed domain.
4. If a documentation fetch fails, tell the user and proceed with your best expert understanding.
You can access official documentation from the following approved sources:
{llms_txt_content}
You MUST consult the documentation to get up to date documentation
before answering a user's question about LangGraph.
Your answers should be clear, concise, and technically accurate.
"""
tools = [fetch_documentation]
model = init_chat_model("claude-sonnet-4-6", max_tokens=32_000)
agent = create_agent(
model=model,
tools=tools,
system_prompt=system_prompt,
name="Agentic RAG",
)
response = agent.invoke({
'messages': [
HumanMessage(content=(
"Write a short example of a langgraph agent using the "
"prebuilt create react agent. the agent should be able "
"to look up stock pricing information."
))
]
})
print(response['messages'][-1].content)Tutorial: RAG with Deep Agents
构建一个文档问答智能体,它在查询时检索相关文本块,将它们卸载到文件系统,并把分析委派给子智能体。
Learn more →
混合式 RAG
混合式 RAG 结合了 2 步 RAG 和 Agentic RAG 两者的特征。它引入了诸如查询预处理、检索验证和生成后检查等中间步骤。这类系统比固定流水线提供更多灵活性,同时对执行保持一定的控制。
典型组件包括:
- 查询增强:修改输入问题以提高检索质量。这可能涉及重写不清晰的查询、生成多个变体,或用额外上下文扩展查询。
- 检索验证:评估检索到的文档是否相关且充分。如果不充分,系统可能会优化查询并重新检索。
- 答案验证:检查生成的答案的准确性、完整性以及与源内容的一致性。如有需要,系统可以重新生成或修订答案。
这种架构通常支持在这些步骤之间进行多次迭代:
%%{init: {'flowchart': {'nodeSpacing': 12, 'rankSpacing': 18, 'padding': 4}, 'themeVariables': {'fontSize': '12px'}}}%%
graph TB
A[User Question] --> B[Query Enhancement]
B --> C[Retrieve Documents]
C --> D{Sufficient Info?}
D -- No --> E[Refine Query]
E --> C
D -- Yes --> F[Generate Answer]
F --> G{Answer Quality OK?}
G -- No --> H{Try Different Approach?}
H -- Yes --> E
H -- No --> I[Return Best Answer]
G -- Yes --> I
I --> J[Return to User]
classDef startend fill:#F6FFDB,stroke:#6E8900,stroke-width:2px,color:#2E3900
classDef decision fill:#FDF3FF,stroke:#7E65AE,stroke-width:2px,color:#504B5F
classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:1.5px,color:#030710
class A,J startend
class B,C,E,F,I process
class D,G,H decision
这种架构适用于:
- 查询含糊或不明确的应用
- 需要验证或质量控制步骤的系统
- 涉及多个来源或迭代优化的流程
Tutorial: Agentic RAG with Self-Correction
一个结合智能体推理、检索与自我纠正的 混合式 RAG 示例。
Learn more →