🧠 图解记忆: 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 的区别:
| 维度 | LlamaIndex | LangChain |
|---|---|---|
| 定位 | 专注于 RAG | 通用 AI 应用框架 |
| 索引 | 丰富(向量、关键词、层次) | 主要是向量 |
| 查询 | 灵活(多阶段查询) | 相对简单 |
| 生态 | 较小 | 更大 |
面试话术:
示例表达(仅在能用本人经历或可复现实验佐证时使用): "LlamaIndex 专注于 RAG,索引和查询更灵活;LangChain 是通用框架,生态更大。我在项目中用 LlamaIndex 做 RAG,因为它支持多阶段查询(先检索摘要,再检索具体段落),检索精度更高。"
