LlamaIndex学习

1:LlamaIndex 介绍

「 LlamaIndex is a framework for building context-augmented LLM applications. Context augmentation refers to any use case that applies LLMs on top of your private or domain-specific data. 」

LlamaIndex 是一个为开发「上下文增强」的大语言模型应用的框架(也就是 SDK)。上下文增强,泛指任何在私有或特定领域数据基础上应用大语言模型的情况。例如:

LlamaIndex 有 Python 和 Typescript 两个版本,Python 版的文档相对更完善。

- Python 文档地址:https://docs.llamaindex.ai/en/stable/
- Python API 接口文档:https://docs.llamaindex.ai/en/stable/api_reference/

- TS 文档地址:https://ts.llamaindex.ai/

- TS API 接口文档:https://ts.llamaindex.ai/api/

LlamaIndex 是一个开源框架,Github 链接:https://github.com/run-llama

2: LlamaIndex 的核心模块

3:安装 LlamaIndex

Python

pip install llama-index
4、数据加载(Loading) 

官方说明:SimpleDirectoryReader is the simplest way to load data from local files into LlamaIndex. For production use cases it's more likely that you'll want to use one of the many Readers available on LlamaHub, but SimpleDirectoryReader is a great way to get started.

 可以通过SimpleDirectoryReader进行简单的本地文件加载器,它会遍历指定目录,并根据文件扩展名自动加载文件,支持格式文件:

.csv - comma-separated values
.docx - Microsoft Word
.epub - EPUB ebook format
.hwp - Hangul Word Processor
.ipynb - Jupyter Notebook
.jpeg, .jpg - JPEG image
.mbox - MBOX email archive
.md - Markdown
.mp3, .mp4 - audio and video
.pdf - Portable Document Format
.png - Portable Network Graphics
.ppt, .pptm, .pptx - Microsoft PowerPoint

from llama_index.core import SimpleDirectoryReader
reader = SimpleDirectoryReader(
        input_dir="./data", # 目标目录
        recursive=False, # 是否递归遍历子目录,默认为True
        required_exts=[".pdf"] # (可选)只读取指定后缀的文件
    )
documents = reader.load_data()

如果默认的PDFReader效果不好,想指定文件加载器,可以使用以下方式:

# !pip install pymupdf


from llama_index.core import SimpleDirectoryReader
from llama_index.readers.file import PyMuPDFReader

reader = SimpleDirectoryReader(
        input_dir="./data", # 目标目录
        recursive=False, # 是否递归遍历子目录
        required_exts=[".pdf"], # (可选)只读取指定后缀的文件
        file_extractor={".pdf": PyMuPDFReader()} # 指定特定的文件加载器
    )

documents = reader.load_data()

print(documents[0].text)
5:文档切分与解析

为方便检索,通常会把document切分为Node。

Node represents a "chunk" of a source Document, whether that is a text chunk, an image, or other. Similar to Documents, they contain metadata and relationship information with other nodes.

Nodes:官方给的方法可以使用SentenceSplitter进行切分

from llama_index.core.node_parser import SentenceSplitter

# load documents
...

# parse nodes
parser = SentenceSplitter()
nodes = parser.get_nodes_from_documents(documents)

# build index
index = VectorStoreIndex(nodes)

也可以使用TextSplitters对文本进行切分

from llama_index.core import Document
from llama_index.core.node_parser import TokenTextSplitter

node_parser = TokenTextSplitter(
    chunk_size=100,  # 每个 chunk 的最大长度
    chunk_overlap=50  # chunk 之间重叠长度 
)

nodes = node_parser.get_nodes_from_documents(
    documents, show_progress=False
)
6:索引(Indexing)与检索(Retrieval)
# 构建 index
index = VectorStoreIndex(nodes)

# 获取 retriever
vector_retriever = index.as_retriever(
    similarity_top_k=2 # 返回2个结果
)
# 检索
results = vector_retriever.retrieve("******")

<think>好的,用户现在想学习如何使用LlamaIndex,需要教程和示例代码。首先,我需要回顾之前的对话历史,确保回答的一致性和连贯性。用户之前询问了LlamaIndex和LangChain的区别,我给出了对比分析,现在用户转向具体的使用方法。 接下来,用户提供的引用内容中,引用了三个资料:[1]是LlamaIndex的查询引擎教程,[2]是入门实战,[3]是项目教程。这些引用都提到了环境配置、数据加载、索引创建和查询等步骤。需要整合这些信息,确保回答覆盖基本概念、安装配置、核心功能及示例代码。 用户的需求很明确:学习使用LlamaIndex的教程和示例代码。因此,回答需要结构清晰,分步骤讲解,并附带代码示例。同时,用户可能希望了解实际应用场景,所以添加示例应用场景会更好。 需要检查之前的回答是否已经涵盖部分内容,避免重复。之前的回答提到LlamaIndex专注于索引和检索,适合文档问答系统,因此在教程中应强调这些方面。此外,用户可能对如何结合LangChain感兴趣,但当前问题聚焦于LlamaIndex,所以暂时不需要涉及,但可以作为相关问题提出。 确保使用正确的中文术语,避免技术术语的混淆。例如,“向量存储”和“索引”需要明确解释。代码示例部分要注意格式正确,使用代码块,并确保语法正确,比如正确的缩进和函数调用。 另外,用户可能遇到的常见问题包括环境配置错误、数据加载路径问题、索引创建失败等,应在教程中提及可能的解决方案或注意事项,比如安装特定依赖项或检查文件目录。 最后,生成的相关问题需要与用户当前的学习路径相关,比如进阶功能、性能优化、实际项目集成等,帮助用户深入学习和解决问题。同时,引用标记要正确对应,确保引用来源准确,例如引用[1]、[2]、[3]对应的内容。 总结回答结构:分步骤教程(安装、数据加载、索引创建、查询)、进阶功能、示例场景、注意事项、相关问题。确保每个部分都有代码示例和解释,帮助用户逐步理解和实践。</think>### LlamaIndex 使用教程与代码示例 #### 一、基础概念与安装 1. **核心功能** LlamaIndex 是连接大语言模型(LLMs)与外部数据的工具,通过构建结构化索引实现**高效文档检索**和**上下文增强的查询响应**[^2]。 - 支持格式:PDF、Markdown、HTML、数据库等 - 核心流程:数据加载 → 索引构建 → 查询执行 2. **环境配置** ```bash # 安装核心库 pip install llama-index-core python-dotenv # 可选安装向量数据库(如Chroma) pip install llama-index-vector-stores-chroma ``` #### 二、基础使用流程 1. **数据加载与处理** ```python from llama_index.core import SimpleDirectoryReader # 加载本地文档(支持PDF/TXT/Markdown) documents = SimpleDirectoryReader("data").load_data() # 替换为你的文档目录[^3] ``` 2. **索引构建** ```python from llama_index.core import VectorStoreIndex # 创建向量索引(自动文本分块与向量化) index = VectorStoreIndex.from_documents(documents) # 默认使用HuggingFace嵌入模型[^1] ``` 3. **查询引擎使用** ```python # 基础查询 query_engine = index.as_query_engine() response = query_engine.query("量子计算的主要应用场景?") print(response) # 输出带上下文的回答 ``` #### 三、进阶功能示例 1. **混合检索模式** ```python from llama_index.core import SummaryIndex # 结合摘要索引提升长文档处理能力 summary_index = SummaryIndex.from_documents(documents) hybrid_engine = summary_index.as_query_engine(similarity_top_k=3) ``` 2. **自定义检索逻辑** ```python from llama_index.core import QueryBundle from llama_index.core.retrievers import VectorIndexRetriever # 自定义相似度阈值 retriever = VectorIndexRetriever(index, similarity_cutoff=0.7) nodes = retriever.retrieve(QueryBundle("神经网络优化方法")) ``` #### 四、典型应用场景 1. **企业知识库** ```python # 连接PostgreSQL数据库 from llama_index.core import SQLDatabase sql_database = SQLDatabase(engine) index = SQLVectorStoreIndex.from_documents(sql_database, documents) ``` 2. **论文检索系统** ```python # 使用结构化元数据过滤 index = VectorStoreIndex.from_documents( documents, metadata_filters={"category": "quantum_computing"} ) ``` #### 五、关键注意事项 1. **性能优化** - 文档分块建议:技术文档 512 tokens/块,论文 1024 tokens/块 - 索引存储:使用`index.storage_context.persist(persist_dir="storage")`持久化索引[^3] 2. **常见问题解决** ```python # 处理特殊字符编码问题 SimpleDirectoryReader("data", filename_as_id=True, file_metadata=lambda x: {"encoding": "utf-8"}) ``` --- ### 示例应用场景代码 **智能客服知识库** ```python from llama_index.core import ServiceContext from llama_index.llms.openai import OpenAI # 配置OpenAI模型 service_context = ServiceContext.from_defaults( llm=OpenAI(model="gpt-3.5-turbo", temperature=0.3) ) # 构建带业务规则的索引 custom_index = VectorStoreIndex.from_documents( documents, service_context=service_context, show_progress=True ) ``` --- ### 相关问题 1. 如何优化LlamaIndex在百万级文档中的检索速度? 2. LlamaIndex支持哪些非结构化数据格式的解析? 3. 如何将LlamaIndex与LangChain结合开发智能问答系统? 4. 在索引构建时如何选择合适的分块策略? [^1]: 使用LLM进行高效查询:LlamaIndex示例教程 [^2]: LlamaIndex 入门实战 : LlamaIndex 项目教程
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值