Appearance
96. LangChain 和 LlamaIndex 在 Agent 开发中的作用是什么?
难度 P1 高频 · 岗位 应用 · 频率 ★★★ · 预计阅读 16 min
本题阅读地图
- 💡 简要回答
- 📝 详细解析
- 🎯 面试总结
👔面试官:LangChain 和 LlamaIndex 在 Agent 开发中起什么作用?
🙋♂️我:LangChain 是开发 LLM 应用的框架,提供了 Agent、Chain、Memory 等组件。LlamaIndex 主要做数据索引和检索,增强 LLM 的上下文。
👔面试官:两者有什么区别?什么时候用哪个?
🙋♂️我:LangChain 更全面,LlamaIndex 专注检索。做 Agent 用 LangChain,做知识库问答用 LlamaIndex。
👔面试官:LangChain 的 Agent 模块提供了什么功能?Retriever 怎么和 Agent 结合?
好,这道题要对比两大框架在 Agent 开发中的角色。
💡 简要回答
LangChain:LLM 应用开发框架,提供模块化组件(Chains、Agents、Memory、Tools)快速构建 Agent。
LlamaIndex:数据连接和索引框架,将私有数据转换为 LLM 可用的格式,专注 RAG 和检索。
对比:
| 特性 | LangChain | LlamaIndex |
|---|---|---|
| 核心定位 | 通用 LLM 应用框架 | 数据连接和检索 |
| Agent 支持 | 完善(多种 Agent 类型) | 基础(结合检索的 Agent) |
| 检索能力 | 基础 | 强大(多种索引、检索策略) |
| 适用场景 | Agent、工作流 | 知识库、文档问答 |
结合使用:LangChain Agent + LlamaIndex Retriever = 有知识检索能力的 Agent
📝 详细解析
LangChain 核心功能
1. Chains(链)
概念:将多个组件串联的执行流程
示例:
输入 → PromptTemplate → LLM → OutputParser → 输出
代码:
from langchain import PromptTemplate, LLMChain
template = "翻译以下文本为中文:{text}"
prompt = PromptTemplate(template=template, input_variables=["text"])
chain = LLMChain(prompt=prompt, llm=llm)
result = chain.run("Hello world")
进阶:
SequentialChain:多步骤链
RouterChain:条件路由链
TransformChain:数据转换链2. Agents(智能体)
提供的 Agent 类型:
- Zero-shot ReAct:通用 ReAct Agent
- Conversational ReAct:带对话记忆的 ReAct
- Plan-and-Execute:先规划后执行
- Self-Ask with Search:自我提问+搜索
- XML Agent:支持 XML 格式的 Agent
代码示例:
from langchain.agents import initialize_agent, Tool
tools = [
Tool(name="Search", func=search, description="搜索工具"),
Tool(name="Calculator", func=calc, description="计算器")
]
agent = initialize_agent(
tools,
llm,
agent="zero-shot-react-description"
)
agent.run("北京明天天气如何?25乘以48等于多少?")3. Memory(记忆)
提供的 Memory 类型:
- ConversationBufferMemory:保存完整对话
- ConversationBufferWindowMemory:滑动窗口
- ConversationSummaryMemory:摘要记忆
- VectorStoreRetrieverMemory:向量检索记忆
与 Agent 结合:
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
agent = initialize_agent(
tools, llm,
agent="conversational-react-description",
memory=memory
)4. Tools(工具)
内置工具:
- search:搜索工具
- llm-math:数学计算
- python_repl:Python 执行
- terminal:终端命令
自定义工具:
@tool
def my_tool(query: str) -> str:
"""工具描述,LLM 用它判断何时调用"""
return do_something(query)LlamaIndex 核心功能
1. 数据连接(Data Connectors)
支持的数据源:
- 文件:PDF、Word、Markdown、TXT
- 数据库:PostgreSQL、MongoDB、Neo4j
- API:Notion、Slack、Discord
- 云服务:AWS S3、Google Drive
代码:
from llama_index import SimpleDirectoryReader
documents = SimpleDirectoryReader('./data').load_data()2. 索引(Indexing)
索引类型:
- VectorStoreIndex:向量索引(最常用)
- ListIndex:顺序列表
- TreeIndex:树形结构
- KeywordTableIndex:关键词表
- KnowledgeGraphIndex:知识图谱
代码:
from llama_index import VectorStoreIndex
index = VectorStoreIndex.from_documents(documents)3. 检索(Retrieval)
检索策略:
- 相似度检索(默认)
- 关键词检索
- 混合检索
- 路由检索(多索引)
检索器配置:
retriever = index.as_retriever(
similarity_top_k=5,
search_mode="default"
)
nodes = retriever.retrieve("查询内容")4. 查询引擎(Query Engine)
封装检索+合成:
- 检索相关文档片段
- 用 LLM 合成回答
代码:
query_engine = index.as_query_engine()
response = query_engine.query("总结这份文档")
Chat Engine(对话):
chat_engine = index.as_chat_engine()
response = chat_engine.chat("之前说了什么?")结合使用场景
场景:企业知识库 Agent
需求:
- 能回答公司文档相关问题
- 能调用工具执行任务
- 保持对话上下文
架构:
┌─────────────────────────────────────────────┐
│ LangChain Agent │
│ ┌──────────────────────────────────────┐ │
│ │ Tools: │ │
│ │ - search: LlamaIndex Retriever │ │
│ │ - calculator: 计算器 │ │
│ │ - email: 发邮件工具 │ │
│ └──────────────────────────────────────┘ │
│ ┌──────────────────────────────────────┐ │
│ │ Memory: ConversationBufferMemory │ │
│ └──────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ LlamaIndex Index │
│ - VectorStoreIndex (公司文档) │
│ - 文档:产品手册、API文档、内部规范 │
└─────────────────────────────────────────────┘
代码实现:
# 1. LlamaIndex 构建知识库
from llama_index import VectorStoreIndex, SimpleDirectoryReader
docs = SimpleDirectoryReader('./company_docs').load_data()
index = VectorStoreIndex.from_documents(docs)
retriever = index.as_retriever(similarity_top_k=3)
# 2. 包装为 LangChain Tool
from langchain.tools import Tool
search_tool = Tool(
name="CompanyDocSearch",
func=lambda q: str(retriever.retrieve(q)),
description="搜索公司内部文档,回答产品、流程相关问题"
)
# 3. 构建 LangChain Agent
from langchain.agents import initialize_agent
agent = initialize_agent(
[search_tool, calculator_tool, email_tool],
llm,
agent="conversational-react-description",
memory=ConversationBufferMemory()
)
agent.run("查一下产品 X 的定价策略,然后发邮件给销售团队")框架选择建议
选 LangChain 如果:
- 构建复杂 Agent
- 需要多工具协调
- 需要工作流编排
- 需要灵活的 Chain 组合
选 LlamaIndex 如果:
- 主要需求是 RAG
- 复杂的数据索引需求
- 多种数据源整合
- 高级检索策略
两者结合如果:
- 需要既有知识检索又有工具调用的 Agent
- 企业级复杂应用
- 需要最佳的两个功能
🎯 面试总结
这道题容易踩的雷:
只说 LangChain 做 Agent:不知道具体组件。
只说 LlamaIndex 做检索:不知道它也有基础 Agent 功能。
不了解结合使用:不知道两者如何配合。
答题要点:
- 说明 LangChain 的四大组件(Chains、Agents、Memory、Tools)
- 说明 LlamaIndex 的四大功能(连接、索引、检索、查询)
- 对比两者定位差异
- 举例说明结合使用场景
来源参考:LangChain Documentation, LlamaIndex Documentation, Building LLM Applications