混合搜索
LangChain 中的标准搜索是通过 vector 相似度完成的。但是,许多矢量存储实现(Astra DB、ElasticSearch、Neo4J、AzureSearch、Qdrant等)也支持更高级的搜索,将矢量相似性搜索与其他搜索技术(全文、BM25 等)相结合。这通常称为 “混合” 搜索。
第 1 步:确保您使用的 vectorstore 支持混合搜索
目前,在 LangChain 中没有统一的混合搜索方法。每个 vectorstore 可能都有自己的方法。这通常作为在similarity_search.
通过阅读文档或源代码,弄清楚您使用的 vectorstore 是否支持混合搜索,如果支持,如何使用它。
第 2 步:将该参数添加为链的可配置字段
这将使你能够在运行时轻松调用链并配置任何相关标志。有关配置的更多信息,请参阅此文档。
第 3 步:使用该可配置字段调用链
现在,在运行时,你可以使用 configurable field 调用这个链。
代码示例
让我们看一个具体的例子,说明这在代码中是什么样子的。在此示例中,我们将使用 Astra DB 的 Cassandra/CQL 接口。
安装以下 Python 包:
!pip install "cassio>=0.1.7"
获取连接密钥。
初始化 cassio:
import cassio
cassio.init(
database_id="Your database ID",
token="Your application token",
keyspace="Your key space",
)
使用标准索引分析器创建 Cassandra VectorStore。需要索引分析器来启用术语匹配。
from cassio.table.cql import STANDARD_ANALYZER
from langchain_community.vectorstores import Cassandra
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
vectorstore = Cassandra(
embedding=embeddings,
table_name="test_hybrid",
body_index_options=[STANDARD_ANALYZER],
session=None,
keyspace=None,
)
vectorstore.add_texts(
[
"In 2023, I visited Paris",
"In 2022, I visited New York",
"In 2021, I visited New Orleans",
]
)
如果我们进行标准的相似性搜索,我们会得到所有文档:
vectorstore.as_retriever().invoke("What city did I visit last?")
[Document(page_content='In 2022, I visited New York'),
Document(page_content='In 2023, I visited Paris'),
Document(page_content='In 2021, I visited New Orleans')]
Astra DB 矢量存储body_search参数可用于筛选对术语的搜索new.
vectorstore.as_retriever(search_kwargs={"body_search": "new"}).invoke(
"What city did I visit last?"
)
[Document(page_content='In 2022, I visited New York'),
Document(page_content='In 2021, I visited New Orleans')]
现在,我们可以创建用于进行问答的链
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import (
ConfigurableField,
RunnablePassthrough,
)
from langchain_openai import ChatOpenAI
这是基本的问答链设置。
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
model = ChatOpenAI()
retriever = vectorstore.as_retriever()
在这里,我们将检索器标记为具有可配置字段。所有 vectorstore 检索器都有search_kwargs作为字段。这只是一个字典,具有 vectorstore 特定的字段
configurable_retriever = retriever.configurable_fields(
search_kwargs=ConfigurableField(
id="search_kwargs",
name="Search Kwargs",
description="The search kwargs to use",
)
)
我们现在可以使用可配置的检索器创建链
chain = (
{"context": configurable_retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
chain.invoke("What city did I visit last?")
Paris
我们现在可以使用可配置的选项调用链。search_kwargs是 Configurable 字段的 ID。该值是用于 Astra DB 的搜索 kwargs 。
chain.invoke(
"What city did I visit last?",
config={"configurable": {"search_kwargs": {"body_search": "new"}}},
)
New York