使用Langchain+Azure嵌入加载Faiss索引时遇Document属性错误
解决Langchain加载FAISS索引时的AttributeError: Can't get attribute 'Document'问题
问题根源
这个错误是pickle反序列化时类路径不匹配导致的:你当前使用的Langchain 0.0.123版本中,Document类位于langchain.docstore.document模块,但生成Faiss索引时使用的Langchain版本(大概率是更高版本)将Document类迁移到了langchain.schema模块。pickle序列化会记录类的完整路径,加载时找不到对应路径就会抛出该错误。
解决方案
方案1:统一Langchain版本
确保生成Faiss索引的ingest.py和加载索引的代码使用完全相同的Langchain版本:
- 查看生成索引时使用的Langchain版本(如果能找到当时的环境记录)
- 在当前环境安装对应版本:
pip install langchain==<生成时的版本号>
如果不确定生成时的版本,也可以尝试升级到较新的稳定版本(比如0.0.280+),同时重新运行ingest.py生成新的Faiss索引:
pip install --upgrade langchain # 重新生成索引 python ingest.py
方案2:手动注册Document类到目标模块
如果无法修改版本或重新生成索引,可在加载FAISS索引前,手动将Document类注册到langchain.schema模块,让pickle能找到对应类:
修改你的启动代码:
from langchain.vectorstores import VectorStore from langchain.docstore.document import Document import langchain.schema from langchain.embeddings.openai import OpenAIEmbeddings from pathlib import Path import logging from typing import Optional # 手动注册Document类到langchain.schema langchain.schema.Document = Document vectorstore: Optional[VectorStore] = None @app.on_event("startup") async def startup_event(): logging.info("loading vectorstore") if not Path("helpdesk_faiss_index").exists(): raise ValueError("helpdesk_faiss_index does not exist, please run ingest.py first") # 确保Azure OpenAI嵌入配置正确 embeddings = OpenAIEmbeddings( deployment="your-azure-deployment-name", model="your-azure-model-name", openai_api_base="https://your-resource-name.openai.azure.com/", openai_api_type="azure", openai_api_version="2023-05-15" ) global vectorstore vectorstore = FAISS.load_local("faiss_index", embeddings)
额外检查:Azure OpenAI嵌入配置
虽然该错误和Azure嵌入无直接关联,但确保嵌入初始化时配置正确的Azure参数,避免后续其他问题。
内容的提问来源于stack exchange,提问作者kslote1
相关产品推荐
相关产品推荐

