外观
大型语言模型(LLM)功能强大,但它们有两个关键限制:
- 有限的上下文:它们无法一次性摄入整个语料库。
- 静态知识:它们的训练数据被冻结在某个时间点。
检索通过在查询时获取相关的外部知识来解决这些问题。这是**检索增强生成(RAG)**的基础,用上下文相关的信息增强 LLM 的答案。
构建知识库
知识库是检索过程中使用的文档或结构化数据的存储库。
如果你需要自定义知识库,可以使用 LangChain 的文档加载器和向量数据库从你自己的数据构建一个。
INFO
如果你已经有一个知识库(例如 SQL 数据库、文档数据库、CRM 或内部文档系统),你不需要重建它。你可以:
- 将其作为智能体在智能体式 RAG(Agentic RAG)中的工具进行连接。
- 查询它,并将检索到的内容作为上下文提供给 LLM (2 步 RAG)。
有关更多信息,请参阅以下教程,以构建可搜索的知识库和最小 RAG 工作流:
- 教程:语义搜索 — 了解如何使用 LangChain 的文档加载器、嵌入和向量数据库从你自己的数据创建可搜索的知识库。 在本教程中,你将在 PDF 之上构建一个搜索引擎,从而能够检索与查询相关的段落。你还将在此引擎之上实现一个最小 RAG 工作流,以了解外部知识如何集成到 LLM 推理中。
从检索到 RAG
检索允许 LLM 在运行时访问相关上下文。但大多数实际应用程序更进一步:它们将检索与生成相结合,以产生基于来源、上下文感知的答案。
这是**检索增强生成(RAG)**背后的核心理念。检索流水线成为将搜索与生成相结合的更广泛系统的基础。
检索流水线
典型的检索工作流如下所示:
mermaid
%%{init: {'flowchart': {'nodeSpacing': 12, 'rankSpacing': 18, 'padding': 4}, 'themeVariables': {'fontSize': '12px'}}}%%
flowchart TB
subgraph ingest[" "]
direction LR
S(["Sources (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每个组件都是模块化的:你可以在不重写应用程序逻辑的情况下更换加载器、拆分器、嵌入或向量数据库。
构建模块
文档加载器 — 从外部来源(Google Drive、Slack、Notion 等)摄取数据,返回标准化的
Document对象。文本拆分器 — 将大型文档拆分为更小的文本块,这些文本块可以单独检索,并能放入模型的上下文窗口。
嵌入模型 — 嵌入模型将文本转换为数字向量,使含义相似的文本在该向量空间中彼此靠近。
向量数据库 — 用于存储和搜索嵌入的专门数据库。
检索器 — 检索器是一个接口,给定非结构化查询,它返回文档。
RAG 架构
根据你的系统需求,RAG 可以有多种实现方式。我们在下面的章节中概述每种类型。
| 架构 | 描述 | 控制力 | 灵活性 | 延迟 | 示例用例 |
|---|---|---|---|---|---|
| 2 步 RAG | 检索总是在生成之前进行。简单且可预测 | ✅ 高 | ❌ 低 | ⚡ 快 | 常见问题解答、文档机器人 |
| 智能体式 RAG | 由 LLM 驱动的智能体在推理过程中决定何时以及如何检索 | ❌ 低 | ✅ 高 | ⏳ 多变 | 可访问多个工具的研究助手 |
| 混合 | 结合了两种方法的特征,并带有验证步骤 | ⚖️ 中等 | ⚖️ 中等 | ⏳ 多变 | 带有质量验证的特定领域问答 |
INFO
延迟:在 2 步 RAG 中,延迟通常更可预测,因为 LLM 调用的最大次数是已知且有上限的。这种可预测性假设 LLM 推理时间是主要因素。然而,实际延迟也可能受检索步骤性能的影响,例如 API 响应时间、网络延迟或数据库查询,这些会因所使用的工具和基础设施而异。
2 步 RAG
在 2 步 RAG 中,检索步骤总是在生成步骤之前执行。这种架构简单直接且可预测,适用于许多将检索相关文档作为生成答案的明确前置条件的应用程序。
mermaid
%%{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]
%% 样式
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- 教程:语义搜索 — 使用文档加载器、嵌入和向量数据库构建可搜索的知识库,然后在其上运行最小的先检索后生成 RAG 工作流。
- 教程:评估 RAG 应用程序 — 构建一个简单的先检索后生成 RAG 应用,并使用 LangSmith 衡量答案的正确性、相关性、基于来源的程度和检索质量。
智能体式 RAG
智能体式检索增强生成(RAG)将检索增强生成的优点与基于智能体的推理相结合。智能体(由 LLM 驱动)不是在回答之前检索文档,而是逐步推理,并在交互过程中决定何时以及如何检索信息。
TIP
智能体启用 RAG 行为所需的唯一条件,是能够访问一个或多个可以获取外部知识的工具,例如文档加载器、Web API 或数据库查询。
mermaid
%%{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]
%% 深色模式友好的样式
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 decisionpython
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], # 用于检索的工具
system_prompt=system_prompt,
)typescript
import { tool, createAgent } from "langchain";
const fetchUrl = tool(
(url: string) => {
return `Fetched content from ${url}`;
},
{ name: "fetch_url", description: "Fetch text content from a URL" }
);
const agent = createAgent({
model: "claude-sonnet-4-6",
tools: [fetchUrl],
systemPrompt,
});此示例实现了一个智能体式 RAG 系统,用于帮助用户查询 LangGraph 文档。智能体首先加载列出可用文档 URL 的 llms.txt,然后可以根据用户的问题动态使用 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)
# 我们将获取 llms.txt 的内容,这样可以在不发起 LLM 请求的情况下
# 提前完成。
llms_txt_content = requests.get(LLMS_TXT).text
# 智能体的系统提示词
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)typescript
import { tool, createAgent, HumanMessage } from "langchain";
import * as z from "zod";
const ALLOWED_DOMAINS = ["https://langchain-ai.github.io/"];
const LLMS_TXT = "https://langchain-ai.github.io/langgraph/llms.txt";
const fetchDocumentation = tool(
async (input) => {
if (!ALLOWED_DOMAINS.some((domain) => input.url.startsWith(domain))) {
return `Error: URL not allowed. Must start with one of: ${ALLOWED_DOMAINS.join(", ")}`;
}
const response = await fetch(input.url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
},
{
name: "fetch_documentation",
description: "Fetch and convert documentation from a URL",
schema: z.object({
url: z.string().describe("The URL of the documentation to fetch"),
}),
}
);
const llmsTxtResponse = await fetch(LLMS_TXT);
const llmsTxtContent = await llmsTxtResponse.text();
const systemPrompt = `
You are an expert TypeScript 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:
${llmsTxtContent}
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.
`;
const tools = [fetchDocumentation];
const agent = createAgent({
model: "claude-sonnet-4-6"
tools,
systemPrompt,
name: "Agentic RAG",
});
const response = await agent.invoke({
messages: [
new HumanMessage(
"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."
),
],
});
console.log(response.messages.at(-1)?.content);- 教程:使用 Deep Agents 进行 RAG — 构建一个在查询时检索相关文本块、将其卸载到文件系统并将分析委派给子智能体的文档问答智能体。
混合 RAG
混合 RAG 结合了 2 步 RAG 和智能体式 RAG 的特征。它引入了查询预处理、检索验证和生成后检查等中间步骤。与固定流水线相比,这些系统提供了更大的灵活性,同时保持对执行的一定控制。
典型组件包括:
- 查询增强:修改输入问题以提高检索质量。这可能涉及重写不清晰的查询、生成多个变体,或用附加上下文扩展查询。
- 检索验证:评估检索到的文档是否相关且充分。如果不是,系统可能会优化查询并重新检索。
- 答案验证:检查生成的答案是否准确、完整,并与源内容一致。如果需要,系统可以重新生成或修改答案。
这种架构通常支持这些步骤之间的多次迭代:
mermaid
%%{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这种架构适用于:
- 查询模糊或规定不明确的应用程序
- 需要验证或质量控制步骤的系统
- 涉及多个来源或迭代优化的工作流
- 教程:带自我纠正的智能体式 RAG — 一个将智能体推理与检索和自我纠正相结合的混合 RAG 示例。