文档API 参考📓 教程🧑‍🍳 食谱🤝 集成💜 Discord🎨 Studio
文档

CohereTextEmbedder

该组件使用 Cohere 嵌入模型将字符串转换为捕获其语义的向量。在执行嵌入检索时,您使用此组件将查询转换为向量。然后,嵌入检索器会查找相似或相关的文档。

pipeline 中的最常见位置在查询/RAG 管道中的嵌入 检索器 之前
必需的初始化变量"api_key": Cohere API 密钥。可以设置为COHERE_API_KEYCO_API_KEY 环境变量。
强制运行变量“text”: 一个字符串
输出变量“embedding”:浮点数列表(向量)

“meta”:字符串元数据字典
API 参考Cohere
GitHub 链接https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/cohere

概述

CohereTextEmbedder 将一个简单的字符串(如查询)嵌入到向量中。对于嵌入文档列表,请使用 CohereDocumentEmbedder,它会用计算出的嵌入(也称为向量)来丰富文档。

该组件支持以下 Cohere 模型
"embed-english-v3.0", "embed-english-light-v3.0", "embed-multilingual-v3.0",
"embed-multilingual-light-v3.0", "embed-english-v2.0", "embed-english-light-v2.0",
"embed-multilingual-v2.0"。默认模型是embed-english-v2.0。您可以在 Cohere 的模型文档中找到所有支持的模型列表。

要开始将此集成与 Haystack 一起使用,请使用以下命令安装它:

pip install cohere-haystack

该组件默认使用COHERE_API_KEY默认情况下使用CO_API_KEY 环境变量。否则,您可以在初始化时通过 Secret 传递 API 密钥,并且Secret.from_token 静态方法传递 API 密钥。

embedder = CohereTextEmbedder(api_key=Secret.from_token("<your-api-key>"))

要获取 Cohere API 密钥,请访问 https://cohere.com/

用法

单独使用

您可以在此处独立使用该组件。您需要通过 Secret 传递 Cohere API 密钥,或将其设置为名为COHERE_API_KEY 的环境变量。下面的示例假定您已设置环境变量。

from haystack_integrations.components.embedders.cohere.text_embedder import CohereTextEmbedder

text_to_embed = "I love pizza!"

text_embedder = CohereTextEmbedder()

print(text_embedder.run(text_to_embed))
# {'embedding': [-0.453125, 1.2236328, 2.0058594, 0.67871094...], 
#  'meta': {'api_version': {'version': '1'}, 'billed_units': {'input_tokens': 4}}}

在 pipeline 中

from haystack import Document
from haystack import Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.embedders.cohere.text_embedder import CohereTextEmbedder
from haystack_integrations.components.embedders.cohere.document_embedder import CohereDocumentEmbedder
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever

document_store = InMemoryDocumentStore(embedding_similarity_function="cosine")

documents = [Document(content="My name is Wolfgang and I live in Berlin"),
             Document(content="I saw a black horse running"),
             Document(content="Germany has many big cities")]

document_embedder = CohereDocumentEmbedder()
documents_with_embeddings = document_embedder.run(documents)['documents']
document_store.write_documents(documents_with_embeddings)

query_pipeline = Pipeline()
query_pipeline.add_component("text_embedder", CohereTextEmbedder())
query_pipeline.add_component("retriever", InMemoryEmbeddingRetriever(document_store=document_store))
query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")

query = "Who lives in Berlin?"

result = query_pipeline.run({"text_embedder":{"text": query}})

print(result['retriever']['documents'][0])

# Document(id=..., content: 'My name is Wolfgang and I live in Berlin')

相关链接

请查看 GitHub 仓库或我们的文档中的 API 参考