CohereChatGenerator
CohereChatGenerator 使用 Cohere 的大型语言模型 (LLM) 来实现聊天补全。
| pipeline 中的最常见位置 | 在 ChatPromptBuilder 之后 |
| 必需的初始化变量 | "api_key": Cohere API 密钥。可以设置为COHERE_API_KEY 或CO_API_KEY 环境变量。 |
| 强制运行变量 | “messages” 一个 ChatMessage 对象列表 |
| 输出变量 | "replies": 一个 ChatMessage 对象列表”meta”:一个包含与每个回复相关的元数据的字典列表,例如 token 计数、结束原因等 |
| API 参考 | Cohere |
| GitHub 链接 | https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/cohere |
此集成支持 Coherechat 模型,例如command,command-r 和comman-r-plus。请参阅 Cohere 文档中的最新完整列表。
概述
CohereChatGenerator 需要 Cohere API 密钥才能工作。您可以将其设置为
- 该
api_key初始化参数中使用 Secret API - 该
COHERE_API_KEY环境变量(推荐)
然后,该组件需要一个 prompt 来运行,但您可以通过Co.chat 方法,直接传递给此组件,使用generation_kwargs 参数,无论是初始化时还是run() 方法。有关 Cohere API 支持的参数的更多详细信息,请参阅 Cohere 文档。
最后,组件需要一个列表ChatMessage 对象列表才能运行。ChatMessage 是一个数据类,其中包含消息、角色(谁生成了消息,例如user, assistant, system, function),以及可选的元数据。
流式传输
此 Generator 支持将 LLM 的 token直接流式传输到输出中。要做到这一点,请将一个函数传递给streaming_callback 初始化参数。
用法
您需要首先安装cohere-haystack 包才能使用CohereChatGenerator:
pip install cohere-haystack
单独使用
from haystack_integrations.components.generators.cohere import CohereChatGenerator
from haystack.dataclasses import ChatMessage
generator = CohereChatGenerator()
message = ChatMessage.from_user("What's Natural Language Processing? Be brief.")
print(generator.run([message]))
在 Pipeline 中
您也可以使用CohereChatGenerator 在您的 pipeline 中使用 cohere 聊天模型。
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.cohere import CohereChatGenerator
from haystack.utils import Secret
pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component("llm", CohereChatGenerator())
pipe.connect("prompt_builder", "llm")
country = "Germany"
system_message = ChatMessage.from_system("You are an assistant giving out valuable information to language learners.")
messages = [system_message, ChatMessage.from_user("What's the official language of {{ country }}?")]
res = pipe.run(data={"prompt_builder": {"template_variables": {"country": country}, "template": messages}})
print(res)
更新于 大约 1 年前
