weave-haystack 0.0.1__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.
@@ -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,20 @@
1
+ # Changelog
2
+
3
+ ## [integrations/weights_bias-v0.0.2] - 2025-03-13
4
+
5
+ ### 🚀 Features
6
+
7
+ - Add weave_init_kwargs to WeaveConnector (#1537)
8
+
9
+ ### 📚 Documentation
10
+
11
+ - Update changelog for integrations/weights_bias (#1426)
12
+ - Fixing WandB README (#1427)
13
+
14
+ ## [integrations/weights_bias-v0.0.1] - 2025-02-21
15
+
16
+ ### 🚀 Features
17
+
18
+ - Integration with Weave the tracer from Weight and Bias (#1412)
19
+
20
+ <!-- generated by git-cliff -->
@@ -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,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: weave-haystack
3
+ Version: 0.0.1
4
+ Summary: An integration of Weights & Biases Weave tracer with Haystack
5
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations
6
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/weights_and_biases_weave/README.md
7
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
8
+ Author-email: 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.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
21
+ Requires-Python: >=3.9
22
+ Requires-Dist: haystack-ai
23
+ Requires-Dist: weave>=0.51.33
24
+ Description-Content-Type: text/markdown
25
+
26
+ # weave-haystack
27
+
28
+ [![PyPI - Version](https://img.shields.io/pypi/v/weave-haystack.svg)](https://pypi.org/project/weave-haystack)
29
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/weave-haystack)](https://pypi.org/project/weave-haystack)
30
+
31
+ - [Installation](#installation)
32
+ - [Example](#example)
33
+ - [License](#license)
34
+
35
+
36
+ ## Installation
37
+
38
+ ```console
39
+ pip install weave-haystack
40
+ ```
41
+
42
+ ## Weave by Weights & Biases
43
+
44
+ ### Example
45
+
46
+ You need to have a Weave account to use this feature. You can sign up for free at https://wandb.ai/site.
47
+
48
+ You then need to set the `WANDB_API_KEY:` environment variable with your Weights & Biases API key. You should find
49
+ your API key in https://wandb.ai/home when you are logged in.
50
+
51
+ You should then head to `https://wandb.ai/<user_name>/projects` and see the complete trace for your pipeline under
52
+ the pipeline name you specified, when creating the `WeaveConnector`.
53
+
54
+ You also need to have the `HAYSTACK_CONTENT_TRACING_ENABLED` environment variable set to `true`.
55
+
56
+ To use this connector simply add it to your pipeline without any connections, and it will automatically start
57
+ sending traces to Weights & Biases.
58
+
59
+ ```python
60
+ import os
61
+
62
+ from haystack import Pipeline
63
+ from haystack.components.builders import ChatPromptBuilder
64
+ from haystack.components.generators.chat import OpenAIChatGenerator
65
+ from haystack.dataclasses import ChatMessage
66
+
67
+ from haystack_integrations.components.connectors import WeaveConnector
68
+
69
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
70
+
71
+ pipe = Pipeline()
72
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
73
+ pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
74
+ pipe.connect("prompt_builder.prompt", "llm.messages")
75
+
76
+ connector = WeaveConnector(pipeline_name="test_pipeline")
77
+ pipe.add_component("weave", connector)
78
+
79
+ messages = [
80
+ ChatMessage.from_system(
81
+ "Always respond in German even if some input data is in other languages."
82
+ ),
83
+ ChatMessage.from_user("Tell me about {{location}}"),
84
+ ]
85
+
86
+ response = pipe.run(
87
+ data={
88
+ "prompt_builder": {
89
+ "template_variables": {"location": "Berlin"},
90
+ "template": messages,
91
+ }
92
+ }
93
+ )
94
+ print(response["llm"]["replies"][0])
95
+ ```
96
+
97
+ ## License
98
+
99
+ `weave-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,74 @@
1
+ # weave-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/weave-haystack.svg)](https://pypi.org/project/weave-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/weave-haystack)](https://pypi.org/project/weave-haystack)
5
+
6
+ - [Installation](#installation)
7
+ - [Example](#example)
8
+ - [License](#license)
9
+
10
+
11
+ ## Installation
12
+
13
+ ```console
14
+ pip install weave-haystack
15
+ ```
16
+
17
+ ## Weave by Weights & Biases
18
+
19
+ ### Example
20
+
21
+ You need to have a Weave account to use this feature. You can sign up for free at https://wandb.ai/site.
22
+
23
+ You then need to set the `WANDB_API_KEY:` environment variable with your Weights & Biases API key. You should find
24
+ your API key in https://wandb.ai/home when you are logged in.
25
+
26
+ You should then head to `https://wandb.ai/<user_name>/projects` and see the complete trace for your pipeline under
27
+ the pipeline name you specified, when creating the `WeaveConnector`.
28
+
29
+ You also need to have the `HAYSTACK_CONTENT_TRACING_ENABLED` environment variable set to `true`.
30
+
31
+ To use this connector simply add it to your pipeline without any connections, and it will automatically start
32
+ sending traces to Weights & Biases.
33
+
34
+ ```python
35
+ import os
36
+
37
+ from haystack import Pipeline
38
+ from haystack.components.builders import ChatPromptBuilder
39
+ from haystack.components.generators.chat import OpenAIChatGenerator
40
+ from haystack.dataclasses import ChatMessage
41
+
42
+ from haystack_integrations.components.connectors import WeaveConnector
43
+
44
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
45
+
46
+ pipe = Pipeline()
47
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
48
+ pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
49
+ pipe.connect("prompt_builder.prompt", "llm.messages")
50
+
51
+ connector = WeaveConnector(pipeline_name="test_pipeline")
52
+ pipe.add_component("weave", connector)
53
+
54
+ messages = [
55
+ ChatMessage.from_system(
56
+ "Always respond in German even if some input data is in other languages."
57
+ ),
58
+ ChatMessage.from_user("Tell me about {{location}}"),
59
+ ]
60
+
61
+ response = pipe.run(
62
+ data={
63
+ "prompt_builder": {
64
+ "template_variables": {"location": "Berlin"},
65
+ "template": messages,
66
+ }
67
+ }
68
+ )
69
+ print(response["llm"]["replies"][0])
70
+ ```
71
+
72
+ ## License
73
+
74
+ `weave-haystack` is distributed under the terms of the [Apache-2.0](https://spdx.org/licenses/Apache-2.0.html) license.
@@ -0,0 +1,9 @@
1
+ # Accessing Weights & Biases Weave
2
+
3
+ You need to have a Weave account to use this feature. You can sign up for free at https://wandb.ai/site.
4
+
5
+ You then need to set the `WANDB_API_KEY:` environment variable with your Weights & Biases API key. You should find
6
+ your API key in https://wandb.ai/home when you are logged in.
7
+
8
+ You should then head to `https://wandb.ai/<user_name>/projects` and see the complete trace for your pipeline under
9
+ the pipeline name you specified, when creating the `WeaveConnector`.
@@ -0,0 +1,67 @@
1
+ from haystack import Document, Pipeline
2
+ from haystack.components.embedders import SentenceTransformersDocumentEmbedder, SentenceTransformersTextEmbedder
3
+ from haystack.components.joiners import DocumentJoiner
4
+ from haystack.components.rankers import TransformersSimilarityRanker
5
+ from haystack.components.retrievers.in_memory import InMemoryBM25Retriever, InMemoryEmbeddingRetriever
6
+ from haystack.document_stores.in_memory import InMemoryDocumentStore
7
+
8
+ from haystack_integrations.components.connectors import WeaveConnector
9
+
10
+
11
+ def index():
12
+
13
+ document_store = InMemoryDocumentStore()
14
+ documents = [
15
+ Document(content="The Eiffel Tower is located in Paris, France."),
16
+ Document(content="The capital of Germany is Berlin."),
17
+ Document(content="The Colosseum is located in Rome, Italy."),
18
+ Document(content="Paris is the capital of France."),
19
+ Document(content="The Louvre is located in Paris, France."),
20
+ Document(content="The Brandenburg Gate is located in Berlin, Germany."),
21
+ ]
22
+
23
+ embedder = SentenceTransformersDocumentEmbedder()
24
+ embedder.warm_up()
25
+ embed_docs = embedder.run(documents)
26
+
27
+ document_store.write_documents(embed_docs["documents"])
28
+
29
+ return document_store
30
+
31
+
32
+ def hybrid_pipeline(document_store):
33
+
34
+ text_embedder = SentenceTransformersTextEmbedder()
35
+ embedding_retriever = InMemoryEmbeddingRetriever(document_store)
36
+ bm25_retriever = InMemoryBM25Retriever(document_store)
37
+ document_joiner = DocumentJoiner()
38
+ ranker = TransformersSimilarityRanker(model="BAAI/bge-reranker-base")
39
+
40
+ hybrid_retrieval = Pipeline()
41
+ hybrid_retrieval.add_component("text_embedder", text_embedder)
42
+ hybrid_retrieval.add_component("embedding_retriever", embedding_retriever)
43
+ hybrid_retrieval.add_component("bm25_retriever", bm25_retriever)
44
+ hybrid_retrieval.add_component("document_joiner", document_joiner)
45
+ hybrid_retrieval.add_component("ranker", ranker)
46
+ hybrid_retrieval.connect("text_embedder", "embedding_retriever")
47
+ hybrid_retrieval.connect("bm25_retriever", "document_joiner")
48
+ hybrid_retrieval.connect("embedding_retriever", "document_joiner")
49
+ hybrid_retrieval.connect("document_joiner", "ranker")
50
+
51
+ connector = WeaveConnector(pipeline_name="test_pipeline")
52
+ hybrid_retrieval.add_component("connector", connector)
53
+
54
+ return hybrid_retrieval
55
+
56
+
57
+ def main():
58
+ doc_store = index()
59
+ pipeline = hybrid_pipeline(doc_store)
60
+
61
+ query = "What is the capital of Germany?"
62
+ r = pipeline.run({"text_embedder": {"text": query}, "bm25_retriever": {"query": query}, "ranker": {"query": query}})
63
+ print(r) # noqa: T201
64
+
65
+
66
+ if __name__ == "__main__":
67
+ main()
@@ -0,0 +1,30 @@
1
+ loaders:
2
+ - type: haystack_pydoc_tools.loaders.CustomPythonLoader
3
+ search_path: [../src]
4
+ modules: [
5
+ "haystack_integrations.components.connectors.weave_connector",
6
+ "haystack_integrations.tracing.weave.tracer",
7
+ ]
8
+ ignore_when_discovered: ["__init__"]
9
+ processors:
10
+ - type: filter
11
+ expression:
12
+ documented_only: true
13
+ do_not_filter_modules: false
14
+ skip_empty_modules: true
15
+ - type: smart
16
+ - type: crossref
17
+ renderer:
18
+ type: haystack_pydoc_tools.renderers.ReadmeIntegrationRenderer
19
+ excerpt: Weights & Bias integration for Haystack
20
+ category_slug: integrations-api
21
+ title: weights and bias
22
+ slug: integrations-weights-bias
23
+ order: 260
24
+ markdown:
25
+ descriptive_class_title: false
26
+ classdef_code_block: false
27
+ descriptive_module_title: true
28
+ add_method_class_prefix: true
29
+ add_member_class_prefix: false
30
+ filename: _readme_weights_and_bias.md
@@ -0,0 +1,159 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "weave-haystack"
7
+ dynamic = ["version"]
8
+ description = "An integration of Weights & Biases Weave tracer with Haystack"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ keywords = []
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Programming Language :: Python :: Implementation :: CPython",
24
+ "Programming Language :: Python :: Implementation :: PyPy",
25
+ ]
26
+ dependencies = ["haystack-ai", "weave>=0.51.33"]
27
+
28
+ [project.urls]
29
+ Source = "https://github.com/deepset-ai/haystack-core-integrations"
30
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/weights_and_biases_weave/README.md"
31
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/haystack_integrations"]
35
+
36
+ [tool.hatch.version]
37
+ source = "vcs"
38
+ tag-pattern = 'integrations\/weights_and_biases_weave-v(?P<version>.*)'
39
+
40
+ [tool.hatch.version.raw-options]
41
+ root = "../.."
42
+ git_describe_command = 'git describe --tags --match="integrations/weights_and_biases_weave-v[0-9]*"'
43
+
44
+ [tool.hatch.envs.default]
45
+ installer = "uv"
46
+ dependencies = ["coverage[toml]>=6.5", "pytest", "pytest-rerunfailures", "haystack-pydoc-tools"]
47
+ [tool.hatch.envs.default.scripts]
48
+ test = "pytest {args:tests}"
49
+ test-cov = "coverage run -m pytest {args:tests}"
50
+ test-cov-retry = "test-cov --reruns 3 --reruns-delay 30 -x"
51
+ cov-report = ["- coverage combine", "coverage report"]
52
+ cov = ["test-cov", "cov-report"]
53
+ cov-retry = ["test-cov-retry", "cov-report"]
54
+ docs = ["pydoc-markdown pydoc/config.yml"]
55
+
56
+ [tool.hatch.envs.lint]
57
+ installer = "uv"
58
+ detached = true
59
+ dependencies = ["pip", "black>=23.1.0", "mypy>=1.0.0", "ruff>=0.0.243"]
60
+ [tool.hatch.envs.lint.scripts]
61
+ typing = "mypy --install-types --non-interactive --explicit-package-bases {args:src/ tests}"
62
+ style = ["ruff check {args:}", "black --check --diff {args:.}"]
63
+ fmt = ["black {args:.}", "ruff check --fix {args:}", "style"]
64
+ all = ["style", "typing"]
65
+
66
+ [tool.black]
67
+ target-version = ["py39"]
68
+ line-length = 120
69
+ skip-string-normalization = true
70
+
71
+ [tool.ruff]
72
+ target-version = "py39"
73
+ line-length = 120
74
+
75
+ [tool.ruff.lint]
76
+ select = [
77
+ "A",
78
+ "ARG",
79
+ "B",
80
+ "C",
81
+ "DTZ",
82
+ "E",
83
+ "EM",
84
+ "F",
85
+ "FBT",
86
+ "I",
87
+ "ICN",
88
+ "ISC",
89
+ "N",
90
+ "PLC",
91
+ "PLE",
92
+ "PLR",
93
+ "PLW",
94
+ "Q",
95
+ "RUF",
96
+ "S",
97
+ "T",
98
+ "TID",
99
+ "UP",
100
+ "W",
101
+ "YTT",
102
+ ]
103
+ ignore = [
104
+ # Allow non-abstract empty methods in abstract base classes
105
+ "B027",
106
+ # Allow boolean positional values in function calls, like `dict.get(... True)`
107
+ "FBT003",
108
+ # Ignore checks for possible passwords
109
+ "S105",
110
+ "S106",
111
+ "S107",
112
+ # Ignore complexity
113
+ "C901",
114
+ "PLR0911",
115
+ "PLR0912",
116
+ "PLR0913",
117
+ "PLR0915",
118
+ ]
119
+ unfixable = [
120
+ # Don't touch unused imports
121
+ "F401",
122
+ ]
123
+
124
+ [tool.ruff.lint.isort]
125
+ known-first-party = ["haystack_integrations"]
126
+
127
+ [tool.ruff.lint.flake8-tidy-imports]
128
+ ban-relative-imports = "parents"
129
+
130
+ [tool.ruff.lint.per-file-ignores]
131
+ # Tests can use magic values, assertions, and relative imports
132
+ "tests/**/*" = ["PLR2004", "S101", "TID252"]
133
+
134
+ [tool.coverage.run]
135
+ source = ["haystack_integrations"]
136
+ branch = true
137
+ parallel = false
138
+
139
+
140
+ [tool.coverage.report]
141
+ omit = ["*/tests/*", "*/__init__.py"]
142
+ show_missing = true
143
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
144
+
145
+ [tool.pytest.ini_options]
146
+ markers = [
147
+ "integration: integration tests"
148
+ ]
149
+
150
+ [[tool.mypy.overrides]]
151
+ module = [
152
+ "grpc",
153
+ "haystack.*",
154
+ "haystack_integrations.*",
155
+ "numpy",
156
+ "pytest.*",
157
+ "weave.*"
158
+ ]
159
+ ignore_missing_imports = true
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .weave_connector import WeaveConnector
6
+
7
+ __all__ = ["WeaveConnector"]
@@ -0,0 +1,127 @@
1
+ from typing import Any, Optional
2
+
3
+ from haystack import component, default_from_dict, default_to_dict, logging, tracing
4
+ from weave.trace.autopatch import AutopatchSettings
5
+
6
+ from haystack_integrations.tracing.weave import WeaveTracer
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ @component
12
+ class WeaveConnector:
13
+ """
14
+ Collects traces from your pipeline and sends them to Weights & Biases.
15
+
16
+ Add this component to your pipeline to integrate with the Weights & Biases Weave framework for tracing and
17
+ monitoring your pipeline components.
18
+
19
+ Note that you need to have the `WANDB_API_KEY` environment variable set to your Weights & Biases API key.
20
+
21
+ NOTE: If you don't have a Weights & Biases account it will interactively ask you to set one and your input
22
+ will then be stored in ~/.netrc
23
+
24
+ In addition, you need to set the `HAYSTACK_CONTENT_TRACING_ENABLED` environment variable to `true` in order to
25
+ enable Haystack tracing in your pipeline.
26
+
27
+ To use this connector simply add it to your pipeline without any connections, and it will automatically start
28
+ sending traces to Weights & Biases.
29
+
30
+ Example:
31
+ ```python
32
+ import os
33
+
34
+ from haystack import Pipeline
35
+ from haystack.components.builders import ChatPromptBuilder
36
+ from haystack.components.generators.chat import OpenAIChatGenerator
37
+ from haystack.dataclasses import ChatMessage
38
+
39
+ from haystack_integrations.components.connectors import WeaveConnector
40
+
41
+ os.environ["HAYSTACK_CONTENT_TRACING_ENABLED"] = "true"
42
+
43
+ pipe = Pipeline()
44
+ pipe.add_component("prompt_builder", ChatPromptBuilder())
45
+ pipe.add_component("llm", OpenAIChatGenerator(model="gpt-3.5-turbo"))
46
+ pipe.connect("prompt_builder.prompt", "llm.messages")
47
+
48
+ connector = WeaveConnector(pipeline_name="test_pipeline")
49
+ pipe.add_component("weave", connector)
50
+
51
+ messages = [
52
+ ChatMessage.from_system(
53
+ "Always respond in German even if some input data is in other languages."
54
+ ),
55
+ ChatMessage.from_user("Tell me about {{location}}"),
56
+ ]
57
+
58
+ response = pipe.run(
59
+ data={
60
+ "prompt_builder": {
61
+ "template_variables": {"location": "Berlin"},
62
+ "template": messages,
63
+ }
64
+ }
65
+ )
66
+ print(response["llm"]["replies"][0])
67
+ ```
68
+
69
+ You should then head to `https://wandb.ai/<user_name>/projects` and see the complete trace for your pipeline under
70
+ the pipeline name you specified, when creating the `WeaveConnector`
71
+
72
+ """
73
+
74
+ def __init__(self, pipeline_name: str, weave_init_kwargs: Optional[dict[str, Any]] = None) -> None:
75
+ """
76
+ Initialize WeaveConnector.
77
+
78
+ :param pipeline_name: The name of the pipeline you want to trace.
79
+ :param weave_init_kwargs: Additional arguments to pass to the WeaveTracer client.
80
+ """
81
+ self.pipeline_name = pipeline_name
82
+ self.weave_init_kwargs = weave_init_kwargs or {}
83
+ self.tracer: Optional[WeaveTracer] = None
84
+
85
+ def warm_up(self) -> None:
86
+ """Initialize the WeaveTracer."""
87
+ if self.tracer is None:
88
+ self.tracer = WeaveTracer(project_name=self.pipeline_name, **self.weave_init_kwargs)
89
+ tracing.enable_tracing(self.tracer)
90
+
91
+ @component.output_types(pipeline_name=str)
92
+ def run(self) -> dict[str, str]:
93
+ # NOTE: this is a no-op component - it simply triggers the Tracer to sends traces to Weights & Biases
94
+ return {"pipeline_name": self.pipeline_name}
95
+
96
+ def to_dict(self) -> dict[str, Any]:
97
+ """
98
+ Serializes the component to a dictionary.
99
+
100
+ :returns:
101
+ Dictionary with all the necessary information to recreate this component.
102
+ """
103
+ weave_init_kwargs = self.weave_init_kwargs.copy()
104
+ autopatch_settings = weave_init_kwargs.get("autopatch_settings", None)
105
+ if isinstance(autopatch_settings, AutopatchSettings):
106
+ weave_init_kwargs["autopatch_settings"] = autopatch_settings.model_dump(exclude_defaults=True)
107
+
108
+ return default_to_dict(self, pipeline_name=self.pipeline_name, weave_init_kwargs=weave_init_kwargs)
109
+
110
+ @classmethod
111
+ def from_dict(cls, data: dict[str, Any]) -> "WeaveConnector":
112
+ """
113
+ Deserializes the component from a dictionary.
114
+
115
+ :param data: Dictionary to deserialize from.
116
+ :returns:
117
+ Deserialized component.
118
+ """
119
+ if (
120
+ autopatch_settings := data.get("init_parameters", {})
121
+ .get("weave_init_kwargs", {})
122
+ .get("autopatch_settings", None)
123
+ ):
124
+ parsed_settings = AutopatchSettings.model_validate(autopatch_settings)
125
+ data["init_parameters"]["weave_init_kwargs"]["autopatch_settings"] = parsed_settings
126
+
127
+ return default_from_dict(cls, data)
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .tracer import WeaveSpan, WeaveTracer
6
+
7
+ __all__ = ["WeaveSpan", "WeaveTracer"]
@@ -0,0 +1,223 @@
1
+ import contextlib
2
+ import os
3
+ from collections.abc import Iterator
4
+ from typing import Any, Optional, Union
5
+
6
+ from haystack import logging
7
+ from haystack.tracing import Span, Tracer
8
+ from haystack.tracing import tracer as haystack_tracer
9
+ from haystack.tracing.utils import coerce_tag_value
10
+
11
+ import weave
12
+ from weave.trace.weave_client import Call, WeaveClient
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class WeaveSpan(Span):
18
+ """
19
+ A bridge between Haystack's Span interface and Weave's Call object.
20
+
21
+ Stores metadata about a component execution and its inputs and outputs, and manages the attributes/tags
22
+ that describe the operation.
23
+ """
24
+
25
+ def __init__(
26
+ self, call: Optional[Call] = None, parent: Optional[Call] = None, operation: Optional[str] = None
27
+ ) -> None:
28
+ self._call = call
29
+ self._parent = parent
30
+ self._operation = operation
31
+ self._attributes: dict[str, Any] = {}
32
+
33
+ def set_tag(self, key: str, value: Any) -> None:
34
+ """
35
+ Set a tag by adding it to the call's inputs.
36
+
37
+ :param key: The tag key.
38
+ :param value: The tag value.
39
+ """
40
+ self._attributes[key] = value
41
+
42
+ def set_tags(self, tags: dict[str, Any]) -> None:
43
+ for k, v in tags.items():
44
+ self.set_tag(k, v)
45
+
46
+ def raw_span(self) -> Any:
47
+ """Access to the underlying Weave Call object."""
48
+ return self._call
49
+
50
+ def get_correlation_data_for_logs(self) -> dict[str, Any]:
51
+ """Correlation data for logging."""
52
+ if not self._call:
53
+ return {}
54
+ return {"weave.call_id": self._call.id, "weave.run_id": getattr(self._call, "run_id", "")}
55
+
56
+ def set_call(self, call: "weave.Call") -> None:
57
+ self._call = call
58
+
59
+ def get_attributes(self) -> dict[str, Any]:
60
+ return self._attributes
61
+
62
+
63
+ class WeaveTracer(Tracer):
64
+ """
65
+ Implements a Haystack's Tracer to make an interface with Weights and Bias Weave.
66
+
67
+ It's responsible for creating and managing Weave calls, and for converting Haystack spans
68
+ to Weave spans. It creates spans for each Haystack component run.
69
+ """
70
+
71
+ def __init__(self, project_name: str, **weave_init_kwargs: Any) -> None:
72
+ """
73
+ Initialize the WeaveTracer.
74
+
75
+ :param project_name: The name of the project to trace, this is will be the name appearing in Weave project.
76
+ :param weave_init_kwargs: Additional arguments to pass to the Weave client.
77
+ """
78
+
79
+ content_tracing_enabled = os.getenv("HAYSTACK_CONTENT_TRACING_ENABLED", "false").lower()
80
+ haystack_tracer.is_content_tracing_enabled = content_tracing_enabled == "true"
81
+ if not haystack_tracer.is_content_tracing_enabled:
82
+ logger.warning(
83
+ "Inputs and Outputs of components traces will not be logged because Haystack tracing is disabled."
84
+ "To enable, set the HAYSTACK_CONTENT_TRACING_ENABLED environment variable to true "
85
+ "before importing Haystack."
86
+ )
87
+
88
+ self._client = weave.init(project_name, **weave_init_kwargs)
89
+ self._current_span: Optional[WeaveSpan] = None
90
+
91
+ @staticmethod
92
+ def create_call(
93
+ attributes: dict, client: WeaveClient, parent_span: Union[WeaveSpan, None], operation_name: str
94
+ ) -> Call:
95
+ comp_name = attributes.pop("haystack.component.name", "")
96
+ comp_type = attributes.pop("haystack.component.type", "")
97
+ comp_input = attributes.pop("haystack.component.input", {})
98
+ call = client.create_call(
99
+ op=operation_name,
100
+ inputs={key: coerce_tag_value(value) for key, value in comp_input.items()},
101
+ attributes={key: coerce_tag_value(value) for key, value in attributes.items()},
102
+ display_name=f"{comp_name}[{comp_type}].run",
103
+ parent=parent_span.raw_span() if parent_span else None,
104
+ )
105
+ return call
106
+
107
+ def current_span(self) -> Optional[Span]:
108
+ """Get the current active span."""
109
+ return self._current_span
110
+
111
+ @staticmethod
112
+ def _create_component_span(parent_span: Optional[WeaveSpan], operation_name: str) -> WeaveSpan:
113
+ """Create a span for component runs with deferred call creation."""
114
+ return WeaveSpan(parent=parent_span.raw_span() if parent_span else None, operation=operation_name)
115
+
116
+ def _create_regular_span(
117
+ self, operation_name: str, tags: Optional[dict], parent_span: Optional[WeaveSpan]
118
+ ) -> WeaveSpan:
119
+ """Create a span for regular operations with immediate call creation."""
120
+ call = self._client.create_call(
121
+ op=operation_name,
122
+ inputs=tags,
123
+ parent=parent_span.raw_span() if parent_span else None,
124
+ )
125
+ return WeaveSpan(call=call)
126
+
127
+ def _finish_component_call(self, span: WeaveSpan, parent_span: Optional[WeaveSpan], operation_name: str) -> None:
128
+ """Create and finish call for component runs."""
129
+ attributes = span.get_attributes()
130
+ call = self.create_call(
131
+ attributes=attributes,
132
+ client=self._client,
133
+ parent_span=parent_span,
134
+ operation_name=operation_name,
135
+ )
136
+ span.set_call(call)
137
+ comp_output = attributes.pop("haystack.component.output", {})
138
+ self._client.finish_call(
139
+ call,
140
+ output={key: coerce_tag_value(value) for key, value in comp_output.items()},
141
+ )
142
+
143
+ def _finish_regular_call(self, span: WeaveSpan) -> None:
144
+ """Finish call for regular operations."""
145
+ attributes = span.get_attributes()
146
+ pipeline_output = attributes.pop("haystack.pipeline.output_data", {})
147
+ self._client.finish_call(
148
+ span.raw_span(),
149
+ output={key: coerce_tag_value(value) for key, value in pipeline_output.items()},
150
+ )
151
+
152
+ @contextlib.contextmanager
153
+ def trace(
154
+ self, operation_name: str, tags: Optional[dict[str, Any]] = None, parent_span: Optional[WeaveSpan] = None
155
+ ) -> Iterator[WeaveSpan]:
156
+ """
157
+ A context manager that creates and manages spans for tracking operations in Weights & Biases Weave.
158
+
159
+ It has two main workflows:
160
+
161
+ A) For regular operations (operation_name != "haystack.component.run"):
162
+ Creates a Weave Call immediately
163
+ Creates a WeaveSpan with this call
164
+ Sets any provided tags
165
+ Yields the span for use in the with block
166
+ When the block ends, updates the call with pipeline output data
167
+
168
+ B) For component runs (operation_name == "haystack.component.run"):
169
+ Creates a WeaveSpan WITHOUT a call initially (deferred creation)
170
+ Sets any provided tags
171
+ Yields the span for use in the with block
172
+ Creates the actual Weave Call only at the end, when all component information is available
173
+ Updates the call with component output data
174
+
175
+ This distinction is important because Weave's calls can't be updated once created, but the content
176
+ tags are only set on the Span at a later stage. To get the inputs on call creation, we need to create
177
+ the call after we yield the span.
178
+
179
+ """
180
+ # create an appropriate span based on operation type
181
+ is_component_run = operation_name == "haystack.component.run"
182
+ span = (
183
+ self._create_component_span(parent_span, operation_name)
184
+ if is_component_run
185
+ else self._create_regular_span(operation_name, tags, parent_span)
186
+ )
187
+
188
+ self._current_span = span
189
+ if tags:
190
+ span.set_tags(tags)
191
+
192
+ # this method acts as a context manager so yielding the span yields the context to the caller
193
+ # try-except-else-finally to ensure that a call is created and finished correctly for both types of operations
194
+ try:
195
+ yield span
196
+
197
+ except Exception as e:
198
+ # case when an exception is raised, an error occurred note that for a component run ensure call is
199
+ # created even on error
200
+ if is_component_run:
201
+ attributes = span.get_attributes()
202
+ call = self.create_call(
203
+ attributes=attributes,
204
+ client=self._client,
205
+ parent_span=parent_span,
206
+ operation_name=operation_name,
207
+ )
208
+ span.set_call(call)
209
+ self._client.finish_call(call, exception=e)
210
+ else:
211
+ self._client.finish_call(span.raw_span(), exception=e)
212
+ raise # re-raise the same exception
213
+
214
+ else:
215
+ # case when no exception is raised, operation was successful
216
+ if is_component_run:
217
+ self._finish_component_call(span, parent_span, operation_name)
218
+ else:
219
+ self._finish_regular_call(span)
220
+
221
+ finally:
222
+ # reset the current span
223
+ self._current_span = None
@@ -0,0 +1,105 @@
1
+ import logging
2
+ from unittest.mock import patch
3
+
4
+ from weave.trace.autopatch import AutopatchSettings
5
+
6
+ from haystack_integrations.tracing.weave.tracer import WeaveSpan, WeaveTracer
7
+
8
+
9
+ class MockCall:
10
+ def __init__(self, op=None, inputs=None, attributes=None, display_name=None, parent=None):
11
+ self.id = "test_id"
12
+ self.run_id = "test_run_id"
13
+ self.op = op
14
+ self.inputs = inputs or {}
15
+ self.attributes = attributes or {}
16
+ self.display_name = display_name
17
+ self.parent = parent
18
+
19
+
20
+ class MockWeaveClient:
21
+ @staticmethod
22
+ def create_call(op=None, inputs=None, attributes=None, display_name=None, parent=None):
23
+ return MockCall(op=op, inputs=inputs, attributes=attributes, display_name=display_name, parent=parent)
24
+
25
+ def finish_call(self, call, output=None, exception=None):
26
+ pass
27
+
28
+
29
+ class TestWeaveTracer:
30
+
31
+ def test_initialization(self):
32
+ with patch("weave.init") as mock_init:
33
+ mock_init.return_value = MockWeaveClient()
34
+ tracer = WeaveTracer(project_name="test_project")
35
+ assert tracer._client is not None
36
+ assert tracer._current_span is None
37
+ mock_init.assert_called_once_with("test_project")
38
+
39
+ def test_initialization_with_weave_init_kwargs(self):
40
+ with patch("weave.init") as mock_init:
41
+ mock_init.return_value = MockWeaveClient()
42
+ tracer = WeaveTracer(
43
+ project_name="test_project",
44
+ autopatch_settings=AutopatchSettings(disable_autopatch=True),
45
+ )
46
+ assert tracer._client is not None
47
+ assert tracer._current_span is None
48
+ mock_init.assert_called_once_with(
49
+ "test_project", autopatch_settings=AutopatchSettings(disable_autopatch=True)
50
+ )
51
+
52
+ def test_create_new_span(self):
53
+ with patch("weave.init") as mock_init:
54
+ mock_client = MockWeaveClient()
55
+ mock_init.return_value = mock_client
56
+ tracer = WeaveTracer(project_name="test_project")
57
+ with tracer.trace("operation_name", tags={"tag1": "value1", "tag2": "value2"}) as span:
58
+ assert isinstance(span, WeaveSpan)
59
+ assert span.raw_span() is not None
60
+ assert tracer.current_span() == span
61
+
62
+ assert tracer.current_span() is None
63
+
64
+ def test_component_run_span(self):
65
+ with patch("weave.init") as mock_init:
66
+ mock_client = MockWeaveClient()
67
+ mock_init.return_value = mock_client
68
+ tracer = WeaveTracer(project_name="test_project")
69
+ component_tags = {
70
+ "haystack.component.name": "TestComponent",
71
+ "haystack.component.type": "test_type",
72
+ "haystack.component.input": {"input_key": "input_value"},
73
+ "haystack.component.output": {"output_key": "output_value"},
74
+ }
75
+
76
+ with tracer.trace("haystack.component.run", tags=component_tags) as span:
77
+ assert isinstance(span, WeaveSpan)
78
+ assert tracer.current_span() == span
79
+
80
+ assert tracer.current_span() is None
81
+
82
+ def test_exception_handling(self):
83
+ with patch("weave.init") as mock_init:
84
+ mock_client = MockWeaveClient()
85
+ mock_init.return_value = mock_client
86
+ tracer = WeaveTracer(project_name="test_project")
87
+ try:
88
+ with tracer.trace("operation_name") as span: # noqa
89
+ msg = "Test error"
90
+ raise ValueError(msg)
91
+ except ValueError:
92
+ assert tracer.current_span() is None
93
+
94
+ def test_init_with_tracing_disabled(self, monkeypatch, caplog):
95
+ # unset environment variable HAYSTACK_CONTENT_TRACING_ENABLED
96
+ monkeypatch.delenv("HAYSTACK_CONTENT_TRACING_ENABLED", raising=False)
97
+ with caplog.at_level(logging.WARNING, logger="haystack_integrations.tracing.weave.tracer"):
98
+ with patch("weave.init") as mock_init:
99
+ mock_init.return_value = MockWeaveClient()
100
+ WeaveTracer(project_name="test_project")
101
+ assert (
102
+ "Inputs and Outputs of components traces will not be logged because Haystack tracing is "
103
+ "disabled.To enable, set the HAYSTACK_CONTENT_TRACING_ENABLED environment variable to true "
104
+ "before importing Haystack.\n"
105
+ ) in caplog.text
@@ -0,0 +1,166 @@
1
+ import os
2
+ from collections.abc import Generator
3
+ from typing import Any
4
+ from unittest.mock import Mock, patch
5
+
6
+ import pytest
7
+ from haystack import Pipeline, component
8
+ from haystack.components.builders import PromptBuilder
9
+ from haystack.core.errors import PipelineRuntimeError
10
+ from haystack.tracing import tracer as haystack_configured_tracer
11
+ from weave.trace.autopatch import AutopatchSettings
12
+
13
+ from haystack_integrations.components.connectors import WeaveConnector
14
+ from haystack_integrations.tracing.weave import WeaveTracer
15
+
16
+
17
+ @component
18
+ class FailingComponent:
19
+ """A component that always raises an exception for testing error handling."""
20
+
21
+ def run(self) -> dict[str, Any]:
22
+ """Execute the component's logic - always raises an exception."""
23
+ msg = "Test error"
24
+ raise PipelineRuntimeError(msg)
25
+
26
+
27
+ @pytest.fixture
28
+ def mock_weave_client() -> Generator[Mock, None, None]:
29
+ mock_client = Mock()
30
+ with patch("weave.init") as mock_init:
31
+ mock_init.return_value = mock_client
32
+ yield mock_client
33
+
34
+
35
+ @pytest.fixture
36
+ def sample_pipeline() -> Pipeline:
37
+ builder_1 = PromptBuilder("Greeting: {{greeting}}")
38
+ builder_2 = PromptBuilder("Predecessor said: {{predecessor}}")
39
+
40
+ pp = Pipeline()
41
+ pp.add_component("comp1", builder_1)
42
+ pp.add_component("comp2", builder_2)
43
+ pp.connect("comp1.prompt", "comp2.predecessor")
44
+
45
+ return pp
46
+
47
+
48
+ class TestWeaveConnector:
49
+ def test_serialization(self) -> None:
50
+ """Test that WeaveConnector can be serialized and deserialized correctly"""
51
+ connector = WeaveConnector(pipeline_name="test_pipeline")
52
+ serialized: dict[str, Any] = connector.to_dict()
53
+
54
+ assert serialized["init_parameters"]["pipeline_name"] == "test_pipeline"
55
+ assert "type" in serialized
56
+ assert serialized["type"] == "haystack_integrations.components.connectors.weave_connector.WeaveConnector"
57
+
58
+ deserialized = WeaveConnector.from_dict(serialized)
59
+
60
+ assert isinstance(deserialized, WeaveConnector)
61
+ assert deserialized.pipeline_name == "test_pipeline"
62
+ assert deserialized.tracer is None # tracer is only initialized with warm_up
63
+ assert deserialized.weave_init_kwargs == {}
64
+
65
+ def test_serialization_of_weave_init_kwargs(self) -> None:
66
+ """Test that WeaveConnector can be serialized and deserialized correctly"""
67
+ connector = WeaveConnector(
68
+ pipeline_name="test_pipeline",
69
+ weave_init_kwargs={"autopatch_settings": AutopatchSettings(disable_autopatch=True)},
70
+ )
71
+ serialized: dict[str, Any] = connector.to_dict()
72
+
73
+ assert serialized["init_parameters"]["pipeline_name"] == "test_pipeline"
74
+ assert serialized["init_parameters"]["weave_init_kwargs"] == {"autopatch_settings": {"disable_autopatch": True}}
75
+ assert "type" in serialized
76
+ assert serialized["type"] == "haystack_integrations.components.connectors.weave_connector.WeaveConnector"
77
+
78
+ deserialized = WeaveConnector.from_dict(serialized)
79
+
80
+ assert isinstance(deserialized, WeaveConnector)
81
+ assert deserialized.pipeline_name == "test_pipeline"
82
+ assert deserialized.tracer is None # tracer is only initialized with warm_up
83
+ assert deserialized.weave_init_kwargs == {"autopatch_settings": AutopatchSettings(disable_autopatch=True)}
84
+
85
+ def test_pipeline_tracing(self, mock_weave_client: Mock, sample_pipeline: Pipeline) -> None:
86
+ """Test that pipeline operations are correctly traced"""
87
+
88
+ connector = WeaveConnector(pipeline_name="test_pipeline")
89
+ sample_pipeline.add_component("weave", connector)
90
+ sample_pipeline.run(data={"greeting": "Hello"})
91
+
92
+ # Verify WeaveClient interactions
93
+ # Should create calls for pipeline and component operations
94
+ mock_weave_client.create_call.assert_called()
95
+
96
+ # Get all create_call arguments
97
+ create_call_args: list[dict[str, Any]] = [call[1] for call in mock_weave_client.create_call.call_args_list]
98
+
99
+ # Verify pipeline operation was traced
100
+ pipeline_calls = [args for args in create_call_args if args.get("op") == "haystack.pipeline.run"]
101
+ assert len(pipeline_calls) > 0
102
+
103
+ # Verify component operations were traced
104
+ component_calls = [args for args in create_call_args if args.get("op") == "haystack.component.run"]
105
+ assert len(component_calls) >= 2 # Should have at least two component runs
106
+
107
+ # Verify finish_call was called for all operations
108
+ assert mock_weave_client.finish_call.call_count >= 3 # Pipeline + 2 components
109
+
110
+ def test_error_handling(self, mock_weave_client: Mock) -> None:
111
+ """Test that errors in pipeline execution are properly traced"""
112
+ pp = Pipeline()
113
+ pp.add_component("failing", FailingComponent())
114
+ pp.add_component("weave", WeaveConnector(pipeline_name="test_pipeline"))
115
+
116
+ # Run pipeline and expect exception
117
+ with pytest.raises(PipelineRuntimeError):
118
+ pp.run(data={})
119
+
120
+ # Verify error was traced
121
+ finish_call_args = mock_weave_client.finish_call.call_args_list
122
+ error_traces = [args for args in finish_call_args if args[1].get("exception") is not None]
123
+ assert len(error_traces) > 0
124
+
125
+ def test_run_method(self) -> None:
126
+ """Test the basic run method of WeaveConnector"""
127
+ connector = WeaveConnector(pipeline_name="test_pipeline")
128
+ result: dict[str, str] = connector.run()
129
+ assert result == {"pipeline_name": "test_pipeline"}
130
+
131
+ @pytest.mark.skipif(
132
+ not os.environ.get("WANDB_API_KEY", None),
133
+ reason="Export an env var called WANDB_API_KEY containing the Weights & Bias API key to run this test.",
134
+ )
135
+ @pytest.mark.integration
136
+ def test_warmup_initializes_tracer(self, monkeypatch) -> None:
137
+ """Test that warm_up initializes the tracer correctly"""
138
+ monkeypatch.setenv("HAYSTACK_CONTENT_TRACING_ENABLED", "true")
139
+ connector = WeaveConnector(pipeline_name="test_pipeline")
140
+ assert connector.tracer is None
141
+
142
+ connector.warm_up() # initialize tracer
143
+
144
+ assert connector.tracer is not None
145
+ assert isinstance(connector.tracer, WeaveTracer)
146
+ assert haystack_configured_tracer.is_content_tracing_enabled is True
147
+
148
+ @pytest.mark.skipif(
149
+ not os.environ.get("WANDB_API_KEY", None),
150
+ reason="Export an env var called WANDB_API_KEY containing the Weights & Bias API key to run this test.",
151
+ )
152
+ @pytest.mark.integration
153
+ def test_warmup_initializes_tracer_with_weave_init_kwargs(self, monkeypatch) -> None:
154
+ """Test that warm_up initializes the tracer correctly"""
155
+ monkeypatch.setenv("HAYSTACK_CONTENT_TRACING_ENABLED", "true")
156
+ connector = WeaveConnector(
157
+ pipeline_name="test_pipeline",
158
+ weave_init_kwargs={"autopatch_settings": AutopatchSettings(disable_autopatch=True)},
159
+ )
160
+ assert connector.tracer is None
161
+
162
+ connector.warm_up() # initialize tracer
163
+
164
+ assert connector.tracer is not None
165
+ assert isinstance(connector.tracer, WeaveTracer)
166
+ assert haystack_configured_tracer.is_content_tracing_enabled is True