arize-otel 0.7.2__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,43 @@
1
+ *.py[cod]
2
+
3
+ # C extensions
4
+ *.so
5
+
6
+ # IDEs
7
+ .idea/
8
+ .vscode/
9
+
10
+ # Packages
11
+ *.egg
12
+ *.egg-info
13
+ .eggs/
14
+ # build
15
+ parts
16
+ bin
17
+ var
18
+ sdist
19
+ dist
20
+ develop-eggs
21
+ .installed.cfg
22
+ lib
23
+ lib64
24
+
25
+ # Installer logs
26
+ pip-log.txt
27
+
28
+ # Unit test / coverage reports
29
+ .coverage
30
+ .tox
31
+ nosetests.xml
32
+
33
+ # Complexity
34
+ output/*.html
35
+ output/*/index.html
36
+
37
+ # Sphinx
38
+ docs/_build
39
+
40
+ # Cookiecutter
41
+ output/
42
+
43
+ .workon
@@ -0,0 +1,12 @@
1
+ Copyright (c) 2024, Arize AI
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5
+
6
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7
+
8
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9
+
10
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11
+
12
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,290 @@
1
+ Metadata-Version: 2.4
2
+ Name: arize-otel
3
+ Version: 0.7.2
4
+ Summary: Helper package for OTEL setup to send traces to Arize & Phoenix
5
+ Project-URL: Documentation, https://docs.arize.com/arize/large-language-models/tracing
6
+ Project-URL: Issues, https://github.com/Arize-ai/arize-otel-python/issues
7
+ Project-URL: Source, https://github.com/Arize-ai/arize-otel-python
8
+ Project-URL: Changelog, https://github.com/Arize-ai/arize-otel-python/blob/main/CHANGELOG.md
9
+ Author-email: Arize AI <support@arize.com>
10
+ Maintainer-email: Arize AI <support@arize.com>
11
+ License: BSD
12
+ License-File: LICENSE
13
+ Keywords: Explainability,Monitoring,Observability,Tracing
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Topic :: System :: Logging
25
+ Classifier: Topic :: System :: Monitoring
26
+ Requires-Python: <3.13,>=3.8
27
+ Requires-Dist: openinference-semantic-conventions>=0.1.5
28
+ Requires-Dist: opentelemetry-exporter-otlp>=1.22
29
+ Requires-Dist: opentelemetry-proto>=1.12.0
30
+ Requires-Dist: opentelemetry-sdk>=1.22
31
+ Description-Content-Type: text/markdown
32
+
33
+ <p align="center">
34
+ <a target="_blank" href="https://arize.com" style="background:none">
35
+ <img alt="arize banner" src="https://storage.googleapis.com/arize-assets/arize-logo-white.jpg" width="auto" height="auto"></img>
36
+ </a>
37
+ <br/>
38
+ <br/>
39
+ <a href="https://docs.arize.com/">
40
+ <img src="https://img.shields.io/static/v1?message=Docs&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAG4ElEQVR4nO2d4XHjNhCFcTf+b3ZgdWCmgmMqOKUC0xXYrsBOBVEqsFRB7ApCVRCygrMriFQBM7h5mNlwKBECARLg7jeDscamSQj7sFgsQfBL27ZK4MtXsT1vRADMEQEwRwTAHBEAc0QAzBEBMEcEwBwRAHNEAMwRATBnjAByFGE+MqVUMcYOY24GVUqpb/h8VErVKAf87QNFcEcbd4WSw+D6803njHscO5sATmGEURGBiCj6yUlv1uX2gv91FsDViArbcA2RUKF8QhAV8RQc0b15DcOt0VaTE1oAfWj3dYdCBfGGsmSM0XX5HsP3nEMAXbqCeCdiOERQPx9og5exGJ0S4zRQN9KrUupfpdQWjZciure/YIj7K0bjqwTyAHdovA805iqCOg2xgnB1nZ97IvaoSCURdIPG/IHGjTH/YAz/A8KdJai7lBQzgbpx/0Hg6DT18UzWMXxSjMkDrElPNEmKfAbl6znwI3IMU/OCa0/1nfckwWaSbvWYYDnEsvCMJDNckhqu7GCMKWYOBXp9yPGd5kvqUAKf6rkAk7M2SY9QDXdEr9wEOr9x96EiejMFnixBNteDISsyNw7hHRqc22evWcP4vt39O85bzZH30AKg4+eo8cQRI4bHAJ7hyYM3CNHrG9RrimSXuZmUkZjN/O6nAPpcwCcJNmipAle2QM/1GU3vITCXhvY91u9geN/jOY27VuTnYL1PCeAcRhwh7/Bl8Ai+IuxPiOCShtfX/sPDtY8w+sZjby86dw6dBeoigD7obd/Ko6fI4BF8DA9HnGdrcU0fLt+n4dfE6H5jpjYcVdu2L23b5lpjHoo+18FDbcszddF1rUee/4C6ZiO+80rHZmjDoIQUQLdRtm3brkcKIUPjjqVPBIUHgW1GGN4YfawAL2IqAVB8iEE31tvIelARlCPPVaFOLoIupzY6xVcM4MoRUyHXyHhslH6PaPl5RP1Lh4UsOeKR2e8dzC0Aiuvc2Nx3fwhfxf/hknouUYbWUk5GTAIwmOh5e+H0cor8vEL91hfOdEqINLq1AV+RKImJ6869f9tFIBVc6y7gd3lHfWyNX0LEr7EuDElhRdAlQjig0e/RU31xxDltM4pF7IY3pLIgxAhhgzF/iC2M0Hi4dkOGlyGMd/g7dsMbUlsR9ICe9WhxbA3DjRkSdjiHzQzlBSKNJsCzIcUlYdfI0dcWS8LMkPDkcJ0n/O+Qyy/IAtDkSPnp4Fu4WpthQR/zm2VcoI/51fI28iYld9/HEh4Pf7D0Bm845pwIPnHMUJSf45pT5x68s5T9AW6INzhHDeP1BYcNMew5SghkinWOwVnaBhHGG5ybMn70zBDe8buh8X6DqV0Sa/5tWOIOIbcWQ8KBiGBnMb/P0OuTd/lddCrY5jn/VLm3nL+fY4X4YREuv8vS9wh6HSkAExMs0viKySZRd44iyOH2FzPe98Fll7A7GNMmjay4GF9BAKGXesfCN0sRsDG+YrhP4O2ACFgZXzHdKPL2RMJoxc34ivFOod3AMMNUj5XxFfOtYrUIXvB5MandS+G+V/AzZ+MrEcBPlpoFtUIEwBwRAG+OIgDe1CIA5ogAmCMCYI4IgDkiAOaIAJgjAmCOCIA5IgDmiACYIwJgjgiAOSIA5ogAmCMCYI4IgDkiAOaIAJgjAmCOCIA5IgDmiACYIwJgjgiAOSIA5ogAmCMCYI4IgDkiAOaIAJgjAmDOVYBXvwvxQV8NWJOd0esvJ94babZaz7B5ovldxnlDpYhp0JFr/KTlLKcEMMQKpcDPXIQxGXsYmhZnXAXQh/EWBQrr3bc80mATyyrEvs4+BdBHgbdxFOIhrDkSg1/6Iu2LCS0AyoqI4ftUF00EY/Q3h1fRj2JKAVCMGErmnsH1lfnemEsAlByvgl0z2qx5B8OPCuB8EIMADBlEEOV79j1whNE3c/X2PmISAGUNr7CEmUSUhjfEKgBDAY+QohCiNrwhdgEYzPv7UxkadvBg0RrekMrNoAozh3vLN4DPhc7S/WL52vkoSO1u4BZC+DOCulC0KJ/gqWaP7C8hlSGgjxyCmDuPsEePT/KuasrrAcyr4H+f6fq01yd7Sz1lD0CZ2hs06PVJufs+lrIiyLwufjfBtXYpjvWnWIoHoJSYe4dIK/t4HX1ULFEACkPCm8e8wXFJvZ6y1EWhJkDcWxw7RINzLc74auGrgg8e4oIm9Sh/CA7LwkvHqaIJ9pLI6Lmy1BigDy2EV8tjdzh+8XB6MGSLKH4INsZXDJ8MGhIBK+Mrpo+GnRIBO+MrZjFAFxoTNBwCvj6u4qvSZJiM3iNX4yvmHoA9Sh4PF0QAzBEBMEcEwBwRAHNEAMwRAXBGKfUfr5hKvglRfO4AAAAASUVORK5CYII=&labelColor=grey&color=blue&logoColor=white&label=%20"/>
41
+ </a>
42
+ <a target="_blank" href="https://join.slack.com/t/arize-ai/shared_invite/zt-1px8dcmlf-fmThhDFD_V_48oU7ALan4Q">
43
+ <img src="https://img.shields.io/static/v1?message=Community&logo=slack&labelColor=grey&color=blue&logoColor=white&label=%20"/>
44
+ </a>
45
+ <br/>
46
+ <a target="_blank" href="https://pypi.org/project/arize-otel/">
47
+ <img src="https://img.shields.io/pypi/v/arize-otel">
48
+ </a>
49
+ <a target="_blank" href="https://pypi.org/project/arize-otel/">
50
+ <img src="https://img.shields.io/pypi/status/arize-otel?style=flat&logo=ticktick&logoColor=white"/>
51
+ </a>
52
+ <a target="_blank" href="https://pypi.org/project/arize-otel/">
53
+ <img src="https://img.shields.io/pypi/pyversions/arize-otel?logo=python&logoColor=white">
54
+ </a>
55
+ <a target="_blank" href="https://github.com/Arize-ai/arize-otel-python/blob/main/LICENSE">
56
+ <img src="https://img.shields.io/pypi/l/arize-otel">
57
+ </a>
58
+
59
+ </p>
60
+
61
+ ---
62
+
63
+ - [Overview](#overview)
64
+ - [Installation](#installation)
65
+ - [Quickstart](#quickstart)
66
+ - [Send traces to Arize](#send-traces-to-arize)
67
+ - [Send traces to Custom Endpoint](#send-traces-to-custom-endpoint)
68
+ - [Specify exporter type](#specify-exporter-type)
69
+ - [Turn off batch processing of spans](#turn-off-batch-processing-of-spans)
70
+ - [Debug](#debug)
71
+ - [Using Environment Variables](#using-environment-variables)
72
+ - [Using OTel Primitives](#using-otel-primitives)
73
+ - [Specifying the `endpoint` directly](#specifying-the-endpoint-directly)
74
+ - [Configuring resources](#configuring-resources)
75
+ - [Using a BatchSpanProcessor](#using-a-batchspanprocessor)
76
+ - [Specifying a custom GRPC endpoint](#specifying-a-custom-grpc-endpoint)
77
+ - [Questions?](#questions)
78
+ - [Copyright, Patent, and License](#copyright-patent-and-license)
79
+
80
+ ## Overview
81
+
82
+ The `arize-otel` package provides a lightweight wrapper around OpenTelemetry primitives with Arize-aware defaults and options. It is meant to be a very lightweight convenience package to help set up OpenTelemetry for tracing LLM applications and send the traces to [Arize](https://arize.com/).
83
+
84
+ ## Installation
85
+
86
+ Install `arize-otel` using `pip`
87
+
88
+ ```bash
89
+ pip install arize-otel
90
+ ```
91
+
92
+ ## Quickstart
93
+
94
+ The `arize.otel` module provides a high-level `register` function to configure OpenTelemetry tracing by returning a `TracerProvider`. The register function can also configure headers and whether or not to process spans one by one or by batch.
95
+
96
+ The following examples showcase how to use `register` to setup Opentelemetry in order to send traces to a collector. However, this is **NOT** the same as [instrumenting](https://docs.arize.com/phoenix/tracing/concepts-tracing/how-does-tracing-work) your application. For instance, you can use any of our [OpenInference AutoInstrumentators](https://github.com/Arize-ai/openinference). Assuming we use the OpenAI AutoInstrumentation, we need to run `instrument()` _after_ using `register`:
97
+
98
+ ```python
99
+ from arize.otel import register
100
+ # Setup OTel via our convenience function
101
+ tracer_provider = register(
102
+ # See details in examples below...
103
+ )
104
+
105
+ # Instrument your application using OpenInference AutoInstrumentators
106
+ from openinference.instrumentation.openai import OpenAIInstrumentor
107
+ OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)
108
+
109
+ ```
110
+
111
+ The above code snippet will yield a fully setup and instrumented application. It is worth noting that this is completely **optional**. The usage of this package is for convenience only, you can set up OpenTelemetry and send traces to Arize without installing this or any other package from Arize.
112
+
113
+ In the following sections we have examples on how to use the `register` function:
114
+
115
+ ### Send traces to Arize
116
+
117
+ To send traces to Arize you need to authenticate via the Space ID and API Key. You can find them in the Space Settings page in the Arize platform. In addition, you'll need to specify the project name, a unique name to identify your project in the Arize platform.
118
+
119
+ ```python
120
+ from arize.otel import register
121
+
122
+ tracer_provider = register(
123
+ space_id = "your-arize-space-id",
124
+ api_key = "your-arize-api-key",
125
+ project_name = "your-model-id",
126
+ )
127
+ ```
128
+
129
+ If you are located in the European Union, you'll need to specify the corresponding `Endpoint` (the default endpoint is `Endpoint.ARIZE`):
130
+
131
+ ```python
132
+ from arize.otel import register, Endpoint
133
+
134
+ tracer_provider = register(
135
+ endpoint=Endpoint.ARIZE_EUROPE,
136
+ space_id = "your-arize-space-id",
137
+ api_key = "your-arize-api-key",
138
+ project_name = "your-model-id",
139
+ )
140
+ ```
141
+
142
+ If you would like to configure your tracing using environment variables instead of passing arguments, read [Using Environment Variables](#using-environment-variables).
143
+
144
+ ### Send traces to Custom Endpoint
145
+
146
+ Sending traces to a collector on a custom endpoint is simple, you just need to provide the endpoint as a string. In addition, it is worth noting that the default is to use a `GRPCSpanExporter`. If you'd like to use a `HTTPSpanExporter` instead, specify the transport as shown below:
147
+
148
+ ```python
149
+ from arize.otel import register
150
+
151
+ tracer_provider = register(
152
+ endpoint = "https://my-custom-endpoint"
153
+ # any other options...
154
+ )
155
+ ```
156
+
157
+ ### Specify exporter type
158
+
159
+ If you're using endpoints from the `Endpoint` enum, you do not need to do this, since we know what exporter to use. However, if you're using a custom endpoint, it is worth noting that the default is to use a `GRPCSpanExporter`. If you'd like to use a `HTTPSpanExporter` instead, specify the transport as shown below:
160
+
161
+ ```python
162
+ from arize.otel import register, Transport
163
+
164
+ tracer_provider = register(
165
+ endpoint = "https://my-custom-endpoint"
166
+ transport = Transport.HTTP,
167
+ # any other options...
168
+ )
169
+ ```
170
+
171
+ ### Turn off batch processing of spans
172
+
173
+ We default to using [BatchSpanProcessor](https://opentelemetry.io/docs/languages/js/instrumentation/#picking-the-right-span-processor) from OpenTelemetry because it is non-blocking in case telemetry goes down. In contrast, "SimpleSpanProcessor processes spans as they are created." This can be helpful in development. You can use `SimpleSpanProcessor` with the option `use_batch_processor=False`.
174
+
175
+ ```python
176
+ from arize.otel import register
177
+
178
+ tracer_provider = register(
179
+ # other options...
180
+ batch=False
181
+ )
182
+ ```
183
+
184
+ ### Debug
185
+
186
+ As you're setting up your tracing, it is helpful to print to console the spans created. You can achieve this by setting `log_to_console=True`.
187
+
188
+ ```python
189
+ from arize.otel import register
190
+
191
+ tracer_provider = register(
192
+ # other options...
193
+ log_to_console=True
194
+ )
195
+ ```
196
+
197
+ ## Using Environment Variables
198
+
199
+ The register function will read from environment variables if the arguments are not passed:
200
+
201
+ ```python
202
+ from arize.otel import register
203
+
204
+ tracer_provider = register(
205
+ space_id = ... # Will be read from ARIZE_SPACE_ID env var
206
+ api_key = ... # Will be read from ARIZE_API_KEY env var
207
+ project_name = ... # Will be read from ARIZE_PROJECT_NAME env var
208
+ endpoint = ... # Will be read from ARIZE_COLLECTOR_ENDPOINT env var, defaults to Endpoint.Arize
209
+ )
210
+ ```
211
+
212
+ In the event of conflict, if an environment variable is set but a different argument is passed, the argument passed will take precedence and the environment variable will be ignored.
213
+
214
+ ## Using OTel Primitives
215
+
216
+ For more granular tracing configuration, these wrappers can be used as drop-in replacements for
217
+ OTel primitives:
218
+
219
+ ```python
220
+ from opentelemetry import trace as trace_api
221
+ from arize.otel import HTTPSpanExporter, TracerProvider, SimpleSpanProcessor
222
+
223
+ tracer_provider = TracerProvider()
224
+ span_exporter = HTTPSpanExporter(endpoint=...)
225
+ span_processor = SimpleSpanProcessor(span_exporter=span_exporter)
226
+ tracer_provider.add_span_processor(span_processor)
227
+ trace_api.set_tracer_provider(tracer_provider)
228
+ ```
229
+
230
+ Wrappers have Arize-aware defaults to greatly simplify the OTel configuration process. A special
231
+ `endpoint` keyword argument can be passed to either a `TracerProvider`, `SimpleSpanProcessor` or
232
+ `BatchSpanProcessor` in order to automatically infer which `SpanExporter` to use to simplify setup.
233
+
234
+ #### Specifying the `endpoint` directly
235
+
236
+ ```python
237
+ from opentelemetry import trace as trace_api
238
+ from arize.otel import TracerProvider
239
+
240
+ tracer_provider = TracerProvider(endpoint="https://your-desired-endpoint.com")
241
+ trace_api.set_tracer_provider(tracer_provider)
242
+ ```
243
+
244
+ ### Configuring resources
245
+
246
+ ```python
247
+ # export ARIZE_COLLECTOR_ENDPOINT=https://your-desired-endpoint.com
248
+
249
+ from opentelemetry import trace as trace_api
250
+ from arize.otel import Resource, PROJECT_NAME, TracerProvider
251
+
252
+ tracer_provider = TracerProvider(resource=Resource({PROJECT_NAME: "my-project"}))
253
+ trace_api.set_tracer_provider(tracer_provider)
254
+ ```
255
+
256
+ ### Using a BatchSpanProcessor
257
+
258
+ ```python
259
+ # export ARIZE_COLLECTOR_ENDPOINT=https://your-desired-endpoint.com
260
+
261
+ from opentelemetry import trace as trace_api
262
+ from arize.otel import TracerProvider, BatchSpanProcessor
263
+
264
+ tracer_provider = TracerProvider()
265
+ batch_processor = BatchSpanProcessor()
266
+ tracer_provider.add_span_processor(batch_processor)
267
+ ```
268
+
269
+ ### Specifying a custom GRPC endpoint
270
+
271
+ ```python
272
+ from opentelemetry import trace as trace_api
273
+ from arize.otel import TracerProvider, BatchSpanProcessor, GRPCSpanExporter
274
+
275
+ tracer_provider = TracerProvider()
276
+ batch_processor = BatchSpanProcessor(
277
+ span_exporter=GRPCSpanExporter(endpoint="https://your-desired-endpoint.com")
278
+ )
279
+ tracer_provider.add_span_processor(batch_processor)
280
+ ```
281
+
282
+ ## Questions?
283
+
284
+ Find us in our [Slack Community](https://join.slack.com/t/arize-ai/shared_invite/zt-1px8dcmlf-fmThhDFD_V_48oU7ALan4Q) or email support@arize.com
285
+
286
+ ## Copyright, Patent, and License
287
+
288
+ Copyright 2024 Arize AI, Inc. All Rights Reserved.
289
+
290
+ This software is licensed under the terms of the 3-Clause BSD License. See [LICENSE](https://github.com/Arize-ai/arize-otel-python/blob/main/LICENSE).
@@ -0,0 +1,258 @@
1
+ <p align="center">
2
+ <a target="_blank" href="https://arize.com" style="background:none">
3
+ <img alt="arize banner" src="https://storage.googleapis.com/arize-assets/arize-logo-white.jpg" width="auto" height="auto"></img>
4
+ </a>
5
+ <br/>
6
+ <br/>
7
+ <a href="https://docs.arize.com/">
8
+ <img src="https://img.shields.io/static/v1?message=Docs&logo=data:image/png;base64,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&labelColor=grey&color=blue&logoColor=white&label=%20"/>
9
+ </a>
10
+ <a target="_blank" href="https://join.slack.com/t/arize-ai/shared_invite/zt-1px8dcmlf-fmThhDFD_V_48oU7ALan4Q">
11
+ <img src="https://img.shields.io/static/v1?message=Community&logo=slack&labelColor=grey&color=blue&logoColor=white&label=%20"/>
12
+ </a>
13
+ <br/>
14
+ <a target="_blank" href="https://pypi.org/project/arize-otel/">
15
+ <img src="https://img.shields.io/pypi/v/arize-otel">
16
+ </a>
17
+ <a target="_blank" href="https://pypi.org/project/arize-otel/">
18
+ <img src="https://img.shields.io/pypi/status/arize-otel?style=flat&logo=ticktick&logoColor=white"/>
19
+ </a>
20
+ <a target="_blank" href="https://pypi.org/project/arize-otel/">
21
+ <img src="https://img.shields.io/pypi/pyversions/arize-otel?logo=python&logoColor=white">
22
+ </a>
23
+ <a target="_blank" href="https://github.com/Arize-ai/arize-otel-python/blob/main/LICENSE">
24
+ <img src="https://img.shields.io/pypi/l/arize-otel">
25
+ </a>
26
+
27
+ </p>
28
+
29
+ ---
30
+
31
+ - [Overview](#overview)
32
+ - [Installation](#installation)
33
+ - [Quickstart](#quickstart)
34
+ - [Send traces to Arize](#send-traces-to-arize)
35
+ - [Send traces to Custom Endpoint](#send-traces-to-custom-endpoint)
36
+ - [Specify exporter type](#specify-exporter-type)
37
+ - [Turn off batch processing of spans](#turn-off-batch-processing-of-spans)
38
+ - [Debug](#debug)
39
+ - [Using Environment Variables](#using-environment-variables)
40
+ - [Using OTel Primitives](#using-otel-primitives)
41
+ - [Specifying the `endpoint` directly](#specifying-the-endpoint-directly)
42
+ - [Configuring resources](#configuring-resources)
43
+ - [Using a BatchSpanProcessor](#using-a-batchspanprocessor)
44
+ - [Specifying a custom GRPC endpoint](#specifying-a-custom-grpc-endpoint)
45
+ - [Questions?](#questions)
46
+ - [Copyright, Patent, and License](#copyright-patent-and-license)
47
+
48
+ ## Overview
49
+
50
+ The `arize-otel` package provides a lightweight wrapper around OpenTelemetry primitives with Arize-aware defaults and options. It is meant to be a very lightweight convenience package to help set up OpenTelemetry for tracing LLM applications and send the traces to [Arize](https://arize.com/).
51
+
52
+ ## Installation
53
+
54
+ Install `arize-otel` using `pip`
55
+
56
+ ```bash
57
+ pip install arize-otel
58
+ ```
59
+
60
+ ## Quickstart
61
+
62
+ The `arize.otel` module provides a high-level `register` function to configure OpenTelemetry tracing by returning a `TracerProvider`. The register function can also configure headers and whether or not to process spans one by one or by batch.
63
+
64
+ The following examples showcase how to use `register` to setup Opentelemetry in order to send traces to a collector. However, this is **NOT** the same as [instrumenting](https://docs.arize.com/phoenix/tracing/concepts-tracing/how-does-tracing-work) your application. For instance, you can use any of our [OpenInference AutoInstrumentators](https://github.com/Arize-ai/openinference). Assuming we use the OpenAI AutoInstrumentation, we need to run `instrument()` _after_ using `register`:
65
+
66
+ ```python
67
+ from arize.otel import register
68
+ # Setup OTel via our convenience function
69
+ tracer_provider = register(
70
+ # See details in examples below...
71
+ )
72
+
73
+ # Instrument your application using OpenInference AutoInstrumentators
74
+ from openinference.instrumentation.openai import OpenAIInstrumentor
75
+ OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)
76
+
77
+ ```
78
+
79
+ The above code snippet will yield a fully setup and instrumented application. It is worth noting that this is completely **optional**. The usage of this package is for convenience only, you can set up OpenTelemetry and send traces to Arize without installing this or any other package from Arize.
80
+
81
+ In the following sections we have examples on how to use the `register` function:
82
+
83
+ ### Send traces to Arize
84
+
85
+ To send traces to Arize you need to authenticate via the Space ID and API Key. You can find them in the Space Settings page in the Arize platform. In addition, you'll need to specify the project name, a unique name to identify your project in the Arize platform.
86
+
87
+ ```python
88
+ from arize.otel import register
89
+
90
+ tracer_provider = register(
91
+ space_id = "your-arize-space-id",
92
+ api_key = "your-arize-api-key",
93
+ project_name = "your-model-id",
94
+ )
95
+ ```
96
+
97
+ If you are located in the European Union, you'll need to specify the corresponding `Endpoint` (the default endpoint is `Endpoint.ARIZE`):
98
+
99
+ ```python
100
+ from arize.otel import register, Endpoint
101
+
102
+ tracer_provider = register(
103
+ endpoint=Endpoint.ARIZE_EUROPE,
104
+ space_id = "your-arize-space-id",
105
+ api_key = "your-arize-api-key",
106
+ project_name = "your-model-id",
107
+ )
108
+ ```
109
+
110
+ If you would like to configure your tracing using environment variables instead of passing arguments, read [Using Environment Variables](#using-environment-variables).
111
+
112
+ ### Send traces to Custom Endpoint
113
+
114
+ Sending traces to a collector on a custom endpoint is simple, you just need to provide the endpoint as a string. In addition, it is worth noting that the default is to use a `GRPCSpanExporter`. If you'd like to use a `HTTPSpanExporter` instead, specify the transport as shown below:
115
+
116
+ ```python
117
+ from arize.otel import register
118
+
119
+ tracer_provider = register(
120
+ endpoint = "https://my-custom-endpoint"
121
+ # any other options...
122
+ )
123
+ ```
124
+
125
+ ### Specify exporter type
126
+
127
+ If you're using endpoints from the `Endpoint` enum, you do not need to do this, since we know what exporter to use. However, if you're using a custom endpoint, it is worth noting that the default is to use a `GRPCSpanExporter`. If you'd like to use a `HTTPSpanExporter` instead, specify the transport as shown below:
128
+
129
+ ```python
130
+ from arize.otel import register, Transport
131
+
132
+ tracer_provider = register(
133
+ endpoint = "https://my-custom-endpoint"
134
+ transport = Transport.HTTP,
135
+ # any other options...
136
+ )
137
+ ```
138
+
139
+ ### Turn off batch processing of spans
140
+
141
+ We default to using [BatchSpanProcessor](https://opentelemetry.io/docs/languages/js/instrumentation/#picking-the-right-span-processor) from OpenTelemetry because it is non-blocking in case telemetry goes down. In contrast, "SimpleSpanProcessor processes spans as they are created." This can be helpful in development. You can use `SimpleSpanProcessor` with the option `use_batch_processor=False`.
142
+
143
+ ```python
144
+ from arize.otel import register
145
+
146
+ tracer_provider = register(
147
+ # other options...
148
+ batch=False
149
+ )
150
+ ```
151
+
152
+ ### Debug
153
+
154
+ As you're setting up your tracing, it is helpful to print to console the spans created. You can achieve this by setting `log_to_console=True`.
155
+
156
+ ```python
157
+ from arize.otel import register
158
+
159
+ tracer_provider = register(
160
+ # other options...
161
+ log_to_console=True
162
+ )
163
+ ```
164
+
165
+ ## Using Environment Variables
166
+
167
+ The register function will read from environment variables if the arguments are not passed:
168
+
169
+ ```python
170
+ from arize.otel import register
171
+
172
+ tracer_provider = register(
173
+ space_id = ... # Will be read from ARIZE_SPACE_ID env var
174
+ api_key = ... # Will be read from ARIZE_API_KEY env var
175
+ project_name = ... # Will be read from ARIZE_PROJECT_NAME env var
176
+ endpoint = ... # Will be read from ARIZE_COLLECTOR_ENDPOINT env var, defaults to Endpoint.Arize
177
+ )
178
+ ```
179
+
180
+ In the event of conflict, if an environment variable is set but a different argument is passed, the argument passed will take precedence and the environment variable will be ignored.
181
+
182
+ ## Using OTel Primitives
183
+
184
+ For more granular tracing configuration, these wrappers can be used as drop-in replacements for
185
+ OTel primitives:
186
+
187
+ ```python
188
+ from opentelemetry import trace as trace_api
189
+ from arize.otel import HTTPSpanExporter, TracerProvider, SimpleSpanProcessor
190
+
191
+ tracer_provider = TracerProvider()
192
+ span_exporter = HTTPSpanExporter(endpoint=...)
193
+ span_processor = SimpleSpanProcessor(span_exporter=span_exporter)
194
+ tracer_provider.add_span_processor(span_processor)
195
+ trace_api.set_tracer_provider(tracer_provider)
196
+ ```
197
+
198
+ Wrappers have Arize-aware defaults to greatly simplify the OTel configuration process. A special
199
+ `endpoint` keyword argument can be passed to either a `TracerProvider`, `SimpleSpanProcessor` or
200
+ `BatchSpanProcessor` in order to automatically infer which `SpanExporter` to use to simplify setup.
201
+
202
+ #### Specifying the `endpoint` directly
203
+
204
+ ```python
205
+ from opentelemetry import trace as trace_api
206
+ from arize.otel import TracerProvider
207
+
208
+ tracer_provider = TracerProvider(endpoint="https://your-desired-endpoint.com")
209
+ trace_api.set_tracer_provider(tracer_provider)
210
+ ```
211
+
212
+ ### Configuring resources
213
+
214
+ ```python
215
+ # export ARIZE_COLLECTOR_ENDPOINT=https://your-desired-endpoint.com
216
+
217
+ from opentelemetry import trace as trace_api
218
+ from arize.otel import Resource, PROJECT_NAME, TracerProvider
219
+
220
+ tracer_provider = TracerProvider(resource=Resource({PROJECT_NAME: "my-project"}))
221
+ trace_api.set_tracer_provider(tracer_provider)
222
+ ```
223
+
224
+ ### Using a BatchSpanProcessor
225
+
226
+ ```python
227
+ # export ARIZE_COLLECTOR_ENDPOINT=https://your-desired-endpoint.com
228
+
229
+ from opentelemetry import trace as trace_api
230
+ from arize.otel import TracerProvider, BatchSpanProcessor
231
+
232
+ tracer_provider = TracerProvider()
233
+ batch_processor = BatchSpanProcessor()
234
+ tracer_provider.add_span_processor(batch_processor)
235
+ ```
236
+
237
+ ### Specifying a custom GRPC endpoint
238
+
239
+ ```python
240
+ from opentelemetry import trace as trace_api
241
+ from arize.otel import TracerProvider, BatchSpanProcessor, GRPCSpanExporter
242
+
243
+ tracer_provider = TracerProvider()
244
+ batch_processor = BatchSpanProcessor(
245
+ span_exporter=GRPCSpanExporter(endpoint="https://your-desired-endpoint.com")
246
+ )
247
+ tracer_provider.add_span_processor(batch_processor)
248
+ ```
249
+
250
+ ## Questions?
251
+
252
+ Find us in our [Slack Community](https://join.slack.com/t/arize-ai/shared_invite/zt-1px8dcmlf-fmThhDFD_V_48oU7ALan4Q) or email support@arize.com
253
+
254
+ ## Copyright, Patent, and License
255
+
256
+ Copyright 2024 Arize AI, Inc. All Rights Reserved.
257
+
258
+ This software is licensed under the terms of the 3-Clause BSD License. See [LICENSE](https://github.com/Arize-ai/arize-otel-python/blob/main/LICENSE).
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [tool.hatch.version]
6
+ path = "src/arize/otel/version.py"
7
+
8
+ [tool.hatch.build]
9
+ only-packages = true
10
+
11
+ [tool.hatch.build.targets.wheel]
12
+ packages = ["src/arize"]
13
+
14
+ [project]
15
+ name = "arize-otel"
16
+ description = "Helper package for OTEL setup to send traces to Arize & Phoenix"
17
+ readme = "README.md"
18
+ requires-python = ">=3.8, <3.13"
19
+ license = { text = "BSD" }
20
+ keywords = [
21
+ "Observability",
22
+ "Monitoring",
23
+ "Explainability",
24
+ "Tracing"
25
+ ]
26
+ authors = [
27
+ { name = "Arize AI", email = "support@arize.com" },
28
+ ]
29
+ maintainers = [
30
+ { name = "Arize AI", email = "support@arize.com" },
31
+ ]
32
+ classifiers = [
33
+ "Development Status :: 5 - Production/Stable",
34
+ "Programming Language :: Python",
35
+ "Programming Language :: Python :: 3.8",
36
+ "Programming Language :: Python :: 3.9",
37
+ "Programming Language :: Python :: 3.10",
38
+ "Programming Language :: Python :: 3.11",
39
+ "Programming Language :: Python :: 3.12",
40
+ "Intended Audience :: Developers",
41
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
42
+ "Topic :: Software Development :: Libraries :: Python Modules",
43
+ "Topic :: System :: Logging",
44
+ "Topic :: System :: Monitoring",
45
+ ]
46
+ dependencies = [
47
+ "openinference-semantic-conventions>=0.1.5",
48
+ "opentelemetry-sdk>=1.22",
49
+ "opentelemetry-exporter-otlp>=1.22",
50
+ "opentelemetry-proto>=1.12.0", # needed to avoid this issue: https://github.com/Arize-ai/phoenix/issues/2695
51
+ ]
52
+ dynamic = ["version"]
53
+
54
+ [project.urls]
55
+ Documentation = "https://docs.arize.com/arize/large-language-models/tracing"
56
+ Issues = "https://github.com/Arize-ai/arize-otel-python/issues"
57
+ Source = "https://github.com/Arize-ai/arize-otel-python"
58
+ Changelog = "https://github.com/Arize-ai/arize-otel-python/blob/main/CHANGELOG.md"
59
+
@@ -0,0 +1,26 @@
1
+ from opentelemetry.sdk.resources import Resource
2
+
3
+ from .otel import (
4
+ PROJECT_NAME,
5
+ BatchSpanProcessor,
6
+ Endpoint,
7
+ GRPCSpanExporter,
8
+ HTTPSpanExporter,
9
+ SimpleSpanProcessor,
10
+ TracerProvider,
11
+ Transport,
12
+ register,
13
+ )
14
+
15
+ __all__ = [
16
+ "PROJECT_NAME",
17
+ "BatchSpanProcessor",
18
+ "Endpoint",
19
+ "GRPCSpanExporter",
20
+ "HTTPSpanExporter",
21
+ "Resource",
22
+ "SimpleSpanProcessor",
23
+ "TracerProvider",
24
+ "Transport",
25
+ "register",
26
+ ]
@@ -0,0 +1,618 @@
1
+ import inspect
2
+ import os
3
+ import sys
4
+ from enum import Enum
5
+ from typing import Any, Dict, List, Optional, Tuple, Type, Union
6
+ from urllib.parse import urlparse
7
+
8
+ from openinference.semconv.resource import ResourceAttributes as _ResourceAttributes
9
+ from opentelemetry import trace as trace_api
10
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
11
+ OTLPSpanExporter as _GRPCSpanExporter,
12
+ )
13
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
14
+ OTLPSpanExporter as _HTTPSpanExporter,
15
+ )
16
+ from opentelemetry.sdk.resources import Resource
17
+ from opentelemetry.sdk.trace import SpanProcessor
18
+ from opentelemetry.sdk.trace import TracerProvider as _TracerProvider
19
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor as _BatchSpanProcessor
20
+ from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SpanExporter
21
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor as _SimpleSpanProcessor
22
+
23
+ from .settings import (
24
+ ENV_ARIZE_API_KEY,
25
+ ENV_ARIZE_PROJECT_NAME,
26
+ ENV_ARIZE_SPACE_ID,
27
+ get_env_arize_api_key,
28
+ get_env_arize_space_id,
29
+ get_env_collector_endpoint,
30
+ get_env_project_name,
31
+ )
32
+
33
+ PROJECT_NAME = _ResourceAttributes.PROJECT_NAME
34
+
35
+
36
+ class Endpoint(str, Enum):
37
+ ARIZE = "https://otlp.arize.com/v1"
38
+ ARIZE_EUROPE = "https://otlp.eu-west-1a.arize.com/v1"
39
+
40
+
41
+ class Transport(str, Enum):
42
+ GRPC = "grpc"
43
+ HTTPS = "https"
44
+ HTTP = "http"
45
+
46
+
47
+ EndpointType = Union[str, Endpoint]
48
+
49
+
50
+ def register(
51
+ *,
52
+ space_id: str = get_env_arize_space_id(),
53
+ api_key: str = get_env_arize_api_key(),
54
+ project_name: str = get_env_project_name(),
55
+ endpoint: EndpointType = get_env_collector_endpoint() or Endpoint.ARIZE,
56
+ transport: Transport = Transport.GRPC,
57
+ batch: bool = True,
58
+ set_global_tracer_provider: bool = False,
59
+ headers: Optional[Dict[str, str]] = None,
60
+ verbose: bool = True,
61
+ log_to_console: bool = False,
62
+ ) -> _TracerProvider:
63
+ """
64
+ Creates an OpenTelemetry TracerProvider for enabling OpenInference tracing.
65
+
66
+ For further configuration, the `arize.otel` module provides drop-in replacements for
67
+ OpenTelemetry TracerProvider, SimpleSpanProcessor, BatchSpanProcessor, HTTPSpanExporter, and
68
+ GRPCSpanExporter objects with Arize-aware defaults. Documentation on how to configure tracing
69
+ can be found at https://opentelemetry.io/docs/specs/otel/trace/sdk/.
70
+
71
+ Args:
72
+ space_id (str): The unique identifier for the Arize space. If not provided,
73
+ the `ARIZE_SPACE_ID` environment variable will be used.
74
+ api_key (str): The API key for authenticating with Arize. If not provided,
75
+ the `ARIZE_API_KEY` environment variable will be used.
76
+ project_name (str): The name of the project to which spans will be associated. If
77
+ not provided, the `ARIZE_PROJECT_NAME` environment variable will be used or the
78
+ default project_name will be "default".
79
+ endpoint (EndpointType): The collector endpoint to which spans will be exported.
80
+ If not provided, the `ARIZE_COLLECTOR_ENDPOINT` environment variable or the default
81
+ `Endpoint.ARIZE` will be used.
82
+ transport (Transport): The transport mechanism to use for exporting spans.
83
+ Options are `Transport.GRPC`, `Transport.HTTP`, or `Transport.HTTPS`.
84
+ Defaults to `Transport.GRPC`.
85
+ batch (bool): If True, spans will be processed using a BatchSpanProcessor. If False, spans
86
+ will be processed one at a time using a SimpleSpanProcessor. Defaults to False.
87
+ set_global_tracer_provider (bool): If True, sets the TracerProvider as the global tracer
88
+ provider. Defaults to False.
89
+ headers (dict): Optional headers to include in requests to the collector.
90
+ Defaults to None.
91
+ verbose (bool): If True, prints configuration details to stdout. Defaults to True.
92
+ log_to_console (bool): If True, spans will be logged to the console, useful for debugging.
93
+ Defaults to False.
94
+ """
95
+ _validate_inputs(space_id, api_key, project_name, endpoint, transport)
96
+
97
+ resource = Resource.create({PROJECT_NAME: project_name})
98
+ tracer_provider = TracerProvider(
99
+ space_id=space_id,
100
+ api_key=api_key,
101
+ project_name=project_name,
102
+ endpoint=endpoint,
103
+ transport=transport,
104
+ resource=resource,
105
+ # verbose=False is important so we don't print details of the default
106
+ # processors, will be deleted below
107
+ verbose=False,
108
+ )
109
+ span_processor: SpanProcessor
110
+ if batch:
111
+ span_processor = BatchSpanProcessor(
112
+ space_id=space_id,
113
+ api_key=api_key,
114
+ endpoint=endpoint,
115
+ transport=transport,
116
+ headers=headers,
117
+ )
118
+ else:
119
+ span_processor = SimpleSpanProcessor(
120
+ space_id=space_id,
121
+ api_key=api_key,
122
+ endpoint=endpoint,
123
+ transport=transport,
124
+ headers=headers,
125
+ )
126
+ tracer_provider.add_span_processor(span_processor)
127
+ if log_to_console:
128
+ tracer_provider.add_span_processor(
129
+ span_processor=_SimpleSpanProcessor(
130
+ span_exporter=ConsoleSpanExporter(),
131
+ )
132
+ )
133
+ tracer_provider._default_processor = True
134
+
135
+ if set_global_tracer_provider:
136
+ trace_api.set_tracer_provider(tracer_provider)
137
+ global_provider_msg = (
138
+ "| \n"
139
+ "| `register` has set this TracerProvider as the global OpenTelemetry default.\n"
140
+ "| To disable this behavior, call `register` with "
141
+ "`set_global_tracer_provider=False`.\n"
142
+ )
143
+ else:
144
+ global_provider_msg = ""
145
+
146
+ details = tracer_provider._tracing_details()
147
+ if verbose:
148
+ print(f"{details}" f"{global_provider_msg}")
149
+ return tracer_provider
150
+
151
+
152
+ class TracerProvider(_TracerProvider):
153
+ """
154
+ An extension of `opentelemetry.sdk.trace.TracerProvider` with Arize-aware defaults.
155
+
156
+ Extended keyword arguments are documented in the `Args` section. For further documentation, see
157
+ the OpenTelemetry documentation at https://opentelemetry.io/docs/specs/otel/trace/sdk/.
158
+
159
+ Args:
160
+ space_id (str): The unique identifier for the Arize space. If not provided,
161
+ the `ARIZE_SPACE_ID` environment variable will be used.
162
+ api_key (str): The API key for authenticating with Arize. If not provided,
163
+ the `ARIZE_API_KEY` environment variable will be used.
164
+ project_name (str): The name of the project to which spans will be associated. If
165
+ not provided, the `ARIZE_PROJECT_NAME` environment variable will be used or the
166
+ default project_name will be "default".
167
+ endpoint (EndpointType): The collector endpoint to which spans will be exported.
168
+ If not provided, the `ARIZE_COLLECTOR_ENDPOINT` environment variable or the default
169
+ `Endpoint.ARIZE` will be used.
170
+ transport (Transport): The transport mechanism to use for exporting spans.
171
+ Options are `Transport.GRPC`, `Transport.HTTP`, or `Transport.HTTPS`.
172
+ Defaults to `Transport.GRPC`.
173
+ verbose (bool): If True, configuration details will be printed to stdout.
174
+ """
175
+
176
+ def __init__(
177
+ self,
178
+ *args: Any,
179
+ space_id: str = get_env_arize_space_id(),
180
+ api_key: str = get_env_arize_api_key(),
181
+ project_name: str = get_env_project_name(),
182
+ endpoint: EndpointType = get_env_collector_endpoint() or Endpoint.ARIZE,
183
+ transport: Transport = Transport.GRPC,
184
+ verbose: bool = True,
185
+ **kwargs: Any,
186
+ ):
187
+ _validate_inputs(space_id, api_key, project_name, endpoint, transport)
188
+
189
+ sig = _get_class_signature(_TracerProvider)
190
+ bound_args = sig.bind_partial(*args, **kwargs)
191
+ bound_args.apply_defaults()
192
+ if bound_args.arguments.get("resource") is None:
193
+ bound_args.arguments["resource"] = Resource.create(
194
+ {PROJECT_NAME: project_name}
195
+ )
196
+ super().__init__(*bound_args.args, **bound_args.kwargs)
197
+
198
+ self._default_processor = False
199
+ if transport == Transport.HTTP:
200
+ exporter: SpanExporter = HTTPSpanExporter(
201
+ space_id=space_id,
202
+ api_key=api_key,
203
+ endpoint=endpoint,
204
+ )
205
+ elif transport == Transport.GRPC:
206
+ exporter: SpanExporter = GRPCSpanExporter(
207
+ space_id=space_id,
208
+ api_key=api_key,
209
+ endpoint=endpoint,
210
+ )
211
+ else:
212
+ raise ValueError(f"Invalid transport: {transport}")
213
+ self.add_span_processor(SimpleSpanProcessor(span_exporter=exporter))
214
+ self._default_processor = True
215
+ if verbose:
216
+ print(self._tracing_details())
217
+
218
+ def add_span_processor(self, *args: Any, **kwargs: Any) -> None:
219
+ """
220
+ Registers a new `SpanProcessor` for this `TracerProvider`.
221
+
222
+ If this `TracerProvider` has a default processor, it will be removed.
223
+ """
224
+
225
+ if self._default_processor:
226
+ self._active_span_processor.shutdown()
227
+ self._active_span_processor._span_processors = (
228
+ tuple()
229
+ ) # remove default processors
230
+ self._default_processor = False
231
+ return super().add_span_processor(*args, **kwargs)
232
+
233
+ def _tracing_details(self) -> str:
234
+ project = self.resource.attributes.get(PROJECT_NAME)
235
+ processor_name: Optional[str] = None
236
+ endpoint: Optional[str] = None
237
+ transport: Optional[str] = None
238
+ headers: Optional[Union[Dict[str, str], str]] = None
239
+
240
+ if self._active_span_processor:
241
+ if processors := self._active_span_processor._span_processors:
242
+ if len(processors) == 1:
243
+ span_processor = self._active_span_processor._span_processors[0]
244
+ if exporter := getattr(span_processor, "span_exporter"):
245
+ processor_name = span_processor.__class__.__name__
246
+ endpoint = exporter._endpoint
247
+ transport = _exporter_transport(exporter)
248
+ headers = _printable_headers(exporter._headers)
249
+ else:
250
+ processor_name = "Multiple Span Processors"
251
+ endpoint = "Multiple Span Exporters"
252
+ transport = "Multiple Span Exporters"
253
+ headers = "Multiple Span Exporters"
254
+
255
+ if os.name == "nt":
256
+ details_header = "OpenTelemetry Tracing Details"
257
+ else:
258
+ details_header = "🔭 OpenTelemetry Tracing Details 🔭"
259
+
260
+ configuration_msg = "| Using a default SpanProcessor. `add_span_processor` will overwrite this default.\n"
261
+
262
+ details_msg = (
263
+ f"{details_header}\n"
264
+ f"| Arize Project: {project}\n"
265
+ f"| Span Processor: {processor_name}\n"
266
+ f"| Collector Endpoint: {endpoint}\n"
267
+ f"| Transport: {transport}\n"
268
+ f"| Transport Headers: {headers}\n"
269
+ "| \n"
270
+ f"{configuration_msg if self._default_processor else ''}"
271
+ )
272
+ return details_msg
273
+
274
+
275
+ class SimpleSpanProcessor(_SimpleSpanProcessor):
276
+ """
277
+ Simple SpanProcessor implementation.
278
+
279
+ SimpleSpanProcessor is an implementation of `SpanProcessor` that passes ended spans directly to
280
+ the configured `SpanExporter`.
281
+
282
+ Args:
283
+ span_exporter (SpanExporter, optional): The `SpanExporter` to which ended spans will be
284
+ passed.
285
+ space_id (str, optional): Only used if span_exporter is None.
286
+ The unique identifier for the Arize space. If not provided, the `ARIZE_SPACE_ID`
287
+ environment variable will be used.
288
+ api_key (str, optional): Only used if span_exporter is None.
289
+ The API key for authenticating with Arize. If not provided, the `ARIZE_API_KEY`
290
+ environment variable will be used.
291
+ endpoint (EndpointType, optional): Only used if span_exporter is None.
292
+ The collector endpoint to which spans will be exported. If not provided, the
293
+ `ARIZE_COLLECTOR_ENDPOINT` environment variable or the default
294
+ `Endpoint.ARIZE` will be used.
295
+ transport (Transport, optional): Only used if span_exporter is None.
296
+ The transport mechanism to use for exporting spans. Options are `Transport.GRPC`,
297
+ `Transport.HTTP`, or `Transport.HTTPS`. Defaults to `Transport.GRPC`.
298
+ headers (dict, optional): Optional headers to include in the request to the collector.
299
+ Defaults to None.
300
+ """
301
+
302
+ def __init__(
303
+ self,
304
+ span_exporter: Optional[SpanExporter] = None,
305
+ space_id: str = get_env_arize_space_id(),
306
+ api_key: str = get_env_arize_api_key(),
307
+ endpoint: EndpointType = get_env_collector_endpoint() or Endpoint.ARIZE,
308
+ transport: Transport = Transport.GRPC,
309
+ headers: Optional[Dict[str, str]] = None,
310
+ **kwargs: Any,
311
+ ):
312
+ if span_exporter is None:
313
+ if transport == Transport.HTTP:
314
+ span_exporter = HTTPSpanExporter(
315
+ space_id=space_id,
316
+ api_key=api_key,
317
+ endpoint=endpoint,
318
+ headers=headers,
319
+ )
320
+ elif transport == Transport.GRPC:
321
+ span_exporter = GRPCSpanExporter(
322
+ space_id=space_id,
323
+ api_key=api_key,
324
+ endpoint=endpoint,
325
+ headers=headers,
326
+ )
327
+ else:
328
+ raise ValueError(f"Invalid transport: {transport}")
329
+ super().__init__(span_exporter, **kwargs)
330
+
331
+
332
+ class BatchSpanProcessor(_BatchSpanProcessor):
333
+ """
334
+ Batch SpanProcessor implementation.
335
+
336
+ `BatchSpanProcessor` is an implementation of `SpanProcessor` that batches ended spans and
337
+ pushes them to the configured `SpanExporter`.
338
+
339
+ `BatchSpanProcessor` is configurable with the following environment variables which correspond
340
+ to constructor parameters:
341
+
342
+ - :envvar:`OTEL_BSP_SCHEDULE_DELAY`
343
+ - :envvar:`OTEL_BSP_MAX_QUEUE_SIZE`
344
+ - :envvar:`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`
345
+ - :envvar:`OTEL_BSP_EXPORT_TIMEOUT`
346
+
347
+ Args:
348
+ span_exporter (SpanExporter, optional): The `SpanExporter` to which ended spans will be
349
+ passed.
350
+ space_id (str, optional): Only used if span_exporter is None.
351
+ The unique identifier for the Arize space. If not provided, the `ARIZE_SPACE_ID`
352
+ environment variable will be used.
353
+ api_key (str, optional): Only used if span_exporter is None.
354
+ The API key for authenticating with Arize. If not provided, the `ARIZE_API_KEY`
355
+ environment variable will be used.
356
+ endpoint (EndpointType, optional): Only used if span_exporter is None.
357
+ The collector endpoint to which spans will be exported. If not provided, the
358
+ `ARIZE_COLLECTOR_ENDPOINT` environment variable or the default
359
+ `Endpoint.ARIZE` will be used.
360
+ transport (Transport, optional): Only used if span_exporter is None.
361
+ The transport mechanism to use for exporting spans. Options are `Transport.GRPC`,
362
+ `Transport.HTTP`, or `Transport.HTTPS`. Defaults to `Transport.GRPC`.
363
+ headers (dict, optional): Optional headers to include in the request to the collector.
364
+ Defaults to None.
365
+ max_queue_size (int, optional): The maximum queue size.
366
+ schedule_delay_millis (float, optional): The delay between two consecutive exports in
367
+ milliseconds.
368
+ max_export_batch_size (int, optional): The maximum batch size.
369
+ export_timeout_millis (float, optional): The batch timeout in milliseconds.
370
+ """
371
+
372
+ def __init__(
373
+ self,
374
+ span_exporter: Optional[SpanExporter] = None,
375
+ space_id: str = get_env_arize_space_id(),
376
+ api_key: str = get_env_arize_api_key(),
377
+ endpoint: EndpointType = get_env_collector_endpoint() or Endpoint.ARIZE,
378
+ transport: Transport = Transport.GRPC,
379
+ headers: Optional[Dict[str, str]] = None,
380
+ **kwargs: Any,
381
+ ):
382
+ if span_exporter is None:
383
+ if transport == Transport.HTTP:
384
+ span_exporter = HTTPSpanExporter(
385
+ space_id=space_id,
386
+ api_key=api_key,
387
+ endpoint=endpoint,
388
+ headers=headers,
389
+ )
390
+ elif transport == Transport.GRPC:
391
+ span_exporter = GRPCSpanExporter(
392
+ space_id=space_id,
393
+ api_key=api_key,
394
+ endpoint=endpoint,
395
+ headers=headers,
396
+ )
397
+ else:
398
+ raise ValueError(f"Invalid transport: {transport}")
399
+ super().__init__(span_exporter, **kwargs)
400
+
401
+
402
+ class HTTPSpanExporter(_HTTPSpanExporter):
403
+ """
404
+ OTLP span exporter using HTTP.
405
+
406
+ For more information, see:
407
+ - `opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter`
408
+
409
+ Args:
410
+ space_id (str, optional): Only used if span_exporter is None.
411
+ The unique identifier for the Arize space. If not provided, the `ARIZE_SPACE_ID`
412
+ environment variable will be used.
413
+ api_key (str, optional): Only used if span_exporter is None.
414
+ The API key for authenticating with Arize. If not provided, the `ARIZE_API_KEY`
415
+ environment variable will be used.
416
+ endpoint (EndpointType, optional): Only used if span_exporter is None.
417
+ The collector endpoint to which spans will be exported. If not provided, the
418
+ `ARIZE_COLLECTOR_ENDPOINT` environment variable or the default
419
+ `Endpoint.ARIZE` will be used.
420
+ headers: Headers to send when exporting. If not provided, the `ARIZE_CLIENT_HEADERS`
421
+ or `OTEL_EXPORTER_OTLP_HEADERS` environment variables will be used.
422
+ """
423
+
424
+ def __init__(
425
+ self,
426
+ *args: Any,
427
+ space_id: str = get_env_arize_space_id(),
428
+ api_key: str = get_env_arize_api_key(),
429
+ endpoint: EndpointType = get_env_collector_endpoint() or Endpoint.ARIZE,
430
+ **kwargs: Any,
431
+ ):
432
+ _validate_inputs(
433
+ space_id, api_key, "", endpoint, Transport.HTTP, skip=["project_name"]
434
+ )
435
+ sig = _get_class_signature(_HTTPSpanExporter)
436
+ bound_args = sig.bind_partial(*args, **kwargs)
437
+ bound_args.apply_defaults()
438
+
439
+ auth_header = _get_arize_auth_headers(space_id, api_key)
440
+ if not bound_args.arguments.get("headers"):
441
+ headers = {
442
+ **(auth_header or dict()),
443
+ }
444
+ bound_args.arguments["headers"] = headers if headers else None
445
+ else:
446
+ headers = dict()
447
+ for header_field, value in bound_args.arguments["headers"].items():
448
+ headers[header_field.lower()] = value
449
+
450
+ # If the auth header is not in the headers, add it
451
+ if "space_id" not in headers or "api_key" not in headers:
452
+ bound_args.arguments["headers"] = {
453
+ **headers,
454
+ **(auth_header or dict()),
455
+ }
456
+ else:
457
+ bound_args.arguments["headers"] = headers
458
+
459
+ if bound_args.arguments.get("endpoint") is None:
460
+ bound_args.arguments["endpoint"] = endpoint
461
+ super().__init__(*bound_args.args, **bound_args.kwargs)
462
+
463
+
464
+ class GRPCSpanExporter(_GRPCSpanExporter):
465
+ """
466
+ OTLP span exporter using gRPC.
467
+
468
+ For more information, see:
469
+ - `opentelemetry.exporter.otlp.proto.grpc.trace_exporter.OTLPSpanExporter`
470
+
471
+ Args:
472
+ space_id (str, optional): Only used if span_exporter is None.
473
+ The unique identifier for the Arize space. If not provided, the `ARIZE_SPACE_ID`
474
+ environment variable will be used.
475
+ api_key (str, optional): Only used if span_exporter is None.
476
+ The API key for authenticating with Arize. If not provided, the `ARIZE_API_KEY`
477
+ environment variable will be used.
478
+ endpoint (EndpointType, optional): Only used if span_exporter is None.
479
+ The collector endpoint to which spans will be exported. If not provided, the
480
+ `ARIZE_COLLECTOR_ENDPOINT` environment variable or the default
481
+ `Endpoint.ARIZE` will be used.
482
+ insecure: Connection type
483
+ credentials: Credentials object for server authentication
484
+ headers: Headers to send when exporting. If not provided, the `ARIZE_CLIENT_HEADERS`
485
+ or `OTEL_EXPORTER_OTLP_HEADERS` environment variables will be used.
486
+ timeout: Backend request timeout in seconds
487
+ compression: gRPC compression method to use
488
+ """
489
+
490
+ def __init__(
491
+ self,
492
+ space_id: str = get_env_arize_space_id(),
493
+ api_key: str = get_env_arize_api_key(),
494
+ endpoint: EndpointType = get_env_collector_endpoint() or Endpoint.ARIZE,
495
+ *args: Any,
496
+ **kwargs: Any,
497
+ ):
498
+ _validate_inputs(
499
+ space_id, api_key, "", endpoint, Transport.GRPC, skip=["project_name"]
500
+ )
501
+ sig = _get_class_signature(_GRPCSpanExporter)
502
+ bound_args = sig.bind_partial(*args, **kwargs)
503
+ bound_args.apply_defaults()
504
+
505
+ auth_header = _get_arize_auth_headers(space_id, api_key)
506
+ if not bound_args.arguments.get("headers"):
507
+ headers = {
508
+ **(auth_header or dict()),
509
+ }
510
+ bound_args.arguments["headers"] = headers if headers else None
511
+ else:
512
+ headers = dict()
513
+ for header_field, value in bound_args.arguments["headers"].items():
514
+ headers[header_field.lower()] = value
515
+
516
+ # If the auth header is not in the headers, add it
517
+ if "authorization" not in headers:
518
+ bound_args.arguments["headers"] = {
519
+ **headers,
520
+ **(auth_header or dict()),
521
+ }
522
+ else:
523
+ bound_args.arguments["headers"] = headers
524
+
525
+ if bound_args.arguments.get("endpoint") is None:
526
+ bound_args.arguments["endpoint"] = endpoint
527
+ super().__init__(*bound_args.args, **bound_args.kwargs)
528
+
529
+
530
+ def _exporter_transport(exporter: SpanExporter) -> str:
531
+ if isinstance(exporter, _HTTPSpanExporter):
532
+ return "HTTP"
533
+ if isinstance(exporter, _GRPCSpanExporter):
534
+ return "gRPC"
535
+ else:
536
+ return exporter.__class__.__name__
537
+
538
+
539
+ def _printable_headers(
540
+ headers: Union[List[Tuple[str, str]], Dict[str, str]],
541
+ ) -> Dict[str, str]:
542
+ if isinstance(headers, dict):
543
+ return {key: "****" for key, _ in headers.items()}
544
+ return {key: "****" for key, _ in headers}
545
+
546
+
547
+ def _get_arize_auth_headers(space_id: str, api_key: str) -> Dict[str, str]:
548
+ return {
549
+ "space_id": space_id,
550
+ "api_key": api_key,
551
+ }
552
+
553
+
554
+ def _validate_inputs(
555
+ space_id: str,
556
+ api_key: str,
557
+ project_name: str,
558
+ endpoint: EndpointType,
559
+ transport: Transport,
560
+ skip: List[str] = list(),
561
+ ) -> None:
562
+ if not space_id and "space_id" not in skip:
563
+ raise ValueError(
564
+ "space_id is required. Please pass it as argument or "
565
+ f"set the {ENV_ARIZE_SPACE_ID} environment variable."
566
+ )
567
+ if not api_key and "api_key" not in skip:
568
+ raise ValueError(
569
+ "api_key is required. Please pass it as argument or "
570
+ f"set the {ENV_ARIZE_API_KEY} environment variable."
571
+ )
572
+ if not project_name and "project_name" not in skip:
573
+ raise ValueError(
574
+ "project_name is required. Please pass it as argument or "
575
+ f"set the {ENV_ARIZE_PROJECT_NAME} environment variable."
576
+ )
577
+ if "endpoint" not in skip:
578
+ _validate_endpoint(endpoint)
579
+ if "transport" not in skip:
580
+ _validate_transport(transport)
581
+
582
+
583
+ def _validate_endpoint(endpoint: Any) -> None:
584
+ parsed = ""
585
+ if isinstance(endpoint, Endpoint):
586
+ parsed = urlparse(endpoint.value)
587
+ elif isinstance(endpoint, str):
588
+ parsed = urlparse(endpoint)
589
+ else:
590
+ raise TypeError(
591
+ f"Invalid endpoint type: {type(endpoint).__name__}. "
592
+ "Expected type 'Endpoint' or 'str'. Please provide a valid endpoint "
593
+ "as a string (e.g., 'https://example.com') or an Endpoint instance, "
594
+ "imported `from arize.otel import Endpoint`."
595
+ )
596
+ if not all([parsed.scheme, parsed.netloc]):
597
+ raise ValueError(f"Invalid endpoint: {endpoint}. Please provide a valid URL.")
598
+
599
+
600
+ def _validate_transport(transport: Any) -> None:
601
+ if not isinstance(transport, Transport):
602
+ raise TypeError(
603
+ f"Invalid transport type: {type(transport).__name__}. "
604
+ "Expected type 'Transport'. Please provide a valid Transport instance, "
605
+ "imported `from arize.otel import Transport`."
606
+ )
607
+
608
+
609
+ def _get_class_signature(fn: Type[Any]) -> inspect.Signature:
610
+ if sys.version_info >= (3, 9):
611
+ return inspect.signature(fn)
612
+ elif sys.version_info >= (3, 8):
613
+ init_signature = inspect.signature(fn.__init__)
614
+ new_params = list(init_signature.parameters.values())[1:] # Skip 'self'
615
+ new_sig = init_signature.replace(parameters=new_params)
616
+ return new_sig
617
+ else:
618
+ raise RuntimeError("Unsupported Python version")
@@ -0,0 +1,24 @@
1
+ import os
2
+ from typing import Optional
3
+
4
+ # Environment variables specific to the subpackage
5
+ ENV_ARIZE_SPACE_ID = "ARIZE_SPACE_ID"
6
+ ENV_ARIZE_API_KEY = "ARIZE_API_KEY"
7
+ ENV_ARIZE_PROJECT_NAME = "ARIZE_PROJECT_NAME"
8
+ ENV_ARIZE_COLLECTOR_ENDPOINT = "ARIZE_COLLECTOR_ENDPOINT"
9
+
10
+
11
+ def get_env_arize_space_id() -> str:
12
+ return os.getenv(ENV_ARIZE_SPACE_ID, "")
13
+
14
+
15
+ def get_env_arize_api_key() -> str:
16
+ return os.getenv(ENV_ARIZE_API_KEY, "")
17
+
18
+
19
+ def get_env_project_name() -> str:
20
+ return os.getenv(ENV_ARIZE_PROJECT_NAME, "default")
21
+
22
+
23
+ def get_env_collector_endpoint() -> Optional[str]:
24
+ return os.getenv(ENV_ARIZE_COLLECTOR_ENDPOINT)
@@ -0,0 +1 @@
1
+ __version__ = "0.7.2"