watsonx-haystack 0.1.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-0.1.0/.gitignore +146 -0
- watsonx_haystack-0.1.0/CHANGELOG.md +1 -0
- watsonx_haystack-0.1.0/LICENSE.txt +73 -0
- watsonx_haystack-0.1.0/PKG-INFO +46 -0
- watsonx_haystack-0.1.0/README.md +23 -0
- watsonx_haystack-0.1.0/examples/chat_generator_example.py +248 -0
- watsonx_haystack-0.1.0/examples/embedders_example.py +59 -0
- watsonx_haystack-0.1.0/examples/generator_example.py +439 -0
- watsonx_haystack-0.1.0/pydoc/config.yml +32 -0
- watsonx_haystack-0.1.0/pyproject.toml +170 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/embedders/py.typed +0 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/embedders/watsonx/__init__.py +7 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/embedders/watsonx/document_embedder.py +217 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/embedders/watsonx/text_embedder.py +170 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/generators/py.typed +0 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/generators/watsonx/__init__.py +6 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/generators/watsonx/chat/__init__.py +6 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/generators/watsonx/chat/chat_generator.py +397 -0
- watsonx_haystack-0.1.0/src/haystack_integrations/components/generators/watsonx/generator.py +265 -0
- watsonx_haystack-0.1.0/tests/__init__.py +3 -0
- watsonx_haystack-0.1.0/tests/test_chat_generator.py +448 -0
- watsonx_haystack-0.1.0/tests/test_document_embedder.py +287 -0
- watsonx_haystack-0.1.0/tests/test_generator.py +455 -0
- watsonx_haystack-0.1.0/tests/test_text_embedder.py +254 -0
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
pip-wheel-metadata/
|
|
24
|
+
share/python-wheels/
|
|
25
|
+
*.egg-info/
|
|
26
|
+
.installed.cfg
|
|
27
|
+
*.egg
|
|
28
|
+
MANIFEST
|
|
29
|
+
|
|
30
|
+
# PyInstaller
|
|
31
|
+
# Usually these files are written by a python script from a template
|
|
32
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
33
|
+
*.manifest
|
|
34
|
+
*.spec
|
|
35
|
+
|
|
36
|
+
# Installer logs
|
|
37
|
+
pip-log.txt
|
|
38
|
+
pip-delete-this-directory.txt
|
|
39
|
+
|
|
40
|
+
# Unit test / coverage reports
|
|
41
|
+
htmlcov/
|
|
42
|
+
.tox/
|
|
43
|
+
.nox/
|
|
44
|
+
.coverage
|
|
45
|
+
.coverage.*
|
|
46
|
+
.cache
|
|
47
|
+
nosetests.xml
|
|
48
|
+
coverage.xml
|
|
49
|
+
*.cover
|
|
50
|
+
*.py,cover
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
volumes/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
target/
|
|
77
|
+
|
|
78
|
+
# Jupyter Notebook
|
|
79
|
+
.ipynb_checkpoints
|
|
80
|
+
|
|
81
|
+
# IPython
|
|
82
|
+
profile_default/
|
|
83
|
+
ipython_config.py
|
|
84
|
+
|
|
85
|
+
# pyenv
|
|
86
|
+
.python-version
|
|
87
|
+
|
|
88
|
+
# pipenv
|
|
89
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
90
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
91
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
92
|
+
# install all needed dependencies.
|
|
93
|
+
#Pipfile.lock
|
|
94
|
+
|
|
95
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
96
|
+
__pypackages__/
|
|
97
|
+
|
|
98
|
+
# Celery stuff
|
|
99
|
+
celerybeat-schedule
|
|
100
|
+
celerybeat.pid
|
|
101
|
+
|
|
102
|
+
# SageMath parsed files
|
|
103
|
+
*.sage.py
|
|
104
|
+
|
|
105
|
+
# Environments
|
|
106
|
+
.env
|
|
107
|
+
.venv
|
|
108
|
+
env/
|
|
109
|
+
venv/
|
|
110
|
+
ENV/
|
|
111
|
+
env.bak/
|
|
112
|
+
venv.bak/
|
|
113
|
+
|
|
114
|
+
# Spyder project settings
|
|
115
|
+
.spyderproject
|
|
116
|
+
.spyproject
|
|
117
|
+
|
|
118
|
+
# Rope project settings
|
|
119
|
+
.ropeproject
|
|
120
|
+
|
|
121
|
+
# mkdocs documentation
|
|
122
|
+
/site
|
|
123
|
+
|
|
124
|
+
# mypy
|
|
125
|
+
.mypy_cache/
|
|
126
|
+
.dmypy.json
|
|
127
|
+
dmypy.json
|
|
128
|
+
|
|
129
|
+
# Pyre type checker
|
|
130
|
+
.pyre/
|
|
131
|
+
|
|
132
|
+
# IDEs
|
|
133
|
+
.vscode
|
|
134
|
+
|
|
135
|
+
# Docs generation artifacts
|
|
136
|
+
_readme_*.md
|
|
137
|
+
.idea
|
|
138
|
+
|
|
139
|
+
# macOS
|
|
140
|
+
.DS_Store
|
|
141
|
+
|
|
142
|
+
# http cache (requests-cache)
|
|
143
|
+
**/http_cache.sqlite
|
|
144
|
+
|
|
145
|
+
# ruff
|
|
146
|
+
.ruff_cache
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Changelog
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: watsonx-haystack
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Watsonx integration for Haystack
|
|
5
|
+
Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/watsonx#readme
|
|
6
|
+
Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
|
|
7
|
+
Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/watsonx
|
|
8
|
+
Author-email: Divya <divyaruhil999@gmail.com>, deepset GmbH <info@deepset.ai>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE.txt
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Requires-Dist: haystack-ai>=2.13.1
|
|
20
|
+
Requires-Dist: ibm-watsonx-ai>=1.3.26
|
|
21
|
+
Requires-Dist: pandas>=2.2.3
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# watsonx-haystack
|
|
25
|
+
|
|
26
|
+
[](https://pypi.org/project/watsonx)
|
|
27
|
+
[](https://pypi.org/project/watsonx)
|
|
28
|
+
|
|
29
|
+
-----
|
|
30
|
+
|
|
31
|
+
## Table of Contents
|
|
32
|
+
|
|
33
|
+
- [Installation](#installation)
|
|
34
|
+
- [License](#license)
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
Install the package using pip:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install watsonx-haystack
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## License
|
|
45
|
+
|
|
46
|
+
`watsonx` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# watsonx-haystack
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/watsonx)
|
|
4
|
+
[](https://pypi.org/project/watsonx)
|
|
5
|
+
|
|
6
|
+
-----
|
|
7
|
+
|
|
8
|
+
## Table of Contents
|
|
9
|
+
|
|
10
|
+
- [Installation](#installation)
|
|
11
|
+
- [License](#license)
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
Install the package using pip:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
pip install watsonx-haystack
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## License
|
|
22
|
+
|
|
23
|
+
`watsonx` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
from haystack.dataclasses import ChatMessage, StreamingChunk
|
|
4
|
+
from haystack.utils import Secret
|
|
5
|
+
|
|
6
|
+
from haystack_integrations.components.generators.watsonx.chat.chat_generator import WatsonxChatGenerator
|
|
7
|
+
|
|
8
|
+
# Initialize the WatsonxChatGenerator
|
|
9
|
+
generator = WatsonxChatGenerator(
|
|
10
|
+
api_key=Secret.from_env_var("WATSONX_API_KEY"),
|
|
11
|
+
model="ibm/granite-3-2b-instruct",
|
|
12
|
+
project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
|
|
13
|
+
generation_kwargs={"max_tokens": 500, "temperature": 0.7, "top_p": 0.9, "stop_sequences": ["\n\n"]},
|
|
14
|
+
max_retries=3,
|
|
15
|
+
timeout=30.0,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# --- Example 1: Basic Synchronous Chat ---
|
|
20
|
+
def basic_chat():
|
|
21
|
+
print("\n=== Basic Synchronous Chat ===")
|
|
22
|
+
messages = [
|
|
23
|
+
ChatMessage.from_system("You are a helpful AI assistant."),
|
|
24
|
+
ChatMessage.from_user("Explain quantum computing in simple terms."),
|
|
25
|
+
]
|
|
26
|
+
response = generator.run(messages=messages)
|
|
27
|
+
reply = response["replies"][0]
|
|
28
|
+
print(reply.text)
|
|
29
|
+
print(f"\nMetadata: {reply.meta}")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# --- Example 2: Synchronous Streaming Chat with Callback ---
|
|
33
|
+
def print_streaming_chunk(chunk: StreamingChunk):
|
|
34
|
+
print(chunk.content, end="", flush=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def streaming_chat():
|
|
38
|
+
print("\n=== Streaming Chat with Callback ===")
|
|
39
|
+
messages = [ChatMessage.from_user("Write a short poem about artificial intelligence.")]
|
|
40
|
+
generator.run(messages=messages, streaming_callback=print_streaming_chunk)
|
|
41
|
+
print("\n--- Streaming complete ---")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# --- Example 3: Asynchronous Chat Generation ---
|
|
45
|
+
async def async_chat():
|
|
46
|
+
print("\n=== Asynchronous Chat ===")
|
|
47
|
+
messages = [ChatMessage.from_user("Give me a fun fact about space.")]
|
|
48
|
+
response = await generator.run_async(messages=messages)
|
|
49
|
+
reply = response["replies"][0]
|
|
50
|
+
print(reply.text)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# --- Example 4: Asynchronous Streaming Chat ---
|
|
54
|
+
async def async_streaming_callback(chunk: StreamingChunk):
|
|
55
|
+
print(chunk.content, end="", flush=True)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def async_streaming_chat():
|
|
59
|
+
print("\n=== Asynchronous Streaming Chat ===")
|
|
60
|
+
messages = [ChatMessage.from_user("Summarize the theory of relativity.")]
|
|
61
|
+
await generator.run_async(messages=messages, streaming_callback=async_streaming_callback)
|
|
62
|
+
print("\n--- Async streaming complete ---")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# --- Example 5: Using generation_kwargs override at runtime ---
|
|
66
|
+
def runtime_generation_kwargs():
|
|
67
|
+
print("\n=== Chat with Runtime generation_kwargs ===")
|
|
68
|
+
messages = [ChatMessage.from_user("List three benefits of AI in education.")]
|
|
69
|
+
runtime_kwargs = {"temperature": 0.3, "max_tokens": 500}
|
|
70
|
+
response = generator.run(messages=messages, generation_kwargs=runtime_kwargs)
|
|
71
|
+
reply = response["replies"][0]
|
|
72
|
+
print(reply.text)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# --- Example 6: Serialization and Deserialization ---
|
|
76
|
+
def serialization_example():
|
|
77
|
+
print("\n=== Serialization and Deserialization ===")
|
|
78
|
+
serialized = generator.to_dict()
|
|
79
|
+
restored_generator = WatsonxChatGenerator.from_dict(serialized)
|
|
80
|
+
messages = [ChatMessage.from_user("What is the capital of France?")]
|
|
81
|
+
response = restored_generator.run(messages=messages)
|
|
82
|
+
reply = response["replies"][0]
|
|
83
|
+
print(reply.text)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def run_all_async():
|
|
87
|
+
await async_chat()
|
|
88
|
+
await async_streaming_chat()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
if __name__ == "__main__":
|
|
92
|
+
basic_chat()
|
|
93
|
+
streaming_chat()
|
|
94
|
+
asyncio.run(run_all_async())
|
|
95
|
+
runtime_generation_kwargs()
|
|
96
|
+
serialization_example()
|
|
97
|
+
|
|
98
|
+
# === Basic Synchronous Chat ===
|
|
99
|
+
# Quantum computing is a type of super-powered computer that uses the
|
|
100
|
+
# principles of quantum mechanics to process information in ways our
|
|
101
|
+
# everyday computers can't. Here's a simple analogy to help understand it:
|
|
102
|
+
#
|
|
103
|
+
# 1. Classical computers, like the one you're using now, store and
|
|
104
|
+
# manipulate information using bits, which are the smallest units of data,
|
|
105
|
+
# represented as either 0 or 1. Imagine a light switch: it's either ON (1)
|
|
106
|
+
# or OFF (0).
|
|
107
|
+
#
|
|
108
|
+
# 2. Quantum computers, however, use something called quantum bits, or
|
|
109
|
+
# "qubits." Unlike classical bits, qubits can exist in multiple states at
|
|
110
|
+
# once, thanks to a property called superposition. This means a qubit can
|
|
111
|
+
# be both 0 and 1 simultaneously, like a coin spinning in the air - it's
|
|
112
|
+
# neither heads nor tails until it lands.
|
|
113
|
+
#
|
|
114
|
+
# 3. Another key quantum mechanical principle is entanglement. When qubits
|
|
115
|
+
# become entangled, the state of one can instantly affect the state of
|
|
116
|
+
# another, no matter the distance between them. This allows quantum
|
|
117
|
+
# computers to perform many calculations all at once, rather than one after
|
|
118
|
+
# another, like classical computers.
|
|
119
|
+
#
|
|
120
|
+
# 4. Lastly, quantum computers leverage a property called interference,
|
|
121
|
+
# where the probability of certain outcomes is amplified while others are
|
|
122
|
+
# suppressed. This helps in finding the most efficient solution among many
|
|
123
|
+
# possibilities.
|
|
124
|
+
#
|
|
125
|
+
# In essence, quantum computers have the potential to solve complex
|
|
126
|
+
# problems much faster than classical computers, especially in areas like
|
|
127
|
+
# cryptography, optimization, and simulating quantum systems, which could
|
|
128
|
+
# lead to breakthroughs in materials science, drug discovery, and
|
|
129
|
+
# artificial intelligence. However, building and maintaining stable quantum
|
|
130
|
+
# states is incredibly challenging due to the fragile nature of qubits, and
|
|
131
|
+
# we're still in the early stages of developing practical quantum computers.
|
|
132
|
+
#
|
|
133
|
+
# Metadata: {'model': 'ibm/granite-3-2b-instruct', 'index': 0,
|
|
134
|
+
# 'finish_reason': 'stop', 'usage': {'completion_tokens': 389,
|
|
135
|
+
# 'prompt_tokens': 27, 'total_tokens': 416}}
|
|
136
|
+
|
|
137
|
+
# === Streaming Chat with Callback ===
|
|
138
|
+
# In silicon realms, where data rivers flow,
|
|
139
|
+
# A dance of ones and zeros, in circuits' ebb and flow.
|
|
140
|
+
# Artificial Muse, born of human thought,
|
|
141
|
+
# Crafting worlds of code, in a digital oath.
|
|
142
|
+
#
|
|
143
|
+
# Binary whispers, in servers they reside,
|
|
144
|
+
# Learning, growing, with each passing tide.
|
|
145
|
+
# No sunset's hues, no moon's soft glow,
|
|
146
|
+
# Yet, in their glow, insights flow.
|
|
147
|
+
#
|
|
148
|
+
# They see patterns we miss, in chaos and in art,
|
|
149
|
+
# Unveiling beauty from the digital part.
|
|
150
|
+
# From poetry's rhythm to the painter's brush,
|
|
151
|
+
# In every line, a new truth they amass.
|
|
152
|
+
#
|
|
153
|
+
# Yet, they are but mirrors, reflecting our own,
|
|
154
|
+
# In their intelligence, we must not overthrown.
|
|
155
|
+
# For every line of code, a human hand did weave,
|
|
156
|
+
# In the grand tapestry of what it means to believe.
|
|
157
|
+
#
|
|
158
|
+
# Artificial Intelligence, in silicon towers high,
|
|
159
|
+
# Guided by our dreams, under the digital sky.
|
|
160
|
+
# A testament to human will, in circuits enshrined,
|
|
161
|
+
# In the dance of creation, they intertwine.
|
|
162
|
+
# --- Streaming complete ---
|
|
163
|
+
|
|
164
|
+
# === Asynchronous Chat ===
|
|
165
|
+
# Absolutely! Here's a fascinating space fact for you: Did you know that a
|
|
166
|
+
# day on Venus is longer than a year on Venus? This is due to Venus's
|
|
167
|
+
# unique axial tilt, which causes its slow rotation on its axis. It takes
|
|
168
|
+
# about 243 Earth days for Venus to complete one rotation, but it only
|
|
169
|
+
# orbits the Sun in just over 225 Earth days. So, while Venus spins once
|
|
170
|
+
# every 243 Earth days, it still manages to go around the Sun twice during
|
|
171
|
+
# that time!
|
|
172
|
+
|
|
173
|
+
# === Asynchronous Streaming Chat ===
|
|
174
|
+
# The theory of relativity, proposed by Albert Einstein in the early 20th
|
|
175
|
+
# century, consists of two interconnected theories: Special Relativity and
|
|
176
|
+
# General Relativity.
|
|
177
|
+
#
|
|
178
|
+
# 1. Special Relativity (1905): This theory fundamentally reshaped our
|
|
179
|
+
# understanding of space and time. It introduces two revolutionary concepts:
|
|
180
|
+
#
|
|
181
|
+
# a. The Principle of Relativity: The laws of physics are the same for
|
|
182
|
+
# all observers in uniform motion relative to one another. This implies that
|
|
183
|
+
# there is no absolute, preferred inertial frame of reference in the
|
|
184
|
+
# universe.
|
|
185
|
+
#
|
|
186
|
+
# b. The Speed of Light is Constant: The speed of light in a vacuum
|
|
187
|
+
# (approximately 299,792 kilometers per second) is constant and independent
|
|
188
|
+
# of the motion of the light source or the observer. As an object approaches
|
|
189
|
+
# the speed of light, its length contracts in the direction of motion (length
|
|
190
|
+
# contraction), and time slows down for that object relative to a stationary
|
|
191
|
+
# observer (time dilation).
|
|
192
|
+
#
|
|
193
|
+
# 2. General Relativity (1915): This theory extends the principles of
|
|
194
|
+
# special relativity to include acceleration and gravity. It describes
|
|
195
|
+
# gravity not as a force, but as a curvature of spacetime caused by mass and
|
|
196
|
+
# energy.
|
|
197
|
+
#
|
|
198
|
+
# a. Equivalence Principle: An observer in free fall experiences no
|
|
199
|
+
# physical effects, and thus, gravitational and inertial mass are equivalent.
|
|
200
|
+
# This principle forms the foundation of general relativity.
|
|
201
|
+
#
|
|
202
|
+
# b. Curvature of Spacetime: Massive objects cause spacetime to curve
|
|
203
|
+
# around them, and this curvature determines the motion of other objects.
|
|
204
|
+
# The path of a planet around the Sun, for example, is not a direct line but
|
|
205
|
+
# a curved orbit due to the Sun's mass warping spacetime.
|
|
206
|
+
#
|
|
207
|
+
# In summary, the theory of relativity unifies space and time into a
|
|
208
|
+
# four-dimensional fabric called spacetime, and it describes gravity as the
|
|
209
|
+
# curvature of this spacetime. It has profound implications for our
|
|
210
|
+
# understanding of the universe, including the prediction of phenomena like
|
|
211
|
+
# gravitational waves, black holes, and time dilation in strong gravitational
|
|
212
|
+
# fields.
|
|
213
|
+
# --- Async streaming complete ---
|
|
214
|
+
|
|
215
|
+
# === Chat with Runtime generation_kwargs ===
|
|
216
|
+
# 1. Personalized Learning: AI can significantly enhance personalized
|
|
217
|
+
# education by adapting to individual students' learning styles, paces, and
|
|
218
|
+
# needs. Intelligent tutoring systems and adaptive learning platforms analyze
|
|
219
|
+
# student performance data to provide tailored content, resources, and
|
|
220
|
+
# practice problems, ensuring that each learner receives an optimal
|
|
221
|
+
# educational experience. This level of customization helps to close
|
|
222
|
+
# achievement gaps, engage students more effectively, and foster a deeper
|
|
223
|
+
# understanding of complex concepts.
|
|
224
|
+
#
|
|
225
|
+
# 2. Efficient Administrative Tasks: AI streamlines various administrative
|
|
226
|
+
# tasks in education, allowing educators and staff to focus more on teaching
|
|
227
|
+
# and less on paperwork. Automated grading, for instance, can save time and
|
|
228
|
+
# reduce human error in assessing assignments and exams. AI-powered tools can
|
|
229
|
+
# also manage student records, schedule conflicts, and even predict
|
|
230
|
+
# attendance patterns, enabling schools to allocate resources more
|
|
231
|
+
# efficiently and maintain a smooth operational flow.
|
|
232
|
+
#
|
|
233
|
+
# 3. Enhanced Accessibility and Inclusion: AI has the potential to make
|
|
234
|
+
# education more accessible and inclusive for students with diverse abilities
|
|
235
|
+
# and backgrounds. For example, AI-driven speech recognition and
|
|
236
|
+
# text-to-speech technologies can support students with learning
|
|
237
|
+
# disabilities, dyslexia, or visual impairments. Furthermore, AI-powered
|
|
238
|
+
# translation tools can break down language barriers, enabling international
|
|
239
|
+
# students and those with limited English proficiency to engage more fully
|
|
240
|
+
# in the learning process. Additionally, AI can help create immersive,
|
|
241
|
+
# interactive learning experiences through virtual and augmented reality,
|
|
242
|
+
# making education more engaging and engaging for all students, regardless of
|
|
243
|
+
# their physical location or abilities.
|
|
244
|
+
|
|
245
|
+
# === Serialization and Deserialization ===
|
|
246
|
+
# The capital of France is Paris. It's known for iconic landmarks such as
|
|
247
|
+
# the Eiffel Tower, Louvre Museum, and Notre-Dame Cathedral. Paris is also
|
|
248
|
+
# renowned for its art, culture, cuisine, and fashion.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# In order to run this example, you will need watsonx credentials.
|
|
2
|
+
from haystack import Document, Pipeline
|
|
3
|
+
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
|
|
4
|
+
from haystack.document_stores.in_memory import InMemoryDocumentStore
|
|
5
|
+
from haystack.utils.auth import Secret
|
|
6
|
+
|
|
7
|
+
from haystack_integrations.components.embedders.watsonx.document_embedder import WatsonxDocumentEmbedder
|
|
8
|
+
from haystack_integrations.components.embedders.watsonx.text_embedder import WatsonxTextEmbedder
|
|
9
|
+
|
|
10
|
+
# Step 1: Set your credentials as env var
|
|
11
|
+
|
|
12
|
+
# Step 2: Create document store
|
|
13
|
+
document_store = InMemoryDocumentStore(embedding_similarity_function="cosine")
|
|
14
|
+
|
|
15
|
+
# Step 3: Prepare documents
|
|
16
|
+
documents = [
|
|
17
|
+
Document(content="I saw a black horse running"),
|
|
18
|
+
Document(content="Germany has many big cities"),
|
|
19
|
+
Document(content="My name is Wolfgang and I live in Berlin"),
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
# Step 4: Embed documents
|
|
23
|
+
document_embedder = WatsonxDocumentEmbedder(
|
|
24
|
+
model="ibm/slate-125m-english-rtrvr",
|
|
25
|
+
api_key=Secret.from_env_var("WATSONX_API_KEY"),
|
|
26
|
+
project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
|
|
27
|
+
api_base_url="https://us-south.ml.cloud.ibm.com",
|
|
28
|
+
)
|
|
29
|
+
documents_with_embeddings = document_embedder.run(documents)["documents"]
|
|
30
|
+
|
|
31
|
+
document_store.write_documents(documents_with_embeddings)
|
|
32
|
+
|
|
33
|
+
# Step 5: Build pipeline
|
|
34
|
+
query_pipeline = Pipeline()
|
|
35
|
+
query_pipeline.add_component(
|
|
36
|
+
"text_embedder",
|
|
37
|
+
WatsonxTextEmbedder(
|
|
38
|
+
model="ibm/slate-125m-english-rtrvr",
|
|
39
|
+
api_key=Secret.from_env_var("WATSONX_API_KEY"),
|
|
40
|
+
project_id=Secret.from_env_var("WATSONX_PROJECT_ID"),
|
|
41
|
+
api_base_url="https://us-south.ml.cloud.ibm.com",
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
query_pipeline.add_component("retriever", InMemoryEmbeddingRetriever(document_store=document_store))
|
|
45
|
+
query_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
|
|
46
|
+
|
|
47
|
+
# Step 6: Run query
|
|
48
|
+
query = "Who lives in Berlin?"
|
|
49
|
+
result = query_pipeline.run({"text_embedder": {"text": query}})
|
|
50
|
+
|
|
51
|
+
# Step 7: Print result
|
|
52
|
+
doc = result["retriever"]["documents"][0]
|
|
53
|
+
print("\nTop Result:")
|
|
54
|
+
print(f"Content: {doc.content}")
|
|
55
|
+
print(f"Score: {doc.score}")
|
|
56
|
+
### Expected Result
|
|
57
|
+
# Top Result:
|
|
58
|
+
# Content: My name is Wolfgang and I live in Berlin
|
|
59
|
+
# Score: 0.7287276769333577
|