步骤⼆:⽂档向量化与索引构建
⽬标: 将预处理后的⽂本块(chunks)转换为数值向量(embeddings),并将这些向量及
其对应的⽂本内容存储到向量数据库中,构建⼀个可供⾼效检索的索引。
具体操作:
1. 初始化Embedding模型
我们将使⽤HuggingFace Hub上的 BAAI/bge-small-zh-v1.5 模型作为⽰例,它是⼀个对中⽂⽀持较好且相对轻量级的模型。LangChain通过 HuggingFaceBgeEmbeddings 类可以方便地加载此类模型。
from langchain_community.embeddings import HuggingFaceBgeEmbeddingsembedding_model_name = "BAAI/bge-small-zh-v1.5"# 如果你的机器有GPU并且安装了CUDA版本的PyTorch,可以设置为'cuda'# 否则, sentence-transformers 会⾃动检测或使⽤ 'cpu'model_kwargs = {'device': 'cpu'}encode_kwargs = {'normalize_embeddings': True} # BGE模型通常推荐对输出向量进⾏归⼀try:embedding_model = HuggingFaceBgeEmbeddings(model_name=embedding_model_name,model_kwargs=model_kwargs,encode_kwargs=encode_kwargs)print(f"\n成功加载Embedding模型: {embedding_model_name}")# 测试⼀下Embedding模型example_text = "这是⼀个⽰例⽂本,⽤于测试向量化功能。"query_vector = embedding_model.embed_query(example_text)print(f"⽰例⽂本的向量维度: {len(query_vector)}")# print(f"向量预览 (前5维): {query_vector[:5]}")except Exception as e:print(f"加载Embedding模型失败: {e}")print("请确保已安装sentence-transformers且模型名称正确,或⽹络连接正常可以下载模型embedding_model = None # 标记模型加载失败
说明: ⾸次运⾏此代码时, sentence-transformers 库会⾃动从HuggingFace Hub下载并缓存BAAI/bge-small-zh-v1.5 模型⽂件,这可能需要⼀些时间,并取决于⽹络连接。如果遇到问题,请检查⽹络或尝试⼿动下载模型到本地指定路径。
2. 构建并填充向量索引
我们将使⽤ ChromaDB 作为向量数据库。ChromaDB易于在本地运⾏和集成。LangChain的Chroma 类提供了便捷的接⼝。
上图描述了将预处理后的⽂本块转化为向量并存⼊向量数据库的过程。每个⽂本块通过选定的Embedding模型转换成⼀个数值向量,这个向量代表了⽂本块的语义信息。这些向量连同原始⽂本和元数据⼀起存储在向量数据库中,并建⽴索引以⽀持快速相似度搜索。
from langchain_community.vectorstores import Chromaimport shutil # ⽤于清理旧的数据库⽬录# 定义ChromaDB的持久化存储路径和集合名称persist_directory = './chroma_db_store'collection_name = 'my_rag_collection_v1'# (可选) 清理旧的数据库⽬录,以便每次运⾏时都创建⼀个新的# if True: # 设置为False则不清空,会尝试加载现有数据# try:# shutil.rmtree(persist_directory)# print(f"已清理旧的数据库⽬录: {persist_directory}")# except FileNotFoundError:# print(f"数据库⽬录 {persist_directory} 不存在,⽆需清理。")# except Exception as e:# print(f"清理⽬录 {persist_directory} 失败: {e}")vector_db = None # 初始化if document_chunks and embedding_model: # 确保前⾯的步骤成功print(f"\n开始构建向量数据库和索引,使⽤集合名: {collection_name}...")try:vector_db = Chroma.from_documents(documents=document_chunks, # 前⾯分割好的⽂本块列表embedding=embedding_model, # 初始化好的Embedding模型实例collection_name=collection_name,persist_directory=persist_directory # 指定持久化路径)# Chroma.from_documents 会⾃动处理持久化,但显式调⽤ persist() 确保写⼊磁盘# vector_db.persist() # 对于某些版本的ChromaDB或特定⽤法可能需要print(f"向量数据库 '{collection_name}' 构建完成并已持久化到 '{persist_dirprint(f"数据库中包含 {vector_db._collection.count()} 个向量条⽬.")except Exception as e:print(f"构建ChromaDB失败: {e}")向量数据库(e.g.,ChromaDB)构建⾼效检索索引else:print("\n由于⽂档块列表为空或Embedding模型未加载,跳过向量数据库构建。")
说明: Chroma.from_documents ⽅法会⾃动对传⼊的 document_chunks 进⾏向量化(使⽤我们提供的 embedding_model ),并将⽂本内容、向量以及元数据⼀同存储到ChromaDB中。通过指定 persist_directory ,数据库的内容会被保存在本地磁盘,方便后续加载使用,避免每次重新计算。如果持久化⽬录已存在且包含同名集合,Chroma通常会尝试加载现有数据,除⾮我们⼿动清空⽬录。