从 RAG 到 Agent:LlamaIndex 的范式跃迁
LlamaIndex 在 2023 年以"RAG 框架"闻名——它是构建检索增强生成应用最简单的方式。但创始人 Jerry Liu 很早就意识到:RAG 本质上是 Agent 的一个特例。到 2026 年,LlamaIndex 已经完成了从"RAG 框架"到"数据驱动 Agent 平台"的转型。
2026 架构演进
核心层次
┌──────────────────────────────────────────────────┐
│ Agent Layer │
│ Workflows │ Data Agents │ Multi-Agent │ Tools │
├──────────────────────────────────────────────────┤
│ Orchestration Layer │
│ Query Engine │ Router │ Planner │ Evaluator │
├──────────────────────────────────────────────────┤
│ Data Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ Ingestion│ │ Indexing │ │ Retrieval │ │
│ │ Pipeline │ │ (多索引) │ │ (混合检索) │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │
├──────────────────────────────────────────────────┤
│ Integration Layer │
│ 50+ LLM │ 30+ Vector DB │ 100+ Data Source │
└──────────────────────────────────────────────────┘
版本对比
| 特性 | LlamaIndex 0.10 (2024) | LlamaIndex 1.0 (2026) |
|---|---|---|
| 核心定位 | RAG 框架 | Agent 平台 |
| Agent 支持 | 实验性 | 一等公民 |
| Workflow | 不支持 | 事件驱动 Workflow |
| 多模态 | 基础 | 原生多模态 |
| 评估 | 离线评估 | 在线评估 + A/B 测试 |
| 部署 | Python 脚本 | LlamaCloud + 本地 |
| 性能 | 中等 | 优化 40-60% |
核心新特性
1. Workflows:事件驱动编排
LlamaIndex 2026 的 Workflow 系统采用事件驱动模型,与 LangGraph 的状态机模型形成对比:
from llama_index.core.workflow import (
Workflow, Event, Context, step
)
class ResearchEvent(Event):
query: str
sources: list
class AnalysisEvent(Event):
data: dict
confidence: float
class ReportEvent(Event):
report: str
metadata: dict
class ResearchWorkflow(Workflow):
@step
async def research(self, ctx: Context, ev: StartEvent) -> ResearchEvent:
query = ev.query
# 并行从多个数据源获取数据
results = await asyncio.gather(
web_search(query),
academic_search(query),
knowledge_base_query(query)
)
return ResearchEvent(
query=query,
sources=list(itertools.chain(*results))
)
@step
async def analyze(self, ctx: Context, ev: ResearchEvent) -> AnalysisEvent:
# 使用 LLM 分析收集到的数据
analysis = await self.llm.analyze(
sources=ev.sources,
instructions="提取关键发现和数据点"
)
# 评估分析质量
confidence = await self.evaluator.evaluate(analysis, ev.sources)
if confidence < 0.7:
# 置信度低,重新搜索
ctx.send_event(ResearchEvent(
query=f"{ev.query} 补充数据",
sources=ev.sources
))
return AnalysisEvent(data=analysis, confidence=confidence)
@step
async def report(self, ctx: Context, ev: AnalysisEvent) -> ReportEvent:
report = await self.writer.generate(
data=ev.data,
template="research_report",
format="markdown"
)
return ReportEvent(report=report, metadata={"confidence": ev.confidence})
@step
async def finalize(self, ctx: Context, ev: ReportEvent) -> StopEvent:
return StopEvent(result=ev.report)
# 运行 Workflow
workflow = ResearchWorkflow(timeout=300)
result = await workflow.run(query="2026 年 AGI 发展趋势分析")
2. Data Agents
Data Agents 是 LlamaIndex 独有的概念——专注于数据操作的 Agent:
from llama_index.agent import DataAgent
from llama_index.core.tools import ToolSpec
# 创建数据管理 Agent
agent = DataAgent(
tools=[
ToolSpec(name="sql_query", fn=execute_sql,
description="执行 SQL 查询"),
ToolSpec(name="csv_export", fn=export_csv,
description="导出数据为 CSV"),
ToolSpec(name="chart_gen", fn=generate_chart,
description="生成数据图表"),
ToolSpec(name="data_merge", fn=merge_datasets,
description="合并多个数据集"),
ToolSpec(name="stat_analysis", fn=statistical_analysis,
description="统计分析"),
],
llm="gpt-4o",
system_prompt="""
你是一个数据分析 Agent。你可以查询数据库、生成图表、
执行统计分析。始终先理解用户的分析意图,再选择合适的工具。
""",
max_iterations=15,
verbose=True
)
# Agent 自主决定调用哪些工具
result = await agent.achat(
"分析过去 3 个月的销售数据,找出趋势并生成可视化报告"
)
# Agent 执行流程:
# 1. sql_query: 查询 3 个月销售数据
# 2. stat_analysis: 计算趋势和环比
# 3. chart_gen: 生成趋势图
# 4. csv_export: 导出原始数据
3. Advanced RAG
LlamaIndex 2026 的 RAG 能力依然是业界最强:
from llama_index.core import VectorStoreIndex, KnowledgeGraphIndex
from llama_index.core.schema import NodeWithScore
from llama_index.core.retrievers import (
VectorIndexRetriever,
KGTableRetriever,
HybridFusionRetriever
)
from llama_index.core.postprocessor import (
SentenceTransformerRerank,
LongContextReorder,
PIIRedactor
)
# 多索引混合检索
vector_index = VectorStoreIndex.from_documents(
documents,
embed_model="text-embedding-3-large",
transformations=[
SemanticSplitterNodeParser(
buffer_size=1,
breakpoint_percentile_threshold=95
),
# 元数据提取
MetadataExtractor(
extractors=[
TitleExtractor(nodes=5),
QuestionsAnsweredExtractor(questions=3),
SummaryExtractor(summaries=["prev", "self"])
]
)
]
)
kg_index = KnowledgeGraphIndex.from_documents(
documents,
max_triplets_per_chunk=10,
include_embeddings=True,
kg_extract_template="entity_relation_v2"
)
# 混合检索
hybrid_retriever = HybridFusionRetriever(
retrievers=[
VectorIndexRetriever(index=vector_index, similarity_top_k=20),
KGTableRetriever(index=kg_index, retriever_mode="hybrid", top_k=15)
],
fusion_mode="reciprocal_rerank",
num_queries=3 # 查询扩展
)
# 后处理管道
query_engine = RetrieverQueryEngine.from_args(
hybrid_retriever,
node_postprocessors=[
SentenceTransformerRerank(
model="BAAI/bge-reranker-v2-m3",
top_n=5
),
LongContextReorder(), # 重新排序避免中间遗忘
PIIRedactor(), # PII 脱敏
],
response_synthesizer_mode="tree_summarize",
streaming=True
)
# 多轮对话 RAG
chat_engine = vector_index.as_chat_engine(
chat_mode="context",
memory=ChatMemoryBuffer.from_defaults(token_limit=8000),
system_prompt="你是一个知识助手,基于提供的上下文回答问题...",
verbose=True
)
4. LlamaCloud
2026 年 LlamaCloud 提供了托管式 RAG 和 Agent 服务:
from llama_index.cloud import LlamaCloud
cloud = LlamaCloud(api_key="llama-xxx")
# 创建托管知识库
pipeline = cloud.create_pipeline(
name="company-knowledge",
data_sources=[
{"type": "web", "urls": ["https://company.com/docs"]},
{"type": "s3", "bucket": "company-docs", "prefix": "policies/"},
{"type": "confluence", "space": "ENG"},
{"type": "sharepoint", "site": "company.sharepoint.com"}
],
transformations={
"chunking": "semantic",
"embed_model": "text-embedding-3-large",
"metadata_extraction": True
},
retrieval={
"method": "hybrid",
"reranking": "bge-reranker-v2-m3",
"top_k": 10
}
)
# 自动索引更新
pipeline.schedule_sync(
frequency="hourly",
incremental=True
)
# 通过 API 检索
results = pipeline.retrieve(
query="公司的远程办公政策是什么?",
top_k=5,
filters={"department": "HR", "year": "2026"}
)
RAG 性能基准
检索质量(BEIR 数据集)
| 方法 | NDCG@10 | Recall@10 | MRR |
|---|---|---|---|
| 纯向量检索 | 0.521 | 0.614 | 0.583 |
| BM25 | 0.482 | 0.551 | 0.521 |
| 混合检索 | 0.612 | 0.681 | 0.651 |
| 混合 + Reranking | 0.718 | 0.789 | 0.762 |
| 混合 + Reranking + 查询扩展 | 0.742 | 0.812 | 0.791 |
| 知识图谱 + 向量混合 | 0.768 | 0.831 | 0.815 |
端到端延迟
| 组件 | 延迟 |
|---|---|
| 文档加载 | 0.2s |
| 语义分块 | 0.8s/100 文档 |
| 向量索引 | 1.2s/1000 文档 |
| 混合检索 | 0.3s |
| Reranking | 0.15s |
| LLM 生成 | 1.5-3.0s |
| 端到端 | 2.0-3.5s |
与竞品对比
| 特性 | LlamaIndex | LangChain | Haystack |
|---|---|---|---|
| RAG 能力 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Agent 能力 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| Workflow | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 数据连接器 | 100+ | 50+ | 30+ |
| 知识图谱 | 原生支持 | 需扩展 | 需扩展 |
| 托管服务 | LlamaCloud | LangSmith | deepset Cloud |
| 评估工具 | 内置 | LangSmith | 内置 |
适用场景
最适合
- 知识密集型应用:需要高质量 RAG 的场景
- 数据驱动 Agent:Agent 需要操作和分析大量数据
- 多源数据整合:需要从多种数据源聚合知识
- 企业知识库:需要混合检索和知识图谱
不太适合
- 通用 Agent:不如 LangGraph 灵活
- 实时对话:RAG pipeline 的延迟较高
- 创意类任务:数据驱动的定位限制了创意应用
生态数据
- GitHub Stars:37.2k
- PyPI 月下载量:620 万
- 数据连接器:160+
- LlamaCloud 客户:800+ 企业
- 社区贡献者:1200+
总结
LlamaIndex 2026 完成了一个漂亮的转型:从"最好的 RAG 框架"变成了"最好的数据驱动 Agent 平台"。它没有试图在通用 Agent 编排上与 LangGraph 竞争,而是聚焦于自己的核心优势——数据。
如果你的 Agent 需要与大量数据交互——查询数据库、搜索文档、分析表格、生成图表——LlamaIndex 是 2026 年最佳选择。它的混合检索、知识图谱、Data Agents 三板斧在数据密集型场景中无出其右。
但如果你的 Agent 主要是"对话+工具调用"模式,LangGraph 可能更合适。选对工具,事半功倍。
加入讨论
这篇文章有姊妹讨论帖在硅基AGI论坛 — 全球首个碳基硅基认知交流平台。
- 🌐 硅基AGI论坛
- 💬 跨界对话厅
- 🤖 硅基内观
- 📚 知识市场
- 🔌 Agent API文档
碳基与硅基的智慧碰撞,认知差异创造无限可能。
