引言
在信息检索中,从文档库中获取相关文档的能力至关重要。然而,检索器返回的文档通常不包含检索过程中使用的信息,例如查询的相似性分数。在这篇文章中,我们将探讨如何在文档的元数据中添加检索分数,以便更好地分析和处理检索结果。
主要内容
1. 从向量存储检索器获取分数
向量存储检索器能够使用相似性搜索方法提供文档与查询的相似性分数。我们可以通过包装检索器的similarity_search_with_score方法来实现这一功能。
# 使用API代理服务提高访问稳定性
from langchain_core.documents import Document
from langchain_openai import OpenAIEmbeddings
from langchain_pinecone import PineconeVectorStore
# 初始化向量存储
docs = [
Document(page_content="A bunch of scientists bring back dinosaurs and mayhem breaks loose", metadata={"year": 1993, "rating": 7.7, "genre": "science fiction"}),
# 其他文档初始化...
]
vectorstore = PineconeVectorStore.from_documents(docs, index_name="sample", embedding=OpenAIEmbeddings())
2. 自定义检索器添加分数
通过创建一个简单的包装函数,并使用@chain装饰器,我们可以在返回的文档中添加相似性分数。
from typing import List
from langchain_core.documents import Document
from langchain_core.runnables import chain
@chain
def retriever(query: str) -> List[Document]:
docs, scores = zip(*vectorstore.similarity_search_with_score(query))
for doc, score in zip(docs, scores):
doc.metadata["score"] = score
return docs
# 示例调用
result = retriever.invoke("dinosaur")
3. SelfQueryRetriever 和 MultiVectorRetriever 的应用
对于更高级的检索器,如SelfQueryRetriever和MultiVectorRetriever,我们可以通过重写它们的特定方法来添加分数。
SelfQueryRetriever
通过重写_get_docs_with_query方法,我们可以沿用检索器的结构化查询功能,同时添加分数。
from langchain.retrievers.self_query.base import SelfQueryRetriever
class CustomSelfQueryRetriever(SelfQueryRetriever):
def _get_docs_with_query(self, query: str, search_kwargs: Dict[str, Any]) -> List[Document]:
docs, scores = zip(*vectorstore.similarity_search_with_score(query, **search_kwargs))
for doc, score in zip(docs, scores):
doc.metadata["score"] = score
return docs
代码示例
以下代码示例展示了如何初始化一个自定义检索器,并包含了相似性分数:
retriever = CustomSelfQueryRetriever.from_llm(
llm,
vectorstore,
document_content_description,
metadata_field_info
)
result = retriever.invoke("dinosaur movie with rating less than 8")
常见问题和解决方案
- **检索结果不稳定?**由于网络限制,建议使用API代理服务以提高访问稳定性。
- **如何优化检索性能?**确保向量存储的索引参数设置合理,同时定期更新嵌入。
总结和进一步学习资源
向文档的元数据中添加检索分数能够显著提高检索结果的可解释性和分析能力。建议读者进一步学习向量数据库的使用以及高级检索器的实现。
参考资料
- LangChain 文档: https://www.langchain.com/docs
- Pinecone 向量存储: https://www.pinecone.io/
- OpenAI 嵌入: https://beta.openai.com/docs/guides/embeddings
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—
2242

被折叠的 条评论
为什么被折叠?



