watsonx-haystack 1.2.0__tar.gz → 1.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/CHANGELOG.md +27 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/PKG-INFO +2 -2
- watsonx_haystack-1.4.0/pydoc/config_docusaurus.yml +16 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/pyproject.toml +2 -4
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/generators/watsonx/chat/chat_generator.py +213 -60
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/generators/watsonx/generator.py +26 -1
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/tests/test_chat_generator.py +420 -31
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/tests/test_generator.py +13 -4
- watsonx_haystack-1.2.0/pydoc/config_docusaurus.yml +0 -31
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/.gitignore +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/LICENSE.txt +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/README.md +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/examples/chat_generator_example.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/examples/embedders_example.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/examples/generator_example.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/embedders/py.typed +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/embedders/watsonx/__init__.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/embedders/watsonx/document_embedder.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/embedders/watsonx/text_embedder.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/generators/py.typed +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/generators/watsonx/__init__.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/src/haystack_integrations/components/generators/watsonx/chat/__init__.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/tests/__init__.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/tests/test_document_embedder.py +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/tests/test_files/apple.jpg +0 -0
- {watsonx_haystack-1.2.0 → watsonx_haystack-1.4.0}/tests/test_text_embedder.py +0 -0
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [integrations/watsonx-v1.3.0] - 2026-03-12
|
|
4
|
+
|
|
5
|
+
### 🚀 Features
|
|
6
|
+
|
|
7
|
+
- `WatsonXChatGenerator` - support Tools and use the `StreamingChunk` fields (#2902)
|
|
8
|
+
|
|
9
|
+
### 📚 Documentation
|
|
10
|
+
|
|
11
|
+
- Simplify pydoc configs (#2855)
|
|
12
|
+
|
|
13
|
+
### 🧹 Chores
|
|
14
|
+
|
|
15
|
+
- Remove unused allow-direct-references (#2866)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## [integrations/watsonx-v1.2.0] - 2026-01-21
|
|
19
|
+
|
|
20
|
+
### 🐛 Bug Fixes
|
|
21
|
+
|
|
22
|
+
- *(watsonx)* Use dataclass replace to avoid modifying input documents (#2766)
|
|
23
|
+
|
|
24
|
+
### 🧹 Chores
|
|
25
|
+
|
|
26
|
+
- Remove Readme API CI workflow and configs (#2573)
|
|
27
|
+
- Make fmt command more forgiving (#2671)
|
|
28
|
+
|
|
29
|
+
|
|
3
30
|
## [integrations/watsonx-v1.1.0] - 2025-11-26
|
|
4
31
|
|
|
5
32
|
### 🧹 Chores
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: watsonx-haystack
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Watsonx integration for Haystack
|
|
5
5
|
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/watsonx#readme
|
|
6
6
|
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.11
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.12
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.13
|
|
18
18
|
Requires-Python: >=3.10
|
|
19
|
-
Requires-Dist: haystack-ai>=2.
|
|
19
|
+
Requires-Dist: haystack-ai>=2.24.1
|
|
20
20
|
Requires-Dist: ibm-watsonx-ai>=1.3.26
|
|
21
21
|
Requires-Dist: pandas>=2.2.3
|
|
22
22
|
Description-Content-Type: text/markdown
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
loaders:
|
|
2
|
+
- modules:
|
|
3
|
+
- haystack_integrations.components.generators.watsonx.generator
|
|
4
|
+
- haystack_integrations.components.generators.watsonx.chat.chat_generator
|
|
5
|
+
- haystack_integrations.components.embedders.watsonx.document_embedder
|
|
6
|
+
- haystack_integrations.components.embedders.watsonx.text_embedder
|
|
7
|
+
search_path: [../src]
|
|
8
|
+
processors:
|
|
9
|
+
- type: filter
|
|
10
|
+
documented_only: true
|
|
11
|
+
skip_empty_modules: true
|
|
12
|
+
renderer:
|
|
13
|
+
description: IBM watsonx.ai integration for Haystack
|
|
14
|
+
id: integrations-watsonx
|
|
15
|
+
filename: watsonx.md
|
|
16
|
+
title: IBM watsonx.ai
|
|
@@ -22,7 +22,7 @@ classifiers = [
|
|
|
22
22
|
"Programming Language :: Python :: 3.12",
|
|
23
23
|
"Programming Language :: Python :: 3.13",
|
|
24
24
|
]
|
|
25
|
-
dependencies = ["haystack-ai>=2.
|
|
25
|
+
dependencies = ["haystack-ai>=2.24.1", "ibm-watsonx-ai>=1.3.26", "pandas>=2.2.3"]
|
|
26
26
|
|
|
27
27
|
[project.urls]
|
|
28
28
|
Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/watsonx#readme"
|
|
@@ -40,15 +40,13 @@ tag-pattern = 'integrations\/watsonx-v(?P<version>.*)'
|
|
|
40
40
|
root = "../.."
|
|
41
41
|
git_describe_command = 'git describe --tags --match="integrations/watsonx-v[0-9]*"'
|
|
42
42
|
|
|
43
|
-
[tool.hatch.metadata]
|
|
44
|
-
allow-direct-references = true
|
|
45
43
|
|
|
46
44
|
[tool.hatch.envs.default]
|
|
47
45
|
installer = "uv"
|
|
48
46
|
dependencies = ["haystack-pydoc-tools", "ruff"]
|
|
49
47
|
|
|
50
48
|
[tool.hatch.envs.default.scripts]
|
|
51
|
-
docs = ["pydoc
|
|
49
|
+
docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
|
|
52
50
|
fmt = "ruff check --fix {args}; ruff format {args}"
|
|
53
51
|
fmt-check = "ruff check {args} && ruff format --check {args}"
|
|
54
52
|
|
|
@@ -2,21 +2,35 @@
|
|
|
2
2
|
#
|
|
3
3
|
# SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
|
|
5
|
+
import json
|
|
6
|
+
from dataclasses import replace
|
|
5
7
|
from datetime import datetime, timezone
|
|
6
|
-
from typing import Any, Literal, get_args
|
|
8
|
+
from typing import Any, ClassVar, Literal, get_args
|
|
7
9
|
|
|
8
10
|
from haystack import component, default_from_dict, default_to_dict, logging
|
|
11
|
+
from haystack.components.generators.utils import _convert_streaming_chunks_to_chat_message
|
|
9
12
|
from haystack.dataclasses import (
|
|
10
13
|
AsyncStreamingCallbackT,
|
|
11
14
|
ChatMessage,
|
|
12
15
|
ChatRole,
|
|
16
|
+
ComponentInfo,
|
|
17
|
+
FinishReason,
|
|
13
18
|
ImageContent,
|
|
14
19
|
StreamingCallbackT,
|
|
15
20
|
StreamingChunk,
|
|
16
21
|
SyncStreamingCallbackT,
|
|
17
22
|
TextContent,
|
|
23
|
+
ToolCall,
|
|
24
|
+
ToolCallDelta,
|
|
18
25
|
select_streaming_callback,
|
|
19
26
|
)
|
|
27
|
+
from haystack.tools import (
|
|
28
|
+
ToolsType,
|
|
29
|
+
_check_duplicate_tool_names,
|
|
30
|
+
deserialize_tools_or_toolset_inplace,
|
|
31
|
+
flatten_tools_or_toolsets,
|
|
32
|
+
serialize_tools_or_toolset,
|
|
33
|
+
)
|
|
20
34
|
from haystack.utils import Secret, deserialize_callable, deserialize_secrets_inplace, serialize_callable
|
|
21
35
|
from ibm_watsonx_ai import Credentials
|
|
22
36
|
from ibm_watsonx_ai.foundation_models import ModelInference
|
|
@@ -29,6 +43,17 @@ logger = logging.getLogger(__name__)
|
|
|
29
43
|
ImageFormat = Literal["image/jpeg", "image/png"]
|
|
30
44
|
IMAGE_SUPPORTED_FORMATS: list[ImageFormat] = list(get_args(ImageFormat))
|
|
31
45
|
|
|
46
|
+
# See https://ibm.github.io/watsonx-ai-node-sdk/enums/1_6_x.WatsonXAI.TextChatResultChoiceStream.Constants.FinishReason.html
|
|
47
|
+
# for possible finish reasons
|
|
48
|
+
FINISH_REASON_MAPPING: dict[str, FinishReason] = {
|
|
49
|
+
"cancelled": "stop",
|
|
50
|
+
"error": "stop",
|
|
51
|
+
"length": "length",
|
|
52
|
+
"stop": "stop",
|
|
53
|
+
"time_limit": "stop",
|
|
54
|
+
"tool_calls": "tool_calls",
|
|
55
|
+
}
|
|
56
|
+
|
|
32
57
|
|
|
33
58
|
@component
|
|
34
59
|
class WatsonxChatGenerator:
|
|
@@ -88,6 +113,31 @@ class WatsonxChatGenerator:
|
|
|
88
113
|
```
|
|
89
114
|
"""
|
|
90
115
|
|
|
116
|
+
SUPPORTED_MODELS: ClassVar[list[str]] = [
|
|
117
|
+
"ibm/granite-3-1-8b-base",
|
|
118
|
+
"ibm/granite-3-8b-instruct",
|
|
119
|
+
"ibm/granite-4-h-small",
|
|
120
|
+
"ibm/granite-8b-code-instruct",
|
|
121
|
+
"ibm/granite-guardian-3-8b",
|
|
122
|
+
"meta-llama/llama-3-1-70b-gptq",
|
|
123
|
+
"meta-llama/llama-3-1-8b",
|
|
124
|
+
"meta-llama/llama-3-2-11b-vision-instruct",
|
|
125
|
+
"meta-llama/llama-3-2-90b-vision-instruct",
|
|
126
|
+
"meta-llama/llama-3-3-70b-instruct",
|
|
127
|
+
"meta-llama/llama-3-405b-instruct",
|
|
128
|
+
"meta-llama/llama-4-maverick-17b-128e-instruct-fp8",
|
|
129
|
+
"meta-llama/llama-guard-3-11b-vision",
|
|
130
|
+
"mistral-large-2512",
|
|
131
|
+
"mistralai/mistral-medium-2505",
|
|
132
|
+
"mistralai/mistral-small-3-1-24b-instruct-2503",
|
|
133
|
+
"openai/gpt-oss-120b",
|
|
134
|
+
]
|
|
135
|
+
"""A non-exhaustive list of models supported by this component.
|
|
136
|
+
|
|
137
|
+
See https://www.ibm.com/docs/en/watsonx/saas?topic=solutions-supported-foundation-models for the
|
|
138
|
+
full list of models and up-to-date model IDs.
|
|
139
|
+
"""
|
|
140
|
+
|
|
91
141
|
def __init__(
|
|
92
142
|
self,
|
|
93
143
|
*,
|
|
@@ -100,6 +150,7 @@ class WatsonxChatGenerator:
|
|
|
100
150
|
max_retries: int | None = None,
|
|
101
151
|
verify: bool | str | None = None,
|
|
102
152
|
streaming_callback: StreamingCallbackT | None = None,
|
|
153
|
+
tools: ToolsType | None = None,
|
|
103
154
|
) -> None:
|
|
104
155
|
"""
|
|
105
156
|
Creates an instance of WatsonxChatGenerator.
|
|
@@ -136,6 +187,8 @@ class WatsonxChatGenerator:
|
|
|
136
187
|
- False: Skip verification (insecure)
|
|
137
188
|
- Path to CA bundle for custom certificates
|
|
138
189
|
:param streaming_callback: A callback function for streaming responses.
|
|
190
|
+
:param tools:
|
|
191
|
+
A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
|
|
139
192
|
"""
|
|
140
193
|
self.api_key = api_key
|
|
141
194
|
self.model = model
|
|
@@ -146,6 +199,7 @@ class WatsonxChatGenerator:
|
|
|
146
199
|
self.max_retries = max_retries
|
|
147
200
|
self.verify = verify
|
|
148
201
|
self.streaming_callback = streaming_callback
|
|
202
|
+
self.tools = tools
|
|
149
203
|
|
|
150
204
|
self._initialize_client()
|
|
151
205
|
|
|
@@ -169,6 +223,7 @@ class WatsonxChatGenerator:
|
|
|
169
223
|
The serialized component as a dictionary.
|
|
170
224
|
"""
|
|
171
225
|
callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None
|
|
226
|
+
serialized_tools = serialize_tools_or_toolset(self.tools) if self.tools else None
|
|
172
227
|
return default_to_dict(
|
|
173
228
|
self,
|
|
174
229
|
model=self.model,
|
|
@@ -180,6 +235,7 @@ class WatsonxChatGenerator:
|
|
|
180
235
|
max_retries=self.max_retries,
|
|
181
236
|
verify=self.verify,
|
|
182
237
|
streaming_callback=callback_name,
|
|
238
|
+
tools=serialized_tools,
|
|
183
239
|
)
|
|
184
240
|
|
|
185
241
|
@classmethod
|
|
@@ -193,6 +249,7 @@ class WatsonxChatGenerator:
|
|
|
193
249
|
The deserialized component instance.
|
|
194
250
|
"""
|
|
195
251
|
deserialize_secrets_inplace(data["init_parameters"], keys=["api_key", "project_id"])
|
|
252
|
+
deserialize_tools_or_toolset_inplace(data["init_parameters"], key="tools")
|
|
196
253
|
init_params = data.get("init_parameters", {})
|
|
197
254
|
serialized_callback = init_params.get("streaming_callback")
|
|
198
255
|
if serialized_callback:
|
|
@@ -206,6 +263,7 @@ class WatsonxChatGenerator:
|
|
|
206
263
|
messages: list[ChatMessage],
|
|
207
264
|
generation_kwargs: dict[str, Any] | None = None,
|
|
208
265
|
streaming_callback: StreamingCallbackT | None = None,
|
|
266
|
+
tools: ToolsType | None = None,
|
|
209
267
|
) -> dict[str, list[ChatMessage]]:
|
|
210
268
|
"""
|
|
211
269
|
Generate chat completions synchronously.
|
|
@@ -218,6 +276,9 @@ class WatsonxChatGenerator:
|
|
|
218
276
|
:param streaming_callback:
|
|
219
277
|
A callback function that is called when a new token is received from the stream.
|
|
220
278
|
If provided this will override the `streaming_callback` set in the `__init__` method.
|
|
279
|
+
:param tools:
|
|
280
|
+
A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
|
|
281
|
+
If set, it will override the `tools` parameter provided during initialization.
|
|
221
282
|
:returns:
|
|
222
283
|
A dictionary with the following key:
|
|
223
284
|
- `replies`: A list containing the generated responses as ChatMessage instances.
|
|
@@ -229,7 +290,7 @@ class WatsonxChatGenerator:
|
|
|
229
290
|
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=False
|
|
230
291
|
)
|
|
231
292
|
|
|
232
|
-
api_args = self._prepare_api_call(messages=messages, generation_kwargs=generation_kwargs)
|
|
293
|
+
api_args = self._prepare_api_call(messages=messages, generation_kwargs=generation_kwargs, tools=tools)
|
|
233
294
|
|
|
234
295
|
if resolved_streaming_callback:
|
|
235
296
|
return self._handle_streaming(api_args=api_args, callback=resolved_streaming_callback)
|
|
@@ -243,6 +304,7 @@ class WatsonxChatGenerator:
|
|
|
243
304
|
messages: list[ChatMessage],
|
|
244
305
|
generation_kwargs: dict[str, Any] | None = None,
|
|
245
306
|
streaming_callback: StreamingCallbackT | None = None,
|
|
307
|
+
tools: ToolsType | None = None,
|
|
246
308
|
) -> dict[str, list[ChatMessage]]:
|
|
247
309
|
"""
|
|
248
310
|
Generate chat completions asynchronously.
|
|
@@ -255,6 +317,9 @@ class WatsonxChatGenerator:
|
|
|
255
317
|
:param streaming_callback:
|
|
256
318
|
A callback function that is called when a new token is received from the stream.
|
|
257
319
|
If provided this will override the `streaming_callback` set in the `__init__` method.
|
|
320
|
+
:param tools:
|
|
321
|
+
A list of Tool and/or Toolset objects, or a single Toolset for which the model can prepare calls.
|
|
322
|
+
If set, it will override the `tools` parameter provided during initialization.
|
|
258
323
|
:returns:
|
|
259
324
|
A dictionary with the following key:
|
|
260
325
|
- `replies`: A list containing the generated responses as ChatMessage instances.
|
|
@@ -266,7 +331,7 @@ class WatsonxChatGenerator:
|
|
|
266
331
|
init_callback=self.streaming_callback, runtime_callback=streaming_callback, requires_async=True
|
|
267
332
|
)
|
|
268
333
|
|
|
269
|
-
api_args = self._prepare_api_call(messages=messages, generation_kwargs=generation_kwargs)
|
|
334
|
+
api_args = self._prepare_api_call(messages=messages, generation_kwargs=generation_kwargs, tools=tools)
|
|
270
335
|
|
|
271
336
|
if resolved_streaming_callback:
|
|
272
337
|
return await self._handle_async_streaming(api_args=api_args, callback=resolved_streaming_callback)
|
|
@@ -274,16 +339,25 @@ class WatsonxChatGenerator:
|
|
|
274
339
|
return await self._handle_async_standard(api_args)
|
|
275
340
|
|
|
276
341
|
def _prepare_api_call(
|
|
277
|
-
self,
|
|
342
|
+
self,
|
|
343
|
+
*,
|
|
344
|
+
messages: list[ChatMessage],
|
|
345
|
+
generation_kwargs: dict[str, Any] | None = None,
|
|
346
|
+
tools: ToolsType | None = None,
|
|
278
347
|
) -> dict[str, Any]:
|
|
279
348
|
merged_kwargs = {**self.generation_kwargs, **(generation_kwargs or {})}
|
|
280
349
|
|
|
281
350
|
watsonx_messages = []
|
|
282
351
|
content: str | None | dict[str, Any] | list[dict[str, Any]]
|
|
283
352
|
|
|
353
|
+
flattened_tools = flatten_tools_or_toolsets(tools or self.tools)
|
|
354
|
+
_check_duplicate_tool_names(flattened_tools)
|
|
355
|
+
tool_definitions = [{"type": "function", "function": {**tool.tool_spec}} for tool in flattened_tools]
|
|
356
|
+
|
|
284
357
|
for msg in messages:
|
|
285
|
-
|
|
286
|
-
|
|
358
|
+
# Watsonx tool call result messages are of the same format as OpenAI chat completions
|
|
359
|
+
if msg.tool_call_results:
|
|
360
|
+
watsonx_messages.append(msg.to_openai_dict_format(require_tool_call_ids=True))
|
|
287
361
|
continue
|
|
288
362
|
|
|
289
363
|
# Check that images are only in user messages
|
|
@@ -325,7 +399,57 @@ class WatsonxChatGenerator:
|
|
|
325
399
|
|
|
326
400
|
merged_kwargs.pop("stream", None)
|
|
327
401
|
|
|
328
|
-
|
|
402
|
+
api_args = {"messages": watsonx_messages, "params": merged_kwargs}
|
|
403
|
+
if tool_definitions:
|
|
404
|
+
api_args["tools"] = tool_definitions
|
|
405
|
+
|
|
406
|
+
return api_args
|
|
407
|
+
|
|
408
|
+
def _convert_chunk_to_streaming_chunk(self, chunk: dict[str, Any], component_info: ComponentInfo) -> StreamingChunk:
|
|
409
|
+
"""
|
|
410
|
+
Convert one Watsonx AI stream-chunk to Haystack StreamingChunk.
|
|
411
|
+
"""
|
|
412
|
+
choice = chunk["choices"][0]
|
|
413
|
+
chunk_meta = {
|
|
414
|
+
"model": self.model,
|
|
415
|
+
"model_id": chunk.get("model_id"),
|
|
416
|
+
"model_version": chunk.get("model_version"),
|
|
417
|
+
"created": chunk.get("created"),
|
|
418
|
+
"created_at": chunk.get("created_at"),
|
|
419
|
+
"received_at": datetime.now(timezone.utc).isoformat(),
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if choice["delta"] and (choice_delta_tool_calls := choice["delta"].get("tool_calls")):
|
|
423
|
+
# create a list of ToolCallDelta objects from the tool calls
|
|
424
|
+
tool_calls_deltas = [
|
|
425
|
+
ToolCallDelta(
|
|
426
|
+
index=tool_call["index"],
|
|
427
|
+
id=tool_call.get("id"),
|
|
428
|
+
tool_name=tool_call.get("function", {}).get("name"),
|
|
429
|
+
arguments=tool_call.get("function", {}).get("arguments"),
|
|
430
|
+
)
|
|
431
|
+
for tool_call in choice_delta_tool_calls
|
|
432
|
+
]
|
|
433
|
+
return StreamingChunk(
|
|
434
|
+
content=choice.get("delta", {}).get("content", ""),
|
|
435
|
+
meta=chunk_meta,
|
|
436
|
+
component_info=component_info,
|
|
437
|
+
# We adopt the first tool_calls_deltas.index as the overall index of the chunk to match OpenAI
|
|
438
|
+
index=tool_calls_deltas[0].index,
|
|
439
|
+
tool_calls=tool_calls_deltas,
|
|
440
|
+
start=tool_calls_deltas[0].tool_name is not None,
|
|
441
|
+
finish_reason=FINISH_REASON_MAPPING.get(choice.get("finish_reason")),
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
index = choice.get("index", 0)
|
|
445
|
+
return StreamingChunk(
|
|
446
|
+
content=choice.get("delta", {}).get("content", ""),
|
|
447
|
+
meta=chunk_meta,
|
|
448
|
+
component_info=component_info,
|
|
449
|
+
index=index,
|
|
450
|
+
start=index == 0,
|
|
451
|
+
finish_reason=FINISH_REASON_MAPPING.get(choice.get("finish_reason")),
|
|
452
|
+
)
|
|
329
453
|
|
|
330
454
|
def _handle_streaming(
|
|
331
455
|
self,
|
|
@@ -342,29 +466,40 @@ class WatsonxChatGenerator:
|
|
|
342
466
|
A dictionary with the generated responses as ChatMessage instances.
|
|
343
467
|
"""
|
|
344
468
|
chunks: list[StreamingChunk] = []
|
|
345
|
-
stream = self.client.chat_stream(
|
|
469
|
+
stream = self.client.chat_stream(
|
|
470
|
+
messages=api_args["messages"], params=api_args["params"], tools=api_args.get("tools")
|
|
471
|
+
)
|
|
472
|
+
component_info = ComponentInfo.from_component(self)
|
|
346
473
|
|
|
347
474
|
for chunk in stream:
|
|
348
475
|
if not isinstance(chunk, dict) or not chunk.get("choices"):
|
|
349
476
|
continue
|
|
350
477
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
"model": self.model,
|
|
355
|
-
"index": chunk["choices"][0].get("index", 0),
|
|
356
|
-
"finish_reason": chunk["choices"][0].get("finish_reason"),
|
|
357
|
-
"received_at": datetime.now(timezone.utc).isoformat(),
|
|
358
|
-
}
|
|
359
|
-
streaming_chunk = StreamingChunk(content=content, meta=chunk_meta)
|
|
360
|
-
chunks.append(streaming_chunk)
|
|
361
|
-
callback(streaming_chunk)
|
|
478
|
+
streaming_chunk = self._convert_chunk_to_streaming_chunk(chunk, component_info)
|
|
479
|
+
chunks.append(streaming_chunk)
|
|
480
|
+
callback(streaming_chunk)
|
|
362
481
|
|
|
363
|
-
|
|
482
|
+
chat_message = _convert_streaming_chunks_to_chat_message(chunks)
|
|
483
|
+
message_tool_calls = [
|
|
484
|
+
replace(tool_call, arguments=self._parse_tool_call_json(tool_call.arguments))
|
|
485
|
+
for tool_call in chat_message.tool_calls
|
|
486
|
+
]
|
|
487
|
+
return {
|
|
488
|
+
"replies": [
|
|
489
|
+
ChatMessage.from_assistant(
|
|
490
|
+
text=chat_message.text,
|
|
491
|
+
meta=chat_message.meta,
|
|
492
|
+
tool_calls=message_tool_calls,
|
|
493
|
+
reasoning=chat_message.reasoning,
|
|
494
|
+
)
|
|
495
|
+
]
|
|
496
|
+
}
|
|
364
497
|
|
|
365
498
|
def _handle_standard(self, api_args: dict[str, Any]) -> dict[str, list[ChatMessage]]:
|
|
366
499
|
"""Handle synchronous standard response."""
|
|
367
|
-
response = self.client.chat(
|
|
500
|
+
response = self.client.chat(
|
|
501
|
+
messages=api_args["messages"], params=api_args["params"], tools=api_args.get("tools")
|
|
502
|
+
)
|
|
368
503
|
return self._process_response(response)
|
|
369
504
|
|
|
370
505
|
async def _handle_async_streaming(
|
|
@@ -375,60 +510,77 @@ class WatsonxChatGenerator:
|
|
|
375
510
|
) -> dict[str, list[ChatMessage]]:
|
|
376
511
|
"""Handle asynchronous streaming response."""
|
|
377
512
|
chunks: list[StreamingChunk] = []
|
|
378
|
-
stream_generator = await self.client.achat_stream(
|
|
513
|
+
stream_generator = await self.client.achat_stream(
|
|
514
|
+
messages=api_args["messages"], params=api_args["params"], tools=api_args.get("tools")
|
|
515
|
+
)
|
|
516
|
+
component_info = ComponentInfo.from_component(self)
|
|
379
517
|
|
|
380
518
|
async for chunk in stream_generator:
|
|
381
519
|
if not isinstance(chunk, dict) or not chunk.get("choices"):
|
|
382
520
|
continue
|
|
383
521
|
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
content = "".join(chunk.content for chunk in chunks)
|
|
404
|
-
last_chunk_meta = chunks[-1].meta if chunks else {}
|
|
405
|
-
|
|
406
|
-
return ChatMessage.from_assistant(
|
|
407
|
-
text=content,
|
|
408
|
-
meta={
|
|
409
|
-
"model": self.model,
|
|
410
|
-
"finish_reason": last_chunk_meta.get("finish_reason"),
|
|
411
|
-
"usage": last_chunk_meta.get("usage", {}),
|
|
412
|
-
"chunks_count": len(chunks),
|
|
413
|
-
},
|
|
414
|
-
)
|
|
522
|
+
streaming_chunk = self._convert_chunk_to_streaming_chunk(chunk, component_info)
|
|
523
|
+
chunks.append(streaming_chunk)
|
|
524
|
+
await callback(streaming_chunk)
|
|
525
|
+
|
|
526
|
+
chat_message = _convert_streaming_chunks_to_chat_message(chunks)
|
|
527
|
+
message_tool_calls = [
|
|
528
|
+
replace(tool_call, arguments=self._parse_tool_call_json(tool_call.arguments))
|
|
529
|
+
for tool_call in chat_message.tool_calls
|
|
530
|
+
]
|
|
531
|
+
return {
|
|
532
|
+
"replies": [
|
|
533
|
+
ChatMessage.from_assistant(
|
|
534
|
+
text=chat_message.text,
|
|
535
|
+
meta=chat_message.meta,
|
|
536
|
+
tool_calls=message_tool_calls,
|
|
537
|
+
reasoning=chat_message.reasoning,
|
|
538
|
+
)
|
|
539
|
+
]
|
|
540
|
+
}
|
|
415
541
|
|
|
416
542
|
async def _handle_async_standard(self, api_args: dict[str, Any]) -> dict[str, list[ChatMessage]]:
|
|
417
543
|
"""Handle asynchronous standard response."""
|
|
418
|
-
response = await self.client.achat(
|
|
544
|
+
response = await self.client.achat(
|
|
545
|
+
messages=api_args["messages"], params=api_args["params"], tools=api_args.get("tools")
|
|
546
|
+
)
|
|
419
547
|
return self._process_response(response)
|
|
420
548
|
|
|
549
|
+
@staticmethod
|
|
550
|
+
def _parse_tool_call_json(tool_call: str | dict) -> dict[str, Any]:
|
|
551
|
+
"""Parse tool call json from Watsonx tool calls."""
|
|
552
|
+
if isinstance(tool_call, dict):
|
|
553
|
+
return tool_call
|
|
554
|
+
obj = json.loads(tool_call)
|
|
555
|
+
if isinstance(obj, str):
|
|
556
|
+
obj = json.loads(obj)
|
|
557
|
+
return obj
|
|
558
|
+
|
|
421
559
|
def _process_response(self, response: dict[str, Any]) -> dict[str, list[ChatMessage]]:
|
|
422
560
|
"""Process standard response into Haystack format."""
|
|
423
561
|
if not response.get("choices"):
|
|
424
562
|
return {"replies": []}
|
|
425
563
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
"
|
|
564
|
+
choices = response["choices"]
|
|
565
|
+
chat_messages = []
|
|
566
|
+
for choice in choices:
|
|
567
|
+
message = choice.get("message", {})
|
|
568
|
+
|
|
569
|
+
message_tool_calls: list[ToolCall] | None = None
|
|
570
|
+
if tool_calls := message.get("tool_calls", []):
|
|
571
|
+
message_tool_calls = [
|
|
572
|
+
ToolCall(
|
|
573
|
+
id=tool_call["id"],
|
|
574
|
+
tool_name=tool_call["function"]["name"],
|
|
575
|
+
arguments=self._parse_tool_call_json(tool_call["function"]["arguments"]),
|
|
576
|
+
)
|
|
577
|
+
for tool_call in tool_calls
|
|
578
|
+
]
|
|
579
|
+
|
|
580
|
+
chat_messages.append(
|
|
430
581
|
ChatMessage.from_assistant(
|
|
431
582
|
text=message.get("content", ""),
|
|
583
|
+
tool_calls=message_tool_calls,
|
|
432
584
|
meta={
|
|
433
585
|
"model": self.model,
|
|
434
586
|
"index": choice.get("index", 0),
|
|
@@ -436,5 +588,6 @@ class WatsonxChatGenerator:
|
|
|
436
588
|
"usage": response.get("usage", {}),
|
|
437
589
|
},
|
|
438
590
|
)
|
|
439
|
-
|
|
440
|
-
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
return {"replies": chat_messages}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
#
|
|
3
3
|
# SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
|
|
5
|
-
from typing import Any, cast
|
|
5
|
+
from typing import Any, ClassVar, cast
|
|
6
6
|
|
|
7
7
|
from haystack import component, logging
|
|
8
8
|
from haystack.dataclasses import ChatMessage, StreamingCallbackT
|
|
@@ -67,6 +67,31 @@ class WatsonxGenerator(WatsonxChatGenerator):
|
|
|
67
67
|
```
|
|
68
68
|
"""
|
|
69
69
|
|
|
70
|
+
SUPPORTED_MODELS: ClassVar[list[str]] = [
|
|
71
|
+
"ibm/granite-3-1-8b-base",
|
|
72
|
+
"ibm/granite-3-8b-instruct",
|
|
73
|
+
"ibm/granite-4-h-small",
|
|
74
|
+
"ibm/granite-8b-code-instruct",
|
|
75
|
+
"ibm/granite-guardian-3-8b",
|
|
76
|
+
"meta-llama/llama-3-1-70b-gptq",
|
|
77
|
+
"meta-llama/llama-3-1-8b",
|
|
78
|
+
"meta-llama/llama-3-2-11b-vision-instruct",
|
|
79
|
+
"meta-llama/llama-3-2-90b-vision-instruct",
|
|
80
|
+
"meta-llama/llama-3-3-70b-instruct",
|
|
81
|
+
"meta-llama/llama-3-405b-instruct",
|
|
82
|
+
"meta-llama/llama-4-maverick-17b-128e-instruct-fp8",
|
|
83
|
+
"meta-llama/llama-guard-3-11b-vision",
|
|
84
|
+
"mistral-large-2512",
|
|
85
|
+
"mistralai/mistral-medium-2505",
|
|
86
|
+
"mistralai/mistral-small-3-1-24b-instruct-2503",
|
|
87
|
+
"openai/gpt-oss-120b",
|
|
88
|
+
]
|
|
89
|
+
"""A non-exhaustive list of models supported by this component.
|
|
90
|
+
|
|
91
|
+
See https://www.ibm.com/docs/en/watsonx/saas?topic=solutions-supported-foundation-models for the
|
|
92
|
+
full list of models and up-to-date model IDs.
|
|
93
|
+
"""
|
|
94
|
+
|
|
70
95
|
def __init__(
|
|
71
96
|
self,
|
|
72
97
|
*,
|