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

WatsonxGenerator

使用此组件与 IBM watsonx 模型,例如granite-3-2b-instruct,用于简单的文本生成任务。

pipeline 中的最常见位置PromptBuilder 之后
必需的初始化变量"api_key": IBM Cloud API 密钥。可以设置为环境变量 WATSONX_API_KEY

"project_id": IBM Cloud 项目 ID。可以设置为环境变量 WATSONX_PROJECT_ID
强制运行变量"prompt": 包含 LLM 提示的字符串
输出变量"replies": 包含 LLM 生成的所有回复的字符串列表

"meta": 包含与每个回复相关的元数据的字典列表,例如 token 计数、结束原因等
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 文档 中的最新完整列表。

参数

WatsonxGenerator 需要 IBM Cloud 凭据才能工作。您可以在以下位置提供这些凭据:

  • WATSONX_API_KEY 环境变量(推荐)
  • WATSONX_PROJECT_ID 环境变量(推荐)
  • api_key使用 Haystack 的 Secret API 在 project_id 初始化参数中提供Secret.from_token("your-api-key-here")

在初始化组件时,在model 参数中设置您偏好的 IBM watsonx.ai 模型。默认模型是ibm/granite-3-2b-instruct.

WatsonxGenerator 需要提示来生成文本,但您可以使用generation_kwargs 参数,无论是初始化时还是run() 方法将 IBM watsonx.ai API 中可用的任何文本生成参数直接传递给此组件。有关 IBM watsonx.ai API 支持的参数的更多详细信息,请参阅 IBM watsonx.ai 文档

该组件还支持系统提示,这些提示可以在初始化时设置或在运行时传递,以提供上下文或生成说明。

最后,组件的 run 方法需要一个单一的字符串提示来生成文本。

流式传输

此 Generator 支持将 LLM 的 token直接流式传输到输出中。要做到这一点,请将一个函数传递给streaming_callback 初始化参数。

用法

安装使用 watsonx-haystack 包来使用WatsonxGenerator:

pip install watsonx-haystack

单独使用

from haystack_integrations.components.generators.watsonx.generator import WatsonxGenerator
from haystack.utils import Secret

generator = WatsonxGenerator(
    api_key=Secret.from_env_var("WATSONX_API_KEY"),
    project_id=Secret.from_env_var("WATSONX_PROJECT_ID")
)

print(generator.run("What's Natural Language Processing? Be brief."))

在 pipeline 中

您也可以使用WatsonxGenerator 与您的 pipeline 中的 IBM watsonx.ai 模型集成。

from haystack import Pipeline
from haystack.components.builders import PromptBuilder
from haystack_integrations.components.generators.watsonx.generator import WatsonxGenerator
from haystack.utils import Secret

template = """
You are an assistant giving out valuable information to language learners.
Answer this question, be brief.

Question: {{ query }}?
"""

pipe = Pipeline()
pipe.add_component("prompt_builder", PromptBuilder(template))
pipe.add_component("llm", WatsonxGenerator(
    api_key=Secret.from_env_var("WATSONX_API_KEY"),
    project_id=Secret.from_env_var("WATSONX_PROJECT_ID")
))
pipe.connect("prompt_builder", "llm")

query = "What language is spoken in Germany?"
res = pipe.run(data={"prompt_builder": {"query": query}})

print(res)