LlamaIndex数据框架应用Skill llamaindex

LlamaIndex是一个用于构建大型语言模型(LLM)应用的数据框架,专注于检索增强生成(RAG)、文档问答、知识检索和多模态支持。它提供300多个数据连接器、向量索引和查询引擎,适用于文档处理、聊天机器人和企业数据集成,帮助开发高效RAG管道和AI应用。关键词:LlamaIndex, RAG, 文档问答, 向量索引, 数据框架, LLM应用, 智能体, 知识检索

RAG应用 0 次安装 0 次浏览 更新于 3/21/2026

名称: llamaindex 描述: 用于构建LLM应用的数据框架,专注于RAG(检索增强生成)。专门处理文档摄入(300多个连接器)、索引和查询。功能包括向量索引、查询引擎、智能体和多模态支持。用于文档问答、聊天机器人、知识检索或构建RAG管道。最适合数据中心的LLM应用。 版本: 1.0.0 作者: Orchestra Research 许可证: MIT 标签: [智能体, LlamaIndex, RAG, 文档摄入, 向量索引, 查询引擎, 知识检索, 数据框架, 多模态, 私有数据, 连接器] 依赖项: [llama-index, openai, anthropic]

LlamaIndex - LLM应用的数据框架

连接LLM与您数据的领先框架。

何时使用LlamaIndex

使用LlamaIndex当:

  • 构建RAG(检索增强生成)应用
  • 需要对私有数据进行文档问答
  • 从多个来源摄入数据(300多个连接器)
  • 为LLM创建知识库
  • 构建包含企业数据的聊天机器人
  • 需要从文档中提取结构化数据

指标:

  • 45,100+ GitHub星标
  • 23,000+ 仓库使用LlamaIndex
  • 300+ 数据连接器(LlamaHub)
  • 1,715+ 贡献者
  • v0.14.7(稳定版)

使用替代方案当:

  • LangChain:更通用,更适合智能体
  • Haystack:生产搜索管道
  • txtai:轻量级语义搜索
  • Chroma:仅需向量存储

快速入门

安装

# 入门包(推荐)
pip install llama-index

# 或最小核心 + 特定集成
pip install llama-index-core
pip install llama-index-llms-openai
pip install llama-index-embeddings-openai

5行RAG示例

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("作者成长过程中做了什么?")
print(response)

核心概念

1. 数据连接器 - 加载文档

from llama_index.core import SimpleDirectoryReader, Document
from llama_index.readers.web import SimpleWebPageReader
from llama_index.readers.github import GithubRepositoryReader

# 文件目录
documents = SimpleDirectoryReader("./data").load_data()

# 网页
reader = SimpleWebPageReader()
documents = reader.load_data(["https://example.com"])

# GitHub仓库
reader = GithubRepositoryReader(owner="user", repo="repo")
documents = reader.load_data(branch="main")

# 手动创建文档
doc = Document(
    text="这是文档内容",
    metadata={"source": "manual", "date": "2025-01-01"}
)

2. 索引 - 结构化数据

from llama_index.core import VectorStoreIndex, ListIndex, TreeIndex

# 向量索引(最常见 - 语义搜索)
vector_index = VectorStoreIndex.from_documents(documents)

# 列表索引(顺序扫描)
list_index = ListIndex.from_documents(documents)

# 树索引(分层摘要)
tree_index = TreeIndex.from_documents(documents)

# 保存索引
index.storage_context.persist(persist_dir="./storage")

# 加载索引
from llama_index.core import load_index_from_storage, StorageContext
storage_context = StorageContext.from_defaults(persist_dir="./storage")
index = load_index_from_storage(storage_context)

3. 查询引擎 - 提问

# 基本查询
query_engine = index.as_query_engine()
response = query_engine.query("主要主题是什么?")
print(response)

# 流式响应
query_engine = index.as_query_engine(streaming=True)
response = query_engine.query("解释量子计算")
for text in response.response_gen:
    print(text, end="", flush=True)

# 自定义配置
query_engine = index.as_query_engine(
    similarity_top_k=3,          # 返回前3个块
    response_mode="compact",     # 或 "tree_summarize", "simple_summarize"
    verbose=True
)

4. 检索器 - 查找相关块

# 向量检索器
retriever = index.as_retriever(similarity_top_k=5)
nodes = retriever.retrieve("机器学习")

# 带过滤
retriever = index.as_retriever(
    similarity_top_k=3,
    filters={"metadata.category": "tutorial"}
)

# 自定义检索器
from llama_index.core.retrievers import BaseRetriever

class CustomRetriever(BaseRetriever):
    def _retrieve(self, query_bundle):
        # 您的自定义检索逻辑
        return nodes

带工具的智能体

基本智能体

from llama_index.core.agent import FunctionAgent
from llama_index.llms.openai import OpenAI

# 定义工具
def multiply(a: int, b: int) -> int:
    """相乘两个数字。"""
    return a * b

def add(a: int, b: int) -> int:
    """相加两个数字。"""
    return a + b

# 创建智能体
llm = OpenAI(model="gpt-4o")
agent = FunctionAgent.from_tools(
    tools=[multiply, add],
    llm=llm,
    verbose=True
)

# 使用智能体
response = agent.chat("25 * 17 + 142 是多少?")
print(response)

RAG智能体(文档搜索 + 工具)

from llama_index.core.tools import QueryEngineTool

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

# 将查询引擎包装为工具
query_tool = QueryEngineTool.from_defaults(
    query_engine=index.as_query_engine(),
    name="python_docs",
    description="用于回答Python编程问题"
)

# 带文档搜索 + 计算器的智能体
agent = FunctionAgent.from_tools(
    tools=[query_tool, multiply, add],
    llm=llm
)

# 智能体决定何时搜索文档或计算
response = agent.chat("根据文档,Python用于什么?")

高级RAG模式

聊天引擎(对话式)

from llama_index.core.chat_engine import CondensePlusContextChatEngine

# 带记忆的聊天
chat_engine = index.as_chat_engine(
    chat_mode="condense_plus_context",  # 或 "context", "react"
    verbose=True
)

# 多轮对话
response1 = chat_engine.chat("Python是什么?")
response2 = chat_engine.chat("能举例吗?")  # 记住上下文
response3 = chat_engine.chat("Web框架呢?")

元数据过滤

from llama_index.core.vector_stores import MetadataFilters, ExactMatchFilter

# 按元数据过滤
filters = MetadataFilters(
    filters=[
        ExactMatchFilter(key="category", value="tutorial"),
        ExactMatchFilter(key="difficulty", value="beginner")
    ]
)

retriever = index.as_retriever(
    similarity_top_k=3,
    filters=filters
)

query_engine = index.as_query_engine(filters=filters)

结构化输出

from pydantic import BaseModel
from llama_index.core.output_parsers import PydanticOutputParser

class Summary(BaseModel):
    title: str
    main_points: list[str]
    conclusion: str

# 获取结构化响应
output_parser = PydanticOutputParser(output_cls=Summary)
query_engine = index.as_query_engine(output_parser=output_parser)

response = query_engine.query("总结文档")
summary = response  # Pydantic模型
print(summary.title, summary.main_points)

数据摄入模式

多种文件类型

# 加载所有支持格式
documents = SimpleDirectoryReader(
    "./data",
    recursive=True,
    required_exts=[".pdf", ".docx", ".txt", ".md"]
).load_data()

网页爬取

from llama_index.readers.web import BeautifulSoupWebReader

reader = BeautifulSoupWebReader()
documents = reader.load_data(urls=[
    "https://docs.python.org/3/tutorial/",
    "https://docs.python.org/3/library/"
])

数据库

from llama_index.readers.database import DatabaseReader

reader = DatabaseReader(
    sql_database_uri="postgresql://user:pass@localhost/db"
)
documents = reader.load_data(query="SELECT * FROM articles")

API端点

from llama_index.readers.json import JSONReader

reader = JSONReader()
documents = reader.load_data("https://api.example.com/data.json")

向量存储集成

Chroma(本地)

from llama_index.vector_stores.chroma import ChromaVectorStore
import chromadb

# 初始化Chroma
db = chromadb.PersistentClient(path="./chroma_db")
collection = db.get_or_create_collection("my_collection")

# 创建向量存储
vector_store = ChromaVectorStore(chroma_collection=collection)

# 用于索引
from llama_index.core import StorageContext
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)

Pinecone(云)

from llama_index.vector_stores.pinecone import PineconeVectorStore
import pinecone

# 初始化Pinecone
pinecone.init(api_key="your-key", environment="us-west1-gcp")
pinecone_index = pinecone.Index("my-index")

# 创建向量存储
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)

FAISS(快速)

from llama_index.vector_stores.faiss import FaissVectorStore
import faiss

# 创建FAISS索引
d = 1536  # 嵌入维度
faiss_index = faiss.IndexFlatL2(d)

vector_store = FaissVectorStore(faiss_index=faiss_index)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)

自定义

自定义LLM

from llama_index.llms.anthropic import Anthropic
from llama_index.core import Settings

# 设置全局LLM
Settings.llm = Anthropic(model="claude-sonnet-4-5-20250929")

# 现在所有查询使用Anthropic
query_engine = index.as_query_engine()

自定义嵌入

from llama_index.embeddings.huggingface import HuggingFaceEmbedding

# 使用HuggingFace嵌入
Settings.embed_model = HuggingFaceEmbedding(
    model_name="sentence-transformers/all-mpnet-base-v2"
)

index = VectorStoreIndex.from_documents(documents)

自定义提示模板

from llama_index.core import PromptTemplate

qa_prompt = PromptTemplate(
    "上下文:{context_str}
"
    "问题:{query_str}
"
    "仅基于上下文回答问题。"
    "如果答案不在上下文中,说'我不知道'。
"
    "答案:"
)

query_engine = index.as_query_engine(text_qa_template=qa_prompt)

多模态RAG

图像 + 文本

from llama_index.core import SimpleDirectoryReader
from llama_index.multi_modal_llms.openai import OpenAIMultiModal

# 加载图像和文档
documents = SimpleDirectoryReader(
    "./data",
    required_exts=[".jpg", ".png", ".pdf"]
).load_data()

# 多模态索引
index = VectorStoreIndex.from_documents(documents)

# 用多模态LLM查询
multi_modal_llm = OpenAIMultiModal(model="gpt-4o")
query_engine = index.as_query_engine(llm=multi_modal_llm)

response = query_engine.query("第3页的图里有什么?")

评估

响应质量

from llama_index.core.evaluation import RelevancyEvaluator, FaithfulnessEvaluator

# 评估相关性
relevancy = RelevancyEvaluator()
result = relevancy.evaluate_response(
    query="Python是什么?",
    response=response
)
print(f"相关性:{result.passing}")

# 评估忠实度(无幻觉)
faithfulness = FaithfulnessEvaluator()
result = faithfulness.evaluate_response(
    query="Python是什么?",
    response=response
)
print(f"忠实度:{result.passing}")

最佳实践

  1. 大多数情况下使用向量索引 - 最佳性能
  2. 保存索引到磁盘 - 避免重新索引
  3. 正确分块文档 - 512-1024令牌最优
  4. 添加元数据 - 启用过滤和跟踪
  5. 使用流式 - 长响应更好用户体验
  6. 开发时启用详细模式 - 查看检索过程
  7. 评估响应 - 检查相关性和忠实度
  8. 对话使用聊天引擎 - 内置记忆
  9. 持久化存储 - 不丢失索引
  10. 监控成本 - 跟踪嵌入和LLM使用

常见模式

文档问答系统

# 完整RAG管道
documents = SimpleDirectoryReader("docs").load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist(persist_dir="./storage")

# 查询
query_engine = index.as_query_engine(
    similarity_top_k=3,
    response_mode="compact",
    verbose=True
)
response = query_engine.query("主要主题是什么?")
print(response)
print(f"来源:{[node.metadata['file_name'] for node in response.source_nodes]}")

带记忆的聊天机器人

# 对话界面
chat_engine = index.as_chat_engine(
    chat_mode="condense_plus_context",
    verbose=True
)

# 多轮聊天
while True:
    user_input = input("您:")
    if user_input.lower() == "quit":
        break
    response = chat_engine.chat(user_input)
    print(f"机器人:{response}")

性能基准

操作 延迟 备注
索引100个文档 ~10-30秒 一次性,可持久化
查询(向量) ~0.5-2秒 检索 + LLM
流式查询 ~0.5秒首个令牌 更好用户体验
带工具智能体 ~3-8秒 多个工具调用

LlamaIndex vs LangChain

功能 LlamaIndex LangChain
最适合 RAG, 文档问答 智能体, 通用LLM应用
数据连接器 300+ (LlamaHub) 100+
RAG焦点 核心功能 众多之一
学习曲线 RAG更易 较陡
自定义 非常高
文档 优秀

使用LlamaIndex当:

  • 您的主要用例是RAG
  • 需要许多数据连接器
  • 想要文档问答更简单API
  • 构建知识检索系统

使用LangChain当:

  • 构建复杂智能体
  • 需要更多通用工具
  • 想要更多灵活性
  • 复杂多步工作流

参考

资源