CohereRanker
使用 Cohere rerank 模型根据与查询的相似性对文档进行排名。
| pipeline 中的最常见位置 | 在查询管道中,在返回文档列表的组件(例如 Retriever)之后 |
| 必需的初始化变量 | "api_key": Cohere API 密钥。可以设置为COHERE_API_KEY 或CO_API_KEY 环境变量。 |
| 强制运行变量 | “documents”: 文档对象列表 “query”: 查询字符串 “top_k”: 要返回的最大文档数 |
| 输出变量 | “documents”: 文档对象列表 |
| API 参考 | Cohere |
| GitHub 链接 | https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/cohere |
概述
CohereRanker 排名Documents 基于与指定查询的语义相关性。它使用 Cohere rerank 模型进行排名。所有支持的模型列表可以在 Cohere 的 文档 中找到。此 Ranker 的默认模型是rerank-english-v2.0.
您也可以指定top_k 参数来设置要返回的文档的最大数量。
要开始将此集成与 Haystack 一起使用,请使用以下命令安装它:
pip install cohere-haystack
该组件默认使用COHERE_API_KEY 或默认情况下,CO_API_KEY 环境变量。否则,您可以在初始化时通过 传入 Cohere API 密钥api_key 按如下方式传递 Jina API 密钥:
ranker = CohereRanker(api_key=Secret.from_token("<your-api-key>"))
用法
单独使用
此示例使用CohereRanker 对两个简单文档进行排名。要运行 Ranker,请传递一个query,提供documents,并在top_k 参数中设置要返回的文档数量。
from haystack import Document
from haystack_integrations.components.rankers.cohere import CohereRanker
docs = [Document(content="Paris"), Document(content="Berlin")]
ranker = CohereRanker()
ranker.run(query="City in France", documents=docs, top_k=1)
在 pipeline 中
以下是一个管道的示例,该管道使用InMemoryDocumentStore 基于关键字搜索(使用InMemoryBM25Retriever)设置要排名的文档数量。然后,它使用CohereRanker 以根据检索到的文档与查询的相似性对其进行排名。该管道使用 Ranker 的默认设置。
from haystack import Document, Pipeline
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.rankers.cohere import CohereRanker
docs = [
Document(content="Paris is in France"),
Document(content="Berlin is in Germany"),
Document(content="Lyon is in France"),
]
document_store = InMemoryDocumentStore()
document_store.write_documents(docs)
retriever = InMemoryBM25Retriever(document_store=document_store)
ranker = CohereRanker()
document_ranker_pipeline = Pipeline()
document_ranker_pipeline.add_component(instance=retriever, name="retriever")
document_ranker_pipeline.add_component(instance=ranker, name="ranker")
document_ranker_pipeline.connect("retriever.documents", "ranker.documents")
query = "Cities in France"
res = document_ranker_pipeline.run(data={"retriever": {"query": query, "top_k": 3}, "ranker": {"query": query, "top_k": 2}})
top_k参数在上面的示例中,检索器和 Ranker 的
top_k值不同。检索器的top_k指定了它返回的文档数量。然后,Ranker 对这些文档进行排序。您可以为 Ranker 设置相同或更小的
top_k值。Ranker 的top_k是它返回的文档数量(如果它是管道中的最后一个组件)或转发到下一个组件的数量。在上面的管道示例中,Ranker 是最后一个组件,因此运行管道时获得的输出是前两个文档,如 Ranker 的top_k.调整
top_k值可以帮助您优化性能。在这种情况下,检索器较小的top_k值意味着 Ranker 需要处理的文档更少,这可以加快管道的运行速度。
更新于 大约 1 年前
