使用LlamaIndex实现语义分块
使用LlamaIndex实现语义分块
在文本处理和自然语言处理领域,如何有效地对文档进行分块是一个关键问题。传统的分块方法通常使用固定的块大小,但这种方法在处理语义复杂的文本时可能不够精准。本文将介绍如何使用LlamaIndex和语义分块(Semantic Chunking)技术,通过自适应选择断点来进行文本分块,从而确保每个“块”中的句子在语义上是相关的。
什么是语义分块
语义分块是Greg Kamradt在其视频教程中提出的新概念。与传统的固定大小分块不同,语义分块通过嵌入相似性自适应地选择句子之间的断点,以确保一个“块”内的句子在语义上是相关的。
我们将这个概念集成到了LlamaIndex模块中。
安装必要的库
首先,我们需要安装一些必要的库:
%pip install llama-index-embeddings-openai
下载示例数据
我们从互联网下载示例文档。这里以Paul Graham的一篇文章为例:
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'pg_essay.txt'
加载文档数据
使用SimpleDirectoryReader
类加载文档数据:
from llama_index.core import SimpleDirectoryReader
# 加载文档
documents = SimpleDirectoryReader(input_files=["pg_essay.txt"]).load_data()
定义语义分块器
通过使用嵌入模型来自适应地进行语义分块:
from llama_index.core.node_parser import (
SentenceSplitter,
SemanticSplitterNodeParser,
)
from llama_index.embeddings.openai import OpenAIEmbedding
import os
os.environ["OPENAI_API_KEY"] = "sk-..."
embed_model = OpenAIEmbedding()
splitter = SemanticSplitterNodeParser(
buffer_size=1, breakpoint_percentile_threshold=95, embed_model=embed_model
)
# 也定义基线分块器
base_splitter = SentenceSplitter(chunk_size=512)
nodes = splitter.get_nodes_from_documents(documents)
检查分块结果
让我们来看一下语义分块产生的结果:
# 打印第一个块内容
print(nodes[1].get_content())
输出示例(第1块内容):
I didn't write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories...
与基线分块对比
我们使用固定块大小的分块方法来对比:
base_nodes = base_splitter.get_nodes_from_documents(documents)
print(base_nodes[2].get_content())
设置查询引擎
初始化向量存储索引和查询引擎:
from llama_index.core import VectorStoreIndex
vector_index = VectorStoreIndex(nodes)
query_engine = vector_index.as_query_engine()
base_vector_index = VectorStoreIndex(base_nodes)
base_query_engine = base_vector_index.as_query_engine()
运行查询
运行一些查询对比效果:
response = query_engine.query(
"Tell me about the author's programming journey through childhood to college"
)
print(str(response))
输出示例(查询结果):
The author's programming journey began in childhood when computers were expensive and not easily accessible...
常见问题
-
API Key 未设置错误:
- 请确保在代码中正确设置了
OPENAI_API_KEY
环境变量。 -
网络问题:
- 如果在下载示例数据时出现网络问题,请检查网络连接,或者手动下载数据文件。
-
分块效果不佳:
- 如果分块效果不理想,可以尝试调整
breakpoint_percentile_threshold
参数。
参考资料:
如果你觉得这篇文章对你有帮助,请点赞,关注我的博客,谢谢!
作者:llzwxh888