Skip to content

检索(Retrieval) ​

大语言模型(LLM)功能强大,但它们存在两个核心局限性:

  • 有限的上下文(Finite context):它们无法一次性摄取整个语料库。
  • 静态的知识(Static knowledge):它们的训练数据冻结在某个时间点。

检索通过在查询时获取相关的外部知识来解决这些问题。这是检索增强生成(Retrieval-Augmented Generation,RAG)的基础,它通过与上下文相关的信息来增强 LLM 的回答。

构建知识库 ​

知识库(knowledge base)是一个文档或结构化数据的存储库,用于在检索过程中提供数据。

如果你需要一个自定义知识库,可以使用 LangChain 的文档加载器(document loaders)和向量存储(vector stores)基于你自己的数据构建一个。

NOTE

如果你已经拥有一个知识库(例如 SQL 数据库、文档数据库、CRM 或内部文档系统),你不需要重建它。你可以:

  • 在 Agentic RAG 中将其作为工具(tool)连接给智能体。
  • 对其进行查询,并将检索到的内容作为上下文提供给 LLM (两步式 RAG)。

有关更多信息,请参阅以下教程以构建可搜索的知识库和最小化 RAG 工作流:

教程:语义搜索

了解如何使用 LangChain 的文档加载器、嵌入模型和向量存储从你自己的数据创建可搜索的知识库。 在本教程中,你将基于 PDF 构建一个搜索引擎,从而能够检索与查询相关的段落。你还将在该引擎之上实现一个最小化的 RAG 工作流,了解如何将外部知识整合到 LLM 推理中。

从检索到 RAG ​

检索允许 LLM 在运行时访问相关上下文。但大多数实际应用更进一步:它们将检索与生成相结合,以产生有事实依据、具备上下文感知能力的回答。

这是检索增强生成(Retrieval-Augmented Generation,RAG)背后的核心思想。检索流水线成为了将搜索与生成相结合的更广泛系统的基石。

检索流水线 ​

一个典型的检索工作流如下所示:

actions={true}
mermaid
%%{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 对象。

嵌入模型(Embedding models)

嵌入模型将文本转换为数字向量,使得具有相似含义的文本在该向量空间中距离相近。

向量存储(Vector stores)

用于存储和搜索嵌入向量的专用数据库。

检索器(Retrievers)

检索器是一个根据非结构化查询返回文档的接口。

RAG 架构 ​

根据你的系统需求,RAG 可以通过多种方式实现。我们在以下各节中概述了每种类型。

架构描述控制度灵活性延迟示例用例
两步式 RAG (2-Step RAG)检索始终发生在生成之前。简单且可预测✅ 高❌ 低⚡ 快速常见问题解答(FAQ)、文档机器人
Agentic RAG由 LLM 驱动的智能体在推理过程中决定何时以及如何进行检索❌ 低✅ 高⏳ 可变可访问多种工具的研究助手
混合式 (Hybrid)结合两种方法的特性,并带有验证步骤⚖️ 中等⚖️ 中等⏳ 可变具备质量验证的特定领域问答(Q&A)

NOTE

延迟(Latency):在两步式 RAG(2-Step RAG)中,延迟通常更加可预测,因为 LLM 调用的最大次数是已知且有上限的。这种可预测性建立在 LLM 推理时间占主导地位的假设之上。然而,实际延迟还可能受到检索步骤性能的影响,例如 API 响应时间、网络延迟或数据库查询,这些因素会根据所使用的工具和基础设施而有所不同。

两步式 RAG(2-step RAG) ​

在两步式 RAG(2-Step RAG)中,检索步骤始终在生成步骤之前执行。这种架构简单直接且可预测,非常适合许多将检索相关文档作为生成答案的明确先决条件的应用场景。

actions={true}
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]

    %% 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

教程:语义搜索

使用文档加载器、嵌入模型和向量存储构建可搜索的知识库,然后在此之上运行一个最小化的“先检索后生成”RAG 工作流。

教程:评估 RAG 应用程序

构建一个简单的“先检索后生成”RAG 应用,并使用 LangSmith 评估回答的正确性、相关性、事实依据和检索质量。

Agentic RAG ​

Agentic 检索增强生成(Agentic RAG)将检索增强生成的优势与基于智能体的推理相结合。智能体(由 LLM 驱动)不是在回答之前就预先检索文档,而是一步步进行推理,并在交互过程中自主决定何时以及如何检索信息。

TIP

智能体启用 RAG 行为唯一需要的就是访问一个或多个能够获取外部知识的工具(tools),例如文档加载器、Web API 或数据库查询。

actions={true}
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]

    %% 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
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,
});

扩展示例:针对 LangGraph llms.txt 的 Agentic RAG

该示例实现了一个 Agentic RAG 系统,用于协助用户查询 LangGraph 文档。智能体首先加载 llms.txt(其中列出了可用的文档 URL),然后可以根据用户的问题动态使用 fetch_documentation 工具检索并处理相关内容。

typescript
import { tool, createAgent, HumanMessage } from "langchain";
import * as z from "zod";

const ALLOWED_DOMAINS = ["https://docs.langchain.com/"];
const LLMS_TXT = "https://docs.langchain.com/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

构建一个文档问答(Q&A)智能体,它在查询时检索相关分块,将它们卸载到文件系统中,并将分析任务委派给子智能体。

混合式 RAG(Hybrid RAG) ​

混合式 RAG(Hybrid RAG)结合了 2 步式 RAG 和 Agentic RAG 两者的特性。它引入了查询预处理、检索验证和生成后检查等中间步骤。与固定流水线相比,这些系统提供了更高的灵活性,同时保持对执行过程的一定控制。

典型组件包括:

  • 查询增强(Query enhancement):修改输入的提问以提高检索质量。这可以包括重写不清晰的查询、生成多种变体,或通过补充上下文来扩展查询。
  • 检索验证(Retrieval validation):评估检索到的文档是否相关且充足。如果不足,系统可以优化查询并重新检索。
  • 答案验证(Answer validation):检查生成的答案的准确性、完整性以及与源内容的一致性。如果需要,系统可以重新生成或修订答案。

该架构通常支持在这些步骤之间进行多次迭代:

actions={true}
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

这种架构适用于:

  • 存在歧义或描述不充分查询的应用程序
  • 需要验证或质量控制步骤的系统
  • 涉及多数据源或迭代优化的工作流

教程:具备自我修正的 Agentic RAG

一个将智能体推理与检索及自我修正相结合的混合式 RAG(Hybrid RAG)示例。