WatsonxChatGenerator
使用此组件与 IBM watsonx 模型,例如granite-3-2b-instruct 进行聊天生成。
| pipeline 中的最常见位置 | 在 ChatPromptBuilder 之后 |
| 必需的初始化变量 | "api_key": IBM Cloud API 密钥。可以设置为环境变量 WATSONX_API_KEY。"project_id": IBM Cloud 项目 ID。可以设置为环境变量 WATSONX_PROJECT_ID。 |
| 强制运行变量 | "messages" 一个 ChatMessage 对象列表 |
| 输出变量 | "replies": 一个 ChatMessage 对象列表 |
| API 参考 | Watsonx |
| GitHub 链接 | https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/watsonx |
此集成支持 IBM watsonx.ai 基础模型,例如ibm/granite-13b-chat-v2, ibm/llama-2-70b-chat, ibm/llama-3-70b-instruct,以及类似的。这些模型通过 IBM 的云平台提供高质量的聊天完成功能。请在 IBM watsonx.ai 文档 中查看最新的完整列表。
概述
WatsonxChatGenerator 需要 IBM Cloud 凭据才能工作。您可以在
- 该
api_key和项目 ID 使用 Secret API 的 init 参数中设置 - 该默认情况下,使用
WATSONX_API_KEY和环境变量WATSONX_PROJECT_ID(推荐)
然后,该组件需要一个提示才能运行,但您可以使用任何适用于 IBM watsonx.ai API 的文本生成参数,直接通过generation_kwargs 参数,无论是初始化时还是run() 方法传递给此组件。有关 IBM watsonx.ai API 支持的参数的更多详细信息,请参阅 IBM watsonx.ai 文档。
最后,该组件需要一个列表ChatMessage 对象列表才能运行。ChatMessage 是一个数据类,其中包含消息、角色(谁生成了消息,例如user, assistant, system, function),以及可选的元数据。
流式传输
此 Generator 支持将 LLM 的 token直接流式传输到输出中。要做到这一点,请将一个函数传递给streaming_callback 初始化参数。
用法
您需要首先安装使用 watsonx-haystack 包来使用WatsonxChatGenerator:
pip install watsonx-haystack
单独使用
from haystack_integrations.components.generators.watsonx.chat.chat_generator import WatsonxChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.utils import Secret
generator = WatsonxChatGenerator(
api_key=Secret.from_env_var("WATSONX_API_KEY"),
project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
model="ibm/granite-13b-instruct-v2"
)
message = ChatMessage.from_user("What's Natural Language Processing? Be brief.")
print(generator.run([message]))
在 Pipeline 中
您也可以使用WatsonxChatGenerator 以在您的管道中使用 IBM watsonx.ai 聊天模型。
from haystack import Pipeline
from haystack.components.builders import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.watsonx.chat.chat_generator import WatsonxChatGenerator
from haystack.utils import Secret
pipe = Pipeline()
pipe.add_component("prompt_builder", ChatPromptBuilder())
pipe.add_component("llm", WatsonxChatGenerator(
api_key=Secret.from_env_var("WATSONX_API_KEY"),
project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
model="ibm/granite-13b-instruct-v2"
))
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)
更新于 3 个月前
