openinference-instrumentation-agentspec 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,5 @@
1
+ # vendored virtual environments
2
+ .venv
3
+
4
+ # gradio work directory
5
+ .gradio
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: openinference-instrumentation-agentspec
3
+ Version: 0.1.0
4
+ Summary: OpenInference Open Agent Spec Instrumentation
5
+ Project-URL: Homepage, https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-agentspec
6
+ Author: Oracle
7
+ Author-email: OpenInference Authors <oss@arize.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Requires-Python: <3.15,>=3.10
21
+ Requires-Dist: openinference-instrumentation>=0.1.27
22
+ Requires-Dist: openinference-semantic-conventions>=0.1.21
23
+ Requires-Dist: opentelemetry-api
24
+ Requires-Dist: opentelemetry-instrumentation
25
+ Requires-Dist: opentelemetry-semantic-conventions
26
+ Requires-Dist: typing-extensions
27
+ Requires-Dist: wrapt
28
+ Provides-Extra: instruments
29
+ Requires-Dist: opentelemetry-sdk; extra == 'instruments'
30
+ Requires-Dist: pyagentspec>=26.1.0; extra == 'instruments'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # OpenInference Agent Spec Instrumentation
34
+
35
+ Python auto-instrumentation library for Agent Spec.
36
+
37
+ Open Agent Spec (Agent Spec) is a portable, platform-agnostic configuration language that allows Agents and Agentic Systems to be described with high fidelity.
38
+ It defines the conceptual building blocks—called components—that make up agents in typical agent-based systems.
39
+ This includes the properties that configure each component and the semantics that govern their behavior.
40
+
41
+ Agent Spec Tracing is an extension of Agent Spec that standardizes how agent and flow executions emit traces.
42
+ It enables:
43
+ - Runtime adapters to emit consistent traces across different frameworks.
44
+ - Consumers (observability backends, UIs, developer tooling) to ingest one standardized format regardless of the producer.
45
+
46
+ You can find more information about Agent Spec and Agent Spec Tracing at:
47
+ - Agent Spec: https://oracle.github.io/agent-spec/development/agentspec/index.html
48
+ - Tracing: https://oracle.github.io/agent-spec/development/agentspec/tracing.html
49
+
50
+ The traces emitted by this instrumentation are fully OpenTelemetry compatible and can be sent to an OpenTelemetry
51
+ collector for viewing, such as [`arize-phoenix`](https://github.com/Arize-ai/phoenix)
52
+
53
+ ## Installation
54
+
55
+ ```shell
56
+ pip install openinference-instrumentation-agentspec
57
+ ```
58
+
59
+ ## Quickstart
60
+
61
+ In this example we will instrument a small program that uses Agent Spec Tracing and observe
62
+ the traces via [`arize-phoenix`](https://github.com/Arize-ai/phoenix).
63
+
64
+ Install packages.
65
+
66
+ ```shell
67
+ pip install openinference-instrumentation-agentspec arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
68
+ ```
69
+
70
+ Start the phoenix server so that it is ready to collect traces.
71
+ The Phoenix server runs entirely on your machine and does not send data over the internet.
72
+
73
+ ```shell
74
+ phoenix serve
75
+ ```
76
+
77
+ In a python file (e.g., `agentspec_agent.py`) , set up the `AgentSpecInstrumentor` and configure
78
+ the tracer to send traces to Phoenix.
79
+
80
+ ```python
81
+ from pyagentspec.adapters.langgraph import AgentSpecLoader
82
+ from pyagentspec.agent import Agent
83
+ from pyagentspec.llms import OpenAiConfig
84
+
85
+ agent = Agent(
86
+ name="assistant",
87
+ description="An general purpose agent without tools",
88
+ llm_config=OpenAiConfig(name="openai-gpt-5-mini", model_id="gpt-5-mini"),
89
+ system_prompt="You are a helpful assistant. Help the user answering politely.",
90
+ )
91
+
92
+ langgraph_agent = AgentSpecLoader().load_component(agent)
93
+
94
+ from phoenix.otel import register
95
+
96
+ from openinference.instrumentation.agentspec import AgentSpecInstrumentor
97
+
98
+ tracer_provider = register(batch=True, project_name="hello-world-app")
99
+ AgentSpecInstrumentor().instrument(tracer_provider=tracer_provider)
100
+
101
+ while True:
102
+ user_input = input("USER >>> ")
103
+ if user_input.lower() in ["exit", "quit"]:
104
+ break
105
+ response = langgraph_agent.invoke(
106
+ input={"messages": [{"role": "user", "content": user_input}]},
107
+ config={"configurable": {"thread_id": "1"}},
108
+ )
109
+ print("AGENT >>>", response['messages'][-1].content.strip())
110
+ ```
111
+
112
+ Now simply run the python file and observe the traces in Phoenix.
113
+
114
+ ```shell
115
+ python agentspec_agent.py
116
+ ```
@@ -0,0 +1,84 @@
1
+ # OpenInference Agent Spec Instrumentation
2
+
3
+ Python auto-instrumentation library for Agent Spec.
4
+
5
+ Open Agent Spec (Agent Spec) is a portable, platform-agnostic configuration language that allows Agents and Agentic Systems to be described with high fidelity.
6
+ It defines the conceptual building blocks—called components—that make up agents in typical agent-based systems.
7
+ This includes the properties that configure each component and the semantics that govern their behavior.
8
+
9
+ Agent Spec Tracing is an extension of Agent Spec that standardizes how agent and flow executions emit traces.
10
+ It enables:
11
+ - Runtime adapters to emit consistent traces across different frameworks.
12
+ - Consumers (observability backends, UIs, developer tooling) to ingest one standardized format regardless of the producer.
13
+
14
+ You can find more information about Agent Spec and Agent Spec Tracing at:
15
+ - Agent Spec: https://oracle.github.io/agent-spec/development/agentspec/index.html
16
+ - Tracing: https://oracle.github.io/agent-spec/development/agentspec/tracing.html
17
+
18
+ The traces emitted by this instrumentation are fully OpenTelemetry compatible and can be sent to an OpenTelemetry
19
+ collector for viewing, such as [`arize-phoenix`](https://github.com/Arize-ai/phoenix)
20
+
21
+ ## Installation
22
+
23
+ ```shell
24
+ pip install openinference-instrumentation-agentspec
25
+ ```
26
+
27
+ ## Quickstart
28
+
29
+ In this example we will instrument a small program that uses Agent Spec Tracing and observe
30
+ the traces via [`arize-phoenix`](https://github.com/Arize-ai/phoenix).
31
+
32
+ Install packages.
33
+
34
+ ```shell
35
+ pip install openinference-instrumentation-agentspec arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp
36
+ ```
37
+
38
+ Start the phoenix server so that it is ready to collect traces.
39
+ The Phoenix server runs entirely on your machine and does not send data over the internet.
40
+
41
+ ```shell
42
+ phoenix serve
43
+ ```
44
+
45
+ In a python file (e.g., `agentspec_agent.py`) , set up the `AgentSpecInstrumentor` and configure
46
+ the tracer to send traces to Phoenix.
47
+
48
+ ```python
49
+ from pyagentspec.adapters.langgraph import AgentSpecLoader
50
+ from pyagentspec.agent import Agent
51
+ from pyagentspec.llms import OpenAiConfig
52
+
53
+ agent = Agent(
54
+ name="assistant",
55
+ description="An general purpose agent without tools",
56
+ llm_config=OpenAiConfig(name="openai-gpt-5-mini", model_id="gpt-5-mini"),
57
+ system_prompt="You are a helpful assistant. Help the user answering politely.",
58
+ )
59
+
60
+ langgraph_agent = AgentSpecLoader().load_component(agent)
61
+
62
+ from phoenix.otel import register
63
+
64
+ from openinference.instrumentation.agentspec import AgentSpecInstrumentor
65
+
66
+ tracer_provider = register(batch=True, project_name="hello-world-app")
67
+ AgentSpecInstrumentor().instrument(tracer_provider=tracer_provider)
68
+
69
+ while True:
70
+ user_input = input("USER >>> ")
71
+ if user_input.lower() in ["exit", "quit"]:
72
+ break
73
+ response = langgraph_agent.invoke(
74
+ input={"messages": [{"role": "user", "content": user_input}]},
75
+ config={"configurable": {"thread_id": "1"}},
76
+ )
77
+ print("AGENT >>>", response['messages'][-1].content.strip())
78
+ ```
79
+
80
+ Now simply run the python file and observe the traces in Phoenix.
81
+
82
+ ```shell
83
+ python agentspec_agent.py
84
+ ```
@@ -0,0 +1,92 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "openinference-instrumentation-agentspec"
7
+ dynamic = ["version"]
8
+ description = "OpenInference Open Agent Spec Instrumentation"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10, <3.15"
12
+ authors = [
13
+ { name = "OpenInference Authors", email = "oss@arize.com" },
14
+ { name = "Oracle", email = "" },
15
+ ]
16
+ classifiers = [
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ ]
28
+ dependencies = [
29
+ "opentelemetry-api",
30
+ "opentelemetry-instrumentation",
31
+ "opentelemetry-semantic-conventions",
32
+ "openinference-instrumentation>=0.1.27",
33
+ "openinference-semantic-conventions>=0.1.21",
34
+ "typing-extensions",
35
+ "wrapt",
36
+ ]
37
+
38
+ [project.optional-dependencies]
39
+ instruments = [
40
+ "opentelemetry-sdk",
41
+ "pyagentspec >= 26.1.0",
42
+ ]
43
+
44
+ [project.entry-points.opentelemetry_instrumentor]
45
+ agentspec = "openinference.instrumentation.agentspec:AgentSpecInstrumentor"
46
+
47
+ [project.entry-points.openinference_instrumentor]
48
+ agentspec = "openinference.instrumentation.agentspec:AgentSpecInstrumentor"
49
+
50
+ [project.urls]
51
+ Homepage = "https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-agentspec"
52
+
53
+ [tool.hatch.version]
54
+ path = "src/openinference/instrumentation/agentspec/version.py"
55
+
56
+ [tool.hatch.build.targets.sdist]
57
+ include = [
58
+ "/src",
59
+ ]
60
+
61
+ [tool.hatch.build.targets.wheel]
62
+ packages = ["src/openinference"]
63
+
64
+ [tool.pytest.ini_options]
65
+ asyncio_mode = "auto"
66
+ asyncio_default_fixture_loop_scope = "function"
67
+ testpaths = [
68
+ "tests",
69
+ ]
70
+
71
+ [tool.mypy]
72
+ strict = true
73
+ explicit_package_bases = true
74
+ exclude = [
75
+ "examples",
76
+ "dist",
77
+ "sdist",
78
+ ]
79
+
80
+ [tool.ruff]
81
+ line-length = 100
82
+ target-version = "py310"
83
+
84
+ [tool.ruff.lint.per-file-ignores]
85
+ "*.ipynb" = ["E402", "E501"]
86
+ "examples/*" = ["E501"]
87
+
88
+ [tool.ruff.lint]
89
+ select = ["E", "F", "W", "I"]
90
+
91
+ [tool.ruff.lint.isort]
92
+ force-single-line = false
@@ -0,0 +1,88 @@
1
+ import logging
2
+ import warnings
3
+ from contextlib import contextmanager
4
+ from typing import Any, Collection, Generator
5
+
6
+ from opentelemetry import trace as trace_api
7
+ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore
8
+ from opentelemetry.sdk.trace.export import SpanProcessor as OtelSdkSpanProcessor # type: ignore
9
+ from pyagentspec.tracing.spanprocessor import SpanProcessor as AgentSpecSpanProcessor
10
+
11
+ from openinference.instrumentation.agentspec._openinference_spanprocessor import (
12
+ OpenInferenceSpanProcessor,
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logger.addHandler(logging.NullHandler())
17
+
18
+
19
+ class AgentSpecInstrumentor(BaseInstrumentor): # type: ignore
20
+ """
21
+ An instrumentor for Agent Spec Tracing
22
+ """
23
+
24
+ def instrumentation_dependencies(self) -> Collection[str]:
25
+ return ["pyagentspec >= 26.1.0"]
26
+
27
+ def _instrument(self, **kwargs: Any) -> None:
28
+ if not (tracer_provider := kwargs.get("tracer_provider", None)):
29
+ tracer_provider = trace_api.get_tracer_provider()
30
+ if not (resource := kwargs.get("resource", None)):
31
+ if hasattr(tracer_provider, "resource"):
32
+ resource = tracer_provider.resource
33
+ mask_sensitive_information = kwargs.get("mask_sensitive_information", False)
34
+
35
+ from pyagentspec.tracing.trace import Trace, get_trace
36
+
37
+ if get_trace() is not None:
38
+ raise ValueError(
39
+ "Agent Spec Trace already active, instrumentation is not allowed. "
40
+ "Close any existing Agent Spec Trace before instrumenting your code."
41
+ )
42
+
43
+ # Look for the span processors attached to the tracer provider
44
+ # and wrap them in an OTel Agent Spec Span Processor
45
+ tp_span_processors: list[OtelSdkSpanProcessor] = []
46
+ if hasattr(tracer_provider, "_active_span_processor"):
47
+ tp_span_processors = getattr(
48
+ tracer_provider._active_span_processor, "_span_processors", []
49
+ )
50
+ agentspec_spanprocessors: list[AgentSpecSpanProcessor] = [
51
+ OpenInferenceSpanProcessor(
52
+ otel_span_processor=otel_span_processor,
53
+ resource=resource,
54
+ mask_sensitive_information=mask_sensitive_information,
55
+ )
56
+ for otel_span_processor in tp_span_processors
57
+ ]
58
+ if len(agentspec_spanprocessors) == 0:
59
+ warnings.warn(
60
+ "Instrumenting a TracerProvider that has no SpanProcessors attached", UserWarning
61
+ )
62
+
63
+ trace = Trace(span_processors=agentspec_spanprocessors, shutdown_on_exit=False)
64
+ trace._start()
65
+
66
+ def _uninstrument(self, **kwargs: Any) -> None:
67
+ from pyagentspec.tracing.trace import get_trace
68
+
69
+ trace = get_trace()
70
+ if trace is not None:
71
+ try:
72
+ trace._end()
73
+ except Exception as e:
74
+ # Whatever happens we do not crash during the final shutdown, but we warn the user
75
+ logger.warning(f"Exception raised during Trace `end`: {e}")
76
+
77
+ @contextmanager
78
+ def instrument_context(self, **kwargs: Any) -> Generator[None, Any, None]:
79
+ """Context manager to instrument and uninstrument the library"""
80
+ self.instrument(**kwargs)
81
+ try:
82
+ yield
83
+ finally:
84
+ if self.is_instrumented_by_opentelemetry:
85
+ self.uninstrument(**kwargs)
86
+
87
+
88
+ __all__ = ["AgentSpecInstrumentor", "OpenInferenceSpanProcessor"]
@@ -0,0 +1,240 @@
1
+ from typing import Any, Dict, Optional
2
+
3
+ from opentelemetry.sdk.trace import Resource as OtelSdkResource # type: ignore
4
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor as OtelSdkBatchSpanProcessor
5
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor as OtelSdkSimpleSpanProcessor
6
+ from opentelemetry.sdk.trace.export import SpanExporter as OtelSdkSpanExporter
7
+ from opentelemetry.sdk.trace.export import SpanProcessor as OtelSdkSpanProcessor # type: ignore
8
+ from pyagentspec.property import _empty_default
9
+ from pyagentspec.tools import Tool as AgentSpecTool
10
+ from pyagentspec.tracing.events import Event as AgentSpecEvent
11
+ from pyagentspec.tracing.events import LlmGenerationRequest as AgentSpecLlmGenerationRequest
12
+ from pyagentspec.tracing.events import LlmGenerationResponse as AgentSpecLlmGenerationResponse
13
+ from pyagentspec.tracing.events import ToolExecutionRequest as AgentSpecToolExecutionRequest
14
+ from pyagentspec.tracing.spans import AgentExecutionSpan as AgentSpecAgentExecutionSpan
15
+ from pyagentspec.tracing.spans import LlmGenerationSpan as AgentSpecLlmGenerationSpan
16
+ from pyagentspec.tracing.spans import Span as AgentSpecSpan
17
+ from pyagentspec.tracing.spans import ToolExecutionSpan as AgentSpecToolExecutionSpan
18
+
19
+ from openinference.instrumentation.agentspec._opentelemetry_spanprocessor import (
20
+ _OtelSpanProcessor,
21
+ _try_json_serialization,
22
+ )
23
+ from openinference.semconv.trace import (
24
+ OpenInferenceSpanKindValues,
25
+ SpanAttributes,
26
+ ToolAttributes,
27
+ ToolCallAttributes,
28
+ )
29
+
30
+
31
+ def _get_event_of_given_type(
32
+ span: AgentSpecSpan, event_type: type[AgentSpecEvent]
33
+ ) -> Optional[AgentSpecEvent]:
34
+ try:
35
+ return next(event for event in span.events if isinstance(event, event_type))
36
+ except StopIteration:
37
+ return None
38
+
39
+
40
+ def _get_tool_json_schema(tool: AgentSpecTool) -> Dict[str, Any]:
41
+ # Return tool's json schema as per OpenAI tools format
42
+ return {
43
+ "type": "function",
44
+ "function": {
45
+ "name": tool.name,
46
+ "description": tool.description,
47
+ "parameters": {
48
+ "type": "object",
49
+ "properties": {p.title: p.json_schema for p in tool.inputs or []},
50
+ "required": [p.title for p in (tool.inputs or []) if p.default is _empty_default],
51
+ },
52
+ },
53
+ }
54
+
55
+
56
+ def _to_open_inference_format_tracing_info(
57
+ span: AgentSpecSpan, mask_sensitive_information: bool = True
58
+ ) -> Dict[str, Any]:
59
+ # See https://arize-ai.github.io/openinference/spec/ for naming conventions
60
+ trace = span._trace
61
+ tracing_info: Dict[str, Any] = span.model_dump(mask_sensitive_information=mask_sensitive_information)
62
+ tracing_info[SpanAttributes.SESSION_ID] = trace.id if trace else None
63
+ # The default value we use for span kind is CHAIN. We will overwrite if we find a better fit.
64
+ tracing_info[SpanAttributes.OPENINFERENCE_SPAN_KIND] = OpenInferenceSpanKindValues.CHAIN.value
65
+ if isinstance(span, AgentSpecAgentExecutionSpan):
66
+ tracing_info[SpanAttributes.OPENINFERENCE_SPAN_KIND] = (
67
+ OpenInferenceSpanKindValues.AGENT.value
68
+ )
69
+ tracing_info[SpanAttributes.AGENT_NAME] = span.agent.name
70
+ # Agent inputs and outputs are set at the end
71
+ elif isinstance(span, AgentSpecLlmGenerationSpan):
72
+ llm_info = tracing_info.pop("llm_config")
73
+ tracing_info[SpanAttributes.OPENINFERENCE_SPAN_KIND] = OpenInferenceSpanKindValues.LLM.value
74
+ tracing_info[SpanAttributes.LLM_MODEL_NAME] = llm_info.get("model_id") or llm_info.get("name") or "unknown"
75
+ tracing_info[SpanAttributes.LLM_INVOCATION_PARAMETERS] = _try_json_serialization(
76
+ {
77
+ k: v
78
+ for k, v in (llm_info.get("default_generation_parameters") or {}).items()
79
+ if v is not None
80
+ }
81
+ )
82
+ # Start event for AgentSpecLlmGenerationSpan is a AgentSpecLlmGenerationRequest
83
+ start_event = _get_event_of_given_type(span, AgentSpecLlmGenerationRequest)
84
+ if start_event is not None:
85
+ # If we find one, we update all the information related to the LLM requests
86
+ # in the Span info
87
+ event_info = start_event.model_dump(
88
+ mask_sensitive_information=mask_sensitive_information
89
+ )
90
+ if event_info["llm_generation_config"]:
91
+ # Update generation parameters with the specific ones for this call
92
+ tracing_info[SpanAttributes.LLM_INVOCATION_PARAMETERS] = _try_json_serialization(
93
+ {
94
+ k: v
95
+ for k, v in (event_info.get("llm_generation_config") or {}).items()
96
+ if v is not None
97
+ }
98
+ )
99
+ # LLM tools seem to require the JSON schema of the tools in OpenAI format
100
+ tracing_info[SpanAttributes.LLM_TOOLS] = [
101
+ {
102
+ ToolAttributes.TOOL_JSON_SCHEMA: _try_json_serialization(
103
+ _get_tool_json_schema(tool)
104
+ )
105
+ }
106
+ for tool in start_event.tools
107
+ ]
108
+ tracing_info[SpanAttributes.LLM_INPUT_MESSAGES] = [
109
+ # The prompt contains the list of messages dumped in dict format,
110
+ # we can use that directly
111
+ {"message": e}
112
+ for e in event_info["prompt"]
113
+ ]
114
+ # End event for AgentSpecLlmGenerationSpan is a AgentSpecLlmGenerationResponse
115
+ end_event = _get_event_of_given_type(span, AgentSpecLlmGenerationResponse)
116
+ if end_event is not None:
117
+ # If we find one, we update all the information related to the LLM response
118
+ # in the Span info
119
+ event_info = end_event.model_dump(mask_sensitive_information=mask_sensitive_information)
120
+ tracing_info[SpanAttributes.LLM_OUTPUT_MESSAGES] = [
121
+ {
122
+ "message": {
123
+ "content": event_info.pop("content"),
124
+ "tool_calls": [
125
+ {
126
+ "tool_call.id": tool_call["call_id"],
127
+ "tool_call.function.name": tool_call["tool_name"],
128
+ "tool_call.function.arguments": tool_call["arguments"],
129
+ }
130
+ for tool_call in event_info["tool_calls"]
131
+ if isinstance(tool_call, dict)
132
+ ],
133
+ "role": "assistant",
134
+ },
135
+ }
136
+ ]
137
+ tracing_info[SpanAttributes.LLM_TOKEN_COUNT_COMPLETION] = event_info.pop(
138
+ "output_tokens"
139
+ )
140
+ tracing_info[SpanAttributes.LLM_TOKEN_COUNT_PROMPT] = event_info.pop("input_tokens")
141
+ elif isinstance(span, AgentSpecToolExecutionSpan):
142
+ tracing_info[SpanAttributes.OPENINFERENCE_SPAN_KIND] = (
143
+ OpenInferenceSpanKindValues.TOOL.value
144
+ )
145
+ tool_info = tracing_info.pop("tool")
146
+ tracing_info[SpanAttributes.TOOL_NAME] = tool_info["name"]
147
+ tracing_info[SpanAttributes.TOOL_DESCRIPTION] = tool_info["description"]
148
+ tracing_info[ToolAttributes.TOOL_JSON_SCHEMA] = _try_json_serialization(
149
+ _get_tool_json_schema(span.tool)
150
+ )
151
+ # Start event for AgentSpecToolExecutionSpan is a AgentSpecToolExecutionRequest
152
+ start_event = _get_event_of_given_type(span, AgentSpecToolExecutionRequest)
153
+ if start_event is not None:
154
+ # If we find one, we update all the information related to the tool execution
155
+ # in the Span info
156
+ event_info = start_event.model_dump(
157
+ mask_sensitive_information=mask_sensitive_information
158
+ )
159
+ tracing_info[ToolCallAttributes.TOOL_CALL_ID] = event_info["request_id"]
160
+ tracing_info[ToolCallAttributes.TOOL_CALL_FUNCTION_NAME] = tracing_info[
161
+ SpanAttributes.TOOL_NAME
162
+ ]
163
+ tracing_info[SpanAttributes.TOOL_PARAMETERS] = event_info["inputs"]
164
+ tracing_info[ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON] = (
165
+ _try_json_serialization(event_info["inputs"])
166
+ )
167
+
168
+ if (
169
+ tracing_info[SpanAttributes.OPENINFERENCE_SPAN_KIND]
170
+ != OpenInferenceSpanKindValues.LLM.value
171
+ ):
172
+ # Spans often have generic `inputs` and `outputs`. When available, we use start event
173
+ # `inputs` attribute as input and end event `outputs` attribute as output of the span
174
+ start_event = span.events[0] if len(span.events) > 0 else None
175
+ if start_event is not None:
176
+ event_info = start_event.model_dump(
177
+ mask_sensitive_information=mask_sensitive_information
178
+ )
179
+ tracing_info[SpanAttributes.INPUT_VALUE] = _try_json_serialization(
180
+ event_info.get("inputs", {})
181
+ )
182
+ end_event = span.events[-1] if len(span.events) > 1 else None
183
+ if end_event is not None:
184
+ event_info = end_event.model_dump(mask_sensitive_information=mask_sensitive_information)
185
+ tracing_info[SpanAttributes.OUTPUT_VALUE] = _try_json_serialization(
186
+ event_info.get("outputs", {})
187
+ )
188
+
189
+ return tracing_info
190
+
191
+
192
+ class OpenInferenceSpanProcessor(_OtelSpanProcessor):
193
+ def __init__(
194
+ self,
195
+ resource: Optional[OtelSdkResource] = None,
196
+ otel_span_processor: Optional[OtelSdkSpanProcessor] = None,
197
+ span_exporter: Optional[OtelSdkSpanExporter] = None,
198
+ use_batch_span_processor: bool = True,
199
+ mask_sensitive_information: bool = True,
200
+ ):
201
+ """
202
+ AgentSpec OpenInference SpanProcessor.
203
+
204
+ This class forwards the calls to AgentSpec's span processors to an OpenInference one
205
+ (based on OpenTelemetry).
206
+
207
+ Parameters
208
+ ----------
209
+ resource:
210
+ The OpenTelemetry Resource to use in Spans.
211
+ otel_span_processor:
212
+ The OpenTelemetry SpanProcessor to use to process spans.
213
+ If None is given, a new instance is created based on ``span_exporter`` and
214
+ ``use_batch_span_processor`` parameters.
215
+ span_exporter:
216
+ The OpenTelemetry SpanExporter to use to export spans.
217
+ This parameter is ignored if an ``otel_span_processor`` is provided.
218
+ use_batch_span_processor:
219
+ If True, an instance of OpenTelemetry BatchSpanProcessor is used to process spans.
220
+ If False, an instance of OpenTelemetry SimpleSpanProcessor is used to process spans.
221
+ This parameter is ignored if an ``otel_span_processor`` is provided.
222
+ mask_sensitive_information
223
+ Whether to mask potentially sensitive information from the span and its events
224
+ """
225
+ self.use_batch_span_processor = use_batch_span_processor
226
+ super().__init__(
227
+ otel_span_processor=otel_span_processor,
228
+ span_exporter=span_exporter,
229
+ resource=resource,
230
+ mask_sensitive_information=mask_sensitive_information,
231
+ span_model_dump_func=_to_open_inference_format_tracing_info,
232
+ )
233
+
234
+ def _create_otel_span_processor(
235
+ self, span_exporter: OtelSdkSpanExporter
236
+ ) -> OtelSdkSpanProcessor:
237
+ if self.use_batch_span_processor:
238
+ return OtelSdkBatchSpanProcessor(span_exporter=span_exporter)
239
+ else:
240
+ return OtelSdkSimpleSpanProcessor(span_exporter=span_exporter)
@@ -0,0 +1,448 @@
1
+ import json
2
+ import logging
3
+ import uuid
4
+ from abc import ABC, abstractmethod
5
+ from typing import Any, Callable, Dict, Optional
6
+
7
+ from opentelemetry import context as context_api
8
+ from opentelemetry.sdk.trace import Event as OtelSdkEvent
9
+ from opentelemetry.sdk.trace import Resource as OtelSdkResource # type: ignore
10
+ from opentelemetry.sdk.trace import Span as OtelSdkSpan
11
+ from opentelemetry.sdk.trace import SpanContext as OtelSdkSpanContext # type: ignore
12
+ from opentelemetry.sdk.trace import sampling as otel_sdk_sampling
13
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor as OtelSdkBatchSpanProcessor
14
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor as OtelSdkSimpleSpanProcessor
15
+ from opentelemetry.sdk.trace.export import SpanExporter as OtelSdkSpanExporter
16
+ from opentelemetry.sdk.trace.export import SpanProcessor as OtelSdkSpanProcessor # type: ignore
17
+ from opentelemetry.trace import TraceFlags as OtelSdkTraceFlags
18
+ from opentelemetry.util.types import Attributes
19
+ from pyagentspec.tracing.events.event import Event as AgentSpecEvent
20
+ from pyagentspec.tracing.spanprocessor import SpanProcessor as AgentSpecSpanProcessor
21
+ from pyagentspec.tracing.spans.span import Span as AgentSpecSpan
22
+
23
+ logger = logging.getLogger(__name__)
24
+ logger.addHandler(logging.NullHandler())
25
+
26
+
27
+ _MAX_UNSIGNED_LONG_LONG = 18446744073709551615
28
+
29
+
30
+ def _try_id_to_int_conversion(id_: Optional[str]) -> int:
31
+ """
32
+ Convert the string ID into an integer ID as per OpenTelemetry requirement
33
+
34
+ https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#spancontext
35
+ """
36
+ if id_ is not None:
37
+ try:
38
+ # First we try to get the original UUID, if the id is a compliant string
39
+ id_ = uuid.UUID(id_) # type: ignore
40
+ except ValueError:
41
+ # If it is not, we try to convert the id as it is
42
+ pass
43
+ try:
44
+ # We try the conversion to int modulo 2**64 (unsigned long long, due to otel limitations),
45
+ # if it is not None. Note also the 0 is not a valid ID,
46
+ # so we reduce the modulo by 1 (2**64-1) and add 1 to the result
47
+ return (int(id_) % _MAX_UNSIGNED_LONG_LONG) + 1 if id_ else id(id_)
48
+ except Exception:
49
+ # If the conversion fails, we fall back to the id, we cannot do better
50
+ return id(id_)
51
+
52
+
53
+ def _try_json_serialization(value: Any) -> str:
54
+ """
55
+ Serialize the given object into the corresponding JSON string.
56
+ If it is not JSON serializable, we simply stringify it
57
+ """
58
+ if isinstance(value, str):
59
+ # Avoid quoting strings with json dump
60
+ return str(value)
61
+ try:
62
+ return json.dumps(value)
63
+ except TypeError:
64
+ return str(value)
65
+
66
+
67
+ def _flatten_attribute_dict(attribute: Dict[str, Any]) -> Dict[str, Any]:
68
+ """Flatten the complex types using OpenTelemetry conventions"""
69
+ flattened_attribute: Dict[str, Any] = {}
70
+ for key, value in attribute.items():
71
+ if isinstance(value, (tuple, set, list)):
72
+ # List-like values have to become dictionaries with the index as the key
73
+ # This will be translated according to dict rules below
74
+ # (e.g., attribute_name.0, attribute_name.1, ...)
75
+ flattened_value = dict()
76
+ for i, inner_value in enumerate(value):
77
+ flattened_value[i] = inner_value
78
+ value = flattened_value
79
+ if isinstance(value, dict):
80
+ # Dictionary attributes are flattened by adding each dict entry
81
+ # as a separate entry with name `attribute_name.key`
82
+ for inner_key, inner_value in _flatten_attribute_dict(value).items():
83
+ flattened_attribute[f"{key}.{inner_key}"] = inner_value
84
+ else:
85
+ flattened_attribute[key] = value
86
+ return flattened_attribute
87
+
88
+
89
+ def _serialize_attribute_values(attributes: Dict[str, Any]) -> Dict[str, Any]:
90
+ """Serialize the attributes dictionary using types that OpenTelemetry supports"""
91
+ # Note that this function performs shallow serialization, i.e., it does not apply recursively
92
+ allowed_types = (str, int, float, bool, bytes)
93
+ return {
94
+ key: value if isinstance(value, allowed_types) else _try_json_serialization(value)
95
+ for key, value in _flatten_attribute_dict(attributes).items()
96
+ }
97
+
98
+
99
+ class _OtelSdkEvent(OtelSdkEvent):
100
+ """Protected implementation of `opentelemetry.trace.Event`.
101
+
102
+ Contains an ID that uniquely identifies the event.
103
+ """
104
+
105
+ def __init__(
106
+ self,
107
+ id: str,
108
+ name: str,
109
+ attributes: Attributes = None,
110
+ timestamp: Optional[int] = None,
111
+ ) -> None:
112
+ super().__init__(name=name, attributes=attributes, timestamp=timestamp)
113
+ self.id = id
114
+
115
+
116
+ class _OtelSdkSpan(OtelSdkSpan):
117
+ """Protected implementation of `opentelemetry.trace.Span`.
118
+
119
+ As Spans cannot be directly instantiated in the opentelemetry SDK,
120
+ we create a materialization of the interface that we use internally.
121
+ This is the same solution that opentelemetry uses to prevent anyone
122
+ from creating a span without a tracer provider, but we need more flexibility.
123
+ """
124
+
125
+ def update_events(self, events: list[AgentSpecEvent], mask_sensitive_information: bool) -> None:
126
+ # We update the events list by adding the missing ones
127
+ # These events should all be _OtelSdkEvent that contain an ID
128
+ # If they are not, we can ignore them because they don't come from us
129
+ current_event_ids = {event.id for event in self.events if hasattr(event, "id")}
130
+ for event in events:
131
+ if event.id not in current_event_ids:
132
+ self._add_event(convert_agentspec_event_into_otel_event(event, mask_sensitive_information))
133
+
134
+
135
+ def convert_agentspec_event_into_otel_event(
136
+ event: AgentSpecEvent,
137
+ mask_sensitive_information: bool = True,
138
+ ) -> _OtelSdkEvent:
139
+ """
140
+ Convert an AgentSpec Event into the equivalent OpenTelemetry Event object.
141
+
142
+ Parameters
143
+ ----------
144
+ event:
145
+ the event to convert
146
+ mask_sensitive_information
147
+ Whether to mask potentially sensitive information from the event attributes
148
+
149
+ Returns
150
+ -------
151
+ opentelemetry.sdk.trace.Event
152
+ The converted event
153
+ """
154
+ try:
155
+ event_dump = event.model_dump(mask_sensitive_information=mask_sensitive_information)
156
+ except Exception as e:
157
+ # If anything goes wrong, we log it, and we go on without event attributes
158
+ logger.warning(f"Error during the dump of an event: {e}")
159
+ event_dump = {}
160
+ return _OtelSdkEvent(
161
+ id=event.id,
162
+ name=event.name or event.__class__.__name__,
163
+ timestamp=event.timestamp,
164
+ attributes=_serialize_attribute_values(event_dump),
165
+ )
166
+
167
+
168
+ def convert_agentspec_span_into_otel_span(
169
+ span: AgentSpecSpan,
170
+ resource: Optional[OtelSdkResource] = None,
171
+ mask_sensitive_information: bool = True,
172
+ span_model_dump: Optional[Callable[[AgentSpecSpan, bool], Dict[str, Any]]] = None,
173
+ span_to_update: Optional[_OtelSdkSpan] = None,
174
+ ) -> _OtelSdkSpan:
175
+ """
176
+ Convert a AgentSpec Span into the equivalent OpenTelemetry Span object.
177
+
178
+ Parameters
179
+ ----------
180
+ span:
181
+ the span to convert
182
+ resource:
183
+ the OpenTelemetry Resource object to use
184
+ mask_sensitive_information
185
+ Whether to mask potentially sensitive information from the span and its events
186
+ span_model_dump
187
+ Function to dump the span model to a dictionary.
188
+ If None, the pydantic model_dump function will be used.
189
+ span_to_update
190
+ OpenTelemetry Span object to be updated with new information from Agent Spec Span.
191
+ If None, a new OpenTelemetry Span object will be created.
192
+
193
+ Returns
194
+ -------
195
+ _OtelSdkSpan
196
+ The converted span
197
+ """
198
+ try:
199
+ if span_model_dump:
200
+ span_attributes = span_model_dump(span, mask_sensitive_information)
201
+ else:
202
+ span_attributes = span.model_dump(mask_sensitive_information=mask_sensitive_information)
203
+ except Exception as e:
204
+ # If anything goes wrong, we log it, and we go on without span attributes
205
+ logger.warning(f"Error during the dump of a span: {e}")
206
+ span_attributes = {}
207
+ # We remove the tracing information we don't want to appear in the attributes,
208
+ # as they will be handled separately
209
+ for attribute_to_pop in (
210
+ "events",
211
+ "id",
212
+ "type",
213
+ "name",
214
+ "start_time",
215
+ "end_time",
216
+ ):
217
+ span_attributes.pop(attribute_to_pop, None)
218
+ # We create the objects required by OpenTelemetry with the expected information
219
+ sampling_result = otel_sdk_sampling.SamplingResult(
220
+ otel_sdk_sampling.Decision.RECORD_AND_SAMPLE,
221
+ span_attributes,
222
+ )
223
+ trace_flags = (
224
+ OtelSdkTraceFlags(OtelSdkTraceFlags.SAMPLED)
225
+ if sampling_result.decision.is_sampled() # type: ignore
226
+ else OtelSdkTraceFlags(OtelSdkTraceFlags.DEFAULT)
227
+ )
228
+ # The IDs in otel are required to be integers, so we try to transform them
229
+ trace_id = _try_id_to_int_conversion(span._trace.id if span._trace else None)
230
+ span_id = _try_id_to_int_conversion(span.id)
231
+ span_name = span.name or span.__class__.__name__
232
+ span_attributes = _serialize_attribute_values(span_attributes)
233
+ if span_to_update:
234
+ span_to_update.set_attributes(span_attributes)
235
+ span_to_update.update_events(span.events, mask_sensitive_information)
236
+ return span_to_update
237
+ else:
238
+ return _OtelSdkSpan(
239
+ name=span_name,
240
+ context=OtelSdkSpanContext(
241
+ trace_id=trace_id,
242
+ span_id=span_id,
243
+ is_remote=False,
244
+ trace_flags=trace_flags,
245
+ trace_state=sampling_result.trace_state,
246
+ ),
247
+ parent=(
248
+ OtelSdkSpanContext(
249
+ trace_id=trace_id,
250
+ span_id=_try_id_to_int_conversion(span._parent_span.id),
251
+ is_remote=False,
252
+ )
253
+ if span._parent_span
254
+ else None
255
+ ),
256
+ resource=resource,
257
+ attributes=span_attributes,
258
+ events=[
259
+ convert_agentspec_event_into_otel_event(
260
+ event,
261
+ mask_sensitive_information=mask_sensitive_information
262
+ )
263
+ for event in span.events
264
+ ],
265
+ )
266
+
267
+
268
+ class _OtelSpanProcessor(AgentSpecSpanProcessor, ABC):
269
+ """AgentSpec wrapper for the OpenTelemetry SpanProcessor"""
270
+
271
+ def __init__(
272
+ self,
273
+ otel_span_processor: Optional[OtelSdkSpanProcessor] = None,
274
+ span_exporter: Optional[OtelSdkSpanExporter] = None,
275
+ resource: Optional[OtelSdkResource] = None,
276
+ mask_sensitive_information: bool = True,
277
+ span_model_dump_func: Optional[Callable[[AgentSpecSpan, bool], Dict[str, Any]]] = None,
278
+ ) -> None:
279
+ """
280
+ AgentSpec wrapper for the OpenTelemetry SpanProcessor.
281
+
282
+ This class forwards the calls to AgentSpec's span processors to an OpenTelemetry one.
283
+
284
+ Parameters
285
+ ----------
286
+ otel_span_processor:
287
+ The OpenTelemetry SpanProcessor to use to process spans.
288
+ If None is given, a new instance is created.
289
+ span_exporter:
290
+ The OpenTelemetry SpanExporter to use to export spans.
291
+ This parameter is ignored if an ``otel_span_processor`` is provided.
292
+ resource:
293
+ The OpenTelemetry Resource to use in Spans.
294
+ mask_sensitive_information
295
+ Whether to mask potentially sensitive information from the span and its events
296
+ span_model_dump_func
297
+ Function to dump the span model to a dictionary, used to get attributes in the
298
+ transformation to OTel Span. The function accepts two parameters: the Agent Spec Span,
299
+ and the mask_sensitive_information boolean flag.
300
+ If None, the pydantic model_dump function on the Agent Spec Span will be used.
301
+ """
302
+ super().__init__(mask_sensitive_information=mask_sensitive_information)
303
+ self.span_exporter = span_exporter
304
+ self.resource = resource
305
+ self.span_model_dump_func = span_model_dump_func
306
+ if otel_span_processor is not None:
307
+ self.span_processor = otel_span_processor
308
+ elif span_exporter is not None:
309
+ self.span_processor = self._create_otel_span_processor(span_exporter=span_exporter)
310
+ else:
311
+ raise ValueError("Span exporter must be provided when no span processor is given")
312
+ # We keep a registry of spans that we already created
313
+ # The idea is to reuse and update the same span at start and end
314
+ self._span_registry: Dict[str, _OtelSdkSpan] = {}
315
+
316
+ @abstractmethod
317
+ def _create_otel_span_processor(
318
+ self, span_exporter: OtelSdkSpanExporter
319
+ ) -> OtelSdkSpanProcessor:
320
+ pass
321
+
322
+ def _create_otel_span_from_agentspec_span(self, span: AgentSpecSpan) -> OtelSdkSpan:
323
+ # We retrieve the span from the registry, and we update it with the new information.
324
+ # If there's no otel span in the registry with this ID, it is created
325
+ span_from_registry = self._span_registry.get(span.id, None)
326
+ otel_span = convert_agentspec_span_into_otel_span(
327
+ span=span,
328
+ resource=self.resource,
329
+ mask_sensitive_information=self.mask_sensitive_information,
330
+ span_model_dump=self.span_model_dump_func,
331
+ span_to_update=span_from_registry,
332
+ )
333
+ # Record the updated span in the registry and return it
334
+ self._span_registry[span.id] = otel_span
335
+ return otel_span
336
+
337
+ def on_start(self, span: AgentSpecSpan) -> None:
338
+ """
339
+ Method called at the start of a Span.
340
+
341
+ Parameters
342
+ ----------
343
+ span:
344
+ The AgentSpec span that is starting
345
+ """
346
+ try:
347
+ otel_span = self._create_otel_span_from_agentspec_span(span=span)
348
+ # If instrumentation is suppressed, we still convert the span,
349
+ # but we don't emit anything
350
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
351
+ return
352
+ otel_span.start(start_time=span.start_time)
353
+ self.span_processor.on_start(span=otel_span)
354
+ except Exception as e:
355
+ # Whatever happens we do not crash the execution of the assistant,
356
+ # but we warn the user
357
+ logger.warning(f"Exception raised during SpanProcessor `on_start`: {e}")
358
+
359
+ def on_end(self, span: AgentSpecSpan) -> None:
360
+ """
361
+ Method called at the end of a Span.
362
+
363
+ Parameters
364
+ ----------
365
+ span:
366
+ The AgentSpec span that is ending
367
+ """
368
+ try:
369
+ # We re-create the span because we might need to re-format
370
+ # the changes happened in the span
371
+ otel_span = self._create_otel_span_from_agentspec_span(span=span)
372
+ # If instrumentation is suppressed, we manage the converted spans statuses,
373
+ # but we don't emit anything
374
+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):
375
+ return
376
+ if otel_span.start_time is None:
377
+ # If the span was not started for some reason, we start it manually here
378
+ otel_span.start(start_time=span.start_time)
379
+ otel_span.end(end_time=span.end_time)
380
+ self.span_processor.on_end(span=otel_span)
381
+ # We remove the span from the registry, since now it's closed
382
+ self._span_registry.pop(span.id, None)
383
+ except Exception as e:
384
+ # Whatever happens we do not crash the execution of the assistant,
385
+ # but we warn the user
386
+ logger.warning(f"Exception raised during SpanProcessor `on_end`: {e}")
387
+
388
+ def on_event(self, event: AgentSpecEvent, span: AgentSpecSpan) -> None:
389
+ # No need to do anything on events occurring, everything is handled at span closure
390
+ pass
391
+
392
+ def startup(self) -> None:
393
+ pass
394
+
395
+ def shutdown(self) -> None:
396
+ try:
397
+ self.span_processor.shutdown()
398
+ self._span_registry = {}
399
+ except Exception as e:
400
+ # Whatever happens we do not crash the execution of the assistant,
401
+ # but we warn the user
402
+ logger.warning(f"Exception raised during SpanProcessor `shutdown`: {e}")
403
+
404
+ async def on_start_async(self, span: AgentSpecSpan) -> None:
405
+ raise NotImplementedError(f"Async stack not implemented for {self.__class__.__name__} yet")
406
+
407
+ async def on_end_async(self, span: AgentSpecSpan) -> None:
408
+ raise NotImplementedError(f"Async stack not implemented for {self.__class__.__name__} yet")
409
+
410
+ async def on_event_async(self, event: AgentSpecEvent, span: AgentSpecSpan) -> None:
411
+ raise NotImplementedError(f"Async stack not implemented for {self.__class__.__name__} yet")
412
+
413
+ async def startup_async(self) -> None:
414
+ raise NotImplementedError(f"Async stack not implemented for {self.__class__.__name__} yet")
415
+
416
+ async def shutdown_async(self) -> None:
417
+ raise NotImplementedError(f"Async stack not implemented for {self.__class__.__name__} yet")
418
+
419
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
420
+ """
421
+ Export all ended spans to the configured Exporter that have not yet been exported.
422
+
423
+ Forwards the call to the internal OpenTelemetry span processor.
424
+ """
425
+ try:
426
+ return self.span_processor.force_flush(timeout_millis=timeout_millis)
427
+ except Exception as e:
428
+ # Whatever happens we do not crash the execution of the assistant, but we warn the user
429
+ logger.warning(f"Exception raised during SpanProcessor `force_flush`: {e}")
430
+ return True
431
+
432
+
433
+ class OtelSimpleSpanProcessor(_OtelSpanProcessor):
434
+ """AgentSpec wrapper for the OpenTelemetry SimpleSpanProcessor"""
435
+
436
+ def _create_otel_span_processor(
437
+ self, span_exporter: OtelSdkSpanExporter
438
+ ) -> OtelSdkSpanProcessor:
439
+ return OtelSdkSimpleSpanProcessor(span_exporter=span_exporter)
440
+
441
+
442
+ class OtelBatchSpanProcessor(_OtelSpanProcessor):
443
+ """AgentSpec wrapper for the OpenTelemetry BatchSpanProcessor"""
444
+
445
+ def _create_otel_span_processor(
446
+ self, span_exporter: OtelSdkSpanExporter
447
+ ) -> OtelSdkSpanProcessor:
448
+ return OtelSdkBatchSpanProcessor(span_exporter=span_exporter)