Haystack 集成 IBM watsonx.ai 完全指南:TextEmbedder、DocumentEmbedder 与 Generator/ChatGenerator 实战
发布时间:2026/9/15 0:17:12来源:尧图网络
Haystack 集成 IBM watsonx.ai 完全指南TextEmbedder、DocumentEmbedder 与 Generator/ChatGenerator 实战【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystackIBM watsonx.ai 是 IBM 的企业级 AI 与数据平台托管了 Granite、Llama、Mistral 等大量开源基础模型与嵌入模型。本文基于 Haystack 仓库中 version-2.21 的 watsonx 集成 API 参考文档系统讲解watsonx-haystack集成包中四大核心组件——WatsonxDocumentEmbedder、WatsonxTextEmbedder、WatsonxChatGenerator、WatsonxGenerator的初始化参数、运行方法与实战用法。读完本文你将能够用 watsonx.ai 的嵌入模型搭建完整的语义检索/RAG 管道并用其生成模型实现对话补全、多模态问答与文本生成。集成概览安装、凭证与模型watsonx 集成是 Haystack 生态中的独立扩展包对应 Python 包watsonx-haystack代码模块统一以haystack_integrations.components.*形式导入在 Haystack 仓库内由 API 参考文档 与各组件的 使用指南 共同维护。使用时先安装pip install watsonx-haystack所有组件都通过同样的两把钥匙认证WATSONX_API_KEY环境变量IBM Cloud API Key可在 IBM Cloud 控制台获取WATSONX_PROJECT_ID环境变量Watson Studio 项目 ID。官方推荐优先使用环境变量使用指南中明确建议将其设为环境变量而非硬编码参数也可以初始化时通过 Haystack 的SecretAPI 传入from haystack.utils import Secret embedder WatsonxTextEmbedder( api_keySecret.from_token(your-api-key), project_idSecret.from_token(your-project-id), )Secret.from_env_var(WATSONX_API_KEY)与Secret.from_token(...)是两种等价的注入方式除凭证外还可通过api_base_url指定服务端点默认值为https://us-south.ml.cloud.ibm.com美国南部区域。需要说明的是watsonx 集成组件的源码托管在独立的 haystack-core-integrations 仓库中当前 Haystack 仓库内只包含其文档与参考说明。WatsonxDocumentEmbedder为文档批量计算向量WatsonxDocumentEmbedder的作用是使用 IBM watsonx.ai 嵌入模型计算文档嵌入并把生成的向量写回每个Document对象。它通常位于索引管道中DocumentWriter之前参考文档与 watsonxdocumentembedder.mdx 均给出了这一典型位置。索引阶段计算好的向量正是检索阶段进行向量相似度比较的基础。基础用法from haystack import Document from haystack_integrations.components.embedders.watsonx.document_embedder import WatsonxDocumentEmbedder documents [ Document(contentI love pizza!), Document(contentPasta is great too), ] document_embedder WatsonxDocumentEmbedder( modelibm/slate-30m-english-rtrvr-v2, api_keySecret.from_env_var(WATSONX_API_KEY), api_base_urlhttps://us-south.ml.cloud.ibm.com, project_idSecret.from_env_var(WATSONX_PROJECT_ID), ) result document_embedder.run(documentsdocuments) print(result[documents][0].embedding) # [0.017020374536514282, -0.023255806416273117, ...]run(documents: list[Document])的返回值包含两个键documents已附加嵌入向量的文档列表meta模型使用信息如所用模型名。完整参数说明参数类型默认值说明modelstribm/slate-30m-english-rtrvr-v2用于计算嵌入的模型名api_keySecretSecret.from_env_var(WATSONX_API_KEY)watsonx API Keyapi_base_urlstrhttps://us-south.ml.cloud.ibm.comwatsonx.ai 服务地址project_idSecretSecret.from_env_var(WATSONX_PROJECT_ID)Watson Studio 项目 IDtruncate_input_tokensint \| NoneNone输入文本最多使用的 token 数设为None时使用完整输入不超过模型上限prefixstr附加到每段文本开头的字符串suffixstr附加到每段文本末尾的字符串batch_sizeint1000单次 API 调用中嵌入的文档数concurrency_limitint5并行请求数timeoutfloat \| NoneNoneAPI 请求超时秒max_retriesint \| NoneNoneAPI 请求最大重试次数meta_fields_to_embedlist[str] \| NoneNone需要一并嵌入的元数据字段名列表embedding_separatorstr\n拼接元数据与正文时使用的分隔符其中batch_size与concurrency_limit是文档嵌入特有的批量控制参数前者决定单次请求的文档数后者决定并发请求数两者共同影响吞吐量与限流表现适合大批量索引场景。嵌入元数据提升检索效果文本文档通常带有一组元数据如标题、页号。若这些元数据有区分度、语义有意义可以将其与正文一起嵌入以提升检索质量。WatsonxDocumentEmbedder通过meta_fields_to_embed支持这一能力见 watsonxdocumentembedder.mdx 的 Embedding Metadata 章节from haystack import Document from haystack_integrations.components.embedders.watsonx.document_embedder import WatsonxDocumentEmbedder from haystack.utils import Secret doc Document(contentsome text, meta{title: relevant title, page number: 18}) embedder WatsonxDocumentEmbedder( api_keySecret.from_env_var(WATSONX_API_KEY), project_idSecret.from_env_var(WATSONX_PROJECT_ID), meta_fields_to_embed[title], ) docs_w_embeddings embedder.run(documents[doc])[documents]被选中的元数据字段会与正文拼接默认以换行符\n分隔可用embedding_separator调整后统一送入模型编码。WatsonxTextEmbedder将查询转为向量WatsonxTextEmbedder用于嵌入单个字符串典型场景是查询/用户问题生成的结果可直接传给嵌入检索器Embedding Retriever做相似度匹配。它通常位于查询/RAG 管道中检索器之前见 watsonxtextembedder.mdx。它和文档嵌入器的核心区别是处理单条文本而非文档列表因此没有batch_size、concurrency_limit、meta_fields_to_embed、embedding_separator这些批量与元数据参数。基础用法from haystack_integrations.components.embedders.watsonx.text_embedder import WatsonxTextEmbedder text_to_embed I love pizza! text_embedder WatsonxTextEmbedder( modelibm/slate-30m-english-rtrvr-v2, api_keySecret.from_env_var(WATSONX_API_KEY), api_base_urlhttps://us-south.ml.cloud.ibm.com, project_idSecret.from_env_var(WATSONX_PROJECT_ID), ) print(text_embedder.run(text_to_embed)) # {embedding: [0.017020374536514282, -0.023255806416273117, ...], # meta: {model: ibm/slate-30m-english-rtrvr-v2, # truncated_input_tokens: 3}}run(text: str)返回两个键embedding输入文本的嵌入向量list[float]meta模型使用信息示例中可见truncated_input_tokens字段——当输入超过truncate_input_tokens限制时模型会截断输入该字段记录实际截断后的 token 数。完整参数说明参数类型默认值说明modelstribm/slate-30m-english-rtrvr-v2嵌入模型名api_keySecretSecret.from_env_var(WATSONX_API_KEY)watsonx API Keyapi_base_urlstrhttps://us-south.ml.cloud.ibm.comwatsonx.ai 服务地址project_idSecretSecret.from_env_var(WATSONX_PROJECT_ID)Watson Studio 项目 IDtruncate_input_tokensint \| NoneNone输入文本最大 token 数None时用完整输入prefixstr附加到待嵌入文本开头的字符串suffixstr附加到待嵌入文本末尾的字符串timeoutfloat \| NoneNoneAPI 请求超时秒max_retriesint \| NoneNoneAPI 请求最大重试次数实战用两大嵌入器搭建语义检索/RAG 管道把两个嵌入器组合进 HaystackPipeline即可完成从文档入库到查询检索的完整闭环。下面的例子来自 watsonxdocumentembedder.mdx 的 In a pipeline 章节使用InMemoryDocumentStore余弦相似度作为向量存储from haystack import Pipeline, Document from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.components.writers import DocumentWriter from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack_integrations.components.embedders.watsonx.document_embedder import ( WatsonxDocumentEmbedder, ) from haystack_integrations.components.embedders.watsonx.text_embedder import ( WatsonxTextEmbedder, ) document_store InMemoryDocumentStore(embedding_similarity_functioncosine) documents [ Document(contentMy name is Wolfgang and I live in Berlin), Document(contentI saw a black horse running), Document(contentGermany has many big cities), ] # 索引管道嵌入 写入 indexing_pipeline Pipeline() indexing_pipeline.add_component(embedder, WatsonxDocumentEmbedder()) indexing_pipeline.add_component(writer, DocumentWriter(document_storedocument_store)) indexing_pipeline.connect(embedder, writer) indexing_pipeline.run({embedder: {documents: documents}}) # 查询管道查询嵌入 - 向量检索 query_pipeline Pipeline() query_pipeline.add_component(text_embedder, WatsonxTextEmbedder()) query_pipeline.add_component( retriever, InMemoryEmbeddingRetriever(document_storedocument_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..., text: My name is Wolfgang and I live in Berlin)要点WatsonxTextEmbedder的输出embedding通过connect接入检索器的query_embedding输入槽文档侧则由WatsonxDocumentEmbedder先算好向量、经DocumentWriter写入存储。整个过程中查询向量与文档向量都由 watsonx 嵌入模型统一编码保证向量空间一致。WatsonxChatGenerator基于 ChatMessage 的对话补全WatsonxChatGenerator使用 IBM watsonx.ai 基础模型完成对话补全输入输出均遵循 Haystack 的ChatMessage数据类格式并支持包含文本与图片的多模态输入。它通常位于聊天管道中ChatPromptBuilder之后watsonxchatgenerator.mdx。基础用法from haystack_integrations.components.generators.watsonx.chat.chat_generator import WatsonxChatGenerator from haystack.dataclasses import ChatMessage from haystack.utils import Secret messages [ChatMessage.from_user(Explain quantum computing in simple terms)] client WatsonxChatGenerator( api_keySecret.from_env_var(WATSONX_API_KEY), modelibm/granite-4-h-small, project_idSecret.from_env_var(WATSONX_PROJECT_ID), ) response client.run(messages) print(response)多模态用法配合ImageContent数据类WatsonxChatGenerator可以直接把本地图片加入对话。ImageContent.from_file_path支持从文件路径构造图片内容也支持 base64from haystack.dataclasses import ChatMessage, ImageContent # Create an image from file path or base64 image_content ImageContent.from_file_path(path/to/your/image.jpg) # Create a multimodal message with both text and image messages [ChatMessage.from_user(content_parts[Whats in this image?, image_content])] # Use a multimodal model client WatsonxChatGenerator( api_keySecret.from_env_var(WATSONX_API_KEY), modelmeta-llama/llama-3-2-11b-vision-instruct, project_idSecret.from_env_var(WATSONX_PROJECT_ID), ) response client.run(messages) print(response)注意多模态能力依赖所选模型本身支持图像输入如 Llama 3.2 Vision 系列。watsonxchatgenerator.mdx 中的示例使用meta-llama/llama-3-2-11b-vision-instruct对一张苹果图片提问得到的回答形如 Red apple on straw.。SUPPORTED_MODELS 列表组件内置了一份非穷尽的受支持模型清单参考文档中完整列出涵盖 Granite、Llama、Mistral、OpenAIOSS等系列SUPPORTED_MODELS: list[str] [ ibm/granite-3-1-8b-base, ibm/granite-3-8b-instruct, ibm/granite-4-h-small, ibm/granite-8b-code-instruct, ibm/granite-guardian-3-8b, meta-llama/llama-3-1-70b-gptq, meta-llama/llama-3-1-8b, meta-llama/llama-3-2-11b-vision-instruct, meta-llama/llama-3-2-90b-vision-instruct, meta-llama/llama-3-3-70b-instruct, meta-llama/llama-3-405b-instruct, meta-llama/llama-4-maverick-17b-128e-instruct-fp8, meta-llama/llama-guard-3-11b-vision, mistral-large-2512, mistralai/mistral-medium-2505, mistralai/mistral-small-3-1-24b-instruct-2503, openai/gpt-oss-120b, ]该列表仅作参考完整且最新的模型 ID 需以 IBM 官方基础模型清单为准模型 ID 需与你在 IBM Cloud 账户中可用的部署一致。初始化参数详解__init__( *, api_key: Secret Secret.from_env_var(WATSONX_API_KEY), model: str ibm/granite-4-h-small, project_id: Secret Secret.from_env_var(WATSONX_PROJECT_ID), api_base_url: str https://us-south.ml.cloud.ibm.com, generation_kwargs: dict[str, Any] | None None, timeout: float | None None, max_retries: int | None None, verify: bool | str | None None, streaming_callback: StreamingCallbackT | None None, tools: ToolsType | None None ) - Noneapi_key/project_idIBM Cloud 凭证可用环境变量或直接传入。model补全所用模型 ID默认ibm/granite-4-h-small。api_base_urlAPI 端点基地址默认https://us-south.ml.cloud.ibm.com。generation_kwargs透传给 watsonx.ai 推理端点的生成参数支持但不限于temperature随机性控制越低越确定性输出max_new_tokens/min_new_tokens生成 token 数的上下限top_p核采样概率阈值top_k考虑的最高概率 token 数量repetition_penalty重复 token 惩罚length_penalty按输出长度的惩罚stop_sequences停止生成的分词序列列表random_seed随机种子用于复现结果timeout请求超时秒。默认读取环境变量WATSONX_TIMEOUT否则 30 秒。max_retries失败请求最大重试次数。默认读取环境变量WATSONX_MAX_RETRIES否则 5 次。verifySSL 校验设置可取True默认校验证书、False跳过校验不安全或自定义 CA 证书包路径。streaming_callback流式响应回调函数逐 token 回调。toolsTool / Toolset 对象列表或单个 Toolset供模型准备函数调用——这一参数使该组件可直接用于 Agent 场景。run 与 run_asyncrun同步生成对话补全run( *, messages: list[ChatMessage] | str, generation_kwargs: dict[str, Any] | None None, streaming_callback: StreamingCallbackT | None None, tools: ToolsType | None None ) - dict[str, list[ChatMessage]]messagesChatMessage列表也可直接传字符串组件会自动包装成一条 user 角色的ChatMessage。generation_kwargs运行时生成参数会覆盖__init__中设置的同名参数。streaming_callback若提供覆盖初始化时的回调。tools若设置覆盖初始化时的tools。返回字典键replies为生成的ChatMessage列表。run_async签名与run完全一致用于异步生成对话补全适合集成到基于asyncio的异步管道中。在管道中使用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_keySecret.from_env_var(WATSONX_API_KEY), project_idSecret.from_env_var(WATSONX_PROJECT_ID), modelibm/granite-4-h-small, ), ) 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(Whats the official language of {{ country }}?), ] res pipe.run( data{ prompt_builder: { template_variables: {country: country}, template: messages, }, }, ) print(res)ChatPromptBuilder负责把带 Jinja 模板变量的消息列表渲染成最终的ChatMessage序列再交给WatsonxChatGenerator生成回复。WatsonxGenerator面向 prompt 字符串的文本生成WatsonxGenerator继承自WatsonxChatGenerator参考文档中明确标注Bases: WatsonxChatGenerator在聊天补全能力之上提供标准的 Haystack Generator 接口——直接接收prompt 字符串而非ChatMessage对象。它通常位于PromptBuilder之后适合简单文本生成任务watsonxgenerator.mdx。基础用法from haystack_integrations.components.generators.watsonx.generator import WatsonxGenerator from haystack.utils import Secret generator WatsonxGenerator( api_keySecret.from_env_var(WATSONX_API_KEY), modelibm/granite-4-h-small, project_idSecret.from_env_var(WATSONX_PROJECT_ID), ) response generator.run( promptExplain quantum computing in simple terms, system_promptYou are a helpful physics teacher., ) print(response)输出示例{ replies: [Quantum computing uses quantum-mechanical phenomena like....], meta: [ { model: ibm/granite-4-h-small, project_id: your-project-id, usage: { prompt_tokens: 12, completion_tokens: 45, total_tokens: 57, }, } ], }从返回结构可见replies是生成的字符串列表meta是每个生成的元数据字典包含模型名、项目 ID 以及usage下的 token 用量统计输入/输出/总计。初始化参数差异WatsonxGenerator.__init__与WatsonxChatGenerator基本一致唯一新增参数是system_prompt: str | None None用于在初始化时固定系统提示词同时它没有tools参数。其余api_key、model、project_id、api_base_url、generation_kwargs、timeout默认WATSONX_TIMEOUT或 30 秒、max_retries默认WATSONX_MAX_RETRIES或 5 次、verify、streaming_callback均与聊天版一致generation_kwargs支持同样的参数集temperature、max_new_tokens、min_new_tokens、top_p、top_k、repetition_penalty、length_penalty、stop_sequences、random_seed等。它也维护了与WatsonxChatGenerator相同的SUPPORTED_MODELS清单。run 与 run_asyncrun( *, prompt: str, system_prompt: str | None None, streaming_callback: StreamingCallbackT | None None, generation_kwargs: dict[str, Any] | None None ) - dict[str, Any]prompt文本生成所需的输入 prompt 字符串。system_prompt可选的系统提示词未传入时使用__init__中设置的版本。streaming_callback若提供则覆盖初始化时的回调实现逐 token 流式输出。generation_kwargs运行时生成参数可覆盖初始化时的同名参数。返回replies生成的文本字符串列表meta每个生成的元数据含模型名、finish reason、token 用量。run_async签名相同用于异步文本生成。在管道中使用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_keySecret.from_env_var(WATSONX_API_KEY), project_idSecret.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)PromptBuilder渲染带{{ query }}变量的模板生成最终 promptWatsonxGenerator随后调用 watsonx.ai 基础模型生成回复。序列化to_dict / from_dict四大组件全部实现了 Haystack 标准的序列化协议详见 API 参考文档to_dict() - dict[str, Any]将组件序列化为字典便于保存到 YAML/JSON 或通过Pipeline.dumps()持久化整条管道from_dict(data: dict[str, Any]) - Watsonx...从字典反序列化还原组件实例data为该组件的字典表示。这意味着由 watsonx 组件构成的管道可以像普通 Haystack 管道一样导出、版本化、在 CI 中重放无需额外定制序列化逻辑。使用建议与注意事项凭证优先走环境变量WATSONX_API_KEY与WATSONX_PROJECT_ID由所有组件默认读取避免在代码或管道 YAML 中泄露密钥临时调试可用Secret.from_token直接注入。区分两个嵌入器查询侧用WatsonxTextEmbedder单条字符串文档侧用WatsonxDocumentEmbedder文档列表 批量/并发控制 元数据嵌入。若希望查询文本也能附带前后缀加工可组合使用prefix/suffix参数。truncate_input_tokens与超长文本文档/查询超出模型 token 上限时会被截断返回的meta.truncated_input_tokens可用于观测实际消费的 token 数需要处理超长文档时建议先做切分配合 Haystack 的 DocumentSplitter 类组件再嵌入。生成参数优先级run()中传入的generation_kwargs会覆盖__init__中设置的参数适合管道级默认值 请求级覆盖的模式。流式输出给streaming_callback传入回调即可把 watsonx 的 token 流逐段吐出该机制在WatsonxGenerator与WatsonxChatGenerator中均可用。工具调用与 AgentWatsonxChatGenerator支持tools参数Tool / Toolset可直接嵌入 Haystack 的 Agent 工作流让模型准备函数调用选择模型时需确认其支持工具调用能力。多模态限制只有 Vision 类模型如meta-llama/llama-3-2-11b-vision-instruct支持图片输入普通文本模型无法处理ImageContent。模型可用性SUPPORTED_MODELS只是组件维护的非穷尽参考清单实际可用的模型 ID 取决于你的 IBM Cloud 账户与部署配置model参数也可直接指定清单之外的新模型。通过本文的四个组件与管道示例你已经可以在 Haystack 中完整使用 IBM watsonx.ai 的嵌入与生成能力一端用WatsonxDocumentEmbedder把语料向量化入库另一端用WatsonxTextEmbedder编码查询并召回对话场景用WatsonxChatGenerator含多模态与工具调用简单文本生成则用WatsonxGenerator。更深入的实现细节可继续查阅本仓库中的 watsonx API 参考 及各组件使用指南text embedder、document embedder、generator、chat generator。【免费下载链接】haystackOpen-source AI orchestration framework for building context-engineered, production-ready LLM applications. Design modular pipelines and agent workflows with explicit control over retrieval, routing, memory, and generation. Built for scalable agents, RAG, multimodal applications, semantic search, and conversational systems.项目地址: https://gitcode.com/GitHub_Trending/ha/haystack创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
网站建设高端定制企业官网