LlamaIndex 入门教程

项目介绍

LlamaIndex 是当前构建基于私有数据的 LLM 应用最核心的开源检索增强生成(RAG)框架之一,它不仅提供高性能的向量化索引系统,更通过文档解析、语义分块、查询路由等机制,显著提升了大语言模型处理私有数据的能力。

主要功能

  • 文档解析与处理:支持多种文档格式(PDF、Word、Markdown等)的自动解析和处理
  • 语义分块:智能将文档分割为有意义的语义单元,优化检索效果
  • 向量索引:高效存储和检索文本嵌入向量
  • 查询路由:根据查询类型自动选择最佳的检索策略
  • 多模态支持:不仅支持文本,还支持图像等多模态数据
  • 与多种LLM集成:支持OpenAI、Anthropic、Hugging Face等多种大语言模型

项目特点

  • 高度模块化:可根据需求灵活组合不同组件
  • 性能优化:针对大规模文档和复杂查询进行了性能优化
  • 易于集成:提供简洁的API接口,易于与现有应用集成
  • 丰富的生态系统:支持多种向量数据库和LLM模型
  • 活跃的社区:持续更新和改进

安装与配置

安装步骤

  1. 安装LlamaIndex核心包
pip install llama-index
  1. 安装可选依赖
# 安装文档处理依赖
pip install "llama-index[docstore]"

# 安装向量数据库依赖(以Chroma为例)
pip install "llama-index[chromadb]"

# 安装OpenAI依赖(用于使用GPT模型)
pip install "llama-index[openai]"

基本配置

from llama_index import set_global_tokenizer
from transformers import AutoTokenizer

# 设置全局tokenizer
set_global_tokenizer(AutoTokenizer.from_pretrained("bert-base-uncased"))

# 配置OpenAI API密钥
import os
os.environ["OPENAI_API_KEY"] = "your-api-key"

核心概念

1. Document(文档)

Document是LlamaIndex中的基本数据单元,代表一个完整的文档,如PDF文件、Markdown文件等。

2. Node(节点)

Node是Document的组成部分,通常是文档的一个语义分块,包含文本内容和元数据。

3. Index(索引)

Index是对Nodes的组织和存储,用于高效检索相关信息。常见的索引类型包括:

  • VectorStoreIndex:基于向量相似度的索引
  • ListIndex:基于列表的简单索引
  • TreeIndex:基于树结构的索引
  • KeywordTableIndex:基于关键词的索引

4. Query Engine(查询引擎)

Query Engine负责处理用户查询,检索相关信息,并生成响应。

5. Retriever(检索器)

Retriever负责从索引中检索与查询相关的Nodes。

6. Response Synthesizer(响应合成器)

Response Synthesizer负责将检索到的信息合成为最终的响应。

基本使用

创建简单的RAG系统

from llama_index import VectorStoreIndex, SimpleDirectoryReader

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

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

# 创建查询引擎
query_engine = index.as_query_engine()

# 执行查询
response = query_engine.query("什么是LlamaIndex?")
print(response)

自定义索引和查询

from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
from llama_index.llms import OpenAI

# 配置LLM
llm = OpenAI(model="gpt-3.5-turbo", temperature=0)

# 创建服务上下文
service_context = ServiceContext.from_defaults(llm=llm)

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

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

# 创建查询引擎
query_engine = index.as_query_engine(
    similarity_top_k=5,  # 检索前5个最相关的节点
    response_mode="compact"  # 使用紧凑模式生成响应
)

# 执行查询
response = query_engine.query("LlamaIndex的核心功能有哪些?")
print(response)

高级特性

1. 自定义分块策略

from llama_index.node_parser import SentenceSplitter

# 创建自定义分块器
node_parser = SentenceSplitter(
    chunk_size=512,  # 块大小
    chunk_overlap=50,  # 块重叠
    separator=" "  # 分隔符
)

# 使用自定义分块器
service_context = ServiceContext.from_defaults(
    node_parser=node_parser
)

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

2. 使用自定义向量数据库

from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores import ChromaVectorStore
from chromadb import PersistentClient

# 创建Chroma客户端
client = PersistentClient(path="./chroma_db")

# 创建向量存储
vector_store = ChromaVectorStore(
    chroma_collection=client.get_or_create_collection("my_collection")
)

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

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

3. 多文档查询和路由

from llama_index import VectorStoreIndex, SimpleDirectoryReader, RouterQueryEngine, QueryEngineTool
from llama_index.tools import QueryEngineTool

# 加载不同类型的文档
documents1 = SimpleDirectoryReader("./data/docs1").load_data()
documents2 = SimpleDirectoryReader("./data/docs2").load_data()

# 创建不同的索引
index1 = VectorStoreIndex.from_documents(documents1)
index2 = VectorStoreIndex.from_documents(documents2)

# 创建查询引擎
query_engine1 = index1.as_query_engine()
query_engine2 = index2.as_query_engine()

# 创建查询引擎工具
tool1 = QueryEngineTool(
    query_engine=query_engine1,
    name="docs1",
    description="关于主题1的文档"
)
tool2 = QueryEngineTool(
    query_engine=query_engine2,
    name="docs2",
    description="关于主题2的文档"
)

# 创建路由查询引擎
router_query_engine = RouterQueryEngine.from_defaults(
    query_engine_tools=[tool1, tool2]
)

# 执行查询
response = router_query_engine.query("主题1的相关内容是什么?")
print(response)

实际应用案例

案例1:知识库问答系统

场景:企业内部知识库问答,帮助员工快速获取公司政策、产品信息等。

实现步骤

  1. 收集和整理企业文档(PDF、Word、Markdown等)
  2. 使用LlamaIndex解析和索引文档
  3. 部署查询接口,允许员工通过自然语言提问
  4. 定期更新索引以包含新文档

示例代码

from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext
from llama_index.llms import OpenAI

# 配置LLM
llm = OpenAI(model="gpt-3.5-turbo", temperature=0)
service_context = ServiceContext.from_defaults(llm=llm)

# 加载企业文档
documents = SimpleDirectoryReader("./company_docs").load_data()

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

# 创建查询引擎
query_engine = index.as_query_engine()

# 示例查询
queries = [
    "公司的年假政策是什么?",
    "如何申请报销?",
    "产品A的主要功能有哪些?"
]

for query in queries:
    response = query_engine.query(query)
    print(f"问题: {query}")
    print(f"回答: {response}\n")

案例2:个人知识库管理

场景:个人收集和管理学习资料,通过自然语言查询获取相关信息。

实现步骤

  1. 收集个人学习资料(笔记、论文、书籍等)
  2. 使用LlamaIndex索引资料
  3. 构建简单的Web界面或命令行工具进行查询
  4. 定期添加新资料并更新索引

示例代码

from llama_index import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores import ChromaVectorStore
from chromadb import PersistentClient

# 创建持久化向量存储
client = PersistentClient(path="./personal_knowledge_base")
vector_store = ChromaVectorStore(
    chroma_collection=client.get_or_create_collection("personal_notes")
)

# 加载个人资料
documents = SimpleDirectoryReader("./personal_notes").load_data()

# 创建或更新索引
index = VectorStoreIndex.from_documents(
    documents, 
    vector_store=vector_store
)

# 创建查询引擎
query_engine = index.as_query_engine()

# 交互式查询
while True:
    query = input("请输入您的问题(输入'退出'结束):")
    if query == "退出":
        break
    response = query_engine.query(query)
    print(f"回答: {response}\n")

总结与展望

LlamaIndex作为一个强大的RAG框架,为构建基于私有数据的LLM应用提供了全面的工具和功能。通过本文的介绍,你应该已经了解了LlamaIndex的核心概念、基本使用方法和高级特性。

关键优势

  • 简化了RAG系统的构建流程
  • 提供了丰富的文档处理和索引选项
  • 支持多种向量数据库和LLM模型
  • 高度可定制,适应不同场景需求

应用前景

  • 企业知识库和智能问答系统
  • 个人知识管理和学习助手
  • 内容推荐和信息检索
  • 智能客服和对话系统
  • 数据分析和决策支持

未来发展

LlamaIndex团队持续改进框架,未来可能会:

  • 支持更多的文档格式和数据源
  • 提供更高级的检索和推理能力
  • 优化性能,支持更大规模的应用
  • 增强与其他AI工具和框架的集成

通过不断学习和实践,你可以利用LlamaIndex构建更加智能、高效的LLM应用,为各种场景提供有价值的AI解决方案。