watsonx-haystack 1.3.0__tar.gz → 1.5.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.
Files changed (25) hide show
  1. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/CHANGELOG.md +22 -0
  2. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/PKG-INFO +2 -2
  3. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/pyproject.toml +15 -3
  4. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/embedders/watsonx/document_embedder.py +1 -1
  5. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/embedders/watsonx/text_embedder.py +1 -1
  6. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/generators/watsonx/chat/chat_generator.py +33 -4
  7. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/generators/watsonx/generator.py +33 -1
  8. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/tests/test_chat_generator.py +40 -0
  9. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/tests/test_generator.py +7 -0
  10. watsonx_haystack-1.3.0/examples/generator_example.py +0 -439
  11. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/.gitignore +0 -0
  12. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/LICENSE.txt +0 -0
  13. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/README.md +0 -0
  14. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/examples/chat_generator_example.py +0 -0
  15. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/examples/embedders_example.py +0 -0
  16. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/pydoc/config_docusaurus.yml +0 -0
  17. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/embedders/py.typed +0 -0
  18. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/embedders/watsonx/__init__.py +0 -0
  19. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/generators/py.typed +0 -0
  20. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/generators/watsonx/__init__.py +0 -0
  21. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/src/haystack_integrations/components/generators/watsonx/chat/__init__.py +0 -0
  22. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/tests/__init__.py +0 -0
  23. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/tests/test_document_embedder.py +0 -0
  24. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/tests/test_files/apple.jpg +0 -0
  25. {watsonx_haystack-1.3.0 → watsonx_haystack-1.5.0}/tests/test_text_embedder.py +0 -0
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## [integrations/watsonx-v1.4.0] - 2026-03-13
4
+
5
+ ### 🚀 Features
6
+
7
+ - List supported models in `WatsonxChatGenerator` (#2956)
8
+
9
+
10
+ ## [integrations/watsonx-v1.3.0] - 2026-03-12
11
+
12
+ ### 🚀 Features
13
+
14
+ - `WatsonXChatGenerator` - support Tools and use the `StreamingChunk` fields (#2902)
15
+
16
+ ### 📚 Documentation
17
+
18
+ - Simplify pydoc configs (#2855)
19
+
20
+ ### 🧹 Chores
21
+
22
+ - Remove unused allow-direct-references (#2866)
23
+
24
+
3
25
  ## [integrations/watsonx-v1.2.0] - 2026-01-21
4
26
 
5
27
  ### 🐛 Bug Fixes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: watsonx-haystack
3
- Version: 1.3.0
3
+ Version: 1.5.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.24.1
19
+ Requires-Dist: haystack-ai>=2.30.0
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
@@ -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.24.1", "ibm-watsonx-ai>=1.3.26", "pandas>=2.2.3"]
25
+ dependencies = ["haystack-ai>=2.30.0", "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"
@@ -66,7 +66,8 @@ dependencies = [
66
66
  unit = 'pytest -m "not integration" {args:tests}'
67
67
  integration = 'pytest -m "integration" {args:tests}'
68
68
  all = 'pytest {args:tests}'
69
- cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x {args:tests}'
69
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
70
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
70
71
  types = """mypy -p haystack_integrations.components.generators.watsonx \
71
72
  -p haystack_integrations.components.embedders.watsonx {args}"""
72
73
 
@@ -89,9 +90,17 @@ line-length = 120
89
90
  [tool.ruff.lint]
90
91
  select = [
91
92
  "A",
93
+ "ANN",
92
94
  "ARG",
93
95
  "B",
94
96
  "C",
97
+ "D102", # Missing docstring in public method
98
+ "D103", # Missing docstring in public function
99
+ "D205", # 1 blank line required between summary line and description
100
+ "D209", # Closing triple quotes go to new line
101
+ "D213", # summary lines must be positioned on the second physical line of the docstring
102
+ "D417", # Missing argument descriptions in the docstring
103
+ "D419", # Docstring is empty
95
104
  "DTZ",
96
105
  "E",
97
106
  "EM",
@@ -116,6 +125,7 @@ select = [
116
125
  ignore = [
117
126
  "T201", # print statements
118
127
  # Allow non-abstract empty methods in abstract base classes
128
+ "ANN401",
119
129
  "B027",
120
130
  # Ignore checks for possible passwords
121
131
  "S105",
@@ -145,11 +155,13 @@ ban-relative-imports = "parents"
145
155
 
146
156
  [tool.ruff.lint.per-file-ignores]
147
157
  # Tests can use magic values, assertions, and relative imports
148
- "tests/**/*" = ["PLR2004", "S101", "TID252"]
158
+ "examples/**/*" = ["D", "ANN"]
159
+ "tests/**/*" = ["D", "ANN", "PLR2004", "S101", "TID252"]
149
160
 
150
161
  [tool.coverage.run]
151
162
  source = ["haystack_integrations"]
152
163
  branch = true
164
+ relative_files = true
153
165
  parallel = true
154
166
 
155
167
  [tool.coverage.report]
@@ -59,7 +59,7 @@ class WatsonxDocumentEmbedder:
59
59
  max_retries: int | None = None,
60
60
  meta_fields_to_embed: list[str] | None = None,
61
61
  embedding_separator: str = "\n",
62
- ):
62
+ ) -> None:
63
63
  """
64
64
  Creates a WatsonxDocumentEmbedder component.
65
65
 
@@ -51,7 +51,7 @@ class WatsonxTextEmbedder:
51
51
  suffix: str = "",
52
52
  timeout: float | None = None,
53
53
  max_retries: int | None = None,
54
- ):
54
+ ) -> None:
55
55
  """
56
56
  Creates an WatsonxTextEmbedder component.
57
57
 
@@ -5,10 +5,10 @@
5
5
  import json
6
6
  from dataclasses import replace
7
7
  from datetime import datetime, timezone
8
- from typing import Any, Literal, get_args
8
+ from typing import Any, ClassVar, Literal, get_args
9
9
 
10
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
11
+ from haystack.components.generators.utils import _convert_streaming_chunks_to_chat_message, _normalize_messages
12
12
  from haystack.dataclasses import (
13
13
  AsyncStreamingCallbackT,
14
14
  ChatMessage,
@@ -113,6 +113,31 @@ class WatsonxChatGenerator:
113
113
  ```
114
114
  """
115
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
+
116
141
  def __init__(
117
142
  self,
118
143
  *,
@@ -235,7 +260,7 @@ class WatsonxChatGenerator:
235
260
  def run(
236
261
  self,
237
262
  *,
238
- messages: list[ChatMessage],
263
+ messages: list[ChatMessage] | str,
239
264
  generation_kwargs: dict[str, Any] | None = None,
240
265
  streaming_callback: StreamingCallbackT | None = None,
241
266
  tools: ToolsType | None = None,
@@ -245,6 +270,7 @@ class WatsonxChatGenerator:
245
270
 
246
271
  :param messages:
247
272
  A list of ChatMessage instances representing the input messages.
273
+ If a string is provided, it is converted to a list containing a ChatMessage with user role.
248
274
  :param generation_kwargs:
249
275
  Additional keyword arguments for text generation. These parameters will potentially override the parameters
250
276
  passed in the `__init__` method.
@@ -258,6 +284,7 @@ class WatsonxChatGenerator:
258
284
  A dictionary with the following key:
259
285
  - `replies`: A list containing the generated responses as ChatMessage instances.
260
286
  """
287
+ messages = _normalize_messages(messages)
261
288
  if not messages:
262
289
  return {"replies": []}
263
290
 
@@ -276,7 +303,7 @@ class WatsonxChatGenerator:
276
303
  async def run_async(
277
304
  self,
278
305
  *,
279
- messages: list[ChatMessage],
306
+ messages: list[ChatMessage] | str,
280
307
  generation_kwargs: dict[str, Any] | None = None,
281
308
  streaming_callback: StreamingCallbackT | None = None,
282
309
  tools: ToolsType | None = None,
@@ -286,6 +313,7 @@ class WatsonxChatGenerator:
286
313
 
287
314
  :param messages:
288
315
  A list of ChatMessage instances representing the input messages.
316
+ If a string is provided, it is converted to a list containing a ChatMessage with user role.
289
317
  :param generation_kwargs:
290
318
  Additional keyword arguments for text generation. These parameters will potentially override the parameters
291
319
  passed in the `__init__` method.
@@ -299,6 +327,7 @@ class WatsonxChatGenerator:
299
327
  A dictionary with the following key:
300
328
  - `replies`: A list containing the generated responses as ChatMessage instances.
301
329
  """
330
+ messages = _normalize_messages(messages)
302
331
  if not messages:
303
332
  return {"replies": []}
304
333
 
@@ -2,7 +2,8 @@
2
2
  #
3
3
  # SPDX-License-Identifier: Apache-2.0
4
4
 
5
- from typing import Any, cast
5
+ import warnings
6
+ from typing import Any, ClassVar, cast
6
7
 
7
8
  from haystack import component, logging
8
9
  from haystack.dataclasses import ChatMessage, StreamingCallbackT
@@ -67,6 +68,31 @@ class WatsonxGenerator(WatsonxChatGenerator):
67
68
  ```
68
69
  """
69
70
 
71
+ SUPPORTED_MODELS: ClassVar[list[str]] = [
72
+ "ibm/granite-3-1-8b-base",
73
+ "ibm/granite-3-8b-instruct",
74
+ "ibm/granite-4-h-small",
75
+ "ibm/granite-8b-code-instruct",
76
+ "ibm/granite-guardian-3-8b",
77
+ "meta-llama/llama-3-1-70b-gptq",
78
+ "meta-llama/llama-3-1-8b",
79
+ "meta-llama/llama-3-2-11b-vision-instruct",
80
+ "meta-llama/llama-3-2-90b-vision-instruct",
81
+ "meta-llama/llama-3-3-70b-instruct",
82
+ "meta-llama/llama-3-405b-instruct",
83
+ "meta-llama/llama-4-maverick-17b-128e-instruct-fp8",
84
+ "meta-llama/llama-guard-3-11b-vision",
85
+ "mistral-large-2512",
86
+ "mistralai/mistral-medium-2505",
87
+ "mistralai/mistral-small-3-1-24b-instruct-2503",
88
+ "openai/gpt-oss-120b",
89
+ ]
90
+ """A non-exhaustive list of models supported by this component.
91
+
92
+ See https://www.ibm.com/docs/en/watsonx/saas?topic=solutions-supported-foundation-models for the
93
+ full list of models and up-to-date model IDs.
94
+ """
95
+
70
96
  def __init__(
71
97
  self,
72
98
  *,
@@ -118,6 +144,12 @@ class WatsonxGenerator(WatsonxChatGenerator):
118
144
  - Path to CA bundle for custom certificates
119
145
  :param streaming_callback: A callback function for streaming responses.
120
146
  """
147
+ warnings.warn(
148
+ "The `WatsonxGenerator` component is deprecated and will be removed in a future version. "
149
+ "Use `WatsonxChatGenerator` instead, which now also supports string inputs.",
150
+ FutureWarning,
151
+ stacklevel=2,
152
+ )
121
153
  super(WatsonxGenerator, self).__init__( # noqa: UP008
122
154
  api_key=api_key,
123
155
  model=model,
@@ -119,6 +119,13 @@ class TestWatsonxChatGenerator:
119
119
 
120
120
  yield {"model": mock_model, "model_instance": mock_model_instance, "select_callback": mock_select_callback}
121
121
 
122
+ def test_supported_models(self) -> None:
123
+ """SUPPORTED_MODELS is a non-empty list of strings."""
124
+ models = WatsonxChatGenerator.SUPPORTED_MODELS
125
+ assert isinstance(models, list)
126
+ assert len(models) > 0
127
+ assert all(isinstance(m, str) for m in models)
128
+
122
129
  def test_init_default(self, mock_watsonx):
123
130
  generator = WatsonxChatGenerator(project_id=Secret.from_token("fake-project-id"))
124
131
 
@@ -359,6 +366,39 @@ class TestWatsonxChatGenerator:
359
366
  assert result["replies"][0].text == "Streaming response"
360
367
  assert result["replies"][0].meta["finish_reason"] == "stop"
361
368
 
369
+ def test_run_with_string_input(self, mock_watsonx):
370
+ generator = WatsonxChatGenerator(
371
+ api_key=Secret.from_token("test-api-key"),
372
+ project_id=Secret.from_token("test-project"),
373
+ )
374
+
375
+ result = generator.run(messages="What's the capital of France?")
376
+
377
+ assert isinstance(result["replies"], list)
378
+ assert len(result["replies"]) == 1
379
+ assert isinstance(result["replies"][0], ChatMessage)
380
+
381
+ mock_watsonx["model_instance"].chat.assert_called_once_with(
382
+ messages=[{"role": "user", "content": "What's the capital of France?"}], params={}, tools=None
383
+ )
384
+
385
+ @pytest.mark.asyncio
386
+ async def test_run_async_with_string_input(self, mock_watsonx):
387
+ generator = WatsonxChatGenerator(
388
+ api_key=Secret.from_token("test-api-key"),
389
+ project_id=Secret.from_token("test-project"),
390
+ )
391
+
392
+ result = await generator.run_async(messages="What's the capital of France?")
393
+
394
+ assert isinstance(result["replies"], list)
395
+ assert len(result["replies"]) == 1
396
+ assert isinstance(result["replies"][0], ChatMessage)
397
+
398
+ mock_watsonx["model_instance"].achat.assert_called_once_with(
399
+ messages=[{"role": "user", "content": "What's the capital of France?"}], params={}, tools=None
400
+ )
401
+
362
402
  def test_run_with_empty_messages(self, mock_watsonx):
363
403
  generator = WatsonxChatGenerator(
364
404
  api_key=Secret.from_token("test-api-key"),
@@ -81,6 +81,13 @@ class TestWatsonxGenerator:
81
81
 
82
82
  yield {"model": mock_model, "model_instance": mock_model_instance}
83
83
 
84
+ def test_supported_models(self) -> None:
85
+ """SUPPORTED_MODELS is a non-empty list of strings."""
86
+ models = WatsonxGenerator.SUPPORTED_MODELS
87
+ assert isinstance(models, list)
88
+ assert len(models) > 0
89
+ assert all(isinstance(m, str) for m in models)
90
+
84
91
  def test_init_default(self, mock_watsonx):
85
92
  generator = WatsonxGenerator(project_id=Secret.from_token("fake-project-id"))
86
93
 
@@ -1,439 +0,0 @@
1
- """
2
- WatsonX Generator Example
3
-
4
- This example demonstrates how to use the WatsonxGenerator component with the Haystack framework.
5
- It shows basic usage, advanced configuration, streaming, pipeline integration, and async operations.
6
-
7
- Prerequisites:
8
- - Set environment variables: WATSONX_API_KEY and WATSONX_PROJECT_ID
9
- - Install: pip install haystack-watsonx
10
- """
11
-
12
- import asyncio
13
- import os
14
-
15
- from haystack import Pipeline
16
- from haystack.dataclasses import StreamingChunk
17
- from haystack.utils import Secret
18
-
19
- from haystack_integrations.components.generators.watsonx.generator import WatsonxGenerator
20
-
21
-
22
- def basic_usage_example():
23
- """Demonstrates basic usage of WatsonxGenerator"""
24
- print("=== Basic Usage Example ===")
25
-
26
- generator = WatsonxGenerator(
27
- model="meta-llama/llama-3-3-70b-instruct",
28
- api_key=Secret.from_env_var("WATSONX_API_KEY"),
29
- project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
30
- generation_kwargs={"max_tokens": 100, "temperature": 0.7, "top_p": 0.9, "decoding_method": "sample"},
31
- )
32
-
33
- system_prompt = "You are a helpful assistant. Provide clear, direct answers."
34
-
35
- questions = [
36
- "What is the capital of France?",
37
- "Explain photosynthesis in one sentence.",
38
- "List benefits of renewable energy.",
39
- ]
40
-
41
- for question in questions:
42
- print(f"\nQuestion: {question}")
43
- result = generator.run(prompt=question, system_prompt=system_prompt)
44
-
45
- response = result["replies"][0]
46
- metadata = result["meta"][0]
47
-
48
- print(f"Answer: {response}")
49
- print(f"Tokens used: {metadata.get('usage', {}).get('total_tokens', 'N/A')}")
50
- print("-" * 60)
51
-
52
-
53
- def advanced_configuration_example():
54
- """Shows advanced configuration options"""
55
- print("\n=== Advanced Configuration Example ===")
56
-
57
- generator = WatsonxGenerator(
58
- model="meta-llama/llama-3-3-70b-instruct",
59
- api_key=Secret.from_env_var("WATSONX_API_KEY"),
60
- project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
61
- generation_kwargs={
62
- "max_tokens": 512,
63
- "temperature": 0.8,
64
- "top_p": 0.95,
65
- "top_k": 50,
66
- "repetition_penalty": 1.1,
67
- "decoding_method": "sample",
68
- "stop_sequences": ["Human:", "Assistant:"],
69
- },
70
- )
71
-
72
- system_prompt = "You are a creative writing assistant. Write engaging, vivid descriptions."
73
- prompt = "Describe a peaceful mountain lake at sunrise."
74
-
75
- result = generator.run(
76
- prompt=prompt, system_prompt=system_prompt, generation_kwargs={"temperature": 0.9, "max_tokens": 512}
77
- )
78
-
79
- print(f"Creative writing prompt: {prompt}")
80
- print(f"Response: {result['replies'][0]}")
81
- print(f"Metadata: {result['meta'][0]}")
82
-
83
-
84
- def streaming_example():
85
- """Demonstrates streaming responses"""
86
- print("\n=== Streaming Example ===")
87
-
88
- generator = WatsonxGenerator(
89
- model="meta-llama/llama-3-3-70b-instruct",
90
- api_key=Secret.from_env_var("WATSONX_API_KEY"),
91
- project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
92
- generation_kwargs={"max_tokens": 512, "temperature": 0.7},
93
- )
94
-
95
- def streaming_callback(chunk: StreamingChunk):
96
- """Handle streaming chunks as they arrive"""
97
- print(chunk.content, end="", flush=True)
98
-
99
- system_prompt = "You are a knowledgeable science teacher. Explain concepts clearly."
100
- prompt = "Explain how rainbows form."
101
-
102
- print(f"Question: {prompt}")
103
- print("Streaming response: ", end="")
104
-
105
- result = generator.run(prompt=prompt, system_prompt=system_prompt, streaming_callback=streaming_callback)
106
-
107
- print("\n\nComplete response received.")
108
- print(f"Total tokens: {result['meta'][0].get('usage', {}).get('total_tokens', 'N/A')}")
109
-
110
-
111
- def pipeline_integration_example():
112
- """Shows how to use WatsonxGenerator in a Haystack pipeline"""
113
- print("\n=== Pipeline Integration Example ===")
114
-
115
- generator = WatsonxGenerator(
116
- model="meta-llama/llama-3-3-70b-instruct",
117
- api_key=Secret.from_env_var("WATSONX_API_KEY"),
118
- project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
119
- generation_kwargs={"max_tokens": 512, "temperature": 0.6},
120
- )
121
-
122
- # Create and configure pipeline
123
- pipeline = Pipeline()
124
- pipeline.add_component("generator", generator)
125
-
126
- system_prompt = "You are an expert historian. Provide accurate, concise historical information."
127
- prompt = "Who built the Great Wall of China and why?"
128
-
129
- result = pipeline.run(
130
- {"generator": {"prompt": prompt, "system_prompt": system_prompt, "generation_kwargs": {"temperature": 0.5}}}
131
- )
132
-
133
- print(f"Pipeline question: {prompt}")
134
- print(f"Pipeline response: {result['generator']['replies'][0]}")
135
- print(f"Pipeline metadata: {result['generator']['meta'][0]}")
136
-
137
-
138
- async def async_example():
139
- """Demonstrates async usage of WatsonxGenerator"""
140
- print("\n=== Async Example ===")
141
-
142
- generator = WatsonxGenerator(
143
- model="meta-llama/llama-3-3-70b-instruct",
144
- api_key=Secret.from_env_var("WATSONX_API_KEY"),
145
- project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
146
- generation_kwargs={"max_tokens": 512, "temperature": 0.7},
147
- )
148
-
149
- system_prompt = "You are a helpful assistant providing practical advice."
150
- questions = [
151
- "What are three tips for better sleep?",
152
- "How can I reduce stress at work?",
153
- "What's a healthy breakfast idea?",
154
- ]
155
-
156
- tasks = []
157
- for question in questions:
158
- task = generator.run_async(prompt=question, system_prompt=system_prompt)
159
- tasks.append((question, task))
160
-
161
- print("Processing multiple questions asynchronously...")
162
-
163
- for question, task in tasks:
164
- result = await task
165
- print(f"\nQ: {question}")
166
- print(f"A: {result['replies'][0]}")
167
-
168
-
169
- def main():
170
- """Run all examples"""
171
- print("WatsonX Generator Examples for Haystack")
172
- print("=" * 50)
173
-
174
- if not os.getenv("WATSONX_API_KEY") or not os.getenv("WATSONX_PROJECT_ID"):
175
- print("Please set WATSONX_API_KEY and WATSONX_PROJECT_ID environment variables")
176
- return
177
-
178
- try:
179
- basic_usage_example()
180
- advanced_configuration_example()
181
- streaming_example()
182
- pipeline_integration_example()
183
-
184
- print("\nRunning async example...")
185
- asyncio.run(async_example())
186
-
187
- print("\n" + "=" * 50)
188
- print("All examples completed successfully!")
189
-
190
- except Exception as e:
191
- print(f"\n Example failed: {e}")
192
- print("Make sure your WatsonX credentials are correctly set.")
193
-
194
-
195
- if __name__ == "__main__":
196
- main()
197
-
198
- # WatsonX Generator Examples for Haystack
199
- # ==================================================
200
- # === Basic Usage Example ===
201
-
202
- # Question: What is the capital of France?
203
- # Answer: The capital of France is Paris.
204
- # Tokens used: 62
205
- # ------------------------------------------------------------
206
-
207
- # Question: Explain photosynthesis in one sentence.
208
- # Answer: Photosynthesis is the process by which plants, algae, and some bacteria convert light energy from the sun
209
- # into chemical energy in the form of glucose, releasing oxygen as a byproduct.
210
- # Tokens used: 92
211
- # ------------------------------------------------------------
212
-
213
- # Question: List benefits of renewable energy.
214
- # Answer: The benefits of renewable energy include:
215
-
216
- # 1. **Sustainability**: Renewable energy sources are replenished naturally and are not depleted over time.
217
- # 2. **Reduced Greenhouse Gas Emissions**: Renewable energy sources produce little to no greenhouse gas emissions,
218
- # contributing to a decrease in climate change.
219
- # 3. **Lower Operating Costs**: Renewable energy sources have lower operating costs compared to traditional fossil
220
- # fuel-based power plants.
221
- # 4. **Energy Independence**: Renewable energy can reduce reliance on imported fuels, improving energy security and
222
- # reducing dependence on foreign energy.
223
-
224
- # Tokens used: 153
225
- # ------------------------------------------------------------
226
-
227
- # === Advanced Configuration Example ===
228
- # Creative writing prompt: Describe a peaceful mountain lake at sunrise.
229
-
230
- # Response: As the first whispers of dawn caressed the sky, the mountain lake awoke from its slumber, its tranquil
231
- # surface mirroring the heavens like a sheet of polished glass. The surrounding peaks, still cloaked in a soft veil of
232
- # night, stood sentinel, their rugged silhouettes etched against a canvas of pink and gold hues that deepened with each
233
- # passing moment.
234
-
235
- # As sunrise approached, the sky transformed into a kaleidoscope of warm colors - coral, salmon, and amber - which
236
- # danced across the water, casting a mesmerizing glow on the lake's surface. The gentle lapping of the water against
237
- # the shore created a soothing melody, a lullaby that seemed to lull the world into a state of serenity.
238
-
239
- # A delicate mist, born from the lake's nocturnal slumber, began to rise, weaving an ethereal veil that swirled and
240
- # eddied above the water. The air was filled with the sweet scent of pine and the earthy aroma of damp soil, as if the
241
- # forest itself was exhaling a sigh of contentment.
242
-
243
- # As the sun slowly ascended, its rays kissed the lake's surface, creating a dazzling display of light and color. The
244
- # water's glassy calm was broken only by the occasional ripple, as if a fish had stirred beneath the surface, leaving
245
- # behind a trail of concentric circles that gradually dissipated into the stillness.
246
-
247
- # The surrounding landscape, bathed in the warm, golden light of dawn, was set ablaze with color - the emerald green of
248
- # the trees, the rusty red of the rocks, and the soft, velvety texture of the wildflowers that dotted the shore. The
249
- # atmosphere was alive with the sweet songs of birds, their melodies intertwining with the gentle lapping of the water
250
- # to create a symphony of peace and tranquility.
251
-
252
- # In this fleeting moment, time stood still, and the world seemed to hold its breath, basking in the serenity of the
253
- # mountain lake at sunrise. The beauty of this scene was almost palpable, a living, breathing entity that wrapped
254
- # itself around the heart, filling the soul with a sense of wonder, awe, and deep, abiding peace.
255
-
256
- # Metadata: {'model': 'meta-llama/llama-3-3-70b-instruct', 'index': 0, 'finish_reason': 'stop',
257
- # 'usage': {'completion_tokens': 441, 'prompt_tokens': 56, 'total_tokens': 497}}
258
-
259
- # === Streaming Example ===
260
- # Question: Explain how rainbows form.
261
-
262
- # Streaming response: Rainbows are one of the most beautiful and fascinating natural wonders. They occur when sunlight
263
- # passes through water droplets in the air, and the process involves a combination of refraction, dispersion, and
264
- # reflection. Let me break it down step by step:
265
-
266
- # **Step 1: Sunlight enters the water droplet**
267
- # When sunlight enters a water droplet, such as a cloud or mist, it is refracted, or bent, as it passes from air into
268
- # the water. This is because light travels at different speeds in air and water.
269
-
270
- # **Step 2: Dispersion occurs**
271
- # As the sunlight is refracted, it is also split into its individual colors, a process known as dispersion. This is
272
- # because each color of light has a slightly different wavelength and is refracted at a slightly different angle. This
273
- # is why we see a band of colors in a rainbow, rather than just a single color.
274
-
275
- # **Step 3: Reflection occurs**
276
- # The dispersed light is then reflected off the back of the water droplet and bounces back towards the front of the
277
- # droplet. This is known as total internal reflection.
278
-
279
- # **Step 4: Refraction occurs again**
280
- # As the reflected light exits the water droplet, it is refracted again, or bent, as it passes from water back into
281
- # air. This second refraction causes the light to spread out and form a band of colors, which we see as a rainbow.
282
-
283
- # **The position of the observer is crucial**
284
- # For a rainbow to be visible, the observer must be in a specific position relative to the sun and the water droplets.
285
- # The sun must be behind the observer, and the water droplets must be in front of them. The angle between the sun, the
286
- # observer, and the water droplets is also critical, typically around 42 degrees.
287
-
288
- # **The colors of the rainbow**
289
- # The colors of the rainbow, often remembered using the acronym ROYGBIV, appear in the following order: Red, Orange,
290
- # Yellow, Green, Blue, Indigo, and Violet. This is because the different wavelengths of light are refracted at slightly
291
- # different angles, with red light being refracted at the smallest angle and violet light being refracted at the largest
292
- # angle.
293
-
294
- # In summary, rainbows form when sunlight passes through water droplets in the air, is refracted, dispersed, reflected,
295
- # and refracted again, creating a beautiful band of colors that we see in the sky. The position of the observer and the
296
- # angle of the sun are critical in determining the visibility and position of the rainbow.
297
-
298
- # Complete response received.
299
- # Total tokens: N/A
300
-
301
- # === Pipeline Integration Example ===
302
- # Pipeline question: Who built the Great Wall of China and why?
303
-
304
- # Pipeline response: The Great Wall of China was built in multiple stages by several Chinese dynasties. The initial
305
- # versions of the wall were constructed as early as the 7th century BC, during the Chu State period. However, the most
306
- # famous and well-preserved versions were built during the following dynasties:
307
-
308
- # 1. **Qin Dynasty (221-206 BC)**: Qin Shi Huang, the first emperor of China, ordered the construction of a long wall
309
- # to protect his empire from invasions by nomadic tribes. This wall was approximately 3,000 miles (4,800 km) long.
310
-
311
- # 2. **Han Dynasty (206 BC-220 AD)**: The Han Dynasty extended and fortified the wall, making it around 6,000 miles
312
- # (9,656 km) long.
313
-
314
- # 3. **Sui and Ming Dynasties (581-1644 AD)**: The Sui and Ming Dynasties renovated and extended the wall, with the Ming
315
- # Dynasty building the most well-known and well-preserved version, which is around 4,000 miles (6,400 km) long.
316
-
317
- # The primary purpose of the Great Wall of China was to:
318
-
319
- # * **Protect the Chinese Empire from invasions**: The wall was built to prevent nomadic tribes, such as the Mongols
320
- # and the Xiongnu, from invading and raiding Chinese territories.
321
-
322
- # * **Control trade and immigration**: The wall helped to regulate trade and immigration, allowing the Chinese
323
- # government to monitor and tax goods and people entering the country.
324
-
325
- # * **Demonstrate the power and prestige of the Chinese Empire**: The wall was also a symbol of the Chinese Empire's
326
- # power, wealth, and engineering prowess.
327
-
328
- # Overall, the Great Wall of China is an impressive architectural achievement that showcases the ingenuity and labor
329
- # of thousands of workers over several centuries.
330
-
331
- # Pipeline metadata: {'model': 'meta-llama/llama-3-3-70b-instruct', 'index': 0, 'finish_reason': 'stop',
332
- # 'usage': {'completion_tokens': 362, 'prompt_tokens': 58, 'total_tokens': 420}}
333
-
334
- # Running async example...
335
-
336
- # === Async Example ===
337
- # Processing multiple questions asynchronously...
338
-
339
- # Q: What are three tips for better sleep?
340
- # A: Here are three tips for better sleep:
341
-
342
- # 1. **Establish a Consistent Sleep Schedule**: Go to bed and wake up at the same time every day, including weekends.
343
- # This helps regulate your body's internal clock and can improve the quality of your sleep. Aim for 7-9 hours of sleep
344
- # each night.
345
-
346
- # 2. **Create a Sleep-Conducive Environment**: Make your bedroom a sleep haven by ensuring it is dark, quiet, and cool.
347
- # Consider using blackout curtains, earplugs, or a white noise machine if necessary. Invest in a comfortable mattress
348
- # and pillows, and keep electronic devices out of the bedroom.
349
-
350
- # 3. **Develop a Relaxing Bedtime Routine**: Wind down before bed with a calming activity, such as reading a book,
351
- # taking a warm bath, or practicing gentle stretches or meditation. Avoid screens (e.g., phones, tablets, or laptops)
352
- # for at least an hour before bedtime, as the blue light they emit can interfere with your sleep. A consistent bedtime
353
- # routine can signal to your brain that it's time to sleep, making it easier to fall asleep and stay asleep.
354
-
355
- # Remember, it may take some time to notice improvements in your sleep quality, so be patient and try to make these
356
- # tips a consistent part of your daily routine.
357
-
358
- # Q: How can I reduce stress at work?
359
- # A: Reducing stress at work is essential for maintaining your overall well-being and productivity. Here are some
360
- # practical tips to help you manage stress at work:
361
-
362
- # 1. **Prioritize tasks**: Make a to-do list and focus on the most important tasks first. Break down large tasks into
363
- # smaller, manageable chunks to help you stay organized and in control.
364
-
365
- # 2. **Take breaks**: Take short breaks throughout the day to stretch, move around, and rest your mind. Use this time
366
- # to do something you enjoy, such as taking a walk or practicing deep breathing exercises.
367
-
368
- # 3. **Communicate with your team**: Don't be afraid to ask for help or support from your colleagues. Communicate your
369
- # workload and deadlines with your team to ensure everyone is on the same page.
370
-
371
- # 4. **Set boundaries**: Learn to say "no" to tasks that are not essential or that you simply cannot fit into your
372
- # schedule. Set realistic expectations with your manager and colleagues to avoid overcommitting.
373
-
374
- # 5. **Stay organized**: Keep your workspace organized and clutter-free. This will help you stay focused and avoid
375
- # wasting time searching for lost documents or supplies.
376
-
377
- # 6. **Practice self-care**: Take care of your physical and emotional needs by getting enough sleep, exercising
378
- # regularly, and eating a healthy diet.
379
-
380
- # 7. **Limit distractions**: Minimize distractions by turning off notifications, finding a quiet workspace, or using
381
- # noise-cancelling headphones.
382
-
383
- # 8. **Seek support**: If you're feeling overwhelmed, don't hesitate to seek support from a supervisor, HR
384
- # representative, or a mental health professional.
385
-
386
- # 9. **Set realistic goals**: Set achievable goals and celebrate your successes. This will help you stay motivated and
387
- # focused.
388
-
389
- # 10. **Disconnect from work**: Establish a clear boundary between your work and personal life by avoiding work-related
390
- # tasks outside of work hours.
391
-
392
- # 11. **Use stress-reducing techniques**: Try techniques such as meditation, yoga, or deep breathing exercises to help
393
- # manage stress and anxiety.
394
-
395
- # 12. **Take time off**: Use your vacation days or take a mental health day if you need to recharge and reduce stress.
396
-
397
- # Remember, everyone experiences stress at work, but by implementing these tips, you can reduce your stress levels and
398
- # improve your overall well-being.
399
-
400
- # Which of these tips resonates with you the most, or is there something specific that's causing you stress at work? I'm
401
- # here to help you brainstorm and find solutions.
402
-
403
- # Q: What's a healthy breakfast idea?
404
- # A: Here's a simple and nutritious breakfast idea:
405
-
406
- # **Avocado Toast with Scrambled Eggs and Cherry Tomatoes**
407
-
408
- # Ingredients:
409
-
410
- # * 1 slice whole grain bread (e.g., whole wheat or multigrain)
411
- # * 1/2 avocado, mashed
412
- # * 2 scrambled eggs
413
- # * 1/2 cup cherry tomatoes, halved
414
- # * Salt and pepper to taste
415
- # * Optional: 1 tablespoon olive oil, 1 tablespoon chopped fresh herbs (e.g., parsley, basil)
416
-
417
- # Instructions:
418
-
419
- # 1. Toast the bread until lightly browned.
420
- # 2. Spread the mashed avocado on top of the toast.
421
- # 3. Scramble the eggs in a bowl and cook them in a non-stick pan until set.
422
- # 4. Place the scrambled eggs on top of the avocado.
423
- # 5. Add the halved cherry tomatoes on top of the eggs.
424
- # 6. Season with salt, pepper, and a drizzle of olive oil (if using).
425
- # 7. Garnish with chopped fresh herbs (if using).
426
-
427
- # This breakfast idea is packed with:
428
-
429
- # * Whole grains (fiber and nutrients)
430
- # * Healthy fats (avocado and olive oil)
431
- # * Protein (eggs)
432
- # * Fresh fruits (cherry tomatoes)
433
- # * Fresh herbs (antioxidants and flavor)
434
-
435
- # Feel free to customize this recipe to your taste preferences and dietary needs. Enjoy your delicious and nutritious
436
- # breakfast!
437
-
438
- # ==================================================
439
- # All examples completed successfully!