openinference-instrumentation-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.
@@ -0,0 +1,2 @@
1
+ # vendored virtual environments
2
+ .venv
@@ -0,0 +1,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright The OpenTelemetry Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.3
2
+ Name: openinference-instrumentation-haystack
3
+ Version: 0.1.0
4
+ Summary: OpenInference Haystack Instrumentation
5
+ Project-URL: Homepage, https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-haystack
6
+ Author-email: OpenInference Authors <oss@arize.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.8
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Requires-Python: <3.13,>=3.8
20
+ Requires-Dist: openinference-instrumentation>=0.1.7
21
+ Requires-Dist: openinference-semantic-conventions
22
+ Requires-Dist: opentelemetry-api
23
+ Requires-Dist: opentelemetry-instrumentation
24
+ Requires-Dist: opentelemetry-semantic-conventions
25
+ Requires-Dist: typing-extensions
26
+ Requires-Dist: wrapt
27
+ Provides-Extra: instruments
28
+ Requires-Dist: haystack-ai>=2.0.0; extra == 'instruments'
29
+ Provides-Extra: test
30
+ Requires-Dist: haystack-ai>=2.0.0; extra == 'test'
31
+ Requires-Dist: opentelemetry-sdk; extra == 'test'
32
+ Requires-Dist: responses; extra == 'test'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # OpenInference Haystack Instrumentation
36
+
37
+ Python auto-instrumentation library for LLM applications implemented with [Haystack](https://haystack.deepset.ai/).
38
+
39
+ Haystack [Pipelines](https://docs.haystack.deepset.ai/docs/pipelines) and [Components](https://docs.haystack.deepset.ai/docs/components) (ex. PromptBuilder, OpenAIGenerator, etc.) are fully OpenTelemetry-compatible and can be sent to an OpenTelemetry collector for monitoring, such as [`arize-phoenix`](https://github.com/Arize-ai/phoenix).
40
+
41
+ ## Installation
42
+
43
+ ```shell
44
+ pip install openinference-instrumentation-haystack
45
+ ```
46
+
47
+ ## Quickstart
48
+
49
+ This quickstart shows you how to instrument your Haystack-orchestrated LLM application
50
+
51
+ Through your *terminal*, install required packages.
52
+
53
+ ```shell
54
+ pip install openinference-instrumentation-haystack haystack arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
55
+ ```
56
+
57
+ You can install Phoenix and start it with the following terminal commands:
58
+ ```shell
59
+ pip install arize-phoenix
60
+ python -m phoenix.server.main serve
61
+ ````
62
+ Start Phoenix in the background as a collector. By default, it listens on `http://localhost:6006`. You can visit the app via a browser at the same address. (Phoenix does not send data over the internet. It only operates locally on your machine.)
63
+
64
+
65
+ Try the following in a *Python file*.
66
+
67
+ Set up `HaystackInstrumentor` to trace your application and sends the traces to Phoenix at the endpoint defined below.
68
+
69
+ ```python
70
+ from openinference.instrumentation.haystack import HaystackInstrumentor
71
+ from opentelemetry import trace as trace_api
72
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
73
+ from opentelemetry.sdk import trace as trace_sdk
74
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
75
+ import os
76
+
77
+ # Set your OpenAI API key
78
+ os.environ["OPENAI_API_KEY"] = "YOUR_KEY_HERE"
79
+
80
+ # Set up the tracer, using Arize Phoenix as the endpoint
81
+ endpoint = "http://127.0.0.1:6006/v1/traces"
82
+ tracer_provider = trace_sdk.TracerProvider()
83
+ trace_api.set_tracer_provider(tracer_provider)
84
+ tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
85
+
86
+ # Instrument the Haystack application
87
+ HaystackInstrumentor().instrument()
88
+ ```
89
+
90
+ Set up a simple Pipeline with a template using `OpenAIGenerator`.
91
+ ```python
92
+ from haystack import Pipeline
93
+ from haystack.components.generators import OpenAIGenerator
94
+
95
+ # Initialize the pipeline
96
+ pipeline = Pipeline()
97
+
98
+ # Initialize the OpenAI generator component
99
+ llm = OpenAIGenerator(model="gpt-3.5-turbo")
100
+
101
+ # Add the generator component to the pipeline
102
+ pipeline.add_component("llm", llm)
103
+
104
+ # Define the question
105
+ question = "What is the location of the Hanging Gardens of Babylon?"
106
+
107
+ # Run the pipeline with the question
108
+ response = pipeline.run({"llm": {"prompt": question}})
109
+
110
+ print(response)
111
+ ```
112
+ Now, on the Phoenix UI on your browser, you should see the traces from your Haystack application. Specifically, you can see attributes from the execution of the OpenAIGenerator.
113
+
@@ -0,0 +1,79 @@
1
+ # OpenInference Haystack Instrumentation
2
+
3
+ Python auto-instrumentation library for LLM applications implemented with [Haystack](https://haystack.deepset.ai/).
4
+
5
+ Haystack [Pipelines](https://docs.haystack.deepset.ai/docs/pipelines) and [Components](https://docs.haystack.deepset.ai/docs/components) (ex. PromptBuilder, OpenAIGenerator, etc.) are fully OpenTelemetry-compatible and can be sent to an OpenTelemetry collector for monitoring, such as [`arize-phoenix`](https://github.com/Arize-ai/phoenix).
6
+
7
+ ## Installation
8
+
9
+ ```shell
10
+ pip install openinference-instrumentation-haystack
11
+ ```
12
+
13
+ ## Quickstart
14
+
15
+ This quickstart shows you how to instrument your Haystack-orchestrated LLM application
16
+
17
+ Through your *terminal*, install required packages.
18
+
19
+ ```shell
20
+ pip install openinference-instrumentation-haystack haystack arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
21
+ ```
22
+
23
+ You can install Phoenix and start it with the following terminal commands:
24
+ ```shell
25
+ pip install arize-phoenix
26
+ python -m phoenix.server.main serve
27
+ ````
28
+ Start Phoenix in the background as a collector. By default, it listens on `http://localhost:6006`. You can visit the app via a browser at the same address. (Phoenix does not send data over the internet. It only operates locally on your machine.)
29
+
30
+
31
+ Try the following in a *Python file*.
32
+
33
+ Set up `HaystackInstrumentor` to trace your application and sends the traces to Phoenix at the endpoint defined below.
34
+
35
+ ```python
36
+ from openinference.instrumentation.haystack import HaystackInstrumentor
37
+ from opentelemetry import trace as trace_api
38
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
39
+ from opentelemetry.sdk import trace as trace_sdk
40
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
41
+ import os
42
+
43
+ # Set your OpenAI API key
44
+ os.environ["OPENAI_API_KEY"] = "YOUR_KEY_HERE"
45
+
46
+ # Set up the tracer, using Arize Phoenix as the endpoint
47
+ endpoint = "http://127.0.0.1:6006/v1/traces"
48
+ tracer_provider = trace_sdk.TracerProvider()
49
+ trace_api.set_tracer_provider(tracer_provider)
50
+ tracer_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))
51
+
52
+ # Instrument the Haystack application
53
+ HaystackInstrumentor().instrument()
54
+ ```
55
+
56
+ Set up a simple Pipeline with a template using `OpenAIGenerator`.
57
+ ```python
58
+ from haystack import Pipeline
59
+ from haystack.components.generators import OpenAIGenerator
60
+
61
+ # Initialize the pipeline
62
+ pipeline = Pipeline()
63
+
64
+ # Initialize the OpenAI generator component
65
+ llm = OpenAIGenerator(model="gpt-3.5-turbo")
66
+
67
+ # Add the generator component to the pipeline
68
+ pipeline.add_component("llm", llm)
69
+
70
+ # Define the question
71
+ question = "What is the location of the Hanging Gardens of Babylon?"
72
+
73
+ # Run the pipeline with the question
74
+ response = pipeline.run({"llm": {"prompt": question}})
75
+
76
+ print(response)
77
+ ```
78
+ Now, on the Phoenix UI on your browser, you should see the traces from your Haystack application. Specifically, you can see attributes from the execution of the OpenAIGenerator.
79
+
@@ -0,0 +1,91 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "openinference-instrumentation-haystack"
7
+ dynamic = ["version"]
8
+ description = "OpenInference Haystack Instrumentation"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.8, <3.13"
12
+ authors = [
13
+ { name = "OpenInference Authors", email = "oss@arize.com" },
14
+ ]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ ]
27
+ dependencies = [
28
+ "opentelemetry-api",
29
+ "opentelemetry-instrumentation",
30
+ "opentelemetry-semantic-conventions",
31
+ "openinference-instrumentation>=0.1.7",
32
+ "openinference-semantic-conventions",
33
+ "wrapt",
34
+ "typing-extensions",
35
+ ]
36
+
37
+
38
+ [project.optional-dependencies]
39
+ instruments = [
40
+ "haystack-ai >= 2.0.0",
41
+ ]
42
+ test = [
43
+ "haystack-ai >= 2.0.0",
44
+ "opentelemetry-sdk",
45
+ "responses",
46
+ ]
47
+
48
+ [project.urls]
49
+ Homepage = "https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-haystack"
50
+
51
+ [tool.hatch.version]
52
+ path = "src/openinference/instrumentation/haystack/version.py"
53
+
54
+ [tool.hatch.build.targets.sdist]
55
+ include = [
56
+ "/src",
57
+ ]
58
+
59
+ [tool.hatch.build.targets.wheel]
60
+ packages = ["src/openinference"]
61
+
62
+ [tool.mypy]
63
+ strict = true
64
+ explicit_package_bases = true
65
+ exclude = [
66
+ "examples",
67
+ "dist",
68
+ "sdist",
69
+ ]
70
+
71
+ [[tool.mypy.overrides]]
72
+ ignore_missing_imports = true
73
+ module = [
74
+ "haystack.*",
75
+ "datasets",
76
+ "openinference.instrumentation.haystack.*",
77
+ "wrapt",
78
+ ]
79
+
80
+ [tool.ruff]
81
+ line-length = 100
82
+ target-version = "py38"
83
+
84
+ [tool.ruff.lint.per-file-ignores]
85
+ "*.ipynb" = ["E402", "E501"]
86
+
87
+ [tool.ruff.lint]
88
+ select = ["E", "F", "W", "I"]
89
+
90
+ [tool.ruff.lint.isort]
91
+ force-single-line = false
@@ -0,0 +1,53 @@
1
+ import logging
2
+ from importlib import import_module
3
+ from typing import Any, Collection
4
+
5
+ from openinference.instrumentation.haystack._wrappers import _ComponentWrapper, _PipelineWrapper
6
+ from openinference.instrumentation.haystack.version import __version__
7
+ from opentelemetry import trace as trace_api
8
+ from opentelemetry.instrumentation.instrumentor import ( # type: ignore[attr-defined]
9
+ BaseInstrumentor,
10
+ )
11
+ from opentelemetry.trace import get_tracer
12
+ from wrapt import wrap_function_wrapper
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ _instruments = ("haystack-ai >= 2.0.0",)
17
+
18
+
19
+ class HaystackInstrumentor(BaseInstrumentor): # type: ignore[misc]
20
+ """An instrumentor for the Haystack framework."""
21
+
22
+ __slots__ = ("_original_pipeline_run", "_original_pipeline_run_component")
23
+
24
+ def instrumentation_dependencies(self) -> Collection[str]:
25
+ return _instruments
26
+
27
+ def _instrument(self, **kwargs: Any) -> None:
28
+ if not (tracer_provider := kwargs.get("tracer_provider")):
29
+ tracer_provider = trace_api.get_tracer_provider()
30
+ tracer = get_tracer(__name__, __version__, tracer_provider)
31
+ pipeline = import_module("haystack.core.pipeline.pipeline")
32
+
33
+ self._original_pipeline_run = pipeline.Pipeline.run
34
+ wrap_function_wrapper(
35
+ module="haystack.core.pipeline.pipeline",
36
+ name="Pipeline.run",
37
+ wrapper=_PipelineWrapper(tracer=tracer),
38
+ )
39
+ self._original_pipeline_run_component = pipeline.Pipeline._run_component
40
+ wrap_function_wrapper(
41
+ module="haystack.core.pipeline.pipeline",
42
+ name="Pipeline._run_component",
43
+ wrapper=_ComponentWrapper(tracer=tracer),
44
+ )
45
+
46
+ def _uninstrument(self, **kwargs: Any) -> None:
47
+ haystack = import_module("haystack.core.pipeline.pipeline")
48
+
49
+ if self._original_pipeline_run is not None:
50
+ haystack.Pipeline.run = self._original_pipeline_run
51
+
52
+ if self._original_pipeline_run_component is not None:
53
+ haystack.Pipeline._run_component = self._original_pipeline_run_component
@@ -0,0 +1,254 @@
1
+ from abc import ABC
2
+ from enum import Enum
3
+ from typing import Any, Callable, Iterator, List, Mapping, Tuple
4
+
5
+ import opentelemetry.context as context_api
6
+ from openinference.instrumentation import get_attributes_from_context, safe_json_dumps
7
+ from openinference.semconv.trace import (
8
+ DocumentAttributes,
9
+ EmbeddingAttributes,
10
+ OpenInferenceMimeTypeValues,
11
+ OpenInferenceSpanKindValues,
12
+ SpanAttributes,
13
+ )
14
+ from opentelemetry import trace as trace_api
15
+ from opentelemetry.util.types import AttributeValue
16
+
17
+
18
+ def _flatten(mapping: Mapping[str, Any]) -> Iterator[Tuple[str, AttributeValue]]:
19
+ for key, value in mapping.items():
20
+ if value is None:
21
+ continue
22
+ if isinstance(value, Mapping):
23
+ for sub_key, sub_value in _flatten(value):
24
+ yield f"{key}.{sub_key}", sub_value
25
+ elif isinstance(value, List) and any(isinstance(item, Mapping) for item in value):
26
+ for index, sub_mapping in enumerate(value):
27
+ for sub_key, sub_value in _flatten(sub_mapping):
28
+ yield f"{key}.{index}.{sub_key}", sub_value
29
+ else:
30
+ if isinstance(value, Enum):
31
+ value = value.value
32
+ yield key, value
33
+
34
+
35
+ class _WithTracer(ABC):
36
+ """
37
+ Base class for wrappers that need a tracer.
38
+ """
39
+
40
+ def __init__(self, tracer: trace_api.Tracer, *args: Any, **kwargs: Any) -> None:
41
+ super().__init__(*args, **kwargs)
42
+ self._tracer = tracer
43
+
44
+
45
+ class _ComponentWrapper(_WithTracer):
46
+ """
47
+ Wrapper for the pipeline processing
48
+ Captures all calls to the pipeline
49
+ """
50
+
51
+ def __call__(
52
+ self,
53
+ wrapped: Callable[..., Any],
54
+ instance: Any,
55
+ args: Tuple[Any, ...],
56
+ kwargs: Mapping[str, Any],
57
+ ) -> Any:
58
+ component_type = args[0]
59
+ input_data = args[1]
60
+
61
+ # Diving into the instance to retrieve the Component instance
62
+ component = instance.graph.nodes._nodes[component_type]["instance"]
63
+
64
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
65
+ return wrapped(*args, **kwargs)
66
+
67
+ # Prepare invocation parameters by merging args and kwargs
68
+ invocation_parameters = {}
69
+ for arg in args:
70
+ if arg and isinstance(arg, dict):
71
+ invocation_parameters.update(arg)
72
+ invocation_parameters.update(kwargs)
73
+
74
+ span_name = component.__class__.__name__
75
+
76
+ with self._tracer.start_as_current_span(span_name, attributes={}) as span:
77
+ if component_type == "llm":
78
+ attributes = dict(
79
+ _flatten(
80
+ {
81
+ SpanAttributes.OPENINFERENCE_SPAN_KIND: LLM,
82
+ SpanAttributes.INPUT_VALUE: safe_json_dumps(input_data),
83
+ SpanAttributes.INPUT_MIME_TYPE: OpenInferenceMimeTypeValues.JSON,
84
+ SpanAttributes.LLM_PROMPT_TEMPLATE: instance.graph.nodes._nodes[
85
+ "prompt_builder"
86
+ ]["instance"]._template_string,
87
+ }
88
+ )
89
+ )
90
+ elif component_type == "text_embedder":
91
+ attributes = dict(
92
+ _flatten(
93
+ {
94
+ SpanAttributes.EMBEDDING_MODEL_NAME: component.model,
95
+ SpanAttributes.OPENINFERENCE_SPAN_KIND: EMBEDDING,
96
+ SpanAttributes.INPUT_VALUE: safe_json_dumps(invocation_parameters),
97
+ SpanAttributes.INPUT_MIME_TYPE: OpenInferenceMimeTypeValues.JSON,
98
+ }
99
+ )
100
+ )
101
+ elif component_type == "retriever":
102
+ attributes = dict(
103
+ _flatten(
104
+ {
105
+ SpanAttributes.OPENINFERENCE_SPAN_KIND: RETRIEVER,
106
+ SpanAttributes.INPUT_VALUE: safe_json_dumps(
107
+ {
108
+ "dimensions": len(input_data["query_embedding"]),
109
+ "embedding": input_data["query_embedding"],
110
+ }
111
+ ),
112
+ SpanAttributes.INPUT_MIME_TYPE: OpenInferenceMimeTypeValues.JSON,
113
+ }
114
+ )
115
+ )
116
+
117
+ elif component_type == "prompt_builder":
118
+ attributes = dict(
119
+ _flatten(
120
+ {
121
+ SpanAttributes.OPENINFERENCE_SPAN_KIND: CHAIN,
122
+ SpanAttributes.LLM_PROMPT_TEMPLATE: instance.graph.nodes._nodes[
123
+ "prompt_builder"
124
+ ]["instance"]._template_string,
125
+ SpanAttributes.INPUT_VALUE: safe_json_dumps(invocation_parameters),
126
+ SpanAttributes.INPUT_MIME_TYPE: OpenInferenceMimeTypeValues.JSON,
127
+ SpanAttributes.RETRIEVAL_DOCUMENTS: safe_json_dumps(
128
+ invocation_parameters["documents"]
129
+ ),
130
+ }
131
+ )
132
+ )
133
+
134
+ try:
135
+ response = wrapped(*args, **kwargs)
136
+ except Exception as exception:
137
+ span.set_status(trace_api.Status(trace_api.StatusCode.ERROR, str(exception)))
138
+ span.record_exception(exception)
139
+ raise
140
+ span.set_status(trace_api.StatusCode.OK)
141
+
142
+ if component_type == "llm":
143
+ attributes.update(
144
+ _flatten(
145
+ {
146
+ SpanAttributes.LLM_MODEL_NAME: response["meta"][0]["model"],
147
+ SpanAttributes.LLM_TOKEN_COUNT_COMPLETION: response["meta"][0]["usage"][
148
+ "completion_tokens"
149
+ ],
150
+ SpanAttributes.LLM_TOKEN_COUNT_PROMPT: response["meta"][0]["usage"][
151
+ "prompt_tokens"
152
+ ],
153
+ SpanAttributes.LLM_TOKEN_COUNT_TOTAL: response["meta"][0]["usage"][
154
+ "total_tokens"
155
+ ],
156
+ SpanAttributes.LLM_OUTPUT_MESSAGES: response["replies"],
157
+ }
158
+ )
159
+ )
160
+ elif component_type == "text_embedder":
161
+ emb_len = len(response["embedding"])
162
+ emb_vec_0 = f"{SpanAttributes.EMBEDDING_EMBEDDINGS}.0."
163
+
164
+ attributes.update(
165
+ _flatten(
166
+ {
167
+ f"{emb_vec_0}{EMBEDDING_VECTOR}": f"<{emb_len} dimensional vector>",
168
+ f"{emb_vec_0}{EMBEDDING_TEXT}": invocation_parameters["text"],
169
+ }
170
+ )
171
+ )
172
+ elif component_type == "retriever":
173
+ attributes.update(
174
+ _flatten(
175
+ {
176
+ SpanAttributes.OUTPUT_VALUE: safe_json_dumps(response["documents"]),
177
+ SpanAttributes.OUTPUT_MIME_TYPE: OpenInferenceMimeTypeValues.JSON,
178
+ }
179
+ )
180
+ )
181
+
182
+ for i, document in enumerate(response["documents"]):
183
+ attributes[
184
+ f"{SpanAttributes.RETRIEVAL_DOCUMENTS}.{i}.{DocumentAttributes.DOCUMENT_CONTENT}"
185
+ ] = document.content
186
+ attributes[
187
+ f"{SpanAttributes.RETRIEVAL_DOCUMENTS}.{i}.{DocumentAttributes.DOCUMENT_ID}"
188
+ ] = document.id
189
+ attributes[
190
+ f"{SpanAttributes.RETRIEVAL_DOCUMENTS}.{i}.{DocumentAttributes.DOCUMENT_SCORE}"
191
+ ] = document.score
192
+ attributes[
193
+ f"{SpanAttributes.RETRIEVAL_DOCUMENTS}.{i}.{DocumentAttributes.DOCUMENT_METADATA}"
194
+ ] = safe_json_dumps(document.meta)
195
+
196
+ span.set_attributes(attributes)
197
+
198
+ return response
199
+
200
+
201
+ class _PipelineWrapper(_WithTracer):
202
+ """
203
+ Wrapper for the pipeline processing
204
+ Captures all calls to the pipeline
205
+ """
206
+
207
+ def __call__(
208
+ self,
209
+ wrapped: Callable[..., Any],
210
+ instance: Any,
211
+ args: Tuple[Any, ...],
212
+ kwargs: Mapping[str, Any],
213
+ ) -> Any:
214
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
215
+ return wrapped(*args, **kwargs)
216
+
217
+ # Prepare invocation parameters by merging args and kwargs
218
+ invocation_parameters = {}
219
+ for arg in args:
220
+ if arg and isinstance(arg, dict):
221
+ invocation_parameters.update(arg)
222
+ invocation_parameters.update(kwargs)
223
+
224
+ span_name = "Pipeline"
225
+ with self._tracer.start_as_current_span(
226
+ span_name,
227
+ attributes=dict(
228
+ _flatten(
229
+ {
230
+ SpanAttributes.OPENINFERENCE_SPAN_KIND: CHAIN,
231
+ SpanAttributes.INPUT_VALUE: safe_json_dumps(invocation_parameters),
232
+ SpanAttributes.INPUT_MIME_TYPE: OpenInferenceMimeTypeValues.JSON,
233
+ }
234
+ )
235
+ ),
236
+ ) as span:
237
+ span.set_attributes(dict(get_attributes_from_context()))
238
+ try:
239
+ response = wrapped(*args, **kwargs)
240
+ except Exception as exception:
241
+ span.set_status(trace_api.Status(trace_api.StatusCode.ERROR, str(exception)))
242
+ span.record_exception(exception)
243
+ raise
244
+ span.set_status(trace_api.StatusCode.OK)
245
+
246
+ return response
247
+
248
+
249
+ CHAIN = OpenInferenceSpanKindValues.CHAIN
250
+ RETRIEVER = OpenInferenceSpanKindValues.RETRIEVER
251
+ EMBEDDING = OpenInferenceSpanKindValues.EMBEDDING
252
+ LLM = OpenInferenceSpanKindValues.LLM
253
+ EMBEDDING_VECTOR = EmbeddingAttributes.EMBEDDING_VECTOR
254
+ EMBEDDING_TEXT = EmbeddingAttributes.EMBEDDING_TEXT