> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/dui-bi/rag-frameworks-comparison.md).

# RAG 框架对比

为你的 Clore.ai GPU 服务器项目选择合适的检索增强生成（RAG）框架。

{% hint style="info" %}
**RAG（检索增强生成）** 让 LLM 使用你自己的文档来回答问题。本指南对四个领先框架进行了比较：LangChain、LlamaIndex、Haystack 和 RAGFlow——涵盖功能、性能以及各自的适用场景。
{% endhint %}

***

## 快速决策矩阵

|               | LangChain | LlamaIndex | Haystack   | RAGFlow    |
| ------------- | --------- | ---------- | ---------- | ---------- |
| **最适合**       | 通用 LLM 应用 | 文档问答       | 企业搜索       | 自托管 RAG    |
| **学习曲线**      | 中等        | 低-中        | 中-高        | 低          |
| **灵活性**       | 非常高       | 高          | 高          | 中等         |
| **内置 UI**     | 否         | 否          | 否          | 是          |
| **GitHub 星标** | 9万+       | 3.5万+      | 15K+       | 12K+       |
| **语言**        | Python    | Python     | Python     | Python     |
| **许可证**       | MIT       | MIT        | Apache 2.0 | Apache 2.0 |

***

## 概览

### LangChain

LangChain 是最受欢迎的 LLM 编排框架。它为链、代理、记忆和 RAG 流水线提供统一接口。

**理念**：一切都是可组合组件的链。

```python
from langchain.chains import RetrievalQA
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
from langchain.llms import OpenAI

# 用 5 行构建 RAG 流水线
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(docs, embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
chain = RetrievalQA.from_chain_type(llm=OpenAI(), retriever=retriever)
result = chain.run("法国的首都是哪里？")
```

### LlamaIndex

LlamaIndex（前身为 GPT Index）专为文档索引和检索而设计。它在将 LLM 连接到多样化数据源方面表现出色。

**理念**：先索引，再智能查询。

```python
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# 加载并索引文档
documents = SimpleDirectoryReader("data/").load_data()
index = VectorStoreIndex.from_documents(documents)

# 查询
query_engine = index.as_query_engine()
response = query_engine.query("总结主要发现")
打印(response)
```

### Haystack

Haystack（由 deepset 开发）是一个面向企业级的 NLP 框架，专注于搜索和问答流水线。它采用基于组件的架构，并提供可视化流水线构建器。

**理念**：模块化流水线，具备企业级可靠性。

```python
from haystack.nodes import DensePassageRetriever, FARMReader
from haystack.pipelines import ExtractiveQAPipeline

retriever = DensePassageRetriever(document_store=document_store)
reader = FARMReader(model_name_or_path="deepset/roberta-base-squad2")
pipeline = ExtractiveQAPipeline(reader, retriever)
result = pipeline.run(query="什么是机器学习？", params={"Retriever": {"top_k": 10}})
```

### RAGFlow

RAGFlow 是一个开源 RAG 引擎，内置 Web UI、文档解析和知识库管理。它旨在作为完整解决方案进行部署。

**理念**：开箱即用的 RAG 系统，无需编码。

```yaml
# RAGFlow 通过 Docker Compose 部署
# 通过 localhost:80 的 Web UI 进行配置
version: "3"
services:
  ragflow:
    image: infiniflow/ragflow:latest
    ports:
      - "80:80"
    volumes:
      - ./ragflow-data:/ragflow/data
```

***

## 功能对比

### RAG 核心功能

| 功能     | LangChain | LlamaIndex | Haystack | RAGFlow |
| ------ | --------- | ---------- | -------- | ------- |
| 向量存储支持 | 50+       | 30+        | 20+      | 内置      |
| 文档加载器  | 100+      | 50+        | 30+      | 内置      |
| 混合搜索   | ✅         | ✅          | ✅        | ✅       |
| 重排序    | ✅         | ✅          | ✅        | ✅       |
| 多模态    | ✅         | ✅          | 部分       | ✅       |
| 流式输出   | ✅         | ✅          | ✅        | ✅       |
| 异步支持   | ✅         | ✅          | ✅        | ✅       |
| 代理     | ✅         | ✅          | ✅        | ❌       |

### 集成生态

| 集成类型    | LangChain                                 | LlamaIndex                         | Haystack                         | RAGFlow                |
| ------- | ----------------------------------------- | ---------------------------------- | -------------------------------- | ---------------------- |
| LLM 提供商 | 50+                                       | 30+                                | 20+                              | 10+                    |
| 向量数据库   | Chroma、Pinecone、Weaviate、Qdrant，以及 40+ 其他 | Chroma、Pinecone、Weaviate，以及 25+ 其他 | Weaviate、Elasticsearch，以及 15+ 其他 | 内置 InfiniFlow          |
| 文档类型    | PDF、Web、CSV、JSON、80+                      | PDF、Web、CSV、数据库、40+                | PDF、TXT、HTML、20+                 | PDF、Word、Excel、PPT、Web |
| 云存储     | S3、GCS、Azure                              | S3、GCS、Azure                       | S3、GCS                           | S3                     |

### 高级 RAG 功能

| 功能            | LangChain | LlamaIndex       | Haystack | RAGFlow |
| ------------- | --------- | ---------------- | -------- | ------- |
| 查询分解          | ✅         | ✅                | ✅        | ✅       |
| HyDE（假设性文档嵌入） | ✅         | ✅                | ❌        | ❌       |
| 多跳检索          | ✅         | ✅                | 部分       | ✅       |
| 上下文压缩         | ✅         | ✅                | ✅        | ✅       |
| Self-RAG      | ✅         | ✅                | ❌        | ❌       |
| GraphRAG      | ✅         | ✅（PropertyGraph） | ❌        | ✅       |
| 引用追踪          | 部分        | ✅                | 部分       | ✅       |

***

## 性能基准

### 检索准确率（RAG-Bench，2024）

{% hint style="info" %}
不同数据集和配置下，基准差异很大。以下为社区基准测试中的近似数值。
{% endhint %}

| 框架              | HotpotQA（F1） | Natural Questions（EM） | TriviaQA（准确率） |
| --------------- | ------------ | --------------------- | ------------- |
| LangChain（RAG）  | \~68%        | \~42%                 | \~72%         |
| LlamaIndex（RAG） | \~71%        | \~45%                 | \~74%         |
| Haystack（RAG）   | \~69%        | \~43%                 | \~71%         |
| RAGFlow（默认）     | \~65%        | \~40%                 | \~68%         |

*结果在很大程度上取决于所选 LLM、嵌入模型和分块大小*

### 索引速度（1 万份文档，每份约 1KB）

| 框架         | 仅 CPU   | GPU 嵌入 |
| ---------- | ------- | ------ |
| LangChain  | \~120 秒 | \~18 秒 |
| LlamaIndex | \~110 秒 | \~15 秒 |
| Haystack   | \~130 秒 | \~20 秒 |
| RAGFlow    | \~150 秒 | 约 25 秒 |

*使用与 text-embedding-ada-002 等效的模型（1536 维）*

### 查询延迟（P50/P99，使用预构建索引）

| 框架         | P50   | P99   | 备注           |
| ---------- | ----- | ----- | ------------ |
| LangChain  | 450毫秒 | 1.2秒  | 无重排序         |
| LlamaIndex | 400毫秒 | 1.0 秒 | 无重排序         |
| Haystack   | 500毫秒 | 1.5 秒 | 含流水线开销       |
| RAGFlow    | 600毫秒 | 2.0 秒 | 包含 UI/API 开销 |

***

## LangChain：深度解析

### 优势

✅ **最大的生态系统** — 50+ 集成，庞大社区\
✅ **代理和工具** — 构建自主 AI 代理\
✅ **LangSmith** — 极佳的可观测性和调试能力\
✅ **LCEL** — 用于组合链的 LangChain 表达式语言\
✅ **记忆系统** — 对话历史、实体记忆

### 弱点

❌ **复杂性** — 对于简单任务来说可能过度设计\
❌ **频繁的破坏性变更** — v0.1、v0.2、v0.3 迁移\
❌ **依赖较重** — 安装体积较大\
❌ **抽象泄漏** — 有时更难调试

### 最佳使用场景

* 具有复杂逻辑的多步骤 LLM 流水线
* 使用工具的 AI 代理（网页搜索、代码执行、API）
* 需要对话记忆的应用
* 需要最大灵活性的项目

### 示例：带来源的高级 RAG

```python
from langchain.chains import RetrievalQAWithSourcesChain
from langchain_community.vectorstores import Chroma
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter

# 设置
llm = ChatOpenAI(model="gpt-4", temperature=0)
embeddings = OpenAIEmbeddings()

# 使用元数据索引文档
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chunks = splitter.split_documents(documents)

vectorstore = Chroma.from_documents(
    chunks, 
    embeddings,
    persist_directory="./chroma_db"
)

# 构建带来源归属的链
chain = RetrievalQAWithSourcesChain.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=vectorstore.as_retriever(search_kwargs={"k": 5}),
    return_source_documents=True
)

result = chain({"question": "主要风险是什么？"})
print(result["answer"])
print("来源：", result["sources"])
```

***

## LlamaIndex：深度解析

### 优势

✅ **以文档为先的设计** — 最适合复杂文档索引\
✅ **索引类型** — 向量、知识图谱、SQL、关键词\
✅ **子问题引擎** — 自动分解复杂查询\
✅ **结构化输出** — Pydantic 集成\
✅ **路由查询引擎** — 智能路由到正确的索引

### 弱点

❌ **比 LangChain** 更少偏向代理\
❌ **更小的生态系统** 更少偏向代理\
❌ **文档** 可能不够一致

### 最佳使用场景

* 文档问答系统（PDF、报告、Wiki）
* 复杂的多文档推理
* 知识图谱构建
* 数据到 LLM 的桥接（数据库、API）

### 示例：多文档查询引擎

```python
from llama_index.core import (
    VectorStoreIndex, 
    SimpleDirectoryReader,
    StorageContext,
    Settings
)
from llama_index.core.query_engine import RouterQueryEngine
from llama_index.core.tools import QueryEngineTool
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding

# 全局配置
Settings.llm = OpenAI(model="gpt-4")
Settings.embed_model = OpenAIEmbedding()

# 为不同文档集创建独立索引
annual_reports = SimpleDirectoryReader("./annual_reports").load_data()
tech_docs = SimpleDirectoryReader("./tech_docs").load_data()

index_reports = VectorStoreIndex.from_documents(annual_reports)
index_tech = VectorStoreIndex.from_documents(tech_docs)

# 构建选择正确索引的路由器
tools = [
    QueryEngineTool.from_defaults(
        query_engine=index_reports.as_query_engine(),
        description="年度财务报告和业务指标"
    ),
    QueryEngineTool.from_defaults(
        query_engine=index_tech.as_query_engine(),
        description="技术文档和 API 参考"
    )
]

router = RouterQueryEngine.from_defaults(query_engine_tools=tools)
response = router.query("去年的收入增长是多少？")
```

***

## Haystack：深度解析

### 优势

✅ **企业级** — 生产级可靠性\
✅ **可视化流水线构建器** — Haystack Studio\
✅ **标注工具** — 内置标注 UI\
✅ **强大的 NLP** — 抽取式问答、摘要\
✅ **deepset Cloud** — 托管部署选项

### 弱点

❌ **学习曲线更陡峭** 比竞争对手\
❌ **社区更小** 比 LangChain/LlamaIndex\
❌ **灵活性较低** 用于新颖架构

### 最佳使用场景

* 企业文档搜索和问答
* 需要审计轨迹和可观测性的项目
* 希望使用可视化流水线设计的团队
* 满足 SLA 要求的生产部署

### 示例：混合搜索流水线

```python
from haystack import Pipeline
from haystack.components.retrievers import InMemoryBM25Retriever, InMemoryEmbeddingRetriever
from haystack.components.joiners import DocumentJoiner
from haystack.components.rankers import MetaFieldRanker
from haystack.components.generators import OpenAIGenerator
from haystack.components.builders import RAGPromptBuilder

# 构建混合搜索流水线
pipeline = Pipeline()
pipeline.add_component("bm25_retriever", InMemoryBM25Retriever(document_store=store, top_k=10))
pipeline.add_component("embedding_retriever", InMemoryEmbeddingRetriever(document_store=store, top_k=10))
pipeline.add_component("joiner", DocumentJoiner(join_mode="reciprocal_rank_fusion"))
pipeline.add_component("ranker", MetaFieldRanker(meta_field="score"))
pipeline.add_component("prompt_builder", RAGPromptBuilder())
pipeline.add_component("llm", OpenAIGenerator(model="gpt-4"))

# 连接组件
pipeline.connect("bm25_retriever", "joiner.documents")
pipeline.connect("embedding_retriever", "joiner.documents")
pipeline.connect("joiner", "ranker")
pipeline.connect("ranker", "prompt_builder.documents")
pipeline.connect("prompt_builder", "llm")

result = pipeline.run({"bm25_retriever": {"query": "深度学习"}, 
                       "embedding_retriever": {"query": "深度学习"}})
```

***

## RAGFlow：深度解析

### 优势

✅ **零代码部署** — 包含完整 UI\
✅ **高级文档解析** — 表格、图片、图表\
✅ **知识库管理** — 可视化界面\
✅ **包含 API** — 开箱即用的 REST API\
✅ **Agentic RAG** — 内置代理

### 弱点

❌ **可定制性较低** 相比代码优先框架\
❌ **资源需求高** （Elasticsearch + Infinity DB）\
❌ **LLM 支持有限** 相比 LangChain\
❌ **较新的项目** — 社区较小

### 最佳使用场景

* 不懂开发、但需要无需编码 RAG 的人
* 希望获得完整知识库产品的团队
* 内部企业 Wiki 和文档搜索
* RAG 应用的快速原型开发

### 在 Clore.ai 上部署

```yaml
# RAGFlow 的 docker-compose.yml
version: "3"
services:
  ragflow:
    image: infiniflow/ragflow:v0.12.0
    container_name: ragflow
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./ragflow-logs:/ragflow/logs
      - ./ragflow-data:/ragflow/data
    depends_on:
      - elasticsearch
      - infinity

  elasticsearch:
    image: elasticsearch:8.11.3
    environment:
      - discovery.type=single-node
      - ES_JAVA_OPTS=-Xms1g -Xmx1g
      - xpack.security.enabled=false
    volumes:
      - es_data:/usr/share/elasticsearch/data

  infinity:
    image: infiniflow/infinity:v0.3.0
    volumes:
      - infinity_data:/var/infinity

volumes:
  es_data:
  infinity_data:
```

```bash
docker compose up -d
# 通过 http://<server-ip>:80 访问 Web UI
```

***

## 何时使用哪一个

### 选择 LangChain 如果：

* 正在构建带工具的 AI 代理（网页搜索、代码执行、API）
* 需要最大的生态系统灵活性
* 正在构建复杂的多步骤流水线
* 需要与许多不同的 LLM 和数据源集成
* 团队熟悉 Python

### 选择 LlamaIndex 如果：

* 主要用例是文档问答
* 处理复杂的文档结构（表格、嵌套内容）
* 需要知识图谱或多索引路由
* 希望拥有一流的文档摄取能力
* 基于结构化数据（数据库、API）构建

### 如果符合以下情况，选择 Haystack：

* 具有合规要求的企业环境
* 需要可视化流水线构建工具
* 基于 Elasticsearch 之上构建
* 想要抽取式（不只是生成式）问答
* 团队需要 NLP 流水线可观测性

### 如果符合以下情况，选择 RAGFlow：

* 非技术团队需要自助式 RAG
* 想要一个完整产品，而不是框架
* 快速部署比自定义更重要
* 构建内部知识库
* 不想编写 Python 代码

***

## 在 Clore.ai 上运行：资源需求

| 框架         | 最低 RAM    | 最低显存        | 推荐 GPU       |
| ---------- | --------- | ----------- | ------------ |
| LangChain  | 8GB       | 8GB（本地 LLM） | RTX 3080     |
| LlamaIndex | 8GB       | 8GB（本地 LLM） | RTX 3080     |
| Haystack   | 16GB      | 8GB（本地 LLM） | RTX 3090     |
| RAGFlow    | 32GB（内存！） | 16GB        | A6000 / A100 |

{% hint style="warning" %}
**RAGFlow 需要更多内存**: 它运行 Elasticsearch + InfinityDB + 应用本身。至少预留 32GB 系统内存。使用 Elasticsearch 的 Haystack 也会受益于 16GB+ 内存。
{% endhint %}

***

## 有用链接

* [LangChain 文档](https://python.langchain.com)
* [LlamaIndex 文档](https://docs.llamaindex.ai)
* [Haystack 文档](https://docs.haystack.deepset.ai)
* [RAGFlow GitHub](https://github.com/infiniflow/ragflow)
* [RAG 调研论文（arXiv）](https://arxiv.org/abs/2312.10997)

***

## 总结建议

```
简单文档问答          → LlamaIndex
复杂 AI 智能体            → LangChain
企业搜索            → Haystack
无代码 RAG 产品          → RAGFlow
最大灵活性          → LangChain
最佳文档理解  → LlamaIndex
```

这四个框架都是很好的选择——合适的选择取决于你的具体需求、团队技能和部署限制。若有疑问，先从 **LlamaIndex** 用于文档密集型用例，或 **LangChain** 如果你需要尽可能广泛的生态系统。

***

## Clore.ai GPU 推荐

| 使用场景  | 推荐 GPU         | Clore.ai 预计成本                     |
| ----- | -------------- | --------------------------------- |
| 开发/测试 | RTX 3090（24GB） | $0.07–0.21/gpu/hr                 |
| 生产环境  | RTX 4090（24GB） | $0.14–0.42/gpu/hr                 |
| 大规模   | A100 80GB      | [裸机](https://clore.ai/bare-metal) |

> 💡 本指南中的所有示例都可以部署在 [Clore.ai](https://clore.ai/marketplace) GPU 服务器上。浏览可用 GPU 并按小时租用——无需承诺，拥有完整 root 访问权限。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/dui-bi/rag-frameworks-comparison.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
