arize-phoenix-otel 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,30 @@
1
+ # Generated dirs
2
+ .vscode
3
+ .idea
4
+ .coverage
5
+ node_modules
6
+ dist
7
+ sdist
8
+ *__pycache__*
9
+ **/.pytest_cache
10
+ **/.ipynb_checkpoints/
11
+ **/.DS_Store
12
+
13
+ # Server static files
14
+ /src/phoenix/server/static/*
15
+
16
+ # Data files
17
+ *.csv
18
+ !tests/**/fixtures/*.csv
19
+ *.hdf
20
+ *.hdf5
21
+
22
+ # Testing
23
+ coverage.xml
24
+ .tox
25
+
26
+ # devtools
27
+ pyrightconfig.json
28
+
29
+ # Demo data
30
+ tutorials/internal/demo_llama_index/*.json
@@ -0,0 +1,5 @@
1
+ Copyright 2024 Arize AI, Inc. All Rights Reserved.
2
+
3
+ Portions of this code are patent protected by one or more of U.S. Patent Nos. 11,315,043 and 11,615,345. The patent protection includes, but is not limited to, functionality enabled by executing the portions of the code, a device or a system executing the portions of the code, a memory storing the portions of the code, etc.
4
+
5
+ This software is licensed under the terms of the Elastic License 2.0 (ELv2). See LICENSE.
@@ -0,0 +1,44 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ **Acceptance**
4
+ By using the software, you agree to all of the terms and conditions below.
5
+
6
+ **Copyright License**
7
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below.
8
+
9
+ **Limitations**
10
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
11
+
12
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
13
+
14
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
15
+
16
+ **Patents**
17
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
18
+
19
+ **Notices**
20
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
21
+
22
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
23
+
24
+ **No Other Rights**
25
+ These terms do not imply any licenses other than those expressly granted in these terms.
26
+
27
+ **Termination**
28
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
29
+
30
+ **No Liability**
31
+ As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
32
+
33
+ **Definitions**
34
+ The *licensor* is the entity offering these terms, and the *software* is the software the licensor makes available under these terms, including any portion of it.
35
+
36
+ *you* refers to the individual or entity agreeing to these terms.
37
+
38
+ *your company* is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. *control* means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
39
+
40
+ *your licenses* are all the licenses granted to you for the software under these terms.
41
+
42
+ *use* means anything you do with the software requiring one of your licenses.
43
+
44
+ *trademark* means trademarks, service marks, and similar rights.
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.3
2
+ Name: arize-phoenix-otel
3
+ Version: 0.1.0
4
+ Summary: LLM Observability
5
+ Project-URL: Documentation, https://docs.arize.com/phoenix/
6
+ Project-URL: Issues, https://github.com/Arize-ai/phoenix/issues
7
+ Project-URL: Source, https://github.com/Arize-ai/phoenix
8
+ Author-email: Arize AI <phoenix-devs@arize.com>
9
+ License: Elastic-2.0
10
+ License-File: IP_NOTICE
11
+ License-File: LICENSE
12
+ Keywords: Explainability,Monitoring,Observability
13
+ Classifier: Programming Language :: Python
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: opentelemetry-exporter-otlp
21
+ Requires-Dist: opentelemetry-proto>=1.12.0
22
+ Requires-Dist: opentelemetry-sdk
23
+ Requires-Dist: opentelemetry-semantic-conventions
24
+ Requires-Dist: typing-extensions<5,>=4.5
25
+ Provides-Extra: test
26
+ Requires-Dist: mypy; extra == 'test'
27
+ Requires-Dist: pytest-asyncio; extra == 'test'
28
+ Requires-Dist: pytest==7.4.4; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ # arize-phoenix-otel
32
+
33
+ Provides a lightweight wrapper around OpenTelemetry primitives with Phoenix-aware defaults.
34
+
35
+ These defaults are aware of the `PHOENIX_COLLECTOR_ENDPOINT`, `PHOENIX_PROJECT_NAME`, and
36
+ ``PHOENIX_CLIENT_HEADERS` environment variables.
37
+
38
+ # Examples
39
+
40
+ The `phoenix.otel` module provides a high-level `register` function to configure OpenTelemetry
41
+ tracing by setting a global `TracerProvider`. The register function can also configure headers
42
+ and whether or not to process spans one by one or by batch.
43
+
44
+ ```
45
+ from phoenix.otel import register
46
+
47
+ tracer_provider = register(endpoint="http://localhost:6006/v1/traces", project_name="test")
48
+ ```
49
+
50
+ For more granular tracing configuration, these wrappers can be used as drop-in replacements for
51
+ OTel primitives:
52
+
53
+ ```
54
+ from opentelemetry import trace as trace_api
55
+ from phoenix.otel import HTTPSpanExporter, TracerProvider, SimpleSpanProcessor
56
+
57
+ tracer_provider = TracerProvider()
58
+ span_exporter = HTTPSpanExporter(endpoint="http://localhost:6006/v1/traces")
59
+ span_processor = SimpleSpanProcessor(exporter=span_exporter)
60
+ tracer_provider.add_span_processor(span_processor)
61
+ trace_api.set_tracer_provider(tracer_provider)
62
+ ```
63
+
64
+ Wrappers have Phoenix-aware defaults to greatly simplify the OTel configuration process.
65
+
66
+ ```
67
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:6006/v1/traces
68
+ from opentelemetry import trace as trace_api
69
+ from phoenix.otel import TracerProvider
70
+
71
+ tracer_provider = TracerProvider()
72
+ trace_api.set_tracer_provider(tracer_provider)
73
+ ```
74
+
75
+ Phoenix supports sending traces via either an HTTP or gRPC protocol, if possible, the exporter
76
+ will be inferred from the endpoint URL. In the following example, tracing is configured to
77
+ export traces via the gRPC protocol based on the `PHOENIX_COLLECTOR_ENDPOINT` URL.
78
+
79
+ ```
80
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:4317
81
+ from opentelemetry import trace as trace_api
82
+ from phoenix.otel import TracerProvider
83
+
84
+ tracer_provider = TracerProvider()
85
+ trace_api.set_tracer_provider(tracer_provider)
86
+ ```
87
+
88
+ The collector endpoint can be passed directly to the tracer provider.
89
+
90
+ ```
91
+ from opentelemetry import trace as trace_api
92
+ from phoenix.otel import TracerProvider
93
+
94
+ tracer_provider = TracerProvider(endpoint="http://localhost:6006/v1/traces")
95
+ trace_api.set_tracer_provider(tracer_provider)
96
+ ```
97
+
98
+ Users can gradually add OTel components as desired:
99
+
100
+ ## Adding resources
101
+ ```
102
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:4317
103
+ from opentelemetry import trace as trace_api
104
+ from phoenix.otel import Resource, PROJECT_NAME, TracerProvider
105
+
106
+ tracer_provider = TracerProvider(resource=Resource({PROJECT_NAME: "my-project"}))
107
+ trace_api.set_tracer_provider(tracer_provider)
108
+ ```
109
+
110
+ ## Using a BatchSpanProcessor
111
+ ```
112
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:4317
113
+ from opentelemetry import trace as trace_api
114
+ from phoenix.otel import TracerProvider, BatchSpanProcessor
115
+
116
+ tracer_provider = TracerProvider()
117
+ batch_processor = BatchSpanProcessor()
118
+ tracer_provider.add_span_processor(batch_processor)
119
+ ```
@@ -0,0 +1,89 @@
1
+ # arize-phoenix-otel
2
+
3
+ Provides a lightweight wrapper around OpenTelemetry primitives with Phoenix-aware defaults.
4
+
5
+ These defaults are aware of the `PHOENIX_COLLECTOR_ENDPOINT`, `PHOENIX_PROJECT_NAME`, and
6
+ ``PHOENIX_CLIENT_HEADERS` environment variables.
7
+
8
+ # Examples
9
+
10
+ The `phoenix.otel` module provides a high-level `register` function to configure OpenTelemetry
11
+ tracing by setting a global `TracerProvider`. The register function can also configure headers
12
+ and whether or not to process spans one by one or by batch.
13
+
14
+ ```
15
+ from phoenix.otel import register
16
+
17
+ tracer_provider = register(endpoint="http://localhost:6006/v1/traces", project_name="test")
18
+ ```
19
+
20
+ For more granular tracing configuration, these wrappers can be used as drop-in replacements for
21
+ OTel primitives:
22
+
23
+ ```
24
+ from opentelemetry import trace as trace_api
25
+ from phoenix.otel import HTTPSpanExporter, TracerProvider, SimpleSpanProcessor
26
+
27
+ tracer_provider = TracerProvider()
28
+ span_exporter = HTTPSpanExporter(endpoint="http://localhost:6006/v1/traces")
29
+ span_processor = SimpleSpanProcessor(exporter=span_exporter)
30
+ tracer_provider.add_span_processor(span_processor)
31
+ trace_api.set_tracer_provider(tracer_provider)
32
+ ```
33
+
34
+ Wrappers have Phoenix-aware defaults to greatly simplify the OTel configuration process.
35
+
36
+ ```
37
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:6006/v1/traces
38
+ from opentelemetry import trace as trace_api
39
+ from phoenix.otel import TracerProvider
40
+
41
+ tracer_provider = TracerProvider()
42
+ trace_api.set_tracer_provider(tracer_provider)
43
+ ```
44
+
45
+ Phoenix supports sending traces via either an HTTP or gRPC protocol, if possible, the exporter
46
+ will be inferred from the endpoint URL. In the following example, tracing is configured to
47
+ export traces via the gRPC protocol based on the `PHOENIX_COLLECTOR_ENDPOINT` URL.
48
+
49
+ ```
50
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:4317
51
+ from opentelemetry import trace as trace_api
52
+ from phoenix.otel import TracerProvider
53
+
54
+ tracer_provider = TracerProvider()
55
+ trace_api.set_tracer_provider(tracer_provider)
56
+ ```
57
+
58
+ The collector endpoint can be passed directly to the tracer provider.
59
+
60
+ ```
61
+ from opentelemetry import trace as trace_api
62
+ from phoenix.otel import TracerProvider
63
+
64
+ tracer_provider = TracerProvider(endpoint="http://localhost:6006/v1/traces")
65
+ trace_api.set_tracer_provider(tracer_provider)
66
+ ```
67
+
68
+ Users can gradually add OTel components as desired:
69
+
70
+ ## Adding resources
71
+ ```
72
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:4317
73
+ from opentelemetry import trace as trace_api
74
+ from phoenix.otel import Resource, PROJECT_NAME, TracerProvider
75
+
76
+ tracer_provider = TracerProvider(resource=Resource({PROJECT_NAME: "my-project"}))
77
+ trace_api.set_tracer_provider(tracer_provider)
78
+ ```
79
+
80
+ ## Using a BatchSpanProcessor
81
+ ```
82
+ # export PHOENIX_COLLECTOR_ENDPOINT=http://localhost:4317
83
+ from opentelemetry import trace as trace_api
84
+ from phoenix.otel import TracerProvider, BatchSpanProcessor
85
+
86
+ tracer_provider = TracerProvider()
87
+ batch_processor = BatchSpanProcessor()
88
+ tracer_provider.add_span_processor(batch_processor)
89
+ ```
@@ -0,0 +1,98 @@
1
+ [project]
2
+ name = "arize-phoenix-otel"
3
+ description = "LLM Observability"
4
+ readme = "README.md"
5
+ requires-python = ">=3.8, <3.13"
6
+ license = {text="Elastic-2.0"}
7
+ license-files = { paths = ["LICENSE", "IP_NOTICE"] }
8
+ keywords = [
9
+ "Observability",
10
+ "Monitoring",
11
+ "Explainability",
12
+ ]
13
+ authors = [
14
+ { name = "Arize AI", email = "phoenix-devs@arize.com" },
15
+ ]
16
+ classifiers = [
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3.8",
19
+ "Programming Language :: Python :: 3.9",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ ]
24
+ version = "0.1.0"
25
+ dependencies = [
26
+ "opentelemetry-semantic-conventions",
27
+ "opentelemetry-exporter-otlp",
28
+ "opentelemetry-proto>=1.12.0",
29
+ "opentelemetry-sdk",
30
+ "typing-extensions>=4.5, <5",
31
+ ]
32
+
33
+ [project.optional-dependencies]
34
+ test = [
35
+ "pytest==7.4.4",
36
+ "pytest-asyncio",
37
+ "mypy",
38
+ ]
39
+
40
+ [project.urls]
41
+ Documentation = "https://docs.arize.com/phoenix/"
42
+ Issues = "https://github.com/Arize-ai/phoenix/issues"
43
+ Source = "https://github.com/Arize-ai/phoenix"
44
+
45
+ [build-system]
46
+ requires = ["hatchling"]
47
+ build-backend = "hatchling.build"
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/phoenix"]
51
+
52
+ [tool.hatch.build]
53
+ only-packages = true
54
+
55
+ [tool.hatch.envs.publish]
56
+ dependencies = [
57
+ "check-wheel-contents",
58
+ "twine",
59
+ ]
60
+
61
+ [tool.hatch.envs.publish.scripts]
62
+ testpypi = [
63
+ "check-wheel-contents dist/",
64
+ "twine upload --verbose --repository testpypi dist/*",
65
+ ]
66
+ pypi = [
67
+ "check-wheel-contents dist/",
68
+ "twine upload --verbose dist/*",
69
+ ]
70
+
71
+ [tool.ruff]
72
+ exclude = [".git", "__pycache__", ".tox", "dist"]
73
+ extend-include = ["*.ipynb"]
74
+ line-length = 100
75
+ target-version = "py38"
76
+
77
+ [tool.ruff.lint]
78
+ select = ["E", "F", "W", "I"]
79
+
80
+ [tool.ruff.lint.isort]
81
+ force-single-line = false
82
+
83
+ [tool.ruff.lint.per-file-ignores]
84
+ "*.ipynb" = ["E402", "E501"]
85
+
86
+ [tool.ruff.format]
87
+ line-ending = "lf"
88
+
89
+ [tool.mypy]
90
+ explicit_package_bases = true
91
+ disallow_untyped_calls = true
92
+ disallow_untyped_defs = true
93
+ disallow_incomplete_defs = true
94
+ strict = true
95
+ exclude = [
96
+ "dist/",
97
+ "tests/",
98
+ ]
@@ -0,0 +1,22 @@
1
+ from opentelemetry.sdk.resources import Resource
2
+
3
+ from .otel import (
4
+ PROJECT_NAME,
5
+ BatchSpanProcessor,
6
+ GRPCSpanExporter,
7
+ HTTPSpanExporter,
8
+ SimpleSpanProcessor,
9
+ TracerProvider,
10
+ register,
11
+ )
12
+
13
+ __all__ = [
14
+ "TracerProvider",
15
+ "SimpleSpanProcessor",
16
+ "BatchSpanProcessor",
17
+ "HTTPSpanExporter",
18
+ "GRPCSpanExporter",
19
+ "Resource",
20
+ "PROJECT_NAME",
21
+ register,
22
+ ]
@@ -0,0 +1,194 @@
1
+ import inspect
2
+ import warnings
3
+ from typing import Any, Dict, Optional
4
+ from urllib.parse import ParseResult, urlparse
5
+
6
+ from openinference.semconv.resource import ResourceAttributes as _ResourceAttributes
7
+ from opentelemetry import trace as trace_api
8
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
9
+ OTLPSpanExporter as _GRPCSpanExporter,
10
+ )
11
+ from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
12
+ OTLPSpanExporter as _HTTPSpanExporter,
13
+ )
14
+ from opentelemetry.sdk.resources import Resource
15
+ from opentelemetry.sdk.trace import SpanProcessor
16
+ from opentelemetry.sdk.trace import TracerProvider as _TracerProvider
17
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor as _BatchSpanProcessor
18
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor as _SimpleSpanProcessor
19
+ from opentelemetry.sdk.trace.export import SpanExporter
20
+
21
+ from .settings import get_env_client_headers, get_env_collector_endpoint, get_env_project_name
22
+
23
+ PROJECT_NAME = _ResourceAttributes.PROJECT_NAME
24
+
25
+
26
+ def register(
27
+ *,
28
+ endpoint: Optional[str] = None,
29
+ project_name: Optional[str] = None,
30
+ batch: bool = False,
31
+ set_global=True,
32
+ headers=None,
33
+ ) -> _TracerProvider:
34
+ """
35
+ Globally sets an OpenTelemetry TracerProvider for enabling OpenInference tracing.
36
+
37
+ For futher configuration, the `phoenix.otel` module provides drop-in replacements for
38
+ OpenTelemetry TracerProvider, SimpleSpanProcessor, BatchSpanProcessor, HTTPSpanExporter, and
39
+ GRPCSpanExporter objects with Phoenix-aware defaults. Documentation on how to configure tracing
40
+ can be found at https://opentelemetry.io/docs/specs/otel/trace/sdk/.
41
+
42
+ Args:
43
+ endpoint (str, optional): The collector endpoint to which spans will be exported. If not
44
+ provided, the `PHOENIX_OTEL_COLLECTOR_ENDPOINT` environment variable will be used. The
45
+ export protocol will be inferred from the endpoint.
46
+ project_name (str, optional): The name of the project to which spans will be associated. If
47
+ not provided, the `PHOENIX_PROJECT_NAME` environment variable will be used.
48
+ batch (bool): If True, spans will be processed using a BatchSpanprocessor. If False, spans
49
+ will be processed one at a time using a SimpleSpanProcessor.
50
+ set_global (bool): If False, the TracerProvider will not be set as the global provider.
51
+ Defaults to True.
52
+ headers (dict, optional): Optional headers to include in the HTTP request to the collector.
53
+ """
54
+
55
+ project_name = project_name or get_env_project_name()
56
+ resource = Resource.create({PROJECT_NAME: project_name})
57
+ tracer_provider = _TracerProvider(resource=resource)
58
+ span_processor: SpanProcessor
59
+ if batch:
60
+ span_processor = BatchSpanProcessor(endpoint=endpoint, headers=headers)
61
+ else:
62
+ span_processor = SimpleSpanProcessor(endpoint=endpoint, headers=headers)
63
+ tracer_provider.add_span_processor(span_processor)
64
+
65
+ if set_global:
66
+ trace_api.set_tracer_provider(tracer_provider)
67
+ return tracer_provider
68
+
69
+
70
+ class TracerProvider(_TracerProvider):
71
+ def __init__(self, *args: Any, endpoint: Optional[str] = None, **kwargs: Any):
72
+ sig = inspect.signature(_TracerProvider)
73
+ bound_args = sig.bind_partial(*args, **kwargs)
74
+ bound_args.apply_defaults()
75
+ if bound_args.arguments.get("resource") is None:
76
+ bound_args.arguments["resource"] = Resource.create(
77
+ {PROJECT_NAME: get_env_project_name()}
78
+ )
79
+ super().__init__(**bound_args.arguments)
80
+
81
+ endpoint = endpoint or get_env_collector_endpoint()
82
+ parsed_url = urlparse(endpoint)
83
+ assert isinstance(parsed_url, ParseResult)
84
+ self._default_processor = False
85
+
86
+ if _maybe_http_endpoint(parsed_url):
87
+ print("Exporting spans via HTTP.")
88
+ http_exporter: SpanExporter = HTTPSpanExporter(endpoint=endpoint)
89
+ self.add_span_processor(SimpleSpanProcessor(exporter=http_exporter))
90
+ self._default_processor = True
91
+ elif _maybe_grpc_endpoint(parsed_url):
92
+ print("Exporting spans via GRPC.")
93
+ grpc_exporter: SpanExporter = GRPCSpanExporter(endpoint=endpoint)
94
+ self.add_span_processor(SimpleSpanProcessor(exporter=grpc_exporter))
95
+ self._default_processor = True
96
+ else:
97
+ warnings.warn(
98
+ "Could not infer exporter to use. Use `add_span_processor` to configure span "
99
+ "processing and export."
100
+ )
101
+
102
+ def add_span_processor(self, *args: Any, **kwargs: Any) -> None:
103
+ if self._default_processor:
104
+ print("Overriding default span processor.")
105
+ self._active_span_processor.shutdown()
106
+ self._active_span_processor._span_processors = tuple() # remove default processors
107
+ self._default_processor = False
108
+ return super().add_span_processor(*args, **kwargs)
109
+
110
+
111
+ class SimpleSpanProcessor(_SimpleSpanProcessor):
112
+ def __init__(
113
+ self,
114
+ exporter: Optional[SpanExporter] = None,
115
+ endpoint: Optional[str] = None,
116
+ headers: Optional[Dict[str, str]] = None,
117
+ ):
118
+ if exporter is None:
119
+ endpoint = endpoint or get_env_collector_endpoint()
120
+ parsed_url = urlparse(endpoint)
121
+ assert isinstance(parsed_url, ParseResult)
122
+ if _maybe_http_endpoint(parsed_url):
123
+ print("Exporting spans via HTTP.")
124
+ exporter = HTTPSpanExporter(endpoint=endpoint, headers=headers)
125
+ elif _maybe_grpc_endpoint(parsed_url):
126
+ print("Exporting spans via GRPC.")
127
+ exporter = GRPCSpanExporter(endpoint=endpoint, headers=headers)
128
+ else:
129
+ warnings.warn("Could not infer collector endpoint protocol, defaulting to HTTP.")
130
+ exporter = HTTPSpanExporter(endpoint=endpoint, headers=headers)
131
+ super().__init__(exporter)
132
+
133
+
134
+ class BatchSpanProcessor(_BatchSpanProcessor):
135
+ def __init__(
136
+ self,
137
+ exporter: Optional[SpanExporter] = None,
138
+ endpoint: Optional[str] = None,
139
+ headers: Optional[Dict[str, str]] = None,
140
+ ):
141
+ if exporter is None:
142
+ endpoint = endpoint or get_env_collector_endpoint()
143
+ parsed_url = urlparse(endpoint)
144
+ assert isinstance(parsed_url, ParseResult)
145
+ if _maybe_http_endpoint(parsed_url):
146
+ print("Exporting spans via HTTP.")
147
+ exporter = HTTPSpanExporter(endpoint=endpoint, headers=headers)
148
+ elif _maybe_grpc_endpoint(parsed_url):
149
+ print("Exporting spans via GRPC.")
150
+ exporter = GRPCSpanExporter(endpoint=endpoint, headers=headers)
151
+ else:
152
+ warnings.warn("Could not infer collector endpoint protocol, defaulting to HTTP.")
153
+ exporter = HTTPSpanExporter(endpoint=endpoint, headers=headers)
154
+ super().__init__(exporter)
155
+
156
+
157
+ class HTTPSpanExporter(_HTTPSpanExporter):
158
+ def __init__(self, *args: Any, **kwargs: Any):
159
+ sig = inspect.signature(_HTTPSpanExporter)
160
+ bound_args = sig.bind_partial(*args, **kwargs)
161
+ bound_args.apply_defaults()
162
+
163
+ if not bound_args.arguments.get("headers"):
164
+ bound_args.arguments["headers"] = get_env_client_headers()
165
+
166
+ if bound_args.arguments.get("endpoint") is None:
167
+ bound_args.arguments["endpoint"] = get_env_collector_endpoint()
168
+ super().__init__(**bound_args.arguments)
169
+
170
+
171
+ class GRPCSpanExporter(_GRPCSpanExporter):
172
+ def __init__(self, *args: Any, **kwargs: Any):
173
+ sig = inspect.signature(_GRPCSpanExporter)
174
+ bound_args = sig.bind_partial(*args, **kwargs)
175
+ bound_args.apply_defaults()
176
+
177
+ if not bound_args.arguments.get("headers"):
178
+ bound_args.arguments["headers"] = get_env_client_headers()
179
+
180
+ if bound_args.arguments.get("endpoint") is None:
181
+ bound_args.arguments["endpoint"] = get_env_collector_endpoint()
182
+ super().__init__(*args, **kwargs)
183
+
184
+
185
+ def _maybe_http_endpoint(parsed_endpoint: ParseResult) -> bool:
186
+ if parsed_endpoint.path == "/v1/traces":
187
+ return True
188
+ return False
189
+
190
+
191
+ def _maybe_grpc_endpoint(parsed_endpoint: ParseResult) -> bool:
192
+ if not parsed_endpoint.path and parsed_endpoint.port == 4317:
193
+ return True
194
+ return False
@@ -0,0 +1,83 @@
1
+ import os
2
+ import urllib
3
+ from logging import getLogger
4
+ from re import compile
5
+ from typing import Dict, List, Optional
6
+
7
+ _logger = getLogger(__name__)
8
+
9
+ # Environment variables specific to the subpackage
10
+ ENV_PHOENIX_COLLECTOR_ENDPOINT = "PHOENIX_COLLECTOR_ENDPOINT"
11
+ ENV_PHOENIX_PROJECT_NAME = "PHOENIX_PROJECT_NAME"
12
+ ENV_PHOENIX_CLIENT_HEADERS = "PHOENIX_CLIENT_HEADERS"
13
+
14
+
15
+ def get_env_collector_endpoint() -> Optional[str]:
16
+ return os.getenv(ENV_PHOENIX_COLLECTOR_ENDPOINT)
17
+
18
+
19
+ def get_env_project_name() -> str:
20
+ return os.getenv(ENV_PHOENIX_PROJECT_NAME, "default")
21
+
22
+
23
+ def get_env_client_headers() -> Optional[Dict[str, str]]:
24
+ if headers_str := os.getenv(ENV_PHOENIX_CLIENT_HEADERS):
25
+ return parse_env_headers(headers_str)
26
+ return None
27
+
28
+
29
+ # Optional whitespace
30
+ _OWS = r"[ \t]*"
31
+ # A key contains printable US-ASCII characters except: SP and "(),/:;<=>?@[\]{}
32
+ _KEY_FORMAT = r"[\x21\x23-\x27\x2a\x2b\x2d\x2e\x30-\x39\x41-\x5a\x5e-\x7a\x7c\x7e]+"
33
+ # A value contains a URL-encoded UTF-8 string. The encoded form can contain any
34
+ # printable US-ASCII characters (0x20-0x7f) other than SP, DEL, and ",;/
35
+ _VALUE_FORMAT = r"[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*"
36
+ # A key-value is key=value, with optional whitespace surrounding key and value
37
+ _KEY_VALUE_FORMAT = rf"{_OWS}{_KEY_FORMAT}{_OWS}={_OWS}{_VALUE_FORMAT}{_OWS}"
38
+
39
+ _HEADER_PATTERN = compile(_KEY_VALUE_FORMAT)
40
+ _DELIMITER_PATTERN = compile(r"[ \t]*,[ \t]*")
41
+
42
+
43
+ def parse_env_headers(s: str) -> Dict[str, str]:
44
+ """
45
+ Parse ``s``, which is a ``str`` instance containing HTTP headers encoded
46
+ for use in ENV variables per the W3C Baggage HTTP header format at
47
+ https://www.w3.org/TR/baggage/#baggage-http-header-format, except that
48
+ additional semi-colon delimited metadata is not supported.
49
+
50
+ If the headers are not urlencoded, we will log a warning and attempt to urldecode them.
51
+ """
52
+ headers: Dict[str, str] = {}
53
+ headers_list: List[str] = _DELIMITER_PATTERN.split(s)
54
+
55
+ for header in headers_list:
56
+ if not header: # empty string
57
+ continue
58
+
59
+ match = _HEADER_PATTERN.fullmatch(header.strip())
60
+ if not match:
61
+ parts = header.split("=", 1)
62
+ if len(parts) == 2:
63
+ name, value = parts
64
+ encoded_header = f"{urllib.parse.quote(name)}={urllib.parse.quote(value)}"
65
+ match = _HEADER_PATTERN.fullmatch(encoded_header.strip())
66
+ if not match:
67
+ _logger.warning(
68
+ "Header format invalid! Header values in environment variables must be "
69
+ "URL encoded: %s",
70
+ header,
71
+ )
72
+ continue
73
+ _logger.warning(
74
+ f"Header values in environment variables should be URL encoded, ``{header}`` "
75
+ f"was urlencoded to: ``{encoded_header}``"
76
+ )
77
+
78
+ name, value = header.split("=", 1)
79
+ name = urllib.parse.unquote(name).strip().lower()
80
+ value = urllib.parse.unquote(value).strip()
81
+ headers[name] = value
82
+
83
+ return headers