Skip to content
🔗 分享本题
查看我的学习进度 →

LlamaIndex 从文档切块、索引、检索到回答的 RAG 流程及其与 LangChain 的定位差异

🧠 图解记忆: LlamaIndex 擅长让数据可检索,LangChain 擅长把能力编成流程。

💡 答案要点

LlamaIndex 核心概念:

概念作用对应 LangChain
Document文档对象Document
Node文档节点(Chunk)Document
Index索引结构VectorStore
QueryEngine查询引擎Retriever + Chain

LlamaIndex 构建 RAG:

python
from llama_index.core import (
    VectorStoreIndex,
    SimpleDirectoryReader,
    Settings
)
from llama_index.llms.openai import OpenAI

# 1. 设置 LLM
Settings.llm = OpenAI(model="gpt-4o")

# 2. 加载文档
documents = SimpleDirectoryReader("./docs").load_data()

# 3. 创建索引
index = VectorStoreIndex.from_documents(documents)

# 4. 创建查询引擎
query_engine = index.as_query_engine(
    similarity_top_k=5,
    response_mode="compact"
)

# 5. 查询
response = query_engine.query("什么是 RAG?")
print(response)

和 LangChain 的区别:

维度LlamaIndexLangChain
定位专注于 RAG通用 AI 应用框架
索引丰富(向量、关键词、层次)主要是向量
查询灵活(多阶段查询)相对简单
生态较小更大

面试话术:

示例表达(仅在能用本人经历或可复现实验佐证时使用): "LlamaIndex 专注于 RAG,索引和查询更灵活;LangChain 是通用框架,生态更大。我在项目中用 LlamaIndex 做 RAG,因为它支持多阶段查询(先检索摘要,再检索具体段落),检索精度更高。"

📚 参考:LlamaIndex 官方文档(RAG 数据框架)